od.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. from services import od
  2. from api import cd
  3. from services.bottom.V0 import Bottom
  4. from services.primitives.boolean_type import Boolean
  5. from services.primitives.integer_type import Integer
  6. from services.primitives.string_type import String
  7. from services.primitives.actioncode_type import ActionCode
  8. from uuid import UUID
  9. from typing import Optional
  10. from util.timer import Timer
  11. NEXT_ID = 0
  12. # Models map names to elements
  13. # This builds the inverse mapping, so we can quickly lookup the name of an element
  14. def build_name_mapping(state, m):
  15. mapping = {}
  16. bottom = Bottom(state)
  17. for name in bottom.read_keys(m):
  18. elements = bottom.read_outgoing_elements(m, name)
  19. if len(elements) > 1:
  20. print(f"Warning: more than one element with name '{name}'")
  21. mapping[elements[0]] = name
  22. return mapping
  23. class NoSuchSlotException(Exception):
  24. pass
  25. # Object Diagram API
  26. # Intended to replace the 'services.od.OD' class eventually
  27. class ODAPI:
  28. def __init__(self, state, m: UUID, mm: UUID):
  29. self.state = state
  30. self.bottom = Bottom(state)
  31. self.m = m
  32. self.mm = mm
  33. self.od = od.OD(mm, m, state)
  34. self.cdapi = cd.CDAPI(state, mm)
  35. self.create_boolean_value = self.od.create_boolean_value
  36. self.create_integer_value = self.od.create_integer_value
  37. self.create_string_value = self.od.create_string_value
  38. self.create_actioncode_value = self.od.create_actioncode_value
  39. self.__recompute_mappings()
  40. # Called after every change - makes querying faster but modifying slower
  41. def __recompute_mappings(self):
  42. self.m_obj_to_name = build_name_mapping(self.state, self.m)
  43. self.mm_obj_to_name = build_name_mapping(self.state, self.mm)
  44. self.type_to_objs = { type_name : set() for type_name in self.bottom.read_keys(self.mm)}
  45. for m_name in self.bottom.read_keys(self.m):
  46. m_element, = self.bottom.read_outgoing_elements(self.m, m_name)
  47. tm_element = self.get_type(m_element)
  48. if tm_element in self.mm_obj_to_name:
  49. tm_name = self.mm_obj_to_name[tm_element]
  50. # self.obj_to_type[m_name] = tm_name
  51. self.type_to_objs[tm_name].add(m_name)
  52. def get_value(self, obj: UUID):
  53. return od.read_primitive_value(self.bottom, obj, self.mm)[0]
  54. def get_target(self, link: UUID):
  55. return self.bottom.read_edge_target(link)
  56. def get_source(self, link: UUID):
  57. return self.bottom.read_edge_source(link)
  58. def get_slot(self, obj: UUID, attr_name: str):
  59. slot = self.od.get_slot(obj, attr_name)
  60. if slot == None:
  61. raise NoSuchSlotException(f"Object '{self.m_obj_to_name[obj]}' has no slot '{attr_name}'")
  62. return slot
  63. def get_slot_link(self, obj: UUID, attr_name: str):
  64. return self.od.get_slot_link(obj, attr_name)
  65. # Parameter 'include_subtypes': whether to include subtypes of the given association
  66. def get_outgoing(self, obj: UUID, assoc_name: str, include_subtypes=True):
  67. outgoing = self.bottom.read_outgoing_edges(obj)
  68. result = []
  69. for o in outgoing:
  70. try:
  71. type_of_outgoing_link = self.get_type_name(o)
  72. except:
  73. continue # OK, not all edges are typed
  74. if (include_subtypes and self.cdapi.is_subtype(super_type_name=assoc_name, sub_type_name=type_of_outgoing_link)
  75. or not include_subtypes and type_of_outgoing_link == assoc_name):
  76. result.append(o)
  77. return result
  78. # Parameter 'include_subtypes': whether to include subtypes of the given association
  79. def get_incoming(self, obj: UUID, assoc_name: str, include_subtypes=True):
  80. incoming = self.bottom.read_incoming_edges(obj)
  81. result = []
  82. for i in incoming:
  83. try:
  84. type_of_incoming_link = self.get_type_name(i)
  85. except:
  86. continue # OK, not all edges are typed
  87. if (include_subtypes and self.cdapi.is_subtype(super_type_name=assoc_name, sub_type_name=type_of_incoming_link)
  88. or not include_subtypes and type_of_incoming_link == assoc_name):
  89. result.append(i)
  90. return result
  91. # Returns list of tuples (name, obj)
  92. def get_all_instances(self, type_name: str, include_subtypes=True):
  93. if include_subtypes:
  94. all_types = self.cdapi.transitive_sub_types[type_name]
  95. else:
  96. all_types = set([type_name])
  97. obj_names = [obj_name for type_name in all_types for obj_name in self.type_to_objs[type_name]]
  98. return [(obj_name, self.bottom.read_outgoing_elements(self.m, obj_name)[0]) for obj_name in obj_names]
  99. def get_type(self, obj: UUID):
  100. types = self.bottom.read_outgoing_elements(obj, "Morphism")
  101. if len(types) != 1:
  102. raise Exception(f"Expected obj to have 1 type, instead got {len(types)} types.")
  103. return types[0]
  104. def get_name(self, obj: UUID):
  105. if obj in self.m_obj_to_name:
  106. return self.m_obj_to_name[obj]
  107. elif obj in self.mm_obj_to_name:
  108. return self.mm_obj_to_name[obj]
  109. else:
  110. raise Exception(f"Couldn't find name of {obj} - are you sure it exists in the (meta-)model?")
  111. def get(self, name: str):
  112. results = self.bottom.read_outgoing_elements(self.m, name)
  113. if len(results) == 1:
  114. return results[0]
  115. elif len(results) >= 2:
  116. raise Exception("this should never happen")
  117. else:
  118. raise Exception(f"No such element in model: '{name}'")
  119. def get_type_name(self, obj: UUID):
  120. return self.get_name(self.get_type(obj))
  121. def is_instance(self, obj: UUID, type_name: str, include_subtypes=True):
  122. typ = self.cdapi.get_type(type_name)
  123. types = set(typ) if not include_subtypes else self.cdapi.transitive_sub_types[type_name]
  124. for type_of_obj in self.bottom.read_outgoing_elements(obj, "Morphism"):
  125. if type_of_obj in types:
  126. return True
  127. return False
  128. def delete(self, obj: UUID):
  129. self.bottom.delete_element(obj)
  130. self.__recompute_mappings()
  131. # Does the class of the object have the given attribute?
  132. def has_slot(self, obj: UUID, attr_name: str):
  133. class_name = self.get_name(self.get_type(obj))
  134. return self.od.get_attr_link_name(class_name, attr_name) != None
  135. def get_slots(self, obj: UUID) -> list[str]:
  136. return [attr_name for attr_name, _ in self.od.get_slots(obj)]
  137. def get_slot_value(self, obj: UUID, attr_name: str):
  138. slot = self.get_slot(obj, attr_name)
  139. return self.get_value(slot)
  140. # does the given slot contain code?
  141. # this complements `get_slot_value` which will return code as a string
  142. def slot_has_code(self, obj: UUID, attr_name: str):
  143. slot = self.get_slot(obj, attr_name)
  144. return self.get_type_name(slot) == "ActionCode"
  145. # Returns the given default value if the slot does not exist on the object.
  146. # The attribute must exist in the object's class, or an exception will be thrown.
  147. # The slot may not exist however, if the attribute is defined as 'optional' in the class.
  148. def get_slot_value_default(self, obj: UUID, attr_name: str, default: any):
  149. try:
  150. return self.get_slot_value(obj, attr_name)
  151. except NoSuchSlotException:
  152. return default
  153. # create or update slot value
  154. def set_slot_value(self, obj: UUID, attr_name: str, new_value: any, is_code=False):
  155. obj_name = self.get_name(obj)
  156. link_name = f"{obj_name}_{attr_name}"
  157. target_name = f"{obj_name}.{attr_name}"
  158. old_slot_link = self.get_slot_link(obj, attr_name)
  159. if old_slot_link != None:
  160. old_target = self.get_target(old_slot_link)
  161. # if old_target != None:
  162. self.bottom.delete_element(old_target) # this also deletes the slot-link
  163. new_target = self.create_primitive_value(target_name, new_value, is_code)
  164. slot_type = self.cdapi.find_attribute_type(self.get_type_name(obj), attr_name)
  165. new_link = self.od._create_link(link_name, slot_type, obj, new_target)
  166. self.__recompute_mappings()
  167. def create_primitive_value(self, name: str, value: any, is_code=False):
  168. # watch out: in Python, 'bool' is subtype of 'int'
  169. # so we must check for 'bool' first
  170. if isinstance(value, bool):
  171. tgt = self.create_boolean_value(name, value)
  172. elif isinstance(value, int):
  173. tgt = self.create_integer_value(name, value)
  174. elif isinstance(value, str):
  175. if is_code:
  176. tgt = self.create_actioncode_value(name, value)
  177. else:
  178. tgt = self.create_string_value(name, value)
  179. else:
  180. raise Exception("Unimplemented type "+value)
  181. self.__recompute_mappings()
  182. return tgt
  183. def overwrite_primitive_value(self, name: str, value: any, is_code=False):
  184. referred_model = UUID(self.bottom.read_value(self.get(name)))
  185. to_overwrite_type = self.get_type_name(self.get(name))
  186. # watch out: in Python, 'bool' is subtype of 'int'
  187. # so we must check for 'bool' first
  188. if isinstance(value, bool):
  189. if to_overwrite_type != "Boolean":
  190. raise Exception(f"Cannot assign boolean value '{value}' to value of type {to_overwrite_type}.")
  191. Boolean(referred_model, self.state).create(value)
  192. elif isinstance(value, int):
  193. if to_overwrite_type != "Integer":
  194. raise Exception(f"Cannot assign integer value '{value}' to value of type {to_overwrite_type}.")
  195. Integer(referred_model, self.state).create(value)
  196. elif isinstance(value, str):
  197. if is_code:
  198. if to_overwrite_type != "ActionCode":
  199. raise Exception(f"Cannot assign code to value of type {to_overwrite_type}.")
  200. ActionCode(referred_model, self.state).create(value)
  201. else:
  202. if to_overwrite_type != "String":
  203. raise Exception(f"Cannot assign string value '{value}' to value of type {to_overwrite_type}.")
  204. String(referred_model, self.state).create(value)
  205. else:
  206. raise Exception("Unimplemented type "+value)
  207. def create_link(self, link_name: Optional[str], assoc_name: str, src: UUID, tgt: UUID):
  208. global NEXT_ID
  209. types = self.bottom.read_outgoing_elements(self.mm, assoc_name)
  210. if len(types) == 0:
  211. raise Exception(f"No such association: '{assoc_name}'")
  212. elif len(types) >= 2:
  213. raise Exception(f"More than one association exists with name '{assoc_name}' - this means the MM is invalid.")
  214. typ = types[0]
  215. if link_name == None:
  216. link_name = f"__{assoc_name}{NEXT_ID}"
  217. NEXT_ID += 1
  218. link_id = self.od._create_link(link_name, typ, src, tgt)
  219. self.__recompute_mappings()
  220. return link_id
  221. def create_object(self, object_name: Optional[str], class_name: str):
  222. obj = self.od.create_object(object_name, class_name)
  223. self.__recompute_mappings()
  224. return obj
  225. # internal use
  226. # Get API methods as bound functions, to pass as globals to 'eval'
  227. # Readonly version is used for:
  228. # - Conformance checking
  229. # - Pattern matching (LHS/NAC of rule)
  230. def bind_api_readonly(odapi):
  231. funcs = {
  232. 'read_value': odapi.state.read_value,
  233. 'get': odapi.get,
  234. 'get_value': odapi.get_value,
  235. 'get_target': odapi.get_target,
  236. 'get_source': odapi.get_source,
  237. 'get_slot': odapi.get_slot,
  238. 'get_slot_value': odapi.get_slot_value,
  239. 'get_slot_value_default': odapi.get_slot_value_default,
  240. 'get_all_instances': odapi.get_all_instances,
  241. 'get_name': odapi.get_name,
  242. 'get_type_name': odapi.get_type_name,
  243. 'get_outgoing': odapi.get_outgoing,
  244. 'get_incoming': odapi.get_incoming,
  245. 'has_slot': odapi.has_slot,
  246. }
  247. return funcs
  248. # internal use
  249. # Get API methods as bound functions, to pass as globals to 'eval'
  250. # Read/write version is used for:
  251. # - Graph rewriting (RHS of rule)
  252. def bind_api(odapi):
  253. funcs = {
  254. **bind_api_readonly(odapi),
  255. 'create_object': odapi.create_object,
  256. 'create_link': odapi.create_link,
  257. 'delete': odapi.delete,
  258. 'set_slot_value': odapi.set_slot_value,
  259. }
  260. return funcs