od.py 13 KB

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