//ArithmeticLL import gi.*; class ArithmeticLL extends LL1_Grammar { ArithmeticLL() throws Exception { put("LITERAL", expression("[[:digit:]]+")); put("SPACE", expression("[[:space:]]+")); // /*\semantics*/semantic specification/*\off*/ //ArithmeticLL.S /*\semantics*/ Semantics print = new Semantics() { public void f(ParseTree t, int l) { System.out.println(t.child[l-1].value); } }; /*\off*/ put("S", new Object[][] { {"E"/*\semantics*/, print/*\off*/} }); //ArithmeticLL.E /*\semantics*/ Semantics zero = new Semantics() { public void f(ParseTree t, int l) { t.value = new Integer(0); } }; Semantics add = new Semantics() { public void f(ParseTree t, int l) { int left = ((Integer)t.child[l-2].value).intValue(); int right = ((Integer)t.child[l-1].value).intValue(); t.value = new Integer(left + right); } }; /*\off*/ put("E", new Object[][] { {"T", "E'"/*\semantics*/, add/*\off*/} }); put("E'", new Object[][] { {/*\semantics*/zero/*\off*/}, {"+", "T", "E'"/*\semantics*/, add/*\off*/}, }); //ArithmeticLL.T /*\semantics*/ Semantics one = new Semantics() { public void f(ParseTree t, int l) { t.value = new Integer(1); } }; Semantics multiply = new Semantics() { public void f(ParseTree t, int l) { int left = ((Integer)t.child[l-2].value).intValue(); int right = ((Integer)t.child[l-1].value).intValue(); t.value = new Integer(left * right); } }; /*\off*/ put("T", new Object[][] { {"F", "T'"/*\semantics*/, multiply/*\off*/} }); put("T'", new Object[][] { {/*\semantics*/one/*\off*/}, {"*", "F", "T'"/*\semantics*/, multiply/*\off*/}, }); //ArithmeticLL.F /*\semantics*/ Semantics decode = new Semantics() { public void f(ParseTree t, int l) { t.value = Integer.decode((String)t.child[l-1].value); } }; Semantics identity = new Semantics() { public void f(ParseTree t, int l) { t.value = t.child[l-1].value; } }; /*\off*/ put("F", new Object[][] { {"LITERAL"/*\semantics*/, decode/*\off*/}, {"(", "E", /*\semantics*/identity, /*\off*/")"}, }); //ArithmeticLL debug = PARSE_TREE; } public static void main(String[] arguments) throws Exception { new ArithmeticLL().interpret(arguments); } }