model_bootstrap_visitor.py 9.6 KB

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