/*****************************************************************/
/**                                                             **/
/**             (C) Copyright 1992 the Regents of the           **/
/**        University of California.  All Rights Reserved.      **/
/**                                                             **/
/**        This work was produced under the sponsorship of      **/
/**         the U.S. Department of Energy.  The Government      **/
/**                retains certain rights therein.              **/
/**                                                             **/
/**                         Written by                          **/
/**         Distributed Programming Environments Project        **/
/**           Computer Software and Networking Division,        **/
/**                   Livermore Computer Center,                **/
/**            Lawrence Livermore National Laboratory           **/
/**                                                             **/
/*****************************************************************/
	
%%

#ifndef ELROS_DEBUG
#undef YYDEBUG
#endif

main(int argc,char *argv[]) 
{
   init(argv); 
   yyparse();
   printf(" Parse Completed.\n");
   fclose(prim);
   argc = 0;
   if (global.error_count > 0)
      exit(1);
   return(0);
}

void yywhere()
{
   fprintf(stderr,
	   "(epp) \"%s\", line %d near \"%s\": ",
	   linedir_file,
	   linedir_line,
	   yytext);
}

void yyerror(char *s)
{
   yywhere();
   fprintf(stderr," %s\n",s);
   if (strncmp(s,"warning",7)) /* if doesn't start with "warning" */
      global.error_count++;
}

void report_error(char *label, char *fmt, ...)
{
   va_list ap; /* points to each unnamed arg in turn */
   char *p, *sval;
   int ival;
   double dval;

   yywhere();
   fprintf(stderr,"\n      (%s) ",label);
   va_start(ap, fmt); /* make ap point to 1st arg */
   for (p = fmt; *p; p++) {
      if (*p != '%') {
	 putc(*p,stderr);
	 continue;
      }
      switch (*++p) {
      case 'd':
	 ival = va_arg(ap, int);
	 fprintf(stderr,"%d", ival);
	 break;
      case 'f':
	 dval = va_arg(ap, double);
	 fprintf(stderr,"%f", dval);
	 break;
      case 's':
	 for (sval = va_arg(ap, char *); *sval; sval++)
	    putc(*sval,stderr);
	 break;
      default:
	 putc(*p,stderr);
	 break;
      }
   }
   va_end(ap); /* clean up */
   fprintf(stderr,"\n");
   if (strncmp(fmt,"warning",7)) /* if doesn't start with "warning" */
      global.error_count++;
}

void nomem ()
{
  fprintf(stderr,"(epp) internal error:  ** Out of memory ** \n\n");
  exit(1);
}

void init(char *argv[])
{
   int  i;

   Keyword  *tmpkey;


   /* initialize globals */

   scopedepth    = 0;
   lookup        = 0;

   oldyyin       = NULL;

   in_interface_spec = FALSE;
   no_lex_echo       = FALSE;

   no_labels_now = 1;   /* no labels until inside a function body.
			 * Note this is an int, not a boolean - it gets
			 * other values than 0 or 1, possibly (nested 
			 * structs, for example) */

   IdentMode = MODE_LOOKUP;
   changeable_mode = TRUE;
   in_config_file = TRUE;

   crack_execute_line(argv);

   /* allocate the global lists */

   interface_list_ptr    = new interface_list;
   global.anon_interfptr = new interface_element("__RO_anoninterf");
   instance_list_ptr     = new instance_list;
   active_instances_ptr  = new active_instance_list;
   primitive_list_ptr    = new primitive_list;
   printer_list_ptr      = new printer_list;
   Symbol_Table		 = new symbol_table;

   /* set up the keyword table by hashing all the 
     "source" tables into Keyword_Table */

   Keyword_Table = new fast_hash_table(KEYTABSIZE);

   for (i=0; i<ANSI_KEYTABSIZE; i++) {
     
     tmpkey        = new Keyword;
     tmpkey->kind  = KEY_ANSI;
     tmpkey->name  = ansi_keyword_table[i].name;
     tmpkey->token = ansi_keyword_table[i].token;

     if (! Keyword_Table->add(tmpkey)) {
       BUG_CHECK("Keyword_Table wrong size for perfect hash.");
       exit(1);
     }
   }
   for (i=0; i<CONFIG_KEYTABSIZE; i++) {

     tmpkey        = new Keyword;
     tmpkey->kind  = KEY_CONFIG;
     tmpkey->name  = config_keyword_table[i].name;
     tmpkey->token = config_keyword_table[i].token;

     if (! Keyword_Table->add(tmpkey)) {
       BUG_CHECK("Keyword_Table wrong size for perfect hash.");
       exit(1);
     }
   }
   for (i=0; i<PRIMITIVE_KEYTABSIZE; i++) {

     tmpkey        = new Keyword;
     tmpkey->kind  = KEY_PRIM;
     tmpkey->name  = prim_table[i].pw_name;
     tmpkey->token = prim_table[i].pw_yylex;
     tmpkey->akind = prim_table[i].pw_primitive;

     if (! Keyword_Table->add(tmpkey)) {
       BUG_CHECK("Keyword_Table wrong size for perfect hash.");
       exit(1);
     }
   }
    for (i=0; i<ELROS_KEYTABSIZE; i++) {

     tmpkey        = new Keyword;
     tmpkey->kind  = KEY_ELROS;
     tmpkey->name  = keyword_table[i].kw_name;
     tmpkey->token = keyword_table[i].kw_yylex;
     tmpkey->lflag = keyword_table[i].lang_flg;

     if (! Keyword_Table->add(tmpkey)) {
       BUG_CHECK("Keyword_Table wrong size for perfect hash.");
       exit(1);
     }
   }
}


void crack_execute_line(char *argv[])
{
   int inlen = strlen(argv[1]);

   /* open argv[1], the input file:  ..e file */

   CREATE_SP(input_file,char,inlen+1)
   strcpy(input_file,argv[1]);
   if ((yyin = fopen(input_file,"r")) == NULL) {
      fprintf(stderr,"*** couldn't open file: %s\n",input_file);
      exit(1);
   }

   /* open the generated code file produced by the preprocessor:  ..c */

   CREATE_SP(output_file,char,inlen+1)
   strcpy(output_file,argv[1]);
   output_file[inlen-1] = 'h';
   if ((prim = fopen(output_file,"w")) == NULL) {
      fprintf(stderr,
		   "*** couldn't open output file:%s\n",output_file);
      exit(1);
   }

   /* open the primary types output file produced by the preprocessor: ..h */

   CREATE_SP(output_file2,char,inlen+1)
   strcpy(output_file2,argv[1]);
   output_file2[inlen-1] = 'c';
   if ((out = fopen(output_file2,"w")) == NULL) {
      fprintf(stderr,"*** couldn't open temporary output file: %s\n",output_file2);
      exit(1);
   }

   /* open the typedef file produced by the preprocessor:  ..t */

   CREATE_SP(types_file,char,inlen+1)
   strcpy(types_file,argv[1]);
   types_file[inlen-1] = 't';
   if ((types = fopen(types_file,"w")) == NULL) {
      fprintf(stderr,"*** couldn't open temporary output file: %s\n",types_file);
      exit(1);
   }


   /* prepare to process parameters.dat file */

   /* open argv[2], the parameters.dat file */

   CREATE_SP(parameters_dat_file,char,strlen(argv[2])+1)
   strcpy(parameters_dat_file,argv[2]);
   oldyyin = yyin;
   oldinput_file = input_file;
   input_file = (char*)malloc(strlen(parameters_dat_file)+1);
   strcpy(input_file,parameters_dat_file);
   if ((yyin = fopen(parameters_dat_file,"r")) == NULL) {
      fprintf(stderr,"*** couldn't open file: %s\n",
		      parameters_dat_file);
      exit(1);
   }

}

static int start_expbuf = 0;   /* shared by dump_expbuf() and clear_expbuf() */

void dump_expbuf(int end)
{
   char temp;
   if (last_bufoffset == end) {
      fprintf(out,"%s", expbuf+start_expbuf);
      last_bufoffset = 0;
      start_expbuf = 0;
      *(expbuf) = '\0';
   }
   else {   				/* don't print the lookahead */
      temp = *(expbuf+last_bufoffset);
      *(expbuf+last_bufoffset) = '\0';
      fprintf(out,"%s", expbuf+start_expbuf);
      *(expbuf+last_bufoffset) = temp;
      start_expbuf = last_bufoffset;
   }
}

void clear_expbuf(int end)
{
   if (last_bufoffset == end) {
      last_bufoffset = 0;
      start_expbuf = 0;
      *(expbuf) = '\0';
   }
   else {   				/* don't print the lookahead */
      start_expbuf = last_bufoffset;
   }
}

void gen_startsend(FILE *out, char *stmt, instance_element* inst_ele)
{
  gen_activateinst_log(out,stmt,inst_ele);
  INDENT(out,1);
  FPRINTF(out,"if (%s->sendPPDU_start(%s))\n",
	       GETINSTNAME,
	       GETINSTNAME);
  gen_exception_goto(out,2,GETINSTNAME,
		     GETEXCEPTIONLAB);
}

void gen_activateinst_log(FILE *out, char *stmt, instance_element* inst_ele)
{

  active_instance_element *active_inst;
  char *oklab, *errlab;

  oklab = gen_exception_label();
  errlab = gen_exception_label();
  active_inst = new active_instance_element(
		   inst_ele, 
		   errlab,
		   oklab);
  active_instances_ptr->insert(active_inst);
  FPRINTF(out,"\n{   /* %s statement */\n",stmt);
  INDENT(out,1);
  FPRINTF(out,"P(%s->exclusion);\n",GETINSTNAME);
}

void gen_startrec(FILE *out, 
		  char *stmt, 
		  char *message, 
		  instance_element *inst_ele)
{

  active_instance_element *active_inst;
  char *oklab, *errlab;

  oklab = gen_exception_label();
  errlab = gen_exception_label();

  FPRINTF(out,"\n{   /* %s statement */\n",stmt);
  active_inst = new active_instance_element(
		   inst_ele, 
		   errlab,
		   oklab);
  active_instances_ptr->insert(active_inst);
  INDENT(out,1);
  FPRINTF(out,"__RO_int32 __RO_type;\n");
  INDENT(out,1);
  FPRINTF(out,"unsigned long __RO_length;\n\n");
  INDENT(out,1);
  FPRINTF(out,"P(%s->exclusion);\n",GETINSTNAME);
  if (global.gen_log) 
     gen_log_statement(out,1,message,GETINSTNAME,GETEXCEPTIONLAB);
  INDENT(out,1);
  FPRINTF(out,"if (%s->getP_start(%s))\n",
	       GETINSTNAME,
	       GETINSTNAME);
  gen_exception_goto(out,2,GETINSTNAME,
		     GETEXCEPTIONLAB);
  gen_getheader(out,1,GETEXCEPTIONLAB,GETINSTNAME);
  INDENT(out,1);
  FPRINTF(out,"switch (__RO_type) {\n");
}

void do_ontype_stmt(boolean is_typeid,
                    type_element *teptr,
                    char *val,
		    char *len)
{
   if (!is_typeid) { /* is ELROS_BASE_TYPE */
      teptr->set_interf(global.anon_interfptr);
      global.anon_interfptr->constant_gen->add_encoding(teptr);
   }
   teptr->gen_leadingTAG_cases(out,1);
   FPRINTF(out,"{   /* ontype_clause */\n");
   if (global.gen_log)
      gen_log_statement(out,1,"DECODING ",GETINSTNAME,GETEXCEPTIONLAB);
   teptr->gen_getP(out,
		   1,
		   val,
		   len,
		   GETEXCEPTIONLAB,
		   GETINSTNAME);
   INDENT(out,1);
   FPRINTF(out,"if (%s->getP_end(%s))\n",
		     GETINSTNAME,
		     GETINSTNAME);
   gen_exception_goto(out,2,GETINSTNAME,
		     GETEXCEPTIONLAB);
   INDENT(out,1);
   FPRINTF(out,"V(%s->exclusion);\n",GETINSTNAME);
}

void do_decode_stmt4(boolean iswrapped)
{
   if (iswrapped) {
      /* OK to generate a default case--none already generated */
      INDENT(out,1);
      FPRINTF(out,"default:\n");
      INDENT(out,2);
      FPRINTF(out,"{__RO_RAISE_RUNTIME((%s),0xffffffff,%s);}\n",
      GETINSTNAME,GETEXCEPTIONLAB); /* need new message like __ROx_ASN_EXPECTKNOWNTYPE */
    }
    INDENT(out,1);
    FPRINTF(out,"} /* End of switch(__RO_type) for ON CLAUSES*/\n");
    if (global.gen_log)
      gen_log_statement(out,1,"EXITING decode statement",GETINSTNAME,GETEXCEPTIONLAB);
}

void do_call_stmt1_a(operation_element* oeptr)
{
   parameter_list *pp;

   act_operation(oeptr);
   if((pp=oeptr->get_params_ptr()) && pp->get_pos_or_named())
       global.kind_of_args = pp->get_pos_or_named();
   else
       global.kind_of_args = TYPE_PARAM_LIST;
}

void do_call_stmt1_b(operation_element* oeptr,
		     instance_element* insteptr,
		     argument_list *callarglist,
		     char *string1,
		     char *string2)
{
  argument_list *ins = NULL, *outs = NULL;

  if (oeptr->get_kind_op() != KIND_CALL)
     report_error("error 24",
		  "\"%s\" is not a Call operation so that \"@\"\n\tnotation may not be used.",
		  oeptr->get_name());
  else {
     gen_startsend(out, 
		   "call",
		   insteptr);

     oeptr->process_call_arguments(callarglist, ins,outs);
     oeptr->get_inv_part()->gen_give(out,
				  string1,
				  string2,
				  ins,
				  GETEXCEPTIONLAB,
				  TRUE);
     fprintf(out,"\n/* middle of call stmt */\n");
     gen_accept_start(out,
		      insteptr,
		      string1,
		      string2,
		      TRUE);
     oeptr->get_res_part()->gen_accept_on(out,
				       outs,
				       callarglist->get_ellipsed(),
				       GETEXCEPTIONLAB,
				       TRUE);
     INDENT(out,3);
     FPRINTF(out,"break;\n");
     INDENT(out,2);
     FPRINTF(out,"} /* End of on_operation */\n");
     gen_accept_end(out,
		    oeptr->get_res_part()->
			      get_internal_number(),
		    GETEXCEPTIONLAB);
     FPRINTF(out,"\n}   /* End of accept part of call statement */\n\n");
  }
}

void do_give_stmt()
{
  fprintf(out,"\n");
  INDENT(out,1);
  FPRINTF(out,"P(%s->exclusion);\n",GETINSTNAME);
  INDENT(out,1);
  FPRINTF(out,"if (%s->sendPPDU_end(%s))\n",
	       GETINSTNAME,GETINSTNAME);
  gen_exception_goto(out,2,GETINSTNAME,GETEXCEPTIONLAB);
  if (global.gen_log)
     gen_log_statement(out,1,"EXITING give statement",
		       GETINSTNAME,GETEXCEPTIONLAB);
  INDENT(out,1);
  FPRINTF(out,"V(%s->exclusion);\n",GETINSTNAME);
  gen_exception_header(out,
		       GETEXCEPTIONLAB,
		       GETOKLAB);
  gen_default_handlers(out,MASK_ZERO,GETOKLAB);
}

void do_give2(symbol_element *septr, instance_element *iptr)
{
  act_give_accept(septr);
  gen_startsend(out, "give", iptr);
  if (global.gen_log)
       gen_log_statement(out, 
                         1,
                         "ENTERING give statement",
			 GETINSTNAME,
			 GETEXCEPTIONLAB);
  INDENT(out,1);
  FPRINTF(out,"V(%s->exclusion);\n",GETINSTNAME);
}

void do_ispec(char *iname) 
{
   extern void END_Interf();

   END_Interf();
   in_interface_spec = FALSE;
   freeable_types_ptr->gen_free_routines(out);
   ieptr->optable_gen->generate(out);
   ieptr->constant_gen->generate(out);
   if (!incomplete_types_ptr->isempty()) {
      link *l;
      type_element *teptr;
      incomplete_types_ptr->reset();
      while (incomplete_types_ptr->next(l)) {
        teptr = (type_element *)l;
        fprintf(stderr,"Forward referenced type not defined: %s",teptr->get_name());
      }
   }
   forward_types_ptr->gen_encode_decode_routines(out);

/* Should these type_element lists be freed?  We get new lists for next
   interface... */

   fprintf(out,"\n\n/* end of Interface %s */\n\n",iname); 
   *expbuf = '\0';
   last_bufoffset = 0;
}

char * do_interface_header(char* string, 
			   boolean auto_present, 
			   boolean autotagged, 
			   boolean explicit_tagging,
			   boolean free_flag)
{
   link *link_ptr;

   if (interface_list_ptr->search(string,link_ptr))
      fprintf(out,"*** Interface '%s' was previously specified\n",
	     ((symbol_element*)link_ptr)->get_name());
   else {
      ieptr = new interface_element(string);
      interface_list_ptr->append(ieptr);
      fprintf(out,"\n\n/* Interface %s */\n\n",string); 
   }
   global.tagging = TRUE; /* autotag by default */
   if ((auto_present == TRUE) && (autotagged == FALSE))
      global.tagging = FALSE;
   global.explicit_tagging  = explicit_tagging;
   global.freeable = (free_flag == -1) ? 1 /* default */ : free_flag;
   incomplete_types_ptr = new type_element_list;
   forward_types_ptr = new type_element_list;
   freeable_types_ptr = new type_element_list;
   return (string);
}

char *negative_string(char *s)
{ char *temp;
  temp = (char *)malloc(strlen(s) + 2);
  temp[0] = '-';
  strcpy(&temp[1],s);
  free(s);
  return temp;
}

operation_element *do_op_def1(enum op_kind kind, 
                              char *nam, 
                              char *num, 
                              parameter_list *pl)
{
  operation_element *temp;
  temp = new operation_element(kind,nam,num,pl);
  temp->set_kind(SYM_OP);
  temp->set_interf(ieptr);
  ieptr->append_op(temp);
  ieptr->optable_gen->add_operation(temp);
  return (temp);
}

operation_element *do_op_def2(enum op_kind kind, 
                              char *nam, 
                              char *num)
{
  operation_element *temp;
  temp = new operation_element(kind,nam,num);
  temp->set_kind(SYM_OP);
  temp->set_interf(ieptr);
  ieptr->append_op(temp);
  ieptr->optable_gen->add_operation(temp);
  return (temp);
}

void do_encode_stmt()
{
      fprintf(out,"\n");
      INDENT(out,1);
      FPRINTF(out,"P(%s->exclusion);\n",GETINSTNAME);
      INDENT(out,1);
      FPRINTF(out,"if (%s->sendPPDU_end(%s))\n",
		   GETINSTNAME,GETINSTNAME);
      gen_exception_goto(out,2,GETINSTNAME,GETEXCEPTIONLAB);
      if (global.gen_log)
	 gen_log_statement(out,1,"EXITING encode statement",
			   GETINSTNAME,GETEXCEPTIONLAB);
      INDENT(out,1);
      FPRINTF(out,"V(%s->exclusion);\n",GETINSTNAME);
      gen_exception_header(out,
			   GETEXCEPTIONLAB,
			   GETOKLAB);
      gen_default_handlers(out,MASK_ZERO,GETOKLAB);
}

void do_encode_stmt2(instance_element *inst)
{
      gen_startsend(out, 
		    "encode", 
		    inst);
      if (global.gen_log)
	   gen_log_statement(out,1,"ENTERING encode statement",GETINSTNAME,GETEXCEPTIONLAB);
      INDENT(out,1);
      FPRINTF(out,"V(%s->exclusion);\n",GETINSTNAME);
}

void do_type_stmt(type_element *teptr, char *val, char *len)
{
       FPRINTF(out,"\n{   /* type_statement */\n");
       INDENT(out,1);
       FPRINTF(out,"if (%s->sendPDV_start(%s))\n",
			 GETINSTNAME,
			 GETINSTNAME);
       gen_exception_goto(out,2,GETINSTNAME, GETEXCEPTIONLAB);
       teptr->gen_sendP(out,1,val,len,
		     GETINSTNAME,
		     GETCONSTNAME,
		     GETEXCEPTIONLAB);
       INDENT(out,1);
       FPRINTF(out,"if (%s->sendPDV_end(%s))\n",
			 GETINSTNAME,
			 GETINSTNAME);
       gen_exception_goto(out,2,GETINSTNAME, GETEXCEPTIONLAB);
       FPRINTF(out,"}   /* End of type_statement */\n\n");
}
