parser.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # Parser for Object Diagrams textual concrete syntax
  2. from lark import Lark, logger, Transformer
  3. from lark.indenter import Indenter
  4. from api.od import ODAPI
  5. from services.scd import SCD
  6. from concrete_syntax.common import _Code
  7. from uuid import UUID
  8. grammar = r"""
  9. %import common.WS
  10. %ignore WS
  11. %ignore COMMENT
  12. ?start: object*
  13. IDENTIFIER: /[A-Za-z_][A-Za-z_0-9]*/
  14. COMMENT: /#[^\n]*/
  15. literal: INT
  16. | STR
  17. | BOOL
  18. | CODE
  19. | INDENTED_CODE
  20. INT: /[0-9]+/
  21. STR: /"[^"]*"/
  22. | /'[^']*'/
  23. BOOL: "True" | "False"
  24. CODE: /`[^`]*`/
  25. INDENTED_CODE: /```[^`]*```/
  26. type_name: IDENTIFIER
  27. # name (optional) type
  28. object: [IDENTIFIER] ":" type_name [link_spec | rev_link_spec] ["{" slot* "}"]
  29. link_spec: "(" IDENTIFIER "->" IDENTIFIER ")"
  30. rev_link_spec: "(" IDENTIFIER "<-" IDENTIFIER ")"
  31. slot: IDENTIFIER "=" literal ";"
  32. """
  33. parser = Lark(grammar, parser='lalr', propagate_positions=True)
  34. class DefaultNameGenerator:
  35. def __init__(self):
  36. self.counter = 0
  37. def __call__(self, type_name):
  38. name = f"__{type_name}_{self.counter}"
  39. self.counter += 1
  40. return name
  41. # given a concrete syntax text string, and a meta-model, parses the CS
  42. # Parameter 'type_transform' is useful for adding prefixes to the type names, when parsing a model and pretending it is an instance of a prefixed meta-model.
  43. def parse_od(state,
  44. m_text, # text to parse
  45. mm, # meta-model of model that will be parsed. The meta-model must already have been parsed.
  46. type_transform=lambda type_name: type_name,
  47. name_generator=DefaultNameGenerator(), # exception to raise if anonymous (nameless) object/link occurs in the model. Main reason for this is to forbid them in LHS of transformation rules.
  48. ):
  49. tree = parser.parse(m_text)
  50. m = state.create_node()
  51. od = ODAPI(state, m, mm)
  52. primitive_types = {
  53. type_name : UUID(state.read_value(state.read_dict(state.read_root(), type_name)))
  54. for type_name in ["Integer", "String", "Boolean", "ActionCode"]
  55. }
  56. class T(Transformer):
  57. def __init__(self, visit_tokens):
  58. super().__init__(visit_tokens)
  59. def IDENTIFIER(self, token):
  60. return (str(token), token.line)
  61. def INT(self, token):
  62. return (int(token), token.line)
  63. def BOOL(self, token):
  64. return (token == "True", token.line)
  65. def STR(self, token):
  66. return (str(token[1:-1]), token.line) # strip the "" or ''
  67. def CODE(self, token):
  68. return (_Code(str(token[1:-1])), token.line) # strip the ``
  69. def INDENTED_CODE(self, token):
  70. skip = 4 # strip the ``` and the following newline character
  71. space_count = 0
  72. while token[skip+space_count] == " ":
  73. space_count += 1
  74. lines = token.split('\n')[1:-1]
  75. for line in lines:
  76. if len(line) >= space_count and line[0:space_count] != ' '*space_count:
  77. raise Exception("wrong indentation of INDENTED_CODE")
  78. unindented_lines = [l[space_count:] for l in lines]
  79. return (_Code('\n'.join(unindented_lines)), token.line)
  80. def literal(self, el):
  81. return el[0]
  82. def link_spec(self, el):
  83. [(src, src_line), (tgt, _)] = el
  84. return (src, tgt, src_line)
  85. def rev_link_spec(self, el):
  86. [(tgt, tgt_line), (src, _)] = el # <-- reversed :)
  87. return (src, tgt, tgt_line)
  88. def type_name(self, el):
  89. type_name, line = el[0]
  90. if type_name in primitive_types:
  91. return (type_name, line)
  92. else:
  93. return (type_transform(type_name), line)
  94. def slot(self, el):
  95. [(attr_name, line), (value, _)] = el
  96. return (attr_name, value, line)
  97. def object(self, el):
  98. [obj, (type_name, line), link] = el[0:3]
  99. slots = el[3:]
  100. try:
  101. if obj != None:
  102. (obj_name, _) = obj
  103. else:
  104. # anonymous object - auto-generate a name
  105. obj_name = name_generator(type_name)
  106. if state.read_dict(m, obj_name) != None:
  107. msg = f"Element '{obj_name}:{type_name}': name '{obj_name}' already in use."
  108. raise Exception(msg + " Names must be unique")
  109. # print(msg + " Ignoring.")
  110. return
  111. if link == None:
  112. obj_node = od.create_object(obj_name, type_name)
  113. else:
  114. (src, tgt, _) = link
  115. if tgt in primitive_types:
  116. if state.read_dict(m, tgt) == None:
  117. scd = SCD(m, state)
  118. scd.create_model_ref(tgt, primitive_types[tgt])
  119. src_obj = od.get(src)
  120. tgt_obj = od.get(tgt)
  121. obj_node = od.create_link(obj_name, type_name, src_obj, tgt_obj)
  122. # Create slots
  123. for attr_name, value, line in slots:
  124. if isinstance(value, _Code):
  125. od.set_slot_value(obj_node, attr_name, value.code, is_code=True)
  126. else:
  127. od.set_slot_value(obj_node, attr_name, value)
  128. return obj_name
  129. except Exception as e:
  130. # raising a *new* exception (instead of adding a note to the existing exception) because Lark will also raise a new exception, and ignore our note:
  131. raise Exception(f"at line {line}:\n " + m_text.split('\n')[line-1] + "\n"+ str(e)) from e
  132. t = T(visit_tokens=True).transform(tree)
  133. return m