1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 2 * Copyright (C) 2001 Gerwin Klein <lsf@jflex.de> * 3 * All rights reserved. * 4 * * 5 * This is a modified version of the example from * 6 * http://www.lincom-asg.com/~rjamison/byacc/ * 7 * * 8 * Thanks to Larry Bell and Bob Jamison for suggestions and comments. * 9 * * 10 * License: BSD * 11 * * 12 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 13 14 %{ 15 import java.io.*; 16 %} 17 18 %token NL /* newline */ 19 %token <dval> NUM /* a number */ 20 21 %type <dval> exp 22 23 %left '-' '+' 24 %left '*' '/' 25 %left NEG /* negation--unary minus */ 26 %right '^' /* exponentiation */ 27 28 %% 29 30 input: /* empty string */ 31 | input line 32 ; 33 34 line: NL { if (interactive) System.out.print("Expression: "); } 35 | exp NL { System.out.println(" = " + $1); 36 if (interactive) System.out.print("Expression: "); } 37 ; 38 39 exp: NUM { $$ = $1; } 40 | exp '+' exp { $$ = $1 + $3; } 41 | exp '-' exp { $$ = $1 - $3; } 42 | exp '*' exp { $$ = $1 * $3; } 43 | exp '/' exp { $$ = $1 / $3; } 44 | '-' exp %prec NEG { $$ = -$2; } 45 | exp '^' exp { $$ = Math.pow($1, $3); } 46 | '(' exp ')' { $$ = $2; } 47 ; 48 49 %% 50 51 private Yylex lexer; 52 53 yylex()54 private int yylex () { 55 int yyl_return = -1; 56 try { 57 yylval = new ParserVal(0); 58 yyl_return = lexer.yylex(); 59 } 60 catch (IOException e) { 61 System.err.println("IO error :"+e); 62 } 63 return yyl_return; 64 } 65 66 yyerror(String error)67 public void yyerror (String error) { 68 System.err.println ("Error: " + error); 69 } 70 71 Parser(Reader r)72 public Parser(Reader r) { 73 lexer = new Yylex(r, this); 74 } 75 76 77 static boolean interactive; 78 main(String args[])79 public static void main(String args[]) throws IOException { 80 System.out.println("BYACC/Java with JFlex Calculator Demo"); 81 82 Parser yyparser; 83 if ( args.length > 0 ) { 84 // parse a file 85 yyparser = new Parser(new FileReader(args[0])); 86 } 87 else { 88 // interactive mode 89 System.out.println("[Quit with CTRL-D]"); 90 System.out.print("Expression: "); 91 interactive = true; 92 yyparser = new Parser(new InputStreamReader(System.in)); 93 } 94 95 yyparser.yyparse(); 96 97 if (interactive) { 98 System.out.println(); 99 System.out.println("Have a nice day"); 100 } 101 } 102