model_visitor.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. from interface.HUTN.hutn_compiler.visitor import Visitor
  2. from interface.HUTN.hutn_compiler.compiler import main as do_compile
  3. import os
  4. def empty(s):
  5. return None
  6. class ModelVisitor(Visitor):
  7. def __init__(self, args):
  8. Visitor.__init__(self, args)
  9. self.constructors = []
  10. self.free_id = 0
  11. self.names = set()
  12. self.current_element = []
  13. self.includes = []
  14. def dump(self):
  15. return [len(self.constructors)] + self.constructors
  16. def __getattr__(self, attr):
  17. if attr.startswith("visit_"):
  18. return empty
  19. else:
  20. raise AttributeError()
  21. def visit_start(self, tree):
  22. for t in tree.get_tail():
  23. self.visit(t)
  24. def visit_include_files(self, tree):
  25. self.includes.append('include %s' % tree.get_children("STRVALUE")[0].get_text())
  26. def visit_model_element(self, tree):
  27. children = tree.get_children("MODEL_ID")
  28. element_type = children[0].get_text()
  29. if len(children) == 2 or len(children) == 4:
  30. element_name = children[1].get_text()
  31. else:
  32. element_name = "__%s" % self.free_id
  33. self.free_id += 1
  34. if element_name in self.names:
  35. raise Exception("Redefinition of element %s" % element_name)
  36. if len(children) > 2:
  37. # So we have a source and target; but aren't sure which is which, because the name is optional!
  38. source_name = children[-2].get_text()
  39. target_name = children[-1].get_text()
  40. if source_name not in self.names:
  41. raise Exception("Source of link %s unknown: %s" % (element_name, source_name))
  42. if target_name not in self.names:
  43. raise Exception("Target of link %s unknown: %s" % (element_name, target_name))
  44. self.constructors.extend(["instantiate_link", element_type, element_name, source_name, target_name])
  45. else:
  46. self.constructors.extend(["instantiate_node", element_type, element_name])
  47. self.names.add(element_name)
  48. self.current_element.append(element_name)
  49. if tree.get_children("inheritance"):
  50. self.visit(tree.get_children("inheritance")[0])
  51. for attr in tree.get_children("model_attribute"):
  52. self.visit(attr)
  53. self.current_element.pop()
  54. return element_name
  55. def visit_inheritance(self, tree):
  56. for token in tree.get_children("MODEL_ID"):
  57. superclass = token.get_text()
  58. if superclass not in self.names:
  59. raise Exception("Superclass %s is undefined" % superclass)
  60. self.constructors.extend(["instantiate_link", "Inheritance", "%s_inherits_from_%s" % (self.current_element[-1], superclass), self.current_element[-1], superclass])
  61. self.names.add("%s_inherits_from_%s" % (self.current_element[-1], superclass))
  62. def visit_model_attribute(self, tree):
  63. children = tree.get_children("MODEL_ID")
  64. is_definition = bool(tree.get_children("COLON"))
  65. is_assign = bool(tree.get_children("model_attr_instance"))
  66. is_nested = bool(tree.get_children("model_element"))
  67. if is_definition:
  68. attr_name = children[0].get_text()
  69. attr_optional = len(tree.get_children("OPTIONAL")) > 0
  70. attr_type = children[1].get_text()
  71. if attr_type not in self.names:
  72. raise Exception("Unknown Attribute type!")
  73. self.constructors.extend(["model_define_attribute", self.current_element[-1], attr_name, attr_optional, attr_type])
  74. full_attribute_name = self.current_element[-1] + "_" + attr_name
  75. if is_assign:
  76. # There are also some attributes to set!
  77. self.current_element.append(full_attribute_name)
  78. for f in tree.get_children("model_attr_instance"):
  79. self.visit(f)
  80. self.current_element.pop()
  81. elif is_assign:
  82. self.visit(tree.get_children("model_attr_instance")[0])
  83. elif is_nested:
  84. if tree.get_children("MODEL_ID"):
  85. contains_link = tree.get_children("MODEL_ID")[0].get_text()
  86. else:
  87. contains_link = ""
  88. entry = self.visit(tree.get_children("model_element")[0])
  89. self.constructors.extend(["instantiate_link", contains_link, "__%s" % self.free_id, self.current_element[-1], entry])
  90. self.names.add("__%s" % self.free_id)
  91. self.free_id += 1
  92. def visit_model_attr_instance(self, tree):
  93. def constructors_compile(code):
  94. code_fragments = code.split("\n")
  95. code_fragments = [i for i in code_fragments if i.strip() != ""]
  96. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  97. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  98. code_fragments = self.includes + [i[initial_tabs:] for i in code_fragments]
  99. code = "\n".join(code_fragments)
  100. code += "\n"
  101. with open(".code.alc", 'w') as f:
  102. f.write(code)
  103. f.flush()
  104. directory = os.path.realpath(__file__).rsplit(os.sep, 1)[0]
  105. compiled = do_compile(".code.alc", directory + "/../grammars/actionlanguage.g", "CS")
  106. return compiled
  107. children = tree.get_children("MODEL_ID")
  108. attr_name = children[0].get_text()
  109. if tree.get_children("value"):
  110. # Value attribute
  111. attr_value = tree.get_children("value")[0].get_tail()[0]
  112. if attr_value.head == "STRVALUE":
  113. attr_value = attr_value.get_text()[1:-1]
  114. elif attr_value.head == "LONG_STR":
  115. attr_value = attr_value.get_text()[3:-3]
  116. print("Got value: " + str(attr_value))
  117. elif attr_value.head == "TRUE":
  118. attr_value = True
  119. elif attr_value.head == "FALSE":
  120. attr_value = False
  121. elif attr_value.head == "DEC_NUMBER":
  122. attr_value = int(attr_value.get_text())
  123. elif attr_value.head == "FLOAT_NUMBER":
  124. attr_value = float(attr_value.get_text())
  125. else:
  126. raise Exception(attr_value.head)
  127. self.constructors.extend(["instantiate_attribute", self.current_element[-1], attr_name, attr_value])
  128. elif tree.get_children("DOLLAR"):
  129. # Coded attribute
  130. self.constructors.extend(["instantiate_attribute_code", self.current_element[-1], attr_name])
  131. self.constructors.extend(constructors_compile(tree.get_children("ANYTHING_EXCEPT_DOLLAR")[0].get_text()))