|
1 #!/usr/bin/env python |
|
2 # |
|
3 # Copyright 2007 Google Inc. |
|
4 # |
|
5 # Licensed under the Apache License, Version 2.0 (the "License"); |
|
6 # you may not use this file except in compliance with the License. |
|
7 # You may obtain a copy of the License at |
|
8 # |
|
9 # http://www.apache.org/licenses/LICENSE-2.0 |
|
10 # |
|
11 # Unless required by applicable law or agreed to in writing, software |
|
12 # distributed under the License is distributed on an "AS IS" BASIS, |
|
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
14 # See the License for the specific language governing permissions and |
|
15 # limitations under the License. |
|
16 # |
|
17 |
|
18 |
|
19 """A wrapper around the generated Groc parser and lexer.""" |
|
20 |
|
21 |
|
22 import google |
|
23 |
|
24 import antlr3 |
|
25 |
|
26 import GrocLexer |
|
27 import GrocParser |
|
28 |
|
29 |
|
30 class GrocException(Exception): |
|
31 """An error occurred while parsing the groc input string.""" |
|
32 |
|
33 |
|
34 class GrocLexerWithErrors(GrocLexer.GrocLexer): |
|
35 """An overridden Lexer that raises exceptions.""" |
|
36 |
|
37 def emitErrorMessage(self, msg): |
|
38 """Raise an exception if the input fails to parse correctly. |
|
39 |
|
40 Overriding the default, which normally just prints a message to |
|
41 stderr. |
|
42 |
|
43 Arguments: |
|
44 msg: the error message |
|
45 Raises: |
|
46 GrocException: always. |
|
47 """ |
|
48 raise GrocException(msg) |
|
49 |
|
50 |
|
51 class GrocParserWithErrors(GrocParser.GrocParser): |
|
52 """An overridden Parser that raises exceptions.""" |
|
53 |
|
54 def emitErrorMessage(self, msg): |
|
55 """Raise an exception if the input fails to parse correctly. |
|
56 |
|
57 Overriding the default, which normally just prints a message to |
|
58 stderr. |
|
59 |
|
60 Arguments: |
|
61 msg: the error message |
|
62 Raises: |
|
63 GrocException: always. |
|
64 """ |
|
65 raise GrocException(msg) |
|
66 |
|
67 |
|
68 def CreateParser(parse_string): |
|
69 """Creates a Groc Parser.""" |
|
70 input_string = antlr3.ANTLRStringStream(parse_string) |
|
71 lexer = GrocLexerWithErrors(input_string) |
|
72 tokens = antlr3.CommonTokenStream(lexer) |
|
73 parser = GrocParserWithErrors(tokens) |
|
74 return parser |