declare_functions_visitor.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import hutn_compiler.symbol_table as st
  2. from hutn_compiler.visitor import Visitor
  3. from hutn_compiler.hutnparser import Tree
  4. # Declare the function but do not visit its body
  5. class DeclareFunctionsVisitor(Visitor):
  6. def __init__(self, symbol_table, inputfiles):
  7. Visitor.__init__(self, [])
  8. self.symbol_table = symbol_table
  9. self.inputfiles = inputfiles
  10. def compute_parameter_types(self, tree):
  11. parameter_types = []
  12. for parameter in Tree.get_children(tree, 'parameter'):
  13. type_specifier = Tree.get_text(Tree.get_children(parameter, "type_specifier")[0])
  14. parameter_types.append(type_specifier)
  15. return parameter_types
  16. def compute_func_type(self, tree):
  17. self.visit(Tree.get_tail(tree)[0])
  18. func_type = self.get_type(Tree.get_tail(tree)[0])
  19. return func_type
  20. def visit_funcdecl(self, tree):
  21. func_name = Tree.get_text(Tree.get_children(tree, "func_name")[0])
  22. func_type = self.compute_func_type(tree)
  23. parameter_types = self.compute_parameter_types(tree)
  24. self.set_type(tree, func_type)
  25. #TODO should check type compatibility if declared multiple times
  26. try:
  27. s = {"name": func_name, "type": func_type, "is_global": True, "node": None, "params": parameter_types}
  28. self.symbol_table.add(s)
  29. except Exception:
  30. if "COLON" in Tree.get_tail(tree) or "ASSIGN" in Tree.get_tail(tree):
  31. raise RuntimeError(
  32. "{}:{}:{}: error: redeclaration of '{}'".format(
  33. self.inputfiles[0], tree['startpos']['line'],
  34. tree['startpos']['column'], func_name))
  35. self.set_symbol(tree, s)
  36. def visit_func_type(self, tree):
  37. self.set_type(tree, Tree.get_text(tree))