/** * オプションの指定 */ //options { // LOOKAHEAD = 1; // 先読みトークン数 // STATIC = false; // true にするとスタティックメソッドを生成 // UNICODE_INPUT = true; // true にすると Unicode 入力を扱う // DEBUG_PARSER = false; // true にするとデバグ情報出力 //} // /** * 作成する構文解析クラスの定義 * PARSER_BEGIN (クラス名) * と * PARSER_END (クラス名) * の間に作成するクラスの main メソッドを記述する。 */ PARSER_BEGIN (Calc) package calc; import java.io.*; /** * Macro statements are as follows : * ::= { "=" } * ::= { ( "+" ) | ( "-" ) } * ::= { ( "*" ) | ( "/" ) | ( "%" ) } * ::= ( "(" ")" ) | INTEGER * Execute as follows : * $ javac Calc.java * $ java Calc [inputfile] */ public class Calc { public static void main (String args[]) { Calc parser; try { if (args.length == 0) { parser = new Calc (System.in); } else { parser = new Calc (new FileReader (args[0])); } parser.enable_tracing(); parser.List(); } catch (Exception err_mes) { System.err.println (err_mes); } } } PARSER_END (Calc) /** * 空白文字の定義 * 空白文字は * SKIP : * { * <パターン> * } * の形で定義され、パターンには正規表現を用いることができる。 */ SKIP : { < " " | "\t" | "\n" | "\r" > } /** * トークンの定義 * トークンは * TOKEN : * { * <トークン名: パターン> * } * の形で定義され、パターンには正規表現を用いることができる。 */ TOKEN : { } /** * ::= { "=" } * void parseList() { * int value; * while (true) { * value = parseE(); * if (token == "=") * System.out.println (value); * } * } */ void List() : { int value; } { ( value = E() "=" { System.out.println (value); } )* } /** * ::= { ( "+" ) | ( "-" ) } * void parseE() { * int result1, result2; * result1 = parseT(); * while (token == "+" || token == "-") { * if (token == "+") { * result2 = parseT(); * result1 += result2; * } else if (token == "-") { * result2 = parseT(); * result1 -= result2; * } * return result1; * } */ int E() : { int result1, result2; } { result1 = T() ( "+" result2 = T() { result1 += result2; } | "-" result2 = T() { result1 -= result2; } )* { return result1; } } /** * ::= { ( "*" ) | ( "/" ) | ( "%" )} * void parseT() { * int result1, result2; * result1 = parseF(); * while (token == "*" || token == "/" || token == "%") { * if (token == "*") { * result2 = parseF(); * result1 *= result2; * } else if (token == "/") { * result2 = parseF(); * result1 /= result2; * } else if (token == "%") { * result2 = parseF(); * result1 %= result2; * } * return result1; * } */ int T() : { int result1, result2; } { result1 = F() ( "*" result2 = F() { result1 *= result2; } | "/" result2 = F() { result1 /= result2; } | "%" result2 = F() { result1 %= result2; } )* { return result1; } } /** * ::= ( "(" ")" ) | INTEGER * void parseF() { * int result; * if (token == "(") { * nextToken(); * result = parseE(); * if (token == ")") nextToken(); * return result; * } else if (token == INTEGER) { * return token.getValue(); * } * } */ int F(): { int result; } { "(" result = E() ")" { return result; } | token = { return Integer.parseInt (token.image); } }