cvisitors.py
23.5 KB
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
# cvisitors.py: modified by Franck Pommereau (2018)
# ---------------------------------------------------------------
# cvisitors.py
#
# Atul Varma
# Python C Compiler - Visitors
# $Id: cvisitors.py,v 1.3 2004/05/27 17:51:47 varmaa Exp $
#
# The Visitor is a pattern outlined in "Design Patterns" by
# Gamma et al., used here to encapsulate different parts of parsing
# and compilation into separate classes via a mechanism called
# double dispatching.
#
# In this compiler, the yacc grammar rules in cparse.py just create
# the abstract syntax tree, and visitors do the bulk of parsing
# and compilation.
# ---------------------------------------------------------------
# TODO: make it so functions can return void.
# TODO: mark all statements with an 'ignore return value' flag
# to enable some optimizations if the statement is an
# expression.
# TODO: move extern, static indicators in functions to their
# Type object, maybe.
#
# Possible things to do:
# Add compilation to JVM/python bytecode/z-machine...
# Implement arrays
# Pass line numbers to constructors for nodes
#
# Faults so far:
# * doesn't check for variable initialization before use.
# * const number ranges aren't being checked.
from . import cparse
class Visitor:
"""The base visitor class. This is an abstract base class."""
def __init__(self):
self.warnings = 0
self.errors = 0
def _visitList(self, list):
"""Visit a list of nodes. 'list' should be an actual list,
not a cparse.NodeList object."""
last = None
for i in list:
last = i.accept(self)
return last
def visit(self, node):
"""Visits the given node by telling the node to call the
visitor's class-specific visitor method for that node's
class (i.e., double dispatching)."""
return node.accept(self)
def warning(self, str):
"""Output a non-fatal compilation warning."""
print("warning: %s" % str)
self.warnings += 1
def error(self, str):
"""Output a fatal compilation error."""
print("error: %s" % str)
self.errors += 1
def has_errors(self):
"""Returns whether the visitor has encountered any
errors."""
return self.errors > 0
# ---------------------------------------------------------------
# ABSTRACT SYNTAX TREE PRINTER (for debugging)
# ---------------------------------------------------------------
class ASTPrinterVisitor(Visitor):
"""Simple visitor that outputs a textual representation of
the abstract syntax tree, for debugging purposes, to an
output file."""
def __init__(self, ast_file, indent_amt=2):
self.ast_file = ast_file
Visitor.__init__(self)
self._indent = 0
self._indent_amt = indent_amt
def indent(self):
self._indent += self._indent_amt
def unindent(self):
self._indent -= self._indent_amt
def p(self, str):
self.ast_file.write(
(' ' * (self._indent_amt * self._indent) ) + str + "\n" )
def pNodeInfo(self, node):
# Print out the name of the node's class.
self.p('+ ' + node.__class__.__name__)
# If the node has a type associated with it,
# print the string of the type.
if hasattr(node, "type"):
self.p(" Type-string: %s" % node.type.get_string())
# Find all attributes of the node that are ints or
# strings and aren't 'private' (i.e., don't begin with
# '_'), and print their values.
for key in dir(node):
if key[0] == '_':
continue
val = getattr(node, key, None)
if (isinstance(val, str) or
isinstance(val, int)):
self.p(" %s: %s" % (key, str(val)))
def pSubnodeInfo(self, subnode, label):
if not subnode.is_null():
self.p(" %s:" % label)
self.indent()
subnode.accept(self)
self.unindent()
def vNullNode(self, node):
self.pNodeInfo(node)
def vArrayExpression(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.expr, "Expression")
self.pSubnodeInfo(node.index, "Index")
def vStringLiteral(self, node):
self.pNodeInfo(node)
self.p(' Value: "%s"' % node.get_sanitized_str())
def vId(self, node):
self.pNodeInfo(node)
def vUnaryop(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.expr, "Expression")
def vFunctionExpression(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.function, "Function")
self.pSubnodeInfo(node.arglist, "Arguments")
def vConst(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.type, "Type")
def vBinop(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.left, "Left operand")
self.pSubnodeInfo(node.right, "Right operand")
def vNodeList(self, node):
self.pNodeInfo(node)
self.indent()
self._visitList(node.nodes)
self.unindent()
def vCompoundStatement(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.declaration_list, "Declaration list")
self.pSubnodeInfo(node.statement_list, "Statement list")
def vBaseType(self, node):
self.pNodeInfo(node)
def vFunctionType(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.params, "Parameters:")
self.pSubnodeInfo(node.child, "Child:")
def vPointerType(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.child, "Child:")
def vDeclaration(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.type, "Type")
def vReturnStatement(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.expr, "Expression")
def vFunctionDefn(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.type, "Type")
self.pSubnodeInfo(node.body, "Body")
def vIfStatement(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.expr, "Expression")
self.pSubnodeInfo(node.then_stmt, "Then statement")
self.pSubnodeInfo(node.else_stmt, "Else statement")
def vWhileLoop(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.expr, "Expression")
self.pSubnodeInfo(node.stmt, "Statement")
def vForLoop(self, node):
self.pNodeInfo(node)
self.pSubnodeInfo(node.begin_stmt, "Begin statement")
self.pSubnodeInfo(node.expr, "Test expression")
self.pSubnodeInfo(node.end_stmt, "End statement")
self.pSubnodeInfo(node.stmt, "Statement")
# ---------------------------------------------------------------
# SYMBOL TABLE GENERATION
# ---------------------------------------------------------------
class Symtab:
"""A symbol table. This is a simple object that just keeps a
hashtable of symbol names and the Declaration or FunctionDefn
nodes that they refer to.
There is a separate symbol table for each code element that
has its own scope (for instance, each compound statement will
have its own symbol table). As a result, symbol tables can
be nested if the code elements are nested, and symbol table
lookups will recurse upwards through parents to represent
lexical scoping rules."""
class SymbolDefinedError(Exception):
"""Exception raised when the code tries to add a symbol
to a table where the symbol has already been defined.
Note that 'defined' is used in the C sense here--i.e.,
'space has been allocated for the symbol', as opposed
to a declaration."""
pass
class SymbolConflictError(Exception):
"""Exception raised when the code tries to add a
symbol to a tamble where the symbol already exists
and its type differs from the previously existing
one."""
pass
def __init__(self, parent=None):
"""Creates an empty symbol table with the given
parent symbol table."""
self.entries = {}
self.parent = parent
if self.parent != None:
self.parent.children.append(self)
self.children = []
def add(self, name, value):
"""Adds a symbol with the given value to the symbol table.
The value is usually an AST node that represents the
declaration or definition of a function/variable (e.g.,
Declaration or FunctionDefn)."""
if name in self.entries:
if not self.entries[name].extern:
raise Symtab.SymbolDefinedError()
elif self.entries[name].type.get_string() != \
value.type.get_string():
raise Symtab.SymbolConflictError()
self.entries[name] = value
def get(self, name):
"""Retrieves the symbol with the given name from the symbol
table, recursing upwards through parent symbol tables if it is
not found in the current one."""
if name in self.entries:
return self.entries[name]
else:
if self.parent != None:
return self.parent.get(name)
else:
return None
class SymtabVisitor(Visitor):
"""Visitor that creates and attaches symbol tables to the AST."""
def push_symtab(self, node):
"""Pushes a new symbol table onto the visitor's symbol table
stack and attaches this symbol table to the given node. This
is used whenever a new lexical scope is encountered, so the
node is usually a CompoundStatement object."""
self.curr_symtab = Symtab(self.curr_symtab)
node.symtab = self.curr_symtab
def pop_symtab(self):
"""Pops a symbol table off the visitor's symbol table stack.
This is used whenever a new lexical scope is exited."""
self.curr_symtab = self.curr_symtab.parent
def vNode(self, node):
pass
def vArrayExpression(self, node):
node.expr.accept(self)
node.index.accept(self)
def vFunctionExpression(self, node):
node.function.accept(self)
node.arglist.accept(self)
def vId(self, node):
symbol = self.curr_symtab.get(node.name)
if symbol != None:
node.symbol = symbol
node.symbol.is_used = 1
node.set_has_address()
else:
self.error("Line %d: Unknown identifier '%s'." % (node.lineno, node.name))
def vUnaryop(self, node):
node.expr.accept(self)
def vBinop(self, node):
node.left.accept(self)
node.right.accept(self)
def vNodeList(self, node):
self._visitList(node.nodes)
def vParamList(self, node):
# Assign a number to each parameter. This will later be
# useful for the code generation phase.
#
# TODO: might be best to just move this to the code
# generation phase, since this doesn't have anything to
# do with symbol table generation.
for param_num, param in enumerate(node.nodes):
param.accept(self)
param.param_num = param_num
def vTranslationUnit(self, node):
self.root_symtab = Symtab()
self.curr_symtab = self.root_symtab
self.vNodeList(node)
node.symtab = self.root_symtab
def vCompoundStatement(self, node):
self.push_symtab(node)
node.declaration_list.accept(self)
node.statement_list.accept(self)
self.pop_symtab()
def _add_symbol(self, node):
"""Attempts to add a symbol for the given node to the current
symbol table, catching any exceptions that occur and printing
errors if necessary."""
try:
self.curr_symtab.add(node.name, node)
except Symtab.SymbolDefinedError:
self.error("Symbol '%s' already defined." % node.name)
except Symtab.SymbolConflictError:
self.error("Symbol '%s' has multiple differing declarations." % node.name)
def vDeclaration(self, node):
self._add_symbol(node)
def vReturnStatement(self, node):
node.expr.accept(self)
def vFunctionType(self, node):
node.params.accept(self)
def vFunctionDefn(self, node):
self._add_symbol(node)
self.push_symtab(node)
node.type.accept(self)
node.body.accept(self)
self.pop_symtab()
def vIfStatement(self, node):
node.expr.accept(self)
node.then_stmt.accept(self)
node.else_stmt.accept(self)
def vWhileLoop(self, node):
node.expr.accept(self)
node.stmt.accept(self)
def vForLoop(self, node):
node.begin_stmt.accept(self)
node.expr.accept(self)
node.end_stmt.accept(self)
node.stmt.accept(self)
# ---------------------------------------------------------------
# TYPE CHECKING
# ---------------------------------------------------------------
class TypeCheckVisitor(Visitor):
"""Visitor that performs type checking on the AST, attaching a
Type object subclass to every eligible node and making sure these
types don't conflict."""
def _process_conditional(self, expr):
"""Does simple type checking for an expression that is
supposed to be the expression for a conditional
statement (e.g., the conditional clause of an if/then
statement or a loop)."""
if expr.type.get_outer_string() not in ['int', 'char']:
self.error("Conditional expression doesn't evaluate to an int/char/etc.")
def _coerce_consts(self, var1, var2):
"""Looks at two typed terminals to see if one of them
is a constant integral. If it is, then coerce it to
the type of the other terminal.
Note that both terminals cannot be constant integrals, or else
they would have already been reduced to one node by the node's
calculate() method in the parsing stage."""
if var1.is_const():
self._coerce_const(var1, var2.type)
elif var2.is_const():
self._coerce_const(var2, var1.type)
def _coerce_const(self, var, type):
"""If the given typed terminal is a constant, coerces it to
the given type."""
if var.is_const() and type.get_string() in ['int', 'char']:
var.type = type
def _check_const_range(self, var, type):
"""Checks the given integral constant to make sure its value
is within the bounds of the given type."""
val = var.value
type_str = type.get_outside_string()
# TODO: implement this!
if type_str == 'char':
pass
elif type_str == 'int':
pass
def _compare_types(self, name_str, from_type, to_type, raise_errors=1, node=None):
"""Compares the two types to see if it's possible to perform a
binary operation on them. If it is not, then the appropriate
errors/warnings are raised, unless raise_errors is set to
0."""
WARNING = 1
ERROR = 2
conflict = 0
from_str = from_type.get_string()
to_str = to_type.get_string()
if (from_str != to_str):
if from_str == 'char':
if to_str == 'int':
pass
else:
conflict = ERROR
elif from_str == 'int':
if to_str == 'char':
conflict = WARNING
else:
conflict = ERROR
elif from_str.startswith("pointer(") and to_str.startswith("pointer(") :
conflict = WARNING
else:
conflict = ERROR
if not raise_errors:
return conflict
if conflict == WARNING:
self.warning("%s%s: Conversion from %s to %s may result in data loss."
% ("[%s] " % node.loc() if node else "",
name_str, from_str, to_str))
elif conflict == ERROR:
self.error("%s%s: Cannot convert from %s to %s."
% ("[%s] " % node.loc() if node else "",
name_str, from_str, to_str))
def vNode(self, node):
pass
def vId(self, node):
node.type = node.symbol.type
def vNegative(self, node):
node.expr.accept(self)
node.type = node.expr.type
# TODO: check to make sure expr is a signed type?
def vAddrOf(self, node):
node.expr.accept(self)
if not node.expr.has_address():
self.error("Address-of (&) target has no address!")
else:
node.expr.output_addr = 1
node.type = cparse.PointerType(node.expr.type)
def vPointer(self, node):
node.expr.accept(self)
if node.expr.type.get_outer_string() == 'pointer':
node.type = node.expr.type.child
node.set_has_address()
else:
self.error("Pointer dereference (*) target is not a pointer!")
def vBinop(self, node):
node.left.accept(self)
node.right.accept(self)
if node.op in cparse.Binop.ASSIGN_OPS:
if not node.left.has_address():
self.error("Invalid lvalue: not an address!")
node.left.output_addr = 1
self._coerce_const(node.right, node.left.type)
# TODO: re-implement this!
# elif node.left.symbol.is_constant:
# self.error("Invalid lvalue: lvalue is constant!")
self._compare_types("Assignment", node.right.type, node.left.type, node=node)
node.right.coerce_to_type = node.left.type
node.type = node.left.type
else:
# TODO: not sure if this results in the ANSI C
# specification for binary operand type coercion.
self._coerce_consts(node.left, node.right)
left_conflicts = self._compare_types("", node.right.type, node.left.type,
raise_errors=0, node=node)
right_conflicts = self._compare_types("", node.left.type, node.right.type,
raise_errors=0, node=node)
if left_conflicts < right_conflicts:
from_node = node.right
to_node = node.left
else:
from_node = node.left
to_node = node.right
self._compare_types("Binop '%s'" % node.op, from_node.type, to_node.type,
node=node)
from_node.coerce_to_type = to_node.type
to_node.coerce_to_type = to_node.type
node.type = to_node.type
def vNodeList(self, node):
self._visitList(node.nodes)
def vCompoundStatement(self, node):
node.statement_list.accept(self)
def vReturnStatement(self, node):
node.expr.accept(self)
return_type = self.curr_func.type.get_return_type()
self._coerce_const(node.expr, return_type)
self._compare_types("Return expression", node.expr.type, return_type, node=node)
node.expr.coerce_to_type = return_type
def vArrayExpression(self, node):
node.expr.accept(self)
node.index.accept(self)
if node.index.type.get_outer_string() not in ['int', 'char']:
self.error("Array index is not an int or char!")
elif node.expr.type.get_outer_string() != 'pointer':
self.error("Array expression is not a pointer!")
else:
node.type = node.expr.type.child
node.set_has_address()
def vFunctionExpression(self, node):
node.function.accept(self)
if not node.function.type.is_function():
self.error("Target of function expression is not a function!")
node.type = node.function.symbol.type.get_return_type()
node.arglist.accept(self)
params = node.function.symbol.type.get_params()
num_args = len(node.arglist.nodes)
num_params = len(params.nodes)
if (not params.has_ellipsis) and (num_args > num_params):
self.error("Too many arguments passed to function.")
elif num_args < num_params:
self.error("Too few arguments passed to function.")
for arg, param in zip(node.arglist.nodes, params.nodes):
self._coerce_const(arg, param.type)
self._compare_types("Function call argument", arg.type, param.type,
node=node)
arg.coerce_to_type = param.type
# If this function takes a variable number of args and
# we've got more args than required parameters, we need
# to set some of the extra arguments' field(s) properly.
if (params.has_ellipsis) and (num_args > num_params):
for arg in node.arglist.nodes[num_params:]:
arg.coerce_to_type = arg.type
def vFunctionDefn(self, node):
self.curr_func = node
node.body.accept(self)
def vIfStatement(self, node):
node.expr.accept(self)
self._process_conditional(node.expr)
node.then_stmt.accept(self)
node.else_stmt.accept(self)
def vWhileLoop(self, node):
node.expr.accept(self)
self._process_conditional(node.expr)
node.stmt.accept(self)
def vForLoop(self, node):
node.begin_stmt.accept(self)
node.expr.accept(self)
self._process_conditional(node.expr)
node.end_stmt.accept(self)
node.stmt.accept(self)
# ---------------------------------------------------------------
# FLOW CONTROL
# ---------------------------------------------------------------
class FlowControlVisitor(Visitor):
"""Performs flow control checking on the AST. This makes sure
that functions return properly through all branches, that
break/continue statements are only present within loops, and so
forth."""
def vNode(self, node):
node.has_return_stmt = 0
def vStatementList(self, node):
node.has_return_stmt = 0
for stmt in node.nodes:
if node.has_return_stmt:
self.warning("Function %s has at least one unreachable statement." % self.curr_func.name)
stmt.accept(self)
if stmt.has_return_stmt:
node.has_return_stmt = 1
def vTranslationUnit(self, node):
self._visitList(node.nodes)
def vWhileLoop(self, node):
old_in_loop = self.in_loop
self.in_loop = 1
node.stmt.accept(self)
self.in_loop = old_in_loop
node.has_return_stmt = node.stmt.has_return_stmt
def vForLoop(self, node):
self.vWhileLoop(node)
def vBreakStatement(self, node):
node.has_return_stmt = 0
if not self.in_loop:
self.error("Break statement outside of loop.")
def vContinueStatement(self, node):
node.has_return_stmt = 0
if not self.in_loop:
self.error("Continue statement outside of loop.")
def vIfStatement(self, node):
node.then_stmt.accept(self)
node.else_stmt.accept(self)
if node.then_stmt.has_return_stmt and node.else_stmt.has_return_stmt:
node.has_return_stmt = 1
else:
node.has_return_stmt = 0
def vFunctionDefn(self, node):
self.curr_func = node
self.in_loop = 0
node.body.accept(self)
if not node.body.has_return_stmt:
self.warning("Function %s doesn't return through all branches." % node.name)
def vReturnStatement(self, node):
node.has_return_stmt = 1
def vCompoundStatement(self, node):
node.statement_list.accept(self)
node.has_return_stmt = node.statement_list.has_return_stmt
# ---------------------------------------------------------------
# End of cvisitors.py
# ---------------------------------------------------------------