// Lexical analyser for online calculator. // Things to point out: yytext() returns token string // yychar represents location in terms of char of input // yylength() is length of token. // if %line directive is given, yyline variable contains the // current line number // To process file: // $ java -cp /shared/csc/local JLex.Main calculator.lex // $ javac calculator.lex.java // where -cp specifies the directory in which JLex is installed. /* **************** */ // User-defined classes goes before the first "%%" below %% %{ // Define utility functions here. private void err(int pos, String s) { System.out.println("\nError at position " + pos + ": " + s); } %} %function next_token %type String %char %line %ignorecase %eofval{ {return "EOF"; } %eofval} ALPHA=[A-Za-z] DIGIT=[0-9] DIGITS=[0-9]+ NONNEWLINE_WHITE_SPACE=[\ \t\b\012] WHITE_SPACE=[\n\ \t\b\012] STRING_TEXT=(\\\"|[^\n\"]|\\{WHITE_SPACE}+\\)* COMMENT_TEXT=([^/*\n]|[^*\n]"/"[^*\n]|[^/\n]"*"[^/\n]|"*"[^/\n]|"/"[^*\n])* ALPHANUM=[A-Za-z][A-Za-z0-9_]* %% "\10" { return "EOF"; } {NONNEWLINE_WHITE_SPACE}+ { /* do nothing */ } {DIGITS} {return "unsigned integer: "+yytext();} [0-9]*\.[0-9]+ {return "double: "+yytext(); } -{DIGITS} {return "integer: "+yytext();} -[0-9]*\.[0-9]+ {return "double: "+yytext(); } "+" {return "plus";} "*" {return "times";} "-" {return "minus";} "/" {return "divide";} "(" {return "(";} ")" {return ")";} "=" {return "= at "+yychar;} "." {return "EOF";} . { System.out.println("\nError at char "+yychar+" line "+yyline); return "EOF"; }