%a 2400
%p 4800
%e 1200

%{

/*****************************************************************/
/**                                                             **/
/**             (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           **/
/**                                                             **/
/*****************************************************************/

#define SILENT_SCAN

#ifdef SILENT_SCAN
#undef lex_output

/*
 * make lex_output do nothing, but make compiler think that the argument 'c'
 * is used, so it doesn't complain. also, make ECHO do nothing
 */

#define lex_output(c) (putc(((c)==0?'\000':'\000'),yyout))
#ifdef ECHO
#undef ECHO
#endif
#define ECHO /* nothing */
#endif


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "abs.h"
#include "decls.h"
#include "keytab.h"
#include "symtab.h"
#include "misc.h"
#include "pnode.h"
#include "y.tab.h"

#define MAX_PRIM_LEN 17		/* maximum string length of a primitive name */
				/* currently big enough for ObjectIdentifier */
char prim_name[MAX_PRIM_LEN];	/* buffer to hold primitive name 	     */
int prim_name_len;		/* length of the primitive name		     */

#define MAX_DIGITS 64		/* max string length of a length specification */
char len1[MAX_DIGITS];		/* buffer to hold length specification digits */
char len2[MAX_DIGITS];		/* buffer to hold length specification digits */

#define EXTRA_CHARS 10		/* __ROt_nameinyytext_0_0     */
				/* \    /            \  /     */
				/*  \  /              \/      */
				/*    6        +       4 = 10 */
#define INIT_EXPBUF_SIZE 256

/* assumes the translation of the string in arg will be no longer than */
/* EXTRA_CHARS longer than the string in arg             */

void prepare_expbuf(char* arg);
#define RETURNIT(arg)						\
   prepare_expbuf(yytext);					\
   yylval.bufoffset = last_bufoffset;				\
   strcpy(expbuf+last_bufoffset, yytext);			\
   return (arg)

#define RET(arg)						\
      {make_string();						\
      prepare_expbuf(yytext);					\
      yylval.string_bufoffset.bufoffset = last_bufoffset;	\
      strcpy(expbuf+last_bufoffset, yytext);			\
      return (arg);}

#define CONTDATMACRO							\
	  char *iname;							\
	  interface_element  *tmp_ieptr;				\
	  iname = (char*)malloc(strlen(yytext)+1);				\
	  if ((sscanf(yytext, "%*[^(] ( %[^) ]", iname)) == 1) {	\
	     IdentMode = MODE_INTERFACE;				\
	     (void)identify(iname); 					\
	     tmp_ieptr = yylval.interface_eptr;				\
	     yylval.ieptr_bufoffset.ieptr = tmp_ieptr;			\
	  }								\
	  else {							\
		BUG_CHECK("Interface must be specified");           	\
	  }								\
	  prepare_expbuf("__RO_Instance_Record_ptr ");			\
	  strcpy(expbuf+last_bufoffset,"__RO_Instance_Record_ptr ");	\
	  yylval.ieptr_bufoffset.bufoffset = last_bufoffset;		\
	  IdentMode = MODE_IDENT;
%}


decimaldigit	[0-9_]
hexdigit	[0-9A-Fa-f_]
nat_num		({decimaldigit}+)
integer_spec    (u|U|l|L)*
integer		{nat_num}{integer_spec}
exponent	([eE]([+-]?){integer})
real_const_spec (f|F|l|L)
real_const1	{nat_num}"."{nat_num}?{exponent}?{real_const_spec}?
real_const2	"."([_])*[0-9]({decimaldigit}*){exponent}?{real_const_spec}?
real_const3     {nat_num}{exponent}{real_const_spec}?
real_const	({real_const1}|{real_const2}|{real_const3})
obj_id		{nat_num}("."{nat_num})+
hex		0[xX]{hexdigit}+{integer_spec}
octaldigit	[0-7_]
octal		0{octaldigit}+{integer_spec}

slash		"\\"
quote		"\""
ques		"?"
apost		"'"

char_const      L?'(\\.|[^\\'])+'
 
EBT_1		("Real")
EBT_2		("ObjectIdentifier")
EBT_3		("Integer"|"Boolean"|"Enumerated")
EBT_4		("NumericString"|"PrintableString"|"GraphicString"|"VisibleString"|"VideotexString"|"IA5String"|"TeletexString"|"GeneralString"|"BitString"|"OctetString")

letter		[a-zA-Z_]
digit		[0-9]
lord		[a-zA-Z_0-9]
white_sp	[ \t\n]

word            ({letter}{lord}*)

%Start Interf
%%

"("               { ECHO; RETURNIT( LPAR ); }
")"               { ECHO; RETURNIT( RPAR ); }
"{"               { ECHO; RETURNIT( LBRACE ); }
"}"               { ECHO; RETURNIT( RBRACE ); }
"<"               { ECHO; RETURNIT( LANGLE ); }
">"               { ECHO; RETURNIT( RANGLE ); }
"["               { ECHO; RETURNIT( LBRACK ); }
"]"               { ECHO; RETURNIT( RBRACK ); }
","               { ECHO; RETURNIT( COMMA ); }
";"	          { ECHO; RETURNIT( SEMI ); }
"="		  { ECHO; RETURNIT( EQUALS ); }
"."		  { ECHO; RETURNIT( DOT ); }
"&"		  { ECHO; RETURNIT( AMPER ); }
"!"		  { ECHO; RETURNIT( BANG ); }
"~"		  { ECHO; RETURNIT( TILDE ); }
"-"		  { ECHO; RETURNIT( MINUS ); }
"+"		  { ECHO; RETURNIT( PLUS ); }
"*"		  { ECHO; RETURNIT( STAR ); }
"/"		  { ECHO; RETURNIT( SLASH ); }
"%"		  { ECHO; RETURNIT( PERCENT ); }
"^"		  { ECHO; RETURNIT( COMP ); }
"|"		  { ECHO; RETURNIT( BITOR ); }
"?"		  { ECHO; RETURNIT( QUES ); }

"..."             { ECHO; RETURNIT( ELLIPSIS      ); }
">>="		  { ECHO; RETURNIT( RIGHT_ASSIGN  ); }
"<<="		  { ECHO; RETURNIT( LEFT_ASSIGN   ); }
"+="		  { ECHO; RETURNIT( ADD_ASSIGN    ); }
"-="		  { ECHO; RETURNIT( SUB_ASSIGN    ); }
"*="		  { ECHO; RETURNIT( MUL_ASSIGN    ); }
"/="		  { ECHO; RETURNIT( DIV_ASSIGN    ); }
"%="		  { ECHO; RETURNIT( MOD_ASSIGN    ); }
"&="		  { ECHO; RETURNIT( AND_ASSIGN    ); }
"^="		  { ECHO; RETURNIT( XOR_ASSIGN    ); }
"|="		  { ECHO; RETURNIT( OR_ASSIGN     ); }
">>"		  { ECHO; RETURNIT( RIGHT_OP      ); }
"<<"		  { ECHO; RETURNIT( LEFT_OP       ); }
"++"		  { ECHO; RETURNIT( INC_OP        ); }
"--"		  { ECHO; RETURNIT( DEC_OP        ); }
"->"		  { ECHO; RETURNIT( PTR_OP        ); }
"&&"		  { ECHO; RETURNIT( AND_OP        ); }
"||"		  { ECHO; RETURNIT( OR_OP         ); }
"<="		  { ECHO; RETURNIT( LE_OP         ); }
">="		  { ECHO; RETURNIT( GE_OP         ); }
"=="		  { ECHO; RETURNIT( EQ_OP         ); }
"!="		  { ECHO; RETURNIT( NE_OP         ); }
"=>"              { ECHO; RETURNIT( ARROW         ); }

":"               { 
                    /* Sometimes a colon is pushed back into the input
                     * stream, but we don't want to echo it twice. */

                    if (!no_lex_echo) {
		      ECHO;
		    }
                    else {
		      no_lex_echo = FALSE;
		    }
                    RETURNIT( COLON );
		  }

{nat_num}         { 
                    ECHO;
                    squeeze_underscores();  
                    RET( NATNUM_CONST );  
                  }

{integer}         {  
                    ECHO;
                    squeeze_underscores();  
                    RET( INTEGER_CONST );  
                  }

{real_const}      {  
                    ECHO;
                    squeeze_underscores();  
                    RET( REAL_CONST );  
                  }

{hex}             {  
                    ECHO;
                    RET( HEX_CONST );  
                  }

{obj_id}          {  
                    ECHO;
                    RET( OBJ_ID_CONST );  
                  } 

{char_const}      {   
                    ECHO;  
                    RET( CHAR_CONST );  
                  }
<Interf>(True|False)      {   
                    ECHO;  
                    RET( BOOLEAN_CONST );  
                  }

On{white_sp}+Com_error      { ECHO; return( ONCOM_ERROR      ); } 
On{white_sp}+Internal_error { ECHO; return( ONINTERNAL_ERROR ); } 
On{white_sp}+Protocol_error { ECHO; return( ONPROTOCOL_ERROR ); }
On{white_sp}+Missing_op     { ECHO; return( ONMISSING_OP     ); }
On{white_sp}+Missing_arg    { ECHO; return( ONMISSING_ARG    ); }
On{white_sp}+Name_error     { ECHO; return( ONNAME_ERROR     ); }
On{white_sp}+Done           { ECHO; return( ONDONE           ); }
On{white_sp}+Bad_op_id      { ECHO; return( ONBAD_OP_ID      ); }

{EBT_1}{white_sp}*"("{white_sp}*{nat_num}{white_sp}*","{white_sp}*{nat_num}{white_sp}*")"	
	{
	    enum abstr_kind ak;
	    enum abstr_kind *which = &ak;
	    ECHO;
	    sscanf(yytext,"%[^( ]",prim_name);
	    if (!is_primitive(prim_name,which)) {
	     report_error("internal error",
			  "lexKeyword should have found primary: <%s>.",
			  prim_name);
	     exit(1);
	    }
	    yylval.ak_len1_len2_bufoffset.abstr_kind = ak;
	    prim_name_len = strlen(prim_name);
	    sscanf(yytext+prim_name_len," ( %[^, ] , %[^) ]",len1,len2);
	    yylval.ak_len1_len2_bufoffset.len1 = len1;
	    yylval.ak_len1_len2_bufoffset.len2 = len2;
	    prepare_expbuf(yytext);
   	    yylval.ak_len1_len2_bufoffset.bufoffset = last_bufoffset;
	    sprintf(expbuf+last_bufoffset,"__ROt_%s_%s_%s",prim_name,len1,len2);
	    if (changeable_mode) IdentMode = MODE_IDENT;
	    return (ELROS_BASE_TYPE);
	 }

{EBT_2}{white_sp}*"("{white_sp}*({nat_num}|"*"){white_sp}*","{white_sp}*{nat_num}{white_sp}*")"	
	{
	    enum abstr_kind ak;
	    enum abstr_kind *which = &ak;
	    ECHO;
	    sscanf(yytext,"%[^( ]",prim_name);
	    if (!is_primitive(prim_name,which)) {
	     report_error("internal error",
			  "lexKeyword should have found primary <%s>.",
			  prim_name);
	     exit(1);
	    }
	    yylval.ak_len1_len2_bufoffset.abstr_kind = ak;
	    prim_name_len = strlen(prim_name);
	    sscanf(yytext+prim_name_len," ( %[^, ] , %[^) ]",len1,len2);
	    prepare_expbuf(yytext);
	    yylval.ak_len1_len2_bufoffset.len2 = len2;
   	    yylval.ak_len1_len2_bufoffset.bufoffset = last_bufoffset;
	    if (strcmp(len1,"*")) {
	      yylval.ak_len1_len2_bufoffset.len1 = len1;
	      sprintf(expbuf+last_bufoffset,"__ROt_%s_%s_%s",prim_name,len1,len2);
            }
            else {
	      yylval.ak_len1_len2_bufoffset.len1 = "0";
	      sprintf(expbuf+last_bufoffset,"__ROt_%s_0_%s",prim_name,len2);
            }
	    if (changeable_mode) IdentMode = MODE_IDENT;
	    return (ELROS_BASE_TYPE);
	 }


{EBT_3}{white_sp}*"("{white_sp}*{nat_num}{white_sp}*")"	
	{
	    enum abstr_kind ak;
	    enum abstr_kind *which = &ak;
	    ECHO;
	    sscanf(yytext,"%[^( ]",prim_name);
	    if (!is_primitive(prim_name,which)) {
	     report_error("internal error",
			  "lexKeyword should have found primary <%s>.",
			  prim_name);
	     exit(1);
	    }
	    yylval.ak_len1_len2_bufoffset.abstr_kind = ak;
	    prim_name_len = strlen(prim_name);
	    sscanf(yytext+prim_name_len," ( %[^) ]",len1);
	    yylval.ak_len1_len2_bufoffset.len1 = len1;
	    yylval.ak_len1_len2_bufoffset.len2 = "0";
	    prepare_expbuf(yytext);
   	    yylval.ak_len1_len2_bufoffset.bufoffset = last_bufoffset;
	    sprintf(expbuf+last_bufoffset, "__ROt_%s_%s_0", prim_name,len1);
	    if (changeable_mode) IdentMode = MODE_IDENT;
	    return (ELROS_BASE_TYPE);
	}

{EBT_4}{white_sp}*"("{white_sp}*({nat_num}|"*"){white_sp}*")"	
	{
	    enum abstr_kind ak;
	    enum abstr_kind *which = &ak;
	    ECHO;
	    sscanf(yytext,"%[^( ]",prim_name);
	    if (!is_primitive(prim_name,which)) {
	     report_error("internal error",
			  "lexKeyword should have found primary <%s>.",
			  prim_name);
	     exit(1);
	    }
	    yylval.ak_len1_len2_bufoffset.abstr_kind = ak;
	    prim_name_len = strlen(prim_name);
	    sscanf(yytext+prim_name_len," ( %[^) ]",len1);
	    yylval.ak_len1_len2_bufoffset.len2 = "0";
	    prepare_expbuf(yytext);
   	    yylval.ak_len1_len2_bufoffset.bufoffset = last_bufoffset;
            if (strcmp(len1,"*")) {
	       yylval.ak_len1_len2_bufoffset.len1 = len1;
	       sprintf(expbuf+last_bufoffset, "__ROt_%s_%s_0", prim_name,len1);
            }
	    else {
	       yylval.ak_len1_len2_bufoffset.len1 = "0";
	       sprintf(expbuf+last_bufoffset, "__ROt_%s_0_0", prim_name);
            }
	    if (changeable_mode) IdentMode = MODE_IDENT;
	    return (ELROS_BASE_TYPE);
	}

Null	{

	    enum abstr_kind ak;
	    enum abstr_kind *which = &ak;
	    ECHO;
	    if (!is_primitive(yytext,which)) {
	     report_error("internal error",
			  "lexKeyword should have found primary <%s>.",
			  prim_name);
	     exit(1);
	    }
	    yylval.ak_len1_len2_bufoffset.abstr_kind = ak;
	    yylval.ak_len1_len2_bufoffset.len1 = "0";
	    yylval.ak_len1_len2_bufoffset.len2 = "0";
	    prepare_expbuf(yytext);
   	    yylval.ak_len1_len2_bufoffset.bufoffset = last_bufoffset;
	    strcpy(expbuf+last_bufoffset, "__ROt_Null_0_0");
	    if (changeable_mode) IdentMode = MODE_IDENT;
	    return (ELROS_BASE_TYPE);
	 }
Any	{

	    enum abstr_kind ak;
	    enum abstr_kind *which = &ak;
	    ECHO;
	    if (!is_primitive(yytext,which)) {
	     report_error("internal error",
			  "lexKeyword should have found primary <%s>.",
			  prim_name);
	     exit(1);
	    }
	    yylval.ak_len1_len2_bufoffset.abstr_kind = ak;
	    yylval.ak_len1_len2_bufoffset.len1 = "0";
	    yylval.ak_len1_len2_bufoffset.len2 = "0";
	    prepare_expbuf(yytext);
   	    yylval.ak_len1_len2_bufoffset.bufoffset = last_bufoffset;
	    strcpy(expbuf+last_bufoffset, "__RO_Memory");
	    if (changeable_mode) IdentMode = MODE_IDENT;
	    return (ELROS_BASE_TYPE);
	 }


Control{white_sp}*"("{white_sp}*{word}?{white_sp}*")"	
	{
	  CONTDATMACRO
	  ECHO;
	  return (CONTROL_DECL);
	}
Data{white_sp}*"("{white_sp}*{word}?{white_sp}*")"	
	{
	  CONTDATMACRO
	  ECHO;
	  return (DATA_DECL);
	}

{word}{white_sp}*[@]{white_sp}*{word}	
	{
	  ECHO;
	  return lexIdAtSign();
	}

{word}{white_sp}*\:	
	{
	  ECHO;
	  if (no_labels_now > 0) {
	    no_lex_echo = TRUE;
	    unput(':');
	    return lexIdColon();
	  }
	  else {
	    RETURNIT (STMT_LABEL);
	  }
	}

{word}{white_sp}*\:\:{white_sp}*{word}	
	{
	  ECHO;
	  return scope_resolve();
	}

\:\:{white_sp}*{word}	
	{
	  /* sometimes the above rule pushes everything after :: back
	   * into the input stream, and it gets lexed again here. 
	   * Don't echo a second time */

	  if (!no_lex_echo) {
	    ECHO;
	  }
	  else {
	    no_lex_echo = FALSE;
	  }
	  return scope_resolve();
	}

"#".*\n       	  
	{
	  ECHO;
	  if (in_config_file)
	    return CONFIG_COMMENT;
	  else {
	    if (in_interface_spec)
	       clear_expbuf(last_bufoffset);
	    else
	       dump_expbuf(last_bufoffset);
	    if (!strncmp(yytext+1,"include",7) ||
	        !strncmp(yytext+1,"define",6)  ||
                !strncmp(yytext+1,"undef",5)   ||
                !strncmp(yytext+1,"if",2)      || /* if, ifdef, ifndef */
	        !strncmp(yytext+1,"else",4)    ||
                !strncmp(yytext+1,"elif",4)    ||
		!strncmp(yytext+1,"pragma",6)  ||
		!strncmp(yytext+1,"error",5)   ||
	        !strncmp(yytext+1,"endif",5)     )

		/* let #directive pass through */
		fprintf(out,"%s", yytext);

	    else { /* process line directive */
	       char ch;
	       int start;
	       int i;
	       int newlen;							
	       newlen = strlen(yytext)+1;
	       if (linedir_file) {
		  if (newlen > linedir_file_size) {
		     linedir_file_size += ((linedir_file_size > newlen)
					 ? linedir_file_size
					 : newlen); 
		     if ((linedir_file = (char*)realloc(linedir_file,linedir_file_size)) 
			  == NULL) nomem();		      
		  }
	       }
	       else {
		 BUG_CHECK("Space should have been malloced at END_CONFIG");
	       }
	       for (i = 1 ; yytext[i] != '\n' ; i++ ) {
		  if (isdigit(yytext[i])) {
		     start = i;
		     while (isdigit(yytext[++i]))
			;
		     ch = yytext[i];
		     yytext[i] = '\0';
		     linedir_line = atoi(yytext+start);
		     yytext[i] = ch;

		     while ( yytext[i++] != '\"')
			; /*scanforquote */
		     start = 0;
		     while (yytext[i] != '\"')
			linedir_file[start++] = yytext[i++];
		     linedir_file[start] = '\0';
		     break;
		  }
	       }
	       linedir_line -=1; /* the newline at end of 
				    this directive must be 
				    taken into account   */
	       if (global.line_dirs) fprintf(out,"%s",yytext);
	    }
	 }
	}

{word}	
	{
	  ECHO;
          return (identify(yytext));
	}

\"([^"\n]|\\["\n])*\"	
	{
	  ECHO;
	  RET(STRING_CONST);
	}

\n	
	{
	  ECHO;
	  prepare_expbuf(yytext);
	  strcpy(expbuf+last_bufoffset, yytext);
	  linedir_line++;
	}

.	
	{
	  ECHO;
	  prepare_expbuf(yytext);
	  strcpy(expbuf+last_bufoffset, yytext);
	  if (isspace(yytext[0])) 

	    /* whitespace just gets dropped on the floor */
	    ;

	  else if (isprint(yytext[0])) {

	    /* When we've finished the parameters.dat (config) file, 
             * we push $ onto the start of the input stream to denote this. 
             * The $ is recognized by this
	     * lex rule, so the we can return the END_CONFIG token. 
             * This token is 
	     * necessary because the final token of the config file 
             * can legally be
             * LONG, and the start of a C program can legally be long. 
             * LONG LONG is
	     * therefore a parsing conflict, and shifting is not necessarily
 	     * always correct - it's wrong in the case given above:
	     * LONG <end-of-file> LONG. Shifting is incorrect, 
             * the 2nd LONG is not
	     * part of a config directive, it's a C decl. */

	    if ((yytext[0]) == '$') {
	      if (config_just_ended) {
                config_just_ended = FALSE;
		last_bufoffset = 0;
		*expbuf = '\0';
		if (input_file) {
		   linedir_file_size = strlen(input_file)+1;  
		   if ((linedir_file = (char*)malloc(linedir_file_size)) == NULL) 
		     nomem();
		   strcpy(linedir_file,input_file);
		}
		else {
		  BUG_CHECK("input_file wasn't specified");
		}
		linedir_line = 1;
                return END_CONFIG;
              }
            }
	    fprintf(yyout," Discarding illegal character: '%c' (%o octal)\n", 
	                  yytext[0],
	                  ((int)(yytext[0])));

	    /* no return - just drop this character on the floor */
	  }
	  else {
	    
	    /* We'll throw away everything else, but print a warning. The
	     * standard does not define what to do here (2.2.1 lines 29-32) */
	   
	    fprintf(yyout," Warning! Discarding useless character: %o octal\n",
	                  ((int)(yytext[0])));
	  }
	}



%%

void BEGIN_Interf()
{BEGIN Interf;}

void END_Interf()
{BEGIN 0;}

int yywrap()
{
	if (oldyyin) {
	   fclose(yyin);
	   yyin = oldyyin;
	   if (!strcmp(input_file,parameters_dat_file)) {
	      in_config_file    = 0;

	      /* see the final rule above for the explaination of this
               * "$" character */

	      config_just_ended = TRUE;
	      unput('$');
	      oldyyin    = NULL;
	      input_file = oldinput_file;
	      linedir_line = 1;
	      return(0);
	   }
	   else {
	      report_error("internal error", 
	  		   "unexpected input file: %s.",
			   input_file);
	      exit(1);
	   }
	}
	else
	   return(1);

        /* Added for g++ */
        return (0);
}


void squeeze_underscores()
{
   int oldpos = 0,newpos = 0;
   char c;
   while (c = yytext[oldpos++]) 
      if (c != '_')
	 yytext[newpos++] = c;
   yytext[newpos] = '\0';
}


void  make_string()
{
  /* Takes the current yytext[] and malloc's enough space on the yacc stack
   * for it, then copies it in. */

  if ((yylval.string_bufoffset.string = (char*)malloc(strlen(yytext)+1)) == NULL) 
     nomem();
  strcpy(yylval.string_bufoffset.string,yytext);
}


int  lexIdColon()

     /* simply takes the white space and colon off of the yytext (see
      * the lex rule that calls this routine) and identifies the
      * resulting symbol */
{
  char *tracer;
  char *ident;

  /* start at the colon... */

  tracer = &(yytext[yyleng-1]);
  if (*tracer != ':') {
    report_error("internal error",
		 "lexIdColon: yytext doesn't end with ':' : %s.",
		 yytext);
    exit(1);
  }
  
  /* and search back for the end of the ident... */

  while (!isalnum(*tracer) && *tracer!='_') tracer--;
  *(++tracer) = '\0';

  /* make a string and identify it just like any other ident */

  if ((ident=NewThings(char,strlen(yytext)+1)) == NULL) nomem();
  strcpy(ident,yytext);
  yylval.string = ident;
  
  return identify(ident);
}


int  lexKeyword( char *word )

     /* this routine decides if the given word is a keyword, and
      * if so, returns the token after performing any actions 
      * necessary to lex that key. It is used by both identify() and
      * scope_resolve() as a first step. */
{
  Keyword *key_info;

  /* First check the Keyword_Table, if found, return the 
   * appropriate token. If it was a primitive elros type, notice that
   * we also put an abstr_kind on the yylval stack. In the other cases,
   * make_string has already been called to create the yylval.string */

  if ((key_info=Keyword_Table->lookup(word)) != NULL) {
    if (strcmp(word,key_info->name) == 0) {

      /* inside this switch is where we can "turn off" a particular 
       * kind of keyword with some arbitrary code. See KEY_CONFIG. */

      switch(key_info->kind) {

      case KEY_ANSI:
	RETURNIT(key_info->token);

      case KEY_ELROS:
	if (key_info->lflag) {
	  if (key_info->lflag == 2)
	     IdentMode = MODE_INSTANCE;
	  RETURNIT(key_info->token);
	}
	else if (in_interface_spec)
	  return(key_info->token);
	else
	  break;

      case KEY_CONFIG:
	if (in_config_file) 
	  return(key_info->token);
	else
	  break;

      case KEY_PRIM:
	return(key_info->token);

      case KEY_UNKNOWN:
      default:
	report_error("internal error",
		     "Unknown KeyKind: %d.",
		     key_info->kind);
	exit(1);
      }
    }
  }

  /* these aren't in the Keyword_Table because they aren't known until
   * the params file is read. The other keywords are known at 
   * compiler compile-time. */

  for (int i=0; i<bind_type_count; i++) {
    if (!strcmp(bind_type[i],word)) {
      yylval.string = bind_type[i];
      return BIND_TYPE;
    }
  }
  return NOT_A_KEY;
}

int  lexIdAtSign()

     /* Similar to scope_resolve, we have to crack ident1@ident2, and
      * ident1 has to be an operation within the interface of
      * ident2 (which it must be an instance variable). */
{
  char *tracer;
  char *opname;
  char *inst;
  link *linkptr;

  SymKind kind;

  symbol_element    *entry;
  interface_element *interf;
  operation_element *oeptr;
  instance_element *insteptr;

  /* break it apart, inserting a NUL char is OK because we're 
   * guarranteed at least one spare char, the @-sign */

  opname = tracer = yytext;
  while( isalnum(*tracer) || *tracer == '_' ) tracer++;
  *tracer = '\0';
  while( !isalnum(*tracer) && *tracer != '_' ) tracer++;
  inst = tracer;

  /* now find the interface for the instance, to get the instance info,
   * all we have to do is look it up in the symbol table */

  entry = Symbol_Table->lookup(inst,SMASK_C);
  
  /* Some error checking... */

  if (entry == NULL) {
    report_error("error 1",
		 "\"%s\" is not a declared instance.\n\tIllegal operation: %s@%s.", 
		 inst, opname, inst);
    linkptr = NULL;
    insteptr = NULL;
  }
  else {
     int reported = FALSE;

     switch(kind = entry->get_kind()) {
     case SYM_IDENT:
     case SYM_TYPEDEF:
     case SYM_INTER:
     case SYM_OP:
     case SYM_TYPE:
     case SYM_NAME:
       {
	 report_error("error 2",
		      "\"%s\" is a %s and can't be used as an\n\tinstance variable in \"%s@%s\".", 
		      inst,NameOfSymKind(kind),opname,inst);
	 reported = TRUE;
	 linkptr = NULL;
       }
       break;
     case SYM_UNKNOWN:
       {
	 BUG_CHECK("Bad symbol_table::lookup() result to lexIdAtSign()");
       }
     case SYM_INST:
       {
	 break;
       }
     }
     if (!reported && !instance_list_ptr->search(inst,linkptr)) {
	BUG_CHECK("Declared instance not on instance list"); 
	reported = TRUE;
	linkptr = NULL;
     }
     insteptr   = (instance_element*)linkptr;
     /* Error checks pass, get the instance's interface and lookup
      * the operation */

     if (!reported) {
	interf = entry->get_interf();
	if (interf) {
	   if (!interf->operations_ptr->search(opname,linkptr)) {
	     report_error("error 4",
			  "Operation \"%s\" not defined in Interface \"%s\".\n\tThis Interface is bound to instance \"%s\".",
			  opname, interf->get_name(), inst);
	     linkptr = NULL;
	   }
	}
	else {
	  BUG_CHECK("No Interface corresponding to the instance variable");
	}
     }
  }


  /* got it (finally!) set state, and tokenize as OPERATION_AT_INSTANCE,
   * which has the same yylval as OPERATION_NAME. A different token is
   * needed to remove the call_stmt / give_op_stmt conflict */

  oeptr   = (operation_element*)linkptr;
  yylval.oeptr_insteptr.oeptr = oeptr;
  yylval.oeptr_insteptr.insteptr = insteptr;
  return OPERATION_AT_INSTANCE;
}

int  lexInsideIspec( char *ident, interface_element *interf )

     /* Similar to lexKeyword(), this call looks up the identifier 
      * in the given i-spec, and makes some consistency checks, too. 
      * It returns the token for the identifier */
{
  int                 found;
  char               *iname;
  link               *linkptr;
  link               *saved_linkptr;
  SymKind             kind;
  operation_element  *oeptr;


  iname = interf->get_name();
  found = FALSE;
  kind  = SYM_UNKNOWN;

  /* search each table, if found, use a SymKind to indicate what it
   * is, and act on it after all checks are made. */

  if (interf->types_ptr) {
    if ((interf->types_ptr)->search(ident,linkptr)) {
      found         = TRUE;
      kind          = SYM_TYPE;
      saved_linkptr = linkptr;
    }
  }
  if (interf->names_ptr) {
    if ((interf->names_ptr)->search(ident,linkptr)) {
      if (found) {
	report_error("internal error",
		     "%s is both a type and a Name in Interface %s.", 
		     ident, iname);
	linkptr = NULL;
      }
      found         = TRUE;
      kind          = SYM_NAME;
      saved_linkptr = linkptr;
    }
  }
  if (interf->operations_ptr) {
    if ((interf->operations_ptr)->search(ident,linkptr)) {
      if (found) {
	report_error("internal error",
		     "%s is both an operation and a %s in Interface %s.", 
		     ident, kind==SYM_NAME?"name":"type", iname);
	linkptr = NULL;
      }
      found         = TRUE;
      kind          = SYM_OP;
      saved_linkptr = linkptr;
    }
  }
    
  /* All the checks pass, lex this ident */

  switch (kind) {
  case SYM_OP:
    {
      oeptr   = (operation_element*)saved_linkptr;
      yylval.operation_eptr = oeptr;
      return OPERATION_NAME;
    }
  case SYM_NAME:
    {
      yylval.name_eptr = (name_element*)saved_linkptr;
      return PARAMETER_NAME;
    }
  case SYM_TYPE:
    {
      type_element *tep;
      tep = yylval.teptr_bufoffset.teptr = (type_element*)saved_linkptr;
      ident = tep->abstr_type_ptr->get_typedef_name();
      prepare_expbuf(ident);
      yylval.teptr_bufoffset.bufoffset = last_bufoffset;
      strcpy(expbuf+last_bufoffset, ident);
      yylval.string_bufoffset_sym_ont.sym = SYM_TYPE;
      yylval.string_bufoffset_sym_ont.ont = (type_element*)saved_linkptr;
      return TYPE_ID;
    }
  case SYM_UNKNOWN:
    {
      /* it's OK not to find the symbol in the interface when it's first
       * being declared. It's grammatically an IDENTIFIER then. If this
       * routine is called from scope_resolve, however, and it gets 
       * IDENTIFER returned, it knows that the symbol was not found in the
       * specified interface */

      if (in_op_def_sect)
	 report_error("error 7",
		      "\"%s\" is not an ELROS type.",
		      yytext);
      yylval.string_bufoffset_sym_ont.sym = SYM_UNKNOWN;
      RET(IDENTIFIER);
    }
  case SYM_IDENT:
  case SYM_TYPEDEF:
  case SYM_INST:
  case SYM_INTER:
    {
      report_error("internal error",
		   "kind has impossible value: %d.",
		   (int) kind );
    }
  }
  BUG_CHECK("Can't get here.");
  return 0; /* keep lame compliers quiet */
}

int scope_resolve()

     /* All scope resolution is handled here, both forms (with an
      * interface name, and an empty interface name). The string passed
      * in contains everything needed */
{
  link *linkptr;

  int   token;
  char *tracer;
  char *iname;
  char *ident;
  char *string;

  interface_element *interf;


  string = yytext;

  /* scope resolution must not occur inside an Ispec */

  if (in_interface_spec) {
    report_error("error 8",
		 "Scope resolution not allowed inside an Interface\n\tspecification: %s.",
		 string);
  }

  /* if the first char of the string is ':', it's empty scope resolution,
   * if it's alphanumeric (or '_'), it's resolved to a particular 
   * interface. Otherwise, somethings wrong, and the lexer shouldn't
   * have called this routine - crash! */

  if (string[0] != ':' && string[0] != '_' && !isalnum(string[0])) {
    report_error("internal error",
		 "1st char in scope_resolve() isn't ':' or alphanumeric: '%c'.",
		 string[0]);
    exit(1);
  }

  if (string[0] == ':') {

    /* empty scope resolution - resolve to the C symbol by calling
     * identify with its second argument... */

    /* extract the identifier, and save it since we're going to call
     * identify, which assumes the usual make_string() call has been done
     * to the idents it receives (i.e. malloc and point to by yylval */

    tracer = string;
    while( !isalnum(*tracer) && *tracer != '_' ) tracer++;
    if ((ident = NewThings(char,strlen(tracer)+1)) == NULL) nomem();
    strcpy(ident,tracer);
    yylval.string = ident;

    return identify(ident,TRUE);
  }
  else {

    /* resolution to an interface, extract the two names from the
     * string (interface, identifer). We insert a '\0' char after
     * interface name (guarranteed at least 2 "spare" chars for the
     * doublecolon) and then find the start of the identifer, and
     * point to it. */

    iname = tracer = string;
    while( isalnum(*tracer) || *tracer == '_' ) tracer++;
    *tracer = '\0';
    while( !isalnum(*tracer) && *tracer != '_' ) tracer++;
    ident = tracer;

    /* Unfortunately, by lexing as {word}{white_sp}*\:\:{white_sp}*{word}
     * has the drawback that we mistakenly gobble a keyword if it
     * appears right in front of an empty-resolved ident as in:
     *
     *   if (...) { ... } else ::ident = 0;
     *
     * (Hopefully rare!) So, we need a keyword check first. Notice
     * that we're assuming ident :: ident can't be ambigous - two idents
     * surrounding a doublecolon must be scope resolution to an interface
     * and not empty resolution preceded by something else. If this 
     * assumption is false, we're in trouble, and have to rethink empty
     * resolution. */

    /* both lexKeyword and lexInsideIspec expect that the ident has
     * malloc'd and copied into the heap, so we need to do that (this is
     * just like calling make_string, but we can't use that call in this
     * case, cause the string has a '::' that we don;t want, and even a
     * second string...) */

    if ((tracer=NewThings(char,strlen(ident)+1)) == NULL) nomem();
    strcpy(tracer,ident);

    if ((token = lexKeyword(iname)) != NOT_A_KEY) {
      
      /* Since the first word was a keyword, we need to put the second
       * part back into the input stream, then return the keyword token */

      tracer = &ident[strlen(ident)];
      tracer--;
      while( tracer >= ident ) {
	unput(*(tracer--));
      }
      unput(':');
      unput(':');

      RETURNIT (token);
    }
    
    /* first word wasn't a key, we have a valid  ident::ident construct */

    if ( ! interface_list_ptr->search(iname,linkptr)) {
      report_error("error 9",
		   " \"%s\" in not a known Interface.\n\tCan't resolve: %s::%s.", 
		   iname, iname, ident);
      exit(1);   /* can't recover */
    }
    else {
      
      /* lookup the ident in the interface, and take the appropriate
       * actions */

      interf = (interface_element *) linkptr;
      token = lexInsideIspec( ident, interf );
      if (token == IDENTIFIER) {
	report_error("error 10",
		     "\"%s\" is scope-resolved to Interface \"%s\",\n\tbut it is neither a Name, type, nor operation there.", 
		     ident, iname);
        exit(1);   /* can't recover */
      }
      else {
	return token;
      }
    }
  }

  /* Added for g++ */
  return (0);
}

int  identify( char *ident, int Cresolve )

     /* This is the HEART OF THE LEXER. Practically every symbol in
      * the program goes through this routine. The second arg is 
      * hardly ever used and defaults to FALSE. It indicates that
      * a C usage is desired, do not return an Elros answer. */

{
  int      token;

  link               *linkptr;
  symbol_element     *entry;
  symbol_element     *symtmp;
  operation_element  *oeptr;
  interface_element  *interf;

  
  symtmp = NULL;

  /*------------------------------------------------------------------*/
  /*                                                                  */
  /*       STEP 1  -  If a symbol is a legimate keyword in the        */
  /*                  current context, we're done - it can't be       */
  /*                  anything else                                   */
  /*                                                                  */
  /*------------------------------------------------------------------*/

  token = lexKeyword(ident);
  if (token != NOT_A_KEY) 
    return token;

  /*------------------------------------------------------------------*/
  /*                                                                  */
  /*       STEP 2  -  In an interface, the only symbols allowed are   */
  /*                  those from the interface                        */
  /*                                                                  */
  /*------------------------------------------------------------------*/

  if (in_interface_spec) {
    if (!ieptr) {
      BUG_CHECK("ieptr is NULL while in_interface_spec is TRUE");
    }
    else {
      return lexInsideIspec(ident,ieptr);
    }
  }
  
  /*------------------------------------------------------------------*/
  /*                                                                  */
  /*       STEP 3  - have we alreay been told what to return ?        */
  /*                                                                  */
  /*------------------------------------------------------------------*/

  switch (IdentMode) {

  case MODE_IDENT:
    {
      IdentMode = MODE_LOOKUP;
      RET(IDENTIFIER);
    }
  case MODE_INSTANCE:
    {
      IdentMode = MODE_LOOKUP;
      entry = Symbol_Table->lookup(ident, 
				   (Cresolve ? SMASK_C : SMASK_INST));
      if (entry == NULL) {
	 report_error("error 11",
		      "\"%s\" is not a declared instance.", 
		      ident);
	 linkptr = NULL;
      }
      else {
	 if (entry->get_kind() == SYM_INST) {
	    if (!instance_list_ptr) {
	       report_error("internal error",
			    "no instances declared - can't find \"%s\".",
			    ident);
	       linkptr = NULL;
	    }
	    if (!instance_list_ptr->search(ident,linkptr)) {
	       report_error("internal error",
			    "\"%s\" is not a declared instance.",
			    ident);
	       linkptr = NULL;
	    }
	 }
      }
    }
    yylval.septr_bufoffset_lptr.lptr = linkptr;
    yylval.septr_bufoffset_lptr.septr = entry;
    prepare_expbuf(ident);
    yylval.septr_bufoffset_lptr.bufoffset = last_bufoffset;
    strcpy(expbuf+last_bufoffset, ident);
    return (INSTANCE_ID);
  case MODE_INTERFACE:
    {
      IdentMode = MODE_LOOKUP;
      if (interface_list_ptr->search(ident,linkptr)) {
	yylval.interface_eptr = (interface_element*)linkptr;
      }
      else {
	report_error("error 14",
		     "No such Interface: \"%s\".",
		     ident);
	yylval.interface_eptr = NULL;
      }
      return 0;
    }
  case MODE_ELROS_TYPE:
    {
      tree_link *tlptr;
      tree_link *tlptr2;
      int duplicate_type = FALSE;

      IdentMode = MODE_LOOKUP;
      if ((entry = Symbol_Table->lookup(ident,SMASK_TYPE)) == NULL) {
	report_error("error 15",
		     "No such type defined: \"%s\".",
		     ident);
	RET(SEMI);
      }

      /* For now, complain if there's multiple definitions, later,
       * we should only complain if there's multiple types */

      if ((tlptr = entry->get_tlptr()) != NULL) {
	if (((symbol_element*)tlptr)->get_kind() == SYM_TYPE)
	   duplicate_type = TRUE;
	for ( ; tlptr2 = tlptr->get_tlptr() ; tlptr = tlptr2) {
	   if (((symbol_element*)tlptr2)->get_kind() == SYM_TYPE)
	      duplicate_type = TRUE;
	}
	if (duplicate_type)
	   report_error("error 16",
			"\"%s\" needs scope resolution.",
			ident);
      }
      interf = entry->get_interf();
      if (interf) {
	if (interf->types_ptr) {
	  if ((interf->types_ptr)->search(ident,linkptr)) {
	    type_element *tep;
	    tep = yylval.teptr_bufoffset.teptr = (type_element*)linkptr;
	    ident = tep->abstr_type_ptr->get_typedef_name();
	    prepare_expbuf(ident);
	    yylval.teptr_bufoffset.bufoffset = last_bufoffset;
	    strcpy(expbuf+last_bufoffset, ident);
	    return TYPE_ID;
	  }
	  else {
	    report_error("internal error",
			 "Type \"%s\" is not in Interface \"%s\".",
			 ident, interf->get_name());
	    RET(SEMI);
	  }
	}
	else {
	  report_error("internal error",
		       "Interface \"%s\" has no types. \"%s\" not found.",
		       interf->get_name(), ident);
	  RET(SEMI);
	}
      }
      else {
	report_error("internal error",
		     "TYPE_ID \"%s\" has no Interface information.", 
		     ident);
	exit(1);
      }
    }

  /*------------------------------------------------------------------*/
  /*                                                                  */
  /*       STEP 4  - look it up in the symbol table                   */
  /*                                                                  */
  /*------------------------------------------------------------------*/

  case MODE_LOOKUP:

    entry = Symbol_Table->lookup(ident, (Cresolve ? SMASK_C : SMASK_ANY));
      
    if (entry == NULL) {

    /* If it's not in the symbol table, it can't be anything but an 
     * identifier. Likely this is either a function with no decl like
     * atoi() or exit(), or an enumeration constant, which aren't in the
     * symbol table. When error recovery time arrives, however, it will
     * probably be best to put everything encountered symbol into the
     * symbol table, so the parser recover/report errors well. */

      RET(IDENTIFIER);
    }
    else {
      switch (entry->get_kind()) {

      case SYM_IDENT:
	{
	  RET(IDENTIFIER);
	}
      case SYM_TYPEDEF:
	{
	  RETURNIT (TYPEDEF_NAME);
	}
      case SYM_INTER:
	{
	  /* at the moment, INTERFACE_NAME tokens are only returned
	   * inside control() and data() decls, and the way this happens
	   * is the IdentMode is set to MODE_INTERFACE to force such a
	   * tokenization. Scope resolution (see scope_resolve(), and the
	   * lex rules that call it) is done lexically, not grammatically
	   * and anywhere else (inside an Roprinti(), for instance) an
	   * interface name appears, it means the C global variable, and is
	   * lexed as IDENTIFER. So, IDENTIFER must be the correct token
	   * if we get to here, and likely we're inside an Roprinti(), or
	   * something similiar */

	  RET(IDENTIFIER);
	}
      case SYM_INST:
	{
	  if (!instance_list_ptr) {
	    report_error("internal error",
			 "No instances declared - can't find \"%s\".",
			 ident);
	    linkptr = NULL;
	  }
	  if (!instance_list_ptr->search(ident,linkptr)) {
	    report_error("internal error",
			 "\"%s\" is not a declared instance.",
			 ident);
	    linkptr = NULL;
	  }
	  yylval.septr_bufoffset_lptr.lptr = linkptr;
	  yylval.septr_bufoffset_lptr.septr = entry;
	  prepare_expbuf(ident);
	  yylval.septr_bufoffset_lptr.bufoffset = last_bufoffset;
	  strcpy(expbuf+last_bufoffset, ident);
	  return (INSTANCE_ID);
	}
      case SYM_TYPE:
	{
	  interf = entry->get_interf();
	  if (interf) {
	    if (interf->types_ptr) {
	      if ((interf->types_ptr)->search(ident,linkptr)) {
      type_element *tep;
		tep = yylval.teptr_bufoffset.teptr = (type_element*)linkptr;
		ident = tep->abstr_type_ptr->get_typedef_name();
	        prepare_expbuf(ident);
		yylval.teptr_bufoffset.bufoffset = last_bufoffset;
	        strcpy(expbuf+last_bufoffset, ident);
		return TYPE_ID;
	      }
	      else {
		report_error("internal error",
			     "Type \"%s\" not in Interface \"%s\".", 
			     ident, interf->get_name());
		RET(SEMI);
	      }
	    }
	    else {
	      report_error("internal error",
			   "Interface \"%s\" has no types. \"%s\" not found.", 
			   interf->get_name(), ident);
	      RET(SEMI);
	    }
	  }
	  else {
	    report_error("internal error",
			 "TYPE_ID \"%s\" has no Interface information.", 
			 ident);
	    exit(1);
	  }
	}
      case SYM_OP:
	{
	  oeptr   = (operation_element*)entry;
	  yylval.operation_eptr = oeptr;
	  return OPERATION_NAME;
	}
      case SYM_NAME:
	{
	  yylval.name_eptr = (name_element*)entry;
	  return PARAMETER_NAME;
	}
      case SYM_UNKNOWN:
	{
	  BUG_CHECK("found SYM_UNKNOWN in identify()");
	}
      }
    }
  default:
    report_error("internal error",
		 "Bad IdentMode: %d.",
		 IdentMode);
    exit(1);
  }
  BUG_CHECK("fell through the bottom of identify()");
  return(0); /* keep compilers happy */
}

void prepare_expbuf(char* arg)
{									
   int newlen;							
   newlen = strlen(arg)+1+EXTRA_CHARS;			
   if (expbuf) {
      last_bufoffset = strlen(expbuf);		
      if ((last_bufoffset+newlen) > max_bufsize) {
	 max_bufsize += ((max_bufsize > (last_bufoffset+newlen))
			 ? max_bufsize
			 : (last_bufoffset+newlen)); 
	 if ((expbuf = (char*)realloc(expbuf,max_bufsize)) == NULL) nomem();		      }
   }
   else {
      last_bufoffset = 0;		
      if ((expbuf = (char*)malloc(INIT_EXPBUF_SIZE)) == NULL) nomem();
      max_bufsize = INIT_EXPBUF_SIZE;  
   }
}

