model_bootstrap_visitor.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. from visitor import Visitor
  2. from compiler import main as do_compile
  3. import os
  4. import uuid
  5. def empty(s):
  6. return None
  7. class ModelBootstrapVisitor(Visitor):
  8. def __init__(self, args):
  9. Visitor.__init__(self, args)
  10. model_name = [arg.split(":", 1)[1] for arg in args if arg.startswith("--modelname:")][0]
  11. self.code = "Void function initialize_%s():\n" % model_name
  12. self.free_id = 0
  13. self.names = set()
  14. self.current_model = None
  15. self.current_element = []
  16. self.includes = []
  17. def dump(self):
  18. return self.code
  19. def __getattr__(self, attr):
  20. if attr.startswith("visit_"):
  21. return empty
  22. else:
  23. raise AttributeError()
  24. def visit_start(self, tree):
  25. for t in tree.get_tail():
  26. self.visit(t)
  27. def visit_include_files(self, tree):
  28. self.includes.append('include %s' % tree.get_children("STRVALUE")[0].get_text())
  29. def visit_import(self, tree):
  30. url = tree.get_children("MV_URL")[0]
  31. target = tree.get_children("MODEL_ID")[0]
  32. #self.constructors.extend(["import_node", url.get_text(), target.get_text()])
  33. self.code += '\tElement %s\n' % target.get_text()
  34. self.code += '\t%s = import_node("%s")\n' % (target.get_text(), url.get_text())
  35. def visit_export(self, tree):
  36. url = tree.get_children("MV_URL")[0]
  37. target = tree.get_children("MODEL_ID")[0]
  38. #self.constructors.extend(["export_node", target.get_text(), url.get_text()])
  39. self.code += '\texport_node(%s, "%s")\n' % (target.get_text(), url.get_text())
  40. def visit_model(self, tree):
  41. children = tree.get_children("MODEL_ID")
  42. model_type = children[0].get_text()
  43. model_name = children[-1].get_text()
  44. #self.constructors.extend(["instantiate_model", model_type, model_name])
  45. self.code += "\tElement %s\n" % model_name
  46. self.code += '\t%s = instantiate_model("%s")\n' % (model_name, model_type)
  47. self.current_model = model_name
  48. self.names = set()
  49. for element in tree.get_children("model_element"):
  50. self.visit(element)
  51. def visit_model_element(self, tree):
  52. children = tree.get_children("MODEL_ID")
  53. element_type = children[0].get_text()
  54. if len(children) == 2 or len(children) == 4:
  55. element_name = children[1].get_text()
  56. else:
  57. element_name = "__%s" % self.free_id
  58. self.free_id += 1
  59. if element_name in self.names:
  60. raise Exception("Redefinition of element %s" % element_name)
  61. if len(children) > 2:
  62. # So we have a source and target; but aren't sure which is which, because the name is optional!
  63. source_name = children[-2].get_text()
  64. target_name = children[-1].get_text()
  65. if source_name not in self.names:
  66. raise Exception("Source of link %s unknown: %s" % (element_name, source_name))
  67. if target_name not in self.names:
  68. raise Exception("Target of link %s unknown: %s" % (element_name, target_name))
  69. #self.constructors.extend(["instantiate_link", self.current_model, element_type, element_name, source_name, target_name])
  70. self.code += '\tinstantiate_link(%s, "%s", "%s", "%s", "%s")\n' % (self.current_model, element_type, element_name, source_name, target_name)
  71. else:
  72. #self.constructors.extend(["instantiate_node", self.current_model, element_type, element_name])
  73. self.code += '\tinstantiate_node(%s, "%s", "%s")\n' % (self.current_model, element_type, element_name)
  74. self.names.add(element_name)
  75. self.current_element.append(element_name)
  76. if tree.get_children("inheritance"):
  77. self.visit(tree.get_children("inheritance")[0])
  78. for attr in tree.get_children("model_attribute"):
  79. self.visit(attr)
  80. self.current_element.pop()
  81. return element_name
  82. def visit_inheritance(self, tree):
  83. for token in tree.get_children("MODEL_ID"):
  84. superclass = token.get_text()
  85. if superclass not in self.names:
  86. raise Exception("Superclass %s is undefined" % superclass)
  87. #self.constructors.extend(["instantiate_link", self.current_model, "Inheritance", "%s_inherits_from_%s" % (self.current_element[-1], superclass), self.current_element[-1], superclass])
  88. self.code += '\tinstantiate_link(%s, "Inheritance", "%s_inherits_from_%s", "%s", "%s")\n' % (self.current_model, self.current_element[-1], superclass, self.current_element[-1], superclass)
  89. self.names.add("%s_inherits_from_%s" % (self.current_element[-1], superclass))
  90. def visit_model_attribute(self, tree):
  91. children = tree.get_children("MODEL_ID")
  92. is_definition = bool(tree.get_children("COLON"))
  93. is_assign = bool(tree.get_children("model_attr_instance"))
  94. is_nested = bool(tree.get_children("model_element"))
  95. if is_definition:
  96. attr_name = children[0].get_text()
  97. attr_optional = len(tree.get_children("OPTIONAL")) > 0
  98. attr_type = children[1].get_text()
  99. #self.constructors.extend(["model_define_attribute", self.current_model, self.current_element[-1], attr_name, attr_optional, attr_type])
  100. self.code += '\tmodel_define_attribute(%s, "%s", "%s", %s, "%s")\n' % (self.current_model, self.current_element[-1], attr_name, attr_optional, attr_type)
  101. full_attribute_name = self.current_element[-1] + "_" + attr_name
  102. if is_assign:
  103. # There are also some attributes to set!
  104. self.current_element.append(full_attribute_name)
  105. for f in tree.get_children("model_attr_instance"):
  106. self.visit(f)
  107. self.current_element.pop()
  108. elif is_assign:
  109. self.visit(tree.get_children("model_attr_instance")[0])
  110. elif is_nested:
  111. if tree.get_children("MODEL_ID"):
  112. contains_link = tree.get_children("MODEL_ID")[0].get_text()
  113. else:
  114. contains_link = ""
  115. entry = self.visit(tree.get_children("model_element")[0])
  116. #self.constructors.extend(["instantiate_link", self.current_model, contains_link, "__%s" % self.free_id, self.current_element[-1], entry])
  117. self.code += '\tinstantiate_link(%s, %s, "__%s", %s, %s)\n' % (self.current_model, contains_link, self.free_id, self.current_element[-1], entry)
  118. self.names.add("__%s" % self.free_id)
  119. self.free_id += 1
  120. def visit_model_attr_instance(self, tree):
  121. def constructors_compile(code):
  122. code_fragments = code.split("\n")
  123. code_fragments = [i for i in code_fragments if i.strip() != ""]
  124. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  125. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  126. code_fragments = self.includes + [i[initial_tabs:] for i in code_fragments]
  127. code = "\n".join(code_fragments)
  128. code += "\n"
  129. with open(".code.alc", 'w') as f:
  130. f.write(code)
  131. f.flush()
  132. directory = os.path.realpath(__file__).rsplit(os.sep, 1)[0]
  133. compiled = do_compile(".code.alc", directory + "/../grammars/actionlanguage.g", "CS")
  134. return compiled
  135. children = tree.get_children("MODEL_ID")
  136. attr_name = children[0].get_text()
  137. if tree.get_children("value"):
  138. # Value attribute
  139. attr_value = tree.get_children("value")[0].get_tail()[0]
  140. if attr_value.head == "STRVALUE":
  141. attr_value = attr_value.get_text()[1:-1]
  142. elif attr_value.head == "TRUE":
  143. attr_value = True
  144. elif attr_value.head == "FALSE":
  145. attr_value = False
  146. elif attr_value.head == "DEC_NUMBER":
  147. attr_value = int(attr_value.get_text())
  148. elif attr_value.head == "FLOAT_NUMBER":
  149. attr_value = float(attr_value.get_text())
  150. else:
  151. raise Exception(attr_value.head)
  152. #self.constructors.extend(["instantiate_attribute", self.current_model, self.current_element[-1], attr_name, attr_value])
  153. self.code += '\tinstantiate_attribute(%s, "%s", "%s", %s)\n' % (self.current_model, self.current_element[-1], attr_name, attr_value)
  154. elif tree.get_children("DOLLAR"):
  155. # Coded attribute
  156. #self.constructors.extend(["instantiate_attribute_code", self.current_model, self.current_element[-1], attr_name])
  157. #self.constructors.extend(constructors_compile(tree.get_children("ANYTHING_EXCEPT_DOLLAR")[0].get_text()))
  158. code = tree.get_children("ANYTHING_EXCEPT_DOLLAR")[0].get_text()
  159. code_fragments = code.split("\n")
  160. code_fragments = [i for i in code_fragments if i.strip() != ""]
  161. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  162. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  163. code_fragments = [i[initial_tabs:] for i in code_fragments]
  164. code_fragments.append("")
  165. code = "\n".join(code_fragments)
  166. func_name = "__code__%s" % abs(hash(code))
  167. self.code += '\tinstantiate_attribute_code(%s, "%s", "%s", %s)\n' % (self.current_model, self.current_element[-1], attr_name, func_name)
  168. # Rewrite the name of the function to func_name
  169. prepend = code
  170. before, after = prepend.split("function ", 1)
  171. before = before + "function "
  172. after = "(" + after.split("(", 1)[1]
  173. prepend = before + func_name + after + "\n"
  174. # And prepend the actual code block
  175. self.code = prepend + self.code