Debian Codegraph @

src/yapps3/yapps_grammar.py

raw symbols SCIP
1 #!/usr/bin/python2
2 #
3 # grammar.py, part of Yapps 2 - yet another python parser system
4 # Copyright 1999-2003 by Amit J. Patel <[email protected]>
5 #
6 # This version of the Yapps 2 grammar can be distributed under the
7 # terms of the MIT open source license, either found in the LICENSE
8 # file included with the Yapps distribution
9 # <http://theory.stanford.edu/~amitp/yapps/> or at
10 # <http://www.opensource.org/licenses/mit-license.php>
11 #
12
13 """Parser for Yapps grammars.
14
15 This file defines the grammar of Yapps grammars. Naturally, it is
16 implemented in Yapps. The grammar.py module needed by Yapps is built
17 by running Yapps on yapps_grammar.g. (Holy circularity, Batman!)
18
19 """
20
21 import sys, re
22 import parsetree
23
24 ######################################################################
25 def cleanup_choice(rule, lst):
26 if len(lst) == 0: return Sequence(rule, [])
27 if len(lst) == 1: return lst[0]
28 return parsetree.Choice(rule, *tuple(lst))
29
30 def cleanup_sequence(rule, lst):
31 if len(lst) == 1: return lst[0]
32 return parsetree.Sequence(rule, *tuple(lst))
33
34 def resolve_name(rule, tokens, id, args):
35 if id in [x[0] for x in tokens]:
36 # It's a token
37 if args:
38 print('Warning: ignoring parameters on TOKEN %s<<%s>>' % (id, args))
39 return parsetree.Terminal(rule, id)
40 else:
41 # It's a name, so assume it's a nonterminal
42 return parsetree.NonTerminal(rule, id, args)
43
44
45 # Begin -- grammar generated by Yapps
46 import sys, re
47 import yapps3_compiled_rt as yappsrt
48
49 class ParserDescriptionScanner(yappsrt.Scanner):
50 patterns = [
51 ('"rule"', re.compile('rule')),
52 ('"ignore"', re.compile('ignore')),
53 ('"token"', re.compile('token')),
54 ('"option"', re.compile('option')),
55 ('":"', re.compile(':')),
56 ('"parser"', re.compile('parser')),
57 ('[ \t\r\n]+', re.compile('[ \t\r\n]+')),
58 ('#.*?\r?\n', re.compile('#.*?\r?\n')),
59 ('EOF', re.compile('$')),
60 ('ATTR', re.compile('<<.+?>>')),
61 ('STMT', re.compile('{{.+?}}')),
62 ('STR', re.compile('[uUrR]?\'([^\\n\'\\\\]|\\\\.)*\'|[uUrR]?"([^\\n"\\\\]|\\\\.)*"')),
63 ('ID', re.compile('[a-zA-Z_][a-zA-Z_0-9]*')),
64 ('LP', re.compile('\\(')),
65 ('RP', re.compile('\\)')),
66 ('LB', re.compile('\\[')),
67 ('RB', re.compile('\\]')),
68 ('OR', re.compile('[|]')),
69 ('STAR', re.compile('[*]')),
70 ('PLUS', re.compile('[+]')),
71 ('QUEST', re.compile('[?]')),
72 ('COLON', re.compile(':')),
73 ]
74 def __init__(self, str):
75 yappsrt.Scanner.__init__(self,None,['[ \t\r\n]+', '#.*?\r?\n'],str)
76
77 class ParserDescription(yappsrt.Parser):
78 Context = yappsrt.Context
79 def LINENO(self, _parent=None):
80 _context = self.Context(_parent, self._scanner, self._pos, 'LINENO', [])
81 return 1 + self._scanner.get_input_scanned().count('\n')
82
83 def Parser(self, _parent=None):
84 _context = self.Context(_parent, self._scanner, self._pos, 'Parser', [])
85 self._scan('"parser"')
86 ID = self._scan('ID')
87 self._scan('":"')
88 Options = self.Options(_context)
89 Tokens = self.Tokens(_context)
90 Rules = self.Rules(Tokens, _context)
91 EOF = self._scan('EOF')
92 return parsetree.Generator(ID,Options,Tokens,Rules)
93
94 def Options(self, _parent=None):
95 _context = self.Context(_parent, self._scanner, self._pos, 'Options', [])
96 opt = {}
97 while self._peek() == '"option"':
98 self._scan('"option"')
99 self._scan('":"')
100 Str = self.Str(_context)
101 opt[Str] = 1
102 if self._peek() not in ['"option"', '"token"', '"ignore"', 'EOF', '"rule"']:
103 raise yappsrt.YappsSyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['"option"', '"token"', '"ignore"', 'EOF', '"rule"']))
104 return opt
105
106 def Tokens(self, _parent=None):
107 _context = self.Context(_parent, self._scanner, self._pos, 'Tokens', [])
108 tok = []
109 while self._peek() in ['"token"', '"ignore"']:
110 _token = self._peek()
111 if _token == '"token"':
112 self._scan('"token"')
113 ID = self._scan('ID')
114 self._scan('":"')
115 Str = self.Str(_context)
116 tok.append( (ID,Str) )
117 elif _token == '"ignore"':
118 self._scan('"ignore"')
119 self._scan('":"')
120 Str = self.Str(_context)
121 tok.append( ('#ignore',Str) )
122 else:
123 raise yappsrt.YappsSyntaxError(_token[0], 'Could not match Tokens')
124 if self._peek() not in ['"token"', '"ignore"', 'EOF', '"rule"']:
125 raise yappsrt.YappsSyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['"token"', '"ignore"', 'EOF', '"rule"']))
126 return tok
127
128 def Rules(self, tokens, _parent=None):
129 _context = self.Context(_parent, self._scanner, self._pos, 'Rules', [tokens])
130 rul = []
131 while self._peek() == '"rule"':
132 LINENO = self.LINENO(_context)
133 self._scan('"rule"')
134 ID = self._scan('ID')
135 OptParam = self.OptParam(_context)
136 self._scan('":"')
137 ClauseA = self.ClauseA(ID, tokens, _context)
138 rul.append( (ID, OptParam, ClauseA) )
139 if self._peek() not in ['"rule"', 'EOF']:
140 raise yappsrt.YappsSyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['"rule"', 'EOF']))
141 return rul
142
143 def ClauseA(self, rule, tokens, _parent=None):
144 _context = self.Context(_parent, self._scanner, self._pos, 'ClauseA', [rule, tokens])
145 ClauseB = self.ClauseB(rule, tokens, _context)
146 v = [ClauseB]
147 while self._peek() == 'OR':
148 OR = self._scan('OR')
149 ClauseB = self.ClauseB(rule, tokens, _context)
150 v.append(ClauseB)
151 if self._peek() not in ['OR', 'RP', 'RB', '"rule"', 'EOF']:
152 raise yappsrt.YappsSyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['OR', 'RP', 'RB', '"rule"', 'EOF']))
153 return cleanup_choice(rule, v)
154
155 def ClauseB(self, rule, tokens, _parent=None):
156 _context = self.Context(_parent, self._scanner, self._pos, 'ClauseB', [rule, tokens])
157 v = []
158 while self._peek() in ['STR', 'ID', 'LP', 'LB', 'STMT']:
159 ClauseC = self.ClauseC(rule, tokens, _context)
160 v.append(ClauseC)
161 if self._peek() not in ['STR', 'ID', 'LP', 'LB', 'STMT', 'OR', 'RP', 'RB', '"rule"', 'EOF']:
162 raise yappsrt.YappsSyntaxError(charpos=self._scanner.get_prev_char_pos(), context=_context, msg='Need one of ' + ', '.join(['STR', 'ID', 'LP', 'LB', 'STMT', 'OR', 'RP', 'RB', '"rule"', 'EOF']))
163 return cleanup_sequence(rule, v)
164
165 def ClauseC(self, rule, tokens, _parent=None):
166 _context = self.Context(_parent, self._scanner, self._pos, 'ClauseC', [rule, tokens])
167 ClauseD = self.ClauseD(rule, tokens, _context)
168 _token = self._peek()
169 if _token == 'PLUS':
170 PLUS = self._scan('PLUS')
171 return parsetree.Plus(rule, ClauseD)
172 elif _token == 'STAR':
173 STAR = self._scan('STAR')
174 return parsetree.Star(rule, ClauseD)
175 elif _token == 'QUEST':
176 QUEST = self._scan('QUEST')
177 return parsetree.Option(rule, ClauseD)
178 elif _token not in ['"ignore"', '"token"', '"option"', '":"', '"parser"', 'ATTR', 'COLON']:
179 return ClauseD
180 else:
181 raise yappsrt.YappsSyntaxError(_token[0], 'Could not match ClauseC')
182
183 def ClauseD(self, rule, tokens, _parent=None):
184 _context = self.Context(_parent, self._scanner, self._pos, 'ClauseD', [rule, tokens])
185 _token = self._peek()
186 if _token == 'STR':
187 STR = self._scan('STR')
188 t = (STR, eval(STR,{},{}))
189 if t not in tokens: tokens.insert( 0, t )
190 return parsetree.Terminal(rule, STR)
191 elif _token == 'ID':
192 ID = self._scan('ID')
193 OptParam = self.OptParam(_context)
194 return resolve_name(rule, tokens, ID, OptParam)
195 elif _token == 'LP':
196 LP = self._scan('LP')
197 ClauseA = self.ClauseA(rule, tokens, _context)
198 RP = self._scan('RP')
199 return ClauseA
200 elif _token == 'LB':
201 LB = self._scan('LB')
202 ClauseA = self.ClauseA(rule, tokens, _context)
203 RB = self._scan('RB')
204 return parsetree.Option(rule, ClauseA)
205 elif _token == 'STMT':
206 STMT = self._scan('STMT')
207 return parsetree.Eval(rule, STMT[2:-2])
208 else:
209 raise yappsrt.YappsSyntaxError(_token[0], 'Could not match ClauseD')
210
211 def OptParam(self, _parent=None):
212 _context = self.Context(_parent, self._scanner, self._pos, 'OptParam', [])
213 _token = self._peek()
214 if _token == 'ATTR':
215 ATTR = self._scan('ATTR')
216 return ATTR[2:-2]
217 elif _token not in ['"ignore"', '"token"', '"option"', '"parser"', 'COLON']:
218 return ''
219 else:
220 raise yappsrt.YappsSyntaxError(_token[0], 'Could not match OptParam')
221
222 def Str(self, _parent=None):
223 _context = self.Context(_parent, self._scanner, self._pos, 'Str', [])
224 STR = self._scan('STR')
225 return eval(STR,{},{})
226
227
228 def parse(rule, text):
229 P = ParserDescription(ParserDescriptionScanner(text))
230 return yappsrt.wrap_error_reporter(P, rule)
231
232 # End -- grammar generated by Yapps