-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
parse.py
322 lines (272 loc) · 8.95 KB
/
parse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import sys
import json
import argparse
import ply
# The FastParser parses input using PLY
class FastParser:
def __init__(self, generatedFilesOutputDir=None):
from ply import lex
from ply import yacc
generateFiles = not generatedFilesOutputDir is None
if generateFiles:
sys.path.append(generatedFilesOutputDir)
# Build the lexer and the parser
self.lexer = lex.lex(module=self,
optimize=generateFiles,
outputdir=generatedFilesOutputDir)
self.parser = yacc.yacc(module=self,
write_tables=generateFiles,
outputdir=generatedFilesOutputDir,
debug=generateFiles)
def parse(self, programString, filePath="Unknown"):
"""
Parse a program string.
The path of the program file is added as metadata to returned object
"""
# Add trailing endline if missing
if len(programString) and programString[-1] != "\n":
programString += "\n"
# Parse program and add FilePath key to object
program = self.parser.parse(programString)
program["FilePath"] = filePath
return program
# Lexer specification
# ---------------------------------------
tokens = (
"NUMERAL",
"STRINGLITERAL",
"BOOLLITERAL",
"BASICTYPE",
"SHOGUNSGTYPE",
"PRINTKEYWORD",
"COMMA",
"DOT",
"COLON",
"ENUMKEYWORD",
"EQUALS",
"LPAREN",
"RPAREN",
"LSQUARE",
"RSQUARE",
"COMMENT",
"NEWLINE",
"IDENTIFIER"
)
reserved = {
'enum': 'ENUMKEYWORD',
'print': 'PRINTKEYWORD',
'True': 'BOOLLITERAL',
'False': 'BOOLLITERAL',
'int': 'BASICTYPE',
'bool': 'BASICTYPE',
'float': 'BASICTYPE',
'real': 'BASICTYPE',
'string': 'BASICTYPE',
'BoolVector': 'SHOGUNSGTYPE',
'CharVector': 'SHOGUNSGTYPE',
'ByteVector': 'SHOGUNSGTYPE',
'WordVector': 'SHOGUNSGTYPE',
'ShortVector': 'SHOGUNSGTYPE',
'IntVector': 'SHOGUNSGTYPE',
'LongIntVector': 'SHOGUNSGTYPE',
'ULongIntVector': 'SHOGUNSGTYPE',
'ShortRealVector': 'SHOGUNSGTYPE',
'RealVector': 'SHOGUNSGTYPE',
'LongRealVector': 'SHOGUNSGTYPE',
'ComplexVector': 'SHOGUNSGTYPE',
'BoolMatrix': 'SHOGUNSGTYPE',
'CharMatrix': 'SHOGUNSGTYPE',
'ByteMatrix': 'SHOGUNSGTYPE',
'WordMatrix': 'SHOGUNSGTYPE',
'ShortMatrix': 'SHOGUNSGTYPE',
'IntMatrix': 'SHOGUNSGTYPE',
'LongIntMatrix': 'SHOGUNSGTYPE',
'ULongIntMatrix': 'SHOGUNSGTYPE',
'ShortRealMatrix': 'SHOGUNSGTYPE',
'RealMatrix': 'SHOGUNSGTYPE',
'LongRealMatrix': 'SHOGUNSGTYPE',
'ComplexMatrix': 'SHOGUNSGTYPE'
}
t_NUMERAL = "[0-9]+(\.[0-9]+)?"
t_STRINGLITERAL = '"[^"\n]*"'
t_COMMA = ","
t_DOT = "\."
t_COLON = ":"
t_EQUALS = "="
t_LPAREN = "\("
t_RPAREN = "\)"
t_LSQUARE = "\["
t_RSQUARE = "\]"
t_ignore = " \t"
def t_IDENTIFIER(self, t):
"[a-zA-Z][a-zA-Z0-9-_]*"
# Check for reserved words
t.type = self.reserved.get(t.value, 'IDENTIFIER')
return t
def t_NEWLINE(self, t):
r'\n'
t.lexer.lineno += 1
return t
def t_COMMENT(self, t):
r"\#.*\n"
t.lexer.lineno += 1
return t
def t_error(self, t):
raise TypeError("Failed to tokenize input. Unknown text on line %d '%s'" % (t.lineno, t.value,))
# Grammar specification
# ---------------------------------------
def p_program(self, p):
"program : statements"
p[0] = {"Program": p[1]}
def p_statements(self, p):
"""
statements : statement statements
| comment statements
|
"""
if len(p) > 2:
p[0] = p[1:2]
p[0].extend(p[2])
else:
p[0] = []
def p_comment(self, p):
"comment : COMMENT"
# Strip leading hashtag symbol and trailing newline
p[0] = {"Comment": p[1][1:-1],
"__PARSER_INFO_LINE_NO": p.lineno(1)}
def p_type(self, p):
"""
type : basictype
| shogunsgtype
| objecttype
"""
p[0] = p[1]
def p_basicType(self, p):
"basictype : BASICTYPE"
p[0] = {"BasicType": p[1]}
def p_shogunSGType(self, p):
"shogunsgtype : SHOGUNSGTYPE"
p[0] = {"ShogunSGType": p[1]}
def p_objectType(self, p):
"objecttype : IDENTIFIER"
p[0] = {"ObjectType": p[1]}
def p_argumentList_nonEmpty(self, p):
"""
argumentListNonEmpty : expr
| expr COMMA argumentListNonEmpty
"""
p[0] = [p[1]]
if len(p) > 2:
p[0].extend(p[3])
def p_argumentList(self, p):
"""
argumentList : argumentListNonEmpty
|
"""
arguments = []
if len(p) > 1:
arguments = p[1]
p[0] = {"ArgumentList": arguments}
def p_identifier(self, p):
"identifier : IDENTIFIER"
p[0] = {"Identifier": p[1]}
def p_methodCall(self, p):
"methodCall : identifier DOT identifier LPAREN argumentList RPAREN"
p[0] = {"MethodCall": [p[1], p[3], p[5]]}
def p_staticCall(self, p):
"staticCall : type COLON identifier LPAREN argumentList RPAREN"
p[0] = {"StaticCall": [p[1], p[3], p[5]]}
def p_indexList(self, p):
"""
indexList : numeral
| numeral COMMA indexList
"""
p[0] = [p[1]]
if len(p) > 2:
p[0].extend(p[3])
def p_elementAccess(self, p):
"elementAccess : identifier LSQUARE indexList RSQUARE"
p[0] = {"ElementAccess": [p[1],
{"IndexList": p[3]}]}
def p_enum(self, p):
"enum : ENUMKEYWORD identifier DOT identifier"
p[0] = {"Enum": [p[2], p[4]]}
def p_string(self, p):
"string : STRINGLITERAL"
# Strip leading and trailing quotes
p[0] = {"StringLiteral": p[1][1:-1]}
def p_bool(self, p):
"bool : BOOLLITERAL"
p[0] = {"BoolLiteral": p[1]}
def p_numeral(self, p):
"numeral : NUMERAL"
p[0] = {"NumberLiteral": p[1]}
def p_expr(self, p):
"""
expr : enum
| methodCall
| staticCall
| elementAccess
| string
| bool
| numeral
| identifier
"""
p[0] = {"Expr": p[1]}
def p_assignment(self, p):
"""
assignment : identifier EQUALS expr
| elementAccess EQUALS expr
"""
p[0] = {"Assign": [p[1], p[3]]}
def p_initialisation(self, p):
"""
initialisation : type identifier EQUALS expr
| type identifier LPAREN argumentList RPAREN
"""
p[0] = {"Init": [p[1], p[2], p[4]]}
def p_output(self, p):
"output : PRINTKEYWORD expr"
p[0] = {"Print": p[2]}
def p_statement(self, p):
"""
statement : initialisation NEWLINE
| assignment NEWLINE
| expr NEWLINE
| output NEWLINE
| NEWLINE
"""
p[0] = {"Statement": p[1],
"__PARSER_INFO_LINE_NO": p.lineno(-1)}
# Error rule for syntax errors
def p_error(self, p):
if p:
print("Syntax error in input: " +
str(p.value) + " on line " + str(p.lineno))
else:
print("Reached end of file without completing parse")
def parse(programString, filePath, generatedFilesOutputDir=None):
parser = FastParser(generatedFilesOutputDir)
# Parse input
return parser.parse(programString, filePath)
if __name__ == "__main__":
# Parse command line arguments
argparser = argparse.ArgumentParser()
argparser.add_argument("--pretty", action="store_true", help="If specified, output is pretty printed")
argparser.add_argument("path", nargs='?', help="Path to input file. If not specified input is read from stdin")
argparser.add_argument("--parser_files_dir", nargs='?', help='Path to directory where generated parser and lexer files should be stored.')
args = argparser.parse_args()
programString = ""
filePath = ""
# Read from specified file or, if not specified, from stdin
if args.path:
with open(args.path, 'r') as file:
programString = file.read()
filePath = args.path
else:
programString = sys.stdin.read()
filePath = "sys.stdin"
indentWidth = 2 if args.pretty > 0 else None
# Parse input and print json output
program = parse(programString, filePath, args.parser_files_dir)
print(json.dumps(program, indent=indentWidth))