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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
|
#!/bin/env python3
import sys
import argparse
import logging
import ply.lex as lex
import ply.yacc as yacc
from enum import Enum
# args
parser = argparse.ArgumentParser(
prog='henshin'
)
parser.add_argument('filename')
args = parser.parse_args()
input = open(args.filename).read()
# log
logging.basicConfig(
level = logging.DEBUG,
filename = "parselog.txt",
filemode = "w",
)
log = logging.getLogger()
# Lexer
reserved = {
"function": "FUNCTION",
"if": "IF",
"else": "ELSE",
"return": "RETURN",
"const": "CONST",
"var": "VAR",
"integer": "TYPE_INTEGER",
"string": "TYPE_STRING",
"void": "TYPE_VOID",
}
tokens = [
"OPERATOR_PLUS",
"OPERATOR_MINUS",
"OPERATOR_MULTIPLY",
"OPERATOR_DIVIDE",
"ASSIGN",
"OPERATOR_PIPE",
"OPERATOR_PIPE_REPLACEMENT",
"PARENTHESIS_LEFT",
"PARENTHESIS_RIGHT",
"BRACE_LEFT",
"BRACE_RIGHT",
"BRACKET_LEFT",
"BRACKET_RIGHT",
"AND",
"OR",
"BIT_AND",
"BIT_OR",
"NAMESPACE_ACCESSOR",
"COMMA",
"COLON",
"SEMICOLON",
"IDENTIFIER",
"NUMBER",
"STRING",
"COMMENT",
] + list(reserved.values())
t_OPERATOR_PLUS = r'\+'
t_OPERATOR_MINUS = r'-'
t_OPERATOR_MULTIPLY = r'\*'
t_OPERATOR_DIVIDE = r'/'
t_ASSIGN = '='
t_OPERATOR_PIPE = r'\|>'
t_OPERATOR_PIPE_REPLACEMENT = r'\$'
t_PARENTHESIS_LEFT = r'\('
t_PARENTHESIS_RIGHT = r'\)'
t_BRACKET_LEFT = r'\['
t_BRACKET_RIGHT = r'\]'
t_BRACE_LEFT = r'{'
t_BRACE_RIGHT = r'}'
t_AND = r'\&\&'
t_OR = r'\|\|'
t_BIT_AND = r'\&'
t_BIT_OR = r'\|'
t_NAMESPACE_ACCESSOR = r'\.'
t_COMMA = r','
t_COLON = r':'
t_SEMICOLON = r';'
def t_IDENTIFIER(t):
r'[a-zA-Z][a-zA-Z0-9_]*'
t.type = reserved.get(t.value, 'IDENTIFIER')
return t
def t_NUMBER(t):
r'[0-9]+'
t.value = int(t.value)
return t
def t_STRING(t):
r'(".+"|\'.*\')'
return t
def t_COMMENT(t):
r'//.*'
pass
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
t_ignore = ' \t'
def t_error(t):
print("undefined: '%s'" % t.value[0])
t.lexer.skip(1)
lexer = lex.lex(debug=True, debuglog=log)
lexer.input(input)
lineno = 0
for token in lexer:
if token.lineno != lineno:
lineno = token.lineno
print("\nLine %s:" % token.lineno)
# print('%s: "%s" --' % (token.type, token.value), end=' ')
print(token.value, end=' ')
print("\n")
# Parser
class AstNodeExpressionType(Enum):
IDENTIFIER = 'identifier'
NUMBER = 'number'
STRING = 'string'
class AstNode: pass
class AstNodeVariableDeclarationStatement(AstNode):
def __init__(self, type, name, value_type, value):
self.type = type
self.name = name
self.value_type = value_type
self.value = value
class AstNodeVariableReassignmentStatement(AstNode):
def __init__(self, name, value):
self.name = name
self.value = value
class AstNodeExpression(AstNode):
def __init__(self, type, value):
self.type = type
self.value = value
class AstNodeOperatorExpression(AstNode):
def __init__(self, type, left, right):
self.type = type
self.left = left
self.right = right
class AstNodeFunctionDeclaration(AstNode):
def __init__(self, name, parameters, return_type, body):
self.name = name
self.parameters = parameters
self.return_type = return_type
self.body = body
class AstNodeFunctionDeclarationParameter(AstNode):
def __init__(self, name, type):
self.name = name
self.type = type
class AstNodeReturnStatement(AstNode):
def __init__(self, expression):
self.expression = expression
class AstNodeFunctionCall(AstNode):
def __init__(self, name, parameters):
self.name = name
self.parameters = parameters
class AstNodeFunctionCallParameter(AstNode):
def __init__(self, name, value):
self.name = name
self.value = value
precedence = (
('left', 'OPERATOR_PLUS', 'OPERATOR_MINUS'),
('left', 'OPERATOR_MULTIPLY', 'OPERATOR_DIVIDE'),
)
def p_statements(p):
'''statements : statement
| statement statements'''
def resolve_nodes(node, level):
node_dict = node.__dict__
for property in node_dict:
node_value = node_dict[property]
if isinstance(node_value, AstNode):
print('> '*level, property, node_value.__class__.__name__)
resolve_nodes(node_value, level+1)
elif isinstance(node_value, list):
list_length = len(node_value)
print('> '*level, property + '[' + str(list_length) + ']:')
for idx in range(list_length):
item = node_value[idx]
print('> '*(level+1), str(idx+1)+'.', item.__class__.__name__)
resolve_nodes(item, level+2)
else:
print('> '*level, property, node_dict[property])
if p[1]:
print(p[1].__class__.__name__)
resolve_nodes(p[1], 0)
statements = [p[1]]
if len(p) > 2:
statements.extend(p[2])
p[0] = statements
def p_statement(p):
'''statement : variable_declaration_statement
| variable_reassignment_statement
| function_declaration
| return_statement'''
p[0] = p[1]
def p_function_declaration(p):
'''function_declaration : FUNCTION IDENTIFIER PARENTHESIS_LEFT function_declaration_parameters PARENTHESIS_RIGHT COLON return_type BRACE_LEFT statements BRACE_RIGHT'''
p[0] = AstNodeFunctionDeclaration(p[2], p[4], p[7], p[9])
def p_function_declaration_parameters(p):
'''function_declaration_parameters : function_declaration_parameter COMMA function_declaration_parameters
| function_declaration_parameter
|'''
parameters = [p[1]]
if len(p) > 2:
parameters.append(p[3])
p[0] = parameters
def p_function_declaration_parameter(p):
'''function_declaration_parameter : IDENTIFIER COLON variable_type'''
p[0] = AstNodeFunctionDeclarationParameter(p[1], p[3])
def p_function_call(p):
'''function_call : IDENTIFIER PARENTHESIS_LEFT function_call_parameters PARENTHESIS_RIGHT SEMICOLON'''
p[0] = AstNodeFunctionCall(p[1], p[3])
def p_function_call_parameters(p):
'''function_call_parameters : function_call_parameter COMMA function_call_parameters
| function_call_parameter
|'''
parameters = [p[1]]
if len(p) > 2:
parameters.append(p[3])
p[0] = parameters
def p_function_call_parameter(p):
'''function_call_parameter : IDENTIFIER ASSIGN expression
| expression'''
if len(p) > 2:
p[0] = AstNodeFunctionCallParameter(p[1], p[3])
else:
p[0] = AstNodeFunctionCallParameter("", p[1])
def p_variable_declaration_statement(p):
'''variable_declaration_statement : variable_declarator IDENTIFIER COLON variable_type ASSIGN expression SEMICOLON'''
p[0] = AstNodeVariableDeclarationStatement(p[1], p[2], p[4], p[6])
def p_variable_reassignment_statement(p):
'''variable_reassignment_statement : IDENTIFIER ASSIGN expression SEMICOLON'''
p[0] = AstNodeVariableReassignmentStatement(p[1], p[3])
def p_variable_declarator(p):
'''variable_declarator : CONST
| VAR'''
p[0] = p[1]
def p_variable_type(p):
'''variable_type : TYPE_INTEGER
| TYPE_STRING'''
p[0] = p[1]
def p_return_statement(p):
'''return_statement : RETURN expression SEMICOLON'''
p[0] = AstNodeReturnStatement(p[2])
def p_return_type(p):
'''return_type : variable_type
| TYPE_VOID'''
p[0] = p[1]
def p_identifier(p):
'''identifier : IDENTIFIER'''
p[0] = AstNodeExpression(AstNodeExpressionType.IDENTIFIER, p[1])
def p_number(p):
'''number : NUMBER'''
p[0] = AstNodeExpression(AstNodeExpressionType.NUMBER, p[1])
def p_string(p):
'''string : STRING'''
p[0] = AstNodeExpression(AstNodeExpressionType.STRING, p[1])
def p_expression(p):
'''expression : identifier
| number
| string
| function_call
| expression OPERATOR_PLUS expression
| expression OPERATOR_MINUS expression
| expression OPERATOR_MULTIPLY expression
| expression OPERATOR_DIVIDE expression'''
if len(p) == 4:
p[0] = AstNodeOperatorExpression(p[2], p[1], p[3])
else:
p[0] = p[1]
def p_error(p):
print("Syntax error in input!", p)
parser = yacc.yacc(debug=True, debuglog=log)
result = parser.parse(input)
# print(result)
# if __name__ == "__main__":
# lex.runmain()
|