/* JParser.y */ %import java.io.*; %import java.util.*; %{ InputStream in; int lineno; int lastchar = -1; public JParserTab(InputStream in) { lineno = 1; lastchar = -1; this.in = in; } %} %token IDENTIFIER %token NUMBER %type expr %right '=' %left '+' '-' %left '*' '/' '%' %right UMINUS %start stmt_list %% stmt_list : /* empty */ | stmt_list stmt ; stmt : expr ';' { System.out.println($1.intValue()) } | IDENTIFIER '=' expr ';' { setsym($1, $3) } ; expr : expr '+' expr { $$ = new Integer($1.intValue() + $3.intValue()) } | expr '-' expr { $$ = new Integer($1.intValue() - $3.intValue()) } | expr '*' expr { $$ = new Integer($1.intValue() * $3.intValue()) } | expr '/' expr { $$ = new Integer($1.intValue() / $3.intValue()) } | expr '%' expr { $$ = new Integer($1.intValue() % $3.intValue()) } | '-' expr %prec UMINUS { $$ = new Integer(-$2.intValue()) } | '(' expr ')' { $$ = $2 } | IDENTIFIER { $$ = getsym($1) } | NUMBER { $$ = $1 } ; %% Hashtable symtab = new Hashtable(); void setsym(String s, Integer val) { symtab.put(s, val); } Integer getsym(String s) { Integer i; if((i = (Integer)symtab.get(s)) == null) i = new Integer(0); return i; } void yyerror(String msg) { System.err.println("line: " + lineno + ": " + msg); } int getc() { int c; if(lastchar != -1) { c = lastchar; lastchar = -1; } else { try { c = in.read(); } catch(Exception e) { c = -1; } } if(c == '\n') lineno++; return c; } void ungetc(int c) { lastchar = c; if(c == '\n') lineno--; } void skip_line() { int c; do c = getc(); while(c != '\n' && c != -1); } void skip_comment() { boolean star; int c; star = false; while((c = getc()) != -1) { if(c == '*') star = true; else if(star && c == '/') break; else star = false; } } int yylex() { int c, c2, i; String token; do { if((c = getc()) == -1) return -1; } while(c == ' ' || c == '\r' || c == '\n' || c == '\t'); if("=+-*%();".indexOf(c) != -1) return c; if(c == '/') { // possible comment start c2 = getc(); if(c2 == '/') { skip_line(); return yylex(); } if(c2 == '*') { skip_comment(); return yylex(); } ungetc(c2); return '/'; } token = ""; if('A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '_') { while('A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '_') { token += (char)c; c = getc(); } ungetc(c); yylval = token; return IDENTIFIER; } i = 0; if('0' <= c && c <= '9') { while('0' <= c && c <= '9') { i = i * 10 + c - '0'; c = getc(); } ungetc(c); yylval = new Integer(i); return NUMBER; } System.err.println("Unexpected char: " + c); return -1; } public static void main(String args[]) { JParserTab parser; parser = new JParserTab(System.in); parser.yyparse(); }