xcc.l


    1 %{
    2 #include "xcc.h"
    3 #include "xcc.tab.h"
    4 #include "AST.h"
    5 
    6 static void string_init(void);
    7 static void string_add_char(char c);
    8 int yyerror(char *mesg);
    9 
   10 enum { MAX_STRING_LEN = 1024 };
   11 char string_buf[MAX_STRING_LEN];
   12 static int string_index;
   13 int line_index = 1;
   14 %}
   15 
   16 ID	[a-zA-Z_]([a-zA-Z_]|[0-9])*
   17 NUMBER	0|[1-9][0-9]*
   18 CHAR	'.'|'\n'
   19 
   20 %x string comment
   21 
   22 %%
   23 [ \t]		;
   24 "\n"		line_index++;
   25 
   26 "+"		return '+';
   27 "-"		return '-';
   28 "*"		return '*';
   29 "/"		return '/';
   30 "%"		return '%';
   31 "("		return '(';
   32 ")"		return ')';
   33 "="		return '=';
   34 "<"		return '<';
   35 ">"		return '>';
   36 "&"		return '&';
   37 "!"		return '!';
   38 ","		return ',';
   39 ";"		return ';';
   40 ":"		return ':';
   41 "{"		return '{';
   42 "}"		return '}';
   43 
   44 "=="		return EQ;
   45 "!="		return NEQ;
   46 "<="		return LEQ;
   47 ">="		return GEQ;
   48 "&&"		return AND;
   49 "||"		return OR;
   50 
   51 "char"		return CHAR;
   52 "else"		return ELSE;
   53 "goto"		return GOTO;
   54 "if"		return IF;
   55 "int"		return INT;
   56 "return"	return RETURN;
   57 "void"		return VOID;
   58 "while"		return WHILE;
   59 
   60 {ID}		{ yylval = create_AST(AST_IDENTIFIER, 1, yytext);
   61 		  return IDENTIFIER; }
   62 {NUMBER}	return INTEGER;
   63 {CHAR}		return CHARACTER;
   64 \"		{ BEGIN(string);
   65 		  string_init(); }
   66 <string>\n	yyerror("unterminated string");
   67 <string><<EOF>>	yyerror("EOF in string");
   68 <string>[^\"]	string_add_char(yytext[0]);
   69 <string>\"	{ BEGIN(INITIAL);
   70 		  string_add_char ('\0');
   71 		  return STRING; }
   72 "/*"			BEGIN(comment);
   73 <comment>[^*\n]*	;
   74 <comment>[^*\n]*\n	;
   75 <comment>"*"+[^*/\n]*	;
   76 <comment>"*"+[^*/\n]*\n	;
   77 <comment><<EOF>>	yyerror("EOF in comment");
   78 <comment>"*"+"/"	BEGIN(INITIAL);
   79 
   80 %%
   81 static void string_init(void) {
   82 	string_index = 0;
   83 }
   84 
   85 static void string_add_char(char c) {
   86 	if (string_index >= MAX_STRING_LEN)
   87 		yyerror("max string length exceeded");
   88 	string_buf[string_index++] = c;
   89 }
   90 
   91 #if DEBUG
   92 int yyerror(char *mesg) {
   93 	fprintf(stderr, "error: %s\n", mesg);
   94 	exit (1);
   95 }
   96 
   97 int main(void) {
   98 	int token;
   99 
  100 	while (token = yylex()) {
  101 		printf("token = %d, lexeme = %s\n", token, yytext);
  102 		if (token = STRING)
  103 			printf("\tstring = %s\n", string_buf);
  104 	}
  105 }
  106 #endif