1 import antlr3 2 import testbase 3 import unittest 4 5 6 class T(testbase.ANTLRTest): 7 def setUp(self): 8 self.compileGrammar(options='-trace') 9 10 11 def lexerClass(self, base): 12 class TLexer(base): 13 def __init__(self, *args, **kwargs): 14 base.__init__(self, *args, **kwargs) 15 16 self.traces = [] 17 18 19 def traceIn(self, ruleName, ruleIndex): 20 self.traces.append('>'+ruleName) 21 22 23 def traceOut(self, ruleName, ruleIndex): 24 self.traces.append('<'+ruleName) 25 26 27 def recover(self, input, re): 28 # no error recovery yet, just crash! 29 raise 30 31 return TLexer 32 33 34 def parserClass(self, base): 35 class TParser(base): 36 def __init__(self, *args, **kwargs): 37 base.__init__(self, *args, **kwargs) 38 39 self.traces = [] 40 41 42 def traceIn(self, ruleName, ruleIndex): 43 self.traces.append('>'+ruleName) 44 45 46 def traceOut(self, ruleName, ruleIndex): 47 self.traces.append('<'+ruleName) 48 49 50 def recover(self, input, re): 51 # no error recovery yet, just crash! 52 raise 53 54 def getRuleInvocationStack(self): 55 return self._getRuleInvocationStack(base.__module__) 56 57 return TParser 58 59 60 def testTrace(self): 61 cStream = antlr3.StringStream('< 1 + 2 + 3 >') 62 lexer = self.getLexer(cStream) 63 tStream = antlr3.CommonTokenStream(lexer) 64 parser = self.getParser(tStream) 65 parser.a() 66 67 self.failUnlessEqual( 68 lexer.traces, 69 [ '>T__7', '<T__7', '>WS', '<WS', '>INT', '<INT', '>WS', '<WS', 70 '>T__6', '<T__6', '>WS', '<WS', '>INT', '<INT', '>WS', '<WS', 71 '>T__6', '<T__6', '>WS', '<WS', '>INT', '<INT', '>WS', '<WS', 72 '>T__8', '<T__8'] 73 ) 74 75 self.failUnlessEqual( 76 parser.traces, 77 [ '>a', '>synpred1_t044trace_fragment', '<synpred1_t044trace_fragment', '>b', '>c', 78 '<c', '>c', '<c', '>c', '<c', '<b', '<a' ] 79 ) 80 81 82 def testInvokationStack(self): 83 cStream = antlr3.StringStream('< 1 + 2 + 3 >') 84 lexer = self.getLexer(cStream) 85 tStream = antlr3.CommonTokenStream(lexer) 86 parser = self.getParser(tStream) 87 parser.a() 88 89 self.failUnlessEqual( 90 parser._stack, 91 ['a', 'b', 'c'] 92 ) 93 94 if __name__ == '__main__': 95 unittest.main() 96