model_visitor.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from visitor import Visitor
  2. def jsonstr(s):
  3. return '"%s"' % s
  4. class ModelVisitor(Visitor):
  5. def __init__(self, args):
  6. Visitor.__init__(self, args)
  7. self.constructors = []
  8. self.free_id = 0
  9. self.name_maps = {}
  10. self.current_model = None
  11. self.current_element = None
  12. def dump(self):
  13. return self.constructors
  14. def visit_start(self, tree):
  15. for t in tree.get_tail():
  16. self.visit(t)
  17. def visit_import(self, tree):
  18. url = tree.get_children("MV_URL")[0]
  19. target = tree.get_children("MODEL_ID")[0]
  20. self.constructors.extend(['"import_node"', jsonstr(url.get_text()), jsonstr(target.get_text())])
  21. def visit_model(self, tree):
  22. children = tree.get_children("MODEL_ID")
  23. model_type = children[0].get_text()
  24. model_name = children[1].get_text()
  25. self.constructors.extend(['"instantiate_model"', jsonstr(model_type), jsonstr(model_name)])
  26. self.current_model = model_name
  27. for element in tree.get_children("model_element"):
  28. self.visit(element)
  29. def visit_model_element(self, tree):
  30. children = tree.get_children("MODEL_ID")
  31. element_type = children[0].get_text()
  32. element_name = children[1].get_text()
  33. if len(children) == 4:
  34. source_name = children[2].get_text()
  35. target_name = children[3].get_text()
  36. self.constructors.extend(['"instantiate_link"', jsonstr(self.current_model), jsonstr(element_type), jsonstr(element_name), jsonstr(source_name), jsonstr(target_name)])
  37. else:
  38. self.constructors.extend(['"instantiate_node"', jsonstr(self.current_model), jsonstr(element_type), jsonstr(element_name)])
  39. self.current_element = element_name
  40. for attr in tree.get_children("model_attribute"):
  41. self.visit(attr)
  42. def visit_model_attribute(self, tree):
  43. children = tree.get_children("MODEL_ID")
  44. is_definition = bool(tree.get_children("COLON"))
  45. if is_definition:
  46. attr_name = children[0].get_text()
  47. attr_type = children[1].get_text()
  48. self.constructors.extend(['"instantiate_link"', jsonstr("Association"), jsonstr(self.current_element + "_" + attr_name), jsonstr(self.current_element), jsonstr(attr_type)])
  49. self.constructors.extend(['"instantiate_attribute"', jsonstr(self.current_element + "_" + attr_name), jsonstr("name"), jsonstr(attr_name)])
  50. else:
  51. attr_name = children[0].get_text()
  52. attr_value = children[1]
  53. self.constructors.extend(['"instantiate_attribute"', jsonstr(self.current_element), jsonstr(attr_name), jsonstr(attr_value.get_text()) if attr_value.head == "STRVALUE" else attr_value.get_text()])