loader.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import os.path
  2. from framework.conformance import Conformance, render_conformance_check_result
  3. from concrete_syntax.textual_od import parser
  4. from transformation.rule import Rule
  5. # parse model and check conformance
  6. def parse_and_check(state, m_cs, mm, descr: str, check_conformance=True):
  7. try:
  8. m = parser.parse_od(
  9. state,
  10. m_text=m_cs,
  11. mm=mm,
  12. )
  13. except Exception as e:
  14. e.add_note("While parsing model " + descr)
  15. raise
  16. try:
  17. if check_conformance:
  18. conf = Conformance(state, m, mm)
  19. errors = conf.check_nominal()
  20. if len(errors) > 0:
  21. print(render_conformance_check_result(errors))
  22. except Exception as e:
  23. e.add_note("In model " + descr)
  24. raise
  25. return m
  26. # get file contents as string
  27. def read_file(filename):
  28. with open(filename) as file:
  29. return file.read()
  30. KINDS = ["nac", "lhs", "rhs"]
  31. # load model transformation rules
  32. def load_rules(state, get_filename, rt_mm_ramified, rule_names, check_conformance=True):
  33. rules = {}
  34. files_read = []
  35. for rule_name in rule_names:
  36. rule = {}
  37. def parse(kind):
  38. filename = get_filename(rule_name, kind)
  39. descr = "'"+filename+"'"
  40. if kind == "nac":
  41. suffix = ""
  42. nacs = []
  43. try:
  44. while True:
  45. base, ext = os.path.splitext(filename)
  46. processed_filename = base+suffix+ext
  47. nac = parse_and_check(state, read_file(processed_filename), rt_mm_ramified, descr, check_conformance)
  48. nacs.append(nac)
  49. suffix = "2" if suffix == "" else str(int(suffix)+1)
  50. files_read.append(processed_filename)
  51. except FileNotFoundError:
  52. if suffix == "":
  53. print(f"Warning: rule {rule_name} has no NAC ({filename} not found)")
  54. return nacs
  55. elif kind == "lhs" or kind == "rhs":
  56. try:
  57. m = parse_and_check(state, read_file(filename), rt_mm_ramified, descr, check_conformance)
  58. files_read.append(filename)
  59. return m
  60. except FileNotFoundError as e:
  61. print(f"Warning: using empty {kind} ({filename} not found)")
  62. # Use empty model as fill-in:
  63. return parse_and_check(
  64. state,
  65. "",
  66. rt_mm_ramified,
  67. descr="'"+filename+"'",
  68. check_conformance=check_conformance)
  69. rules[rule_name] = Rule(*(parse(kind) for kind in KINDS))
  70. print("Rules loaded:\n" + '\n'.join(files_read))
  71. return rules