// 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); } private java_cup.runtime.Symbol tok(int k, Object val) { return new java_cup.runtime.Symbol(k, yychar, yychar+yylength(), val); } %} %function next_token %type java_cup.runtime.Symbol %char %line %ignorecase %eofval{ {return tok(sym.EOF,null); } %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_]* %% {NONNEWLINE_WHITE_SPACE}+ { /* do nothing */ } \n { return tok(sym.EOF,null); } [0-9]*\.[0-9]+ {return tok(sym.NUM,new Double(yytext())); } {DIGITS} {return tok(sym.NUM,new Double(yytext())); } "+" {return tok(sym.PLUS,null); } "*" {return tok(sym.TIMES,null);} "-" {return tok(sym.MINUS,null); } "/" {return tok(sym.DIVIDE,null); } "(" {return tok(sym.LPAREN,null); } ")" {return tok(sym.RPAREN,null); } "[" {return tok(sym.LBRACK,null); } "]" {return tok(sym.RBRACK,null); } "=" {return tok(sym.EQUALS,null); } "," {return tok(sym.COMMA,null); } "sum" {return tok(sym.SUM,null); } [a-zA-Z]([a-zA-Z0-9_]*) { return tok(sym.ID, yytext()); } "." {return tok(sym.EOF,null); } . { System.out.println("\nError at char "+yychar+" line "+yyline); return tok(sym.EOF,null); }