loader.py 3.0 KB

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