rewriter.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. # Things you can do:
  2. # - Create/delete objects, associations, attributes
  3. # - Change attribute values
  4. # - ? that's it?
  5. import re
  6. from uuid import UUID
  7. from api.od import ODAPI, bind_api
  8. from services.bottom.V0 import Bottom
  9. from transformation import ramify
  10. from services import od
  11. from services.primitives.string_type import String
  12. from services.primitives.actioncode_type import ActionCode
  13. from services.primitives.integer_type import Integer
  14. from util.eval import exec_then_eval, simply_exec
  15. identifier_regex_pattern = '[_A-Za-z][._A-Za-z0-9]*'
  16. identifier_regex = re.compile(identifier_regex_pattern)
  17. class TryAgainNextRound(Exception):
  18. pass
  19. # Rewrite is performed in-place (modifying `host_m`)
  20. def rewrite(state,
  21. rhs_m: UUID, # RHS-pattern
  22. pattern_mm: UUID, # meta-model of both patterns (typically the RAMified host_mm)
  23. lhs_match: dict, # a match, morphism, from lhs_m to host_m (mapping pattern name -> host name), typically found by the 'match_od'-function.
  24. host_m: UUID, # host model
  25. host_mm: UUID, # host meta-model
  26. eval_context={}, # optional: additional variables/functions to be available while executing condition-code. These will be seen as global variables.
  27. ):
  28. bottom = Bottom(state)
  29. # Need to come up with a new, unique name when creating new element in host-model:
  30. def first_available_name(suggested_name: str):
  31. if len(bottom.read_outgoing_elements(host_m, suggested_name)) == 0:
  32. return suggested_name # already unique :)
  33. i = 0
  34. while True:
  35. name = suggested_name + str(i)
  36. if len(bottom.read_outgoing_elements(host_m, name)) == 0:
  37. return name # found unique name
  38. i += 1
  39. # function that can be called from within RHS action code
  40. def matched_callback(pattern_name: str):
  41. host_name = lhs_match[pattern_name]
  42. return bottom.read_outgoing_elements(host_m, host_name)[0]
  43. scd_metamodel_id = state.read_dict(state.read_root(), "SCD")
  44. scd_metamodel = UUID(state.read_value(scd_metamodel_id))
  45. class_type = od.get_scd_mm_class_node(bottom)
  46. attr_link_type = od.get_scd_mm_attributelink_node(bottom)
  47. assoc_type = od.get_scd_mm_assoc_node(bottom)
  48. actioncode_type = od.get_scd_mm_actioncode_node(bottom)
  49. modelref_type = od.get_scd_mm_modelref_node(bottom)
  50. # To be replaced by ODAPI (below)
  51. host_od = od.OD(host_mm, host_m, bottom.state)
  52. rhs_od = od.OD(pattern_mm, rhs_m, bottom.state)
  53. host_odapi = ODAPI(state, host_m, host_mm)
  54. host_mm_odapi = ODAPI(state, host_mm, scd_metamodel)
  55. rhs_odapi = ODAPI(state, rhs_m, pattern_mm)
  56. rhs_mm_odapi = ODAPI(state, pattern_mm, scd_metamodel)
  57. lhs_keys = lhs_match.keys()
  58. rhs_keys = set(k for k in bottom.read_keys(rhs_m)
  59. # extremely dirty - should think of a better way
  60. if "GlobalCondition" not in k and not k.endswith("_condition") and not k.endswith(".condition")
  61. and (not k.endswith("_name") or k.endswith("RAM_name")) and (not k.endswith(".name")))
  62. # See which keys were ignored by the rewriter:
  63. # print('filtered out:', set(k for k in bottom.read_keys(rhs_m) if k.endswith(".name") or k.endswith("_name")))
  64. common = lhs_keys & rhs_keys
  65. to_delete = lhs_keys - common
  66. to_create = rhs_keys - common
  67. # print("to delete:", to_delete)
  68. # print("to create:", to_create)
  69. # to be grown
  70. rhs_match = { name : lhs_match[name] for name in common }
  71. bound_api = bind_api(host_odapi)
  72. original_delete = bound_api["delete"]
  73. def wrapped_delete(obj):
  74. not_allowed_to_delete = { host_odapi.get(host_name): pattern_name for pattern_name, host_name in rhs_match.items() }
  75. if obj in not_allowed_to_delete:
  76. pattern_name = not_allowed_to_delete[obj]
  77. raise Exception(f"\n\nYou're trying to delete the element that was matched with the RHS-element '{pattern_name}'. This is not allowed! You're allowed to delete anything BUT NOT elements matched with your RHS-pattern. Instead, simply remove the element '{pattern_name}' from your RHS, if you want to delete it.")
  78. return original_delete(obj)
  79. bound_api["delete"] = wrapped_delete
  80. builtin = {
  81. **bound_api,
  82. 'matched': matched_callback,
  83. 'odapi': host_odapi,
  84. }
  85. for key in eval_context:
  86. if key in builtin:
  87. print(f"WARNING: custom global '{key}' overrides pre-defined API function. Consider renaming it.")
  88. eval_globals = {
  89. **builtin,
  90. **eval_context,
  91. }
  92. # 1. Perform creations - in the right order!
  93. remaining_to_create = list(to_create)
  94. while len(remaining_to_create) > 0:
  95. next_round = []
  96. for rhs_name in remaining_to_create:
  97. # Determine the type of the thing to create
  98. rhs_obj = rhs_odapi.get(rhs_name)
  99. # what to name our new object?
  100. try:
  101. name_expr = rhs_odapi.get_slot_value(rhs_obj, "name")
  102. except:
  103. name_expr = f'"{rhs_name}"' # <- if the 'name' slot doesnt exist, use the pattern element name
  104. suggested_name = exec_then_eval(name_expr, _globals=eval_globals)
  105. if not identifier_regex.match(suggested_name):
  106. raise Exception(f"In the RHS pattern element '{rhs_name}', the following name-expression:\n {name_expr}\nproduced the name:\n '{suggested_name}'\nwhich contains illegal characters.\nNames should match the following regex: {identifier_regex_pattern}")
  107. rhs_type = rhs_odapi.get_type(rhs_obj)
  108. host_type = ramify.get_original_type(bottom, rhs_type)
  109. # for debugging:
  110. if host_type != None:
  111. host_type_name = host_odapi.get_name(host_type)
  112. else:
  113. host_type_name = ""
  114. def get_src_tgt():
  115. src = rhs_odapi.get_source(rhs_obj)
  116. tgt = rhs_odapi.get_target(rhs_obj)
  117. src_name = rhs_odapi.get_name(src)
  118. tgt_name = rhs_odapi.get_name(tgt)
  119. try:
  120. host_src_name = rhs_match[src_name]
  121. host_tgt_name = rhs_match[tgt_name]
  122. except KeyError:
  123. # some creations (e.g., edges) depend on other creations
  124. raise TryAgainNextRound()
  125. host_src = host_odapi.get(host_src_name)
  126. host_tgt = host_odapi.get(host_tgt_name)
  127. return (host_src_name, host_tgt_name, host_src, host_tgt)
  128. try:
  129. if od.is_typed_by(bottom, rhs_type, class_type):
  130. obj_name = first_available_name(suggested_name)
  131. host_od._create_object(obj_name, host_type)
  132. host_odapi.recompute_mappings()
  133. rhs_match[rhs_name] = obj_name
  134. elif od.is_typed_by(bottom, rhs_type, assoc_type):
  135. _, _, host_src, host_tgt = get_src_tgt()
  136. link_name = first_available_name(suggested_name)
  137. host_od._create_link(link_name, host_type, host_src, host_tgt)
  138. host_odapi.recompute_mappings()
  139. rhs_match[rhs_name] = link_name
  140. elif od.is_typed_by(bottom, rhs_type, attr_link_type):
  141. host_src_name, _, host_src, host_tgt = get_src_tgt()
  142. host_attr_link = ramify.get_original_type(bottom, rhs_type)
  143. host_attr_name = host_mm_odapi.get_slot_value(host_attr_link, "name")
  144. link_name = f"{host_src_name}_{host_attr_name}" # must follow naming convention here
  145. host_od._create_link(link_name, host_type, host_src, host_tgt)
  146. host_odapi.recompute_mappings()
  147. rhs_match[rhs_name] = link_name
  148. elif rhs_type == rhs_mm_odapi.get("ActionCode"):
  149. # If we encounter ActionCode in our RHS, we assume that the code computes the value of an attribute...
  150. # This will be the *value* of an attribute. The attribute-link (connecting an object to the attribute) will be created as an edge later.
  151. # Problem: attributes must follow the naming pattern '<obj_name>.<attr_name>'
  152. # So we must know the host-object-name, and the host-attribute-name.
  153. # However, all we have access to here is the name of the attribute in the RHS.
  154. # We cannot even see the link to the RHS-object.
  155. # But, assuming the RHS-attribute is also named '<RAMified_obj_name>.<RAMified_attr_name>', we can:
  156. rhs_src_name, rhs_attr_name = rhs_name.split('.')
  157. try:
  158. host_src_name = rhs_match[rhs_src_name]
  159. except KeyError:
  160. # unmet dependency - object to which attribute belongs not created yet
  161. raise TryAgainNextRound()
  162. rhs_src_type = rhs_odapi.get_type(rhs_odapi.get(rhs_src_name))
  163. rhs_src_type_name = rhs_mm_odapi.get_name(rhs_src_type)
  164. rhs_attr_link_name = f"{rhs_src_type_name}_{rhs_attr_name}"
  165. rhs_attr_link = rhs_mm_odapi.get(rhs_attr_link_name)
  166. host_attr_link = ramify.get_original_type(bottom, rhs_attr_link)
  167. host_attr_name = host_mm_odapi.get_slot_value(host_attr_link, "name")
  168. val_name = f"{host_src_name}.{host_attr_name}"
  169. python_expr = ActionCode(UUID(bottom.read_value(rhs_obj)), bottom.state).read()
  170. result = exec_then_eval(python_expr, _globals=eval_globals)
  171. host_odapi.create_primitive_value(val_name, result, is_code=False)
  172. rhs_match[rhs_name] = val_name
  173. else:
  174. rhs_type_name = rhs_odapi.get_name(rhs_type)
  175. raise Exception(f"Host type {host_type_name} of pattern element '{rhs_name}:{rhs_type_name}' is not a class, association or attribute link. Don't know what to do with it :(")
  176. except TryAgainNextRound:
  177. next_round.append(rhs_name)
  178. if len(next_round) == len(remaining_to_create):
  179. raise Exception("Creation of objects did not make any progress - there must be some kind of cyclic dependency?!")
  180. remaining_to_create = next_round
  181. # 2. Perform updates (only on values)
  182. for common_name in common:
  183. host_obj_name = rhs_match[common_name]
  184. host_obj = host_odapi.get(host_obj_name)
  185. host_type = host_odapi.get_type(host_obj)
  186. if od.is_typed_by(bottom, host_type, class_type):
  187. # nothing to do
  188. pass
  189. elif od.is_typed_by(bottom, host_type, assoc_type):
  190. # nothing to do
  191. pass
  192. elif od.is_typed_by(bottom, host_type, attr_link_type):
  193. # nothing to do
  194. pass
  195. elif od.is_typed_by(bottom, host_type, modelref_type):
  196. rhs_obj = rhs_odapi.get(common_name)
  197. python_expr = ActionCode(UUID(bottom.read_value(rhs_obj)), bottom.state).read()
  198. result = exec_then_eval(python_expr,
  199. _globals=eval_globals,
  200. _locals={'this': host_obj}) # 'this' can be used to read the previous value of the slot
  201. # print("EVAL", common_name, python_expr, "RESULT", result, host_obj_name)
  202. try:
  203. host_odapi.overwrite_primitive_value(host_obj_name, result, is_code=False)
  204. except Exception as e:
  205. e.add_note(f"while evaluating attribute {common_name}")
  206. raise
  207. else:
  208. msg = f"Don't know what to do with element '{common_name}' -> '{host_obj_name}:{host_type}')"
  209. # print(msg)
  210. raise Exception(msg)
  211. # 3. Perform deletions
  212. # This way, action code can read from elements that are deleted...
  213. # Even better would be to not modify the model in-place, but use copy-on-write...
  214. for pattern_name_to_delete in to_delete:
  215. # For every name in `to_delete`, look up the name of the matched element in the host graph
  216. model_el_name_to_delete = lhs_match[pattern_name_to_delete]
  217. # print('deleting', model_el_name_to_delete)
  218. # Look up the matched element in the host graph
  219. els_to_delete = bottom.read_outgoing_elements(host_m, model_el_name_to_delete)
  220. if len(els_to_delete) == 0:
  221. # This can happen: if the SRC/TGT of a link was deleted, the link itself is also immediately deleted.
  222. # If we then try to delete the link, it is not found (already gone).
  223. # The most accurate way of handling this, would be to perform deletions in opposite order of creations (see the whole TryNextRound-mechanism above)
  224. # However I *think* it is also OK to simply ignore this case.
  225. pass
  226. elif len(els_to_delete) == 1:
  227. bottom.delete_element(els_to_delete[0])
  228. else:
  229. raise Exception("This should never happen!")
  230. # 4. Object-level actions
  231. # Iterate over the (now complete) mapping RHS -> Host
  232. for rhs_name, host_name in rhs_match.items():
  233. host_obj = host_odapi.get(host_name)
  234. rhs_obj = rhs_odapi.get(rhs_name)
  235. rhs_type = rhs_odapi.get_type(rhs_obj)
  236. rhs_type_of_type = rhs_mm_odapi.get_type(rhs_type)
  237. rhs_type_of_type_name = rhs_mm_odapi.get_name(rhs_type_of_type)
  238. if rhs_mm_odapi.cdapi.is_subtype(super_type_name="Class", sub_type_name=rhs_type_of_type_name):
  239. # rhs_obj is an object or link (because association is subtype of class)
  240. python_code = rhs_odapi.get_slot_value_default(rhs_obj, "condition", default="")
  241. simply_exec(python_code,
  242. _globals=eval_globals,
  243. _locals={'this': host_obj})
  244. # 5. Execute global actions
  245. for cond_name, cond in rhs_odapi.get_all_instances("GlobalCondition"):
  246. python_code = rhs_odapi.get_slot_value(cond, "condition")
  247. simply_exec(python_code, _globals=eval_globals)
  248. return rhs_match