• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import antlr3
2import testbase
3import unittest
4
5class t010lexer(testbase.ANTLRTest):
6    def setUp(self):
7        self.compileGrammar()
8
9
10    def lexerClass(self, base):
11        class TLexer(base):
12            def emitErrorMessage(self, msg):
13                # report errors to /dev/null
14                pass
15
16            def reportError(self, re):
17                # no error recovery yet, just crash!
18                raise re
19
20        return TLexer
21
22
23    def testValid(self):
24        stream = antlr3.StringStream('foobar _Ab98 \n A12sdf')
25        lexer = self.getLexer(stream)
26
27        token = lexer.nextToken()
28        self.assertEqual(token.type, self.lexerModule.IDENTIFIER)
29        self.assertEqual(token.start, 0)
30        self.assertEqual(token.stop, 5)
31        self.assertEqual(token.text, 'foobar')
32
33        token = lexer.nextToken()
34        self.assertEqual(token.type, self.lexerModule.WS)
35        self.assertEqual(token.start, 6)
36        self.assertEqual(token.stop, 6)
37        self.assertEqual(token.text, ' ')
38
39        token = lexer.nextToken()
40        self.assertEqual(token.type, self.lexerModule.IDENTIFIER)
41        self.assertEqual(token.start, 7)
42        self.assertEqual(token.stop, 11)
43        self.assertEqual(token.text, '_Ab98')
44
45        token = lexer.nextToken()
46        self.assertEqual(token.type, self.lexerModule.WS)
47        self.assertEqual(token.start, 12)
48        self.assertEqual(token.stop, 14)
49        self.assertEqual(token.text, ' \n ')
50
51        token = lexer.nextToken()
52        self.assertEqual(token.type, self.lexerModule.IDENTIFIER)
53        self.assertEqual(token.start, 15)
54        self.assertEqual(token.stop, 20)
55        self.assertEqual(token.text, 'A12sdf')
56
57        token = lexer.nextToken()
58        self.assertEqual(token.type, self.lexerModule.EOF)
59
60
61    def testMalformedInput(self):
62        stream = antlr3.StringStream('a-b')
63        lexer = self.getLexer(stream)
64
65        lexer.nextToken()
66        try:
67            token = lexer.nextToken()
68            self.fail(token)
69
70        except antlr3.NoViableAltException as exc:
71            self.assertEqual(exc.unexpectedType, '-')
72            self.assertEqual(exc.charPositionInLine, 1)
73            self.assertEqual(exc.line, 1)
74
75
76
77if __name__ == '__main__':
78    unittest.main()
79