compiler.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import cPickle as pickle
  2. import os
  3. import sys
  4. from grammar_compiler_visitor import GrammarCompilerVisitor
  5. from hutnparser import Parser, Tree
  6. from meta_grammar import Grammar
  7. global parsers
  8. parsers = {}
  9. def read(filename):
  10. with open(filename, 'r') as f:
  11. return f.read()
  12. def do_parse(inputfile, grammarfile):
  13. new_grammar = True
  14. picklefile = grammarfile + ".pickle"
  15. if grammarfile not in parsers:
  16. try:
  17. if os.path.getmtime(picklefile) > os.path.getmtime(grammarfile):
  18. # Pickle is more recent than grammarfile, so use it
  19. grammar = pickle.load(open(picklefile, 'rb'))
  20. new_grammar = False
  21. else:
  22. # Will be catched immediately
  23. raise Exception("Pickle is invalid!")
  24. except:
  25. result = parser = Parser(Grammar(), hide_implicit = True).parse(read(grammarfile))
  26. if result['status'] != Parser.Constants.Success:
  27. print 'not a valid grammar!'
  28. print result
  29. tree = result['tree']
  30. visitor = GrammarCompilerVisitor()
  31. structure = visitor.visit(tree)
  32. grammar = Grammar()
  33. grammar.rules = structure['rules']
  34. grammar.tokens = structure['tokens']
  35. pickle.dump(grammar, open(picklefile, 'wb'), pickle.HIGHEST_PROTOCOL)
  36. parsers[grammarfile] = grammar
  37. else:
  38. new_grammar = False
  39. grammar = parsers[grammarfile]
  40. picklefile = inputfile + ".pickle"
  41. try:
  42. if new_grammar:
  43. # Stop anyway, as the grammar is new
  44. raise Exception()
  45. if os.path.getmtime(picklefile) > os.path.getmtime(inputfile):
  46. # Pickle is more recent than inputfile, so use it
  47. result = pickle.load(open(picklefile, 'rb'))
  48. else:
  49. # Inputfile has changed
  50. raise Exception()
  51. except:
  52. result = Parser(grammar, line_position = True).parse(read(inputfile))
  53. if result['status'] != Parser.Constants.Success:
  54. msg = "%s:%s:%s: %s" % (inputfile, result["line"], result["column"], result["text"])
  55. raise Exception(msg)
  56. pickle.dump(result, open(picklefile, 'wb'), pickle.HIGHEST_PROTOCOL)
  57. return result
  58. def find_file(filename, include_paths):
  59. import os.path
  60. include_paths = ["."] + \
  61. [os.path.abspath(os.path.dirname(working_file))] + \
  62. [os.path.abspath("%s/../includes/" % (os.path.dirname(os.path.abspath(__file__))))] + \
  63. include_paths + \
  64. []
  65. attempts = []
  66. for include in include_paths:
  67. testfile = include + os.sep + filename
  68. if os.path.isfile(os.path.abspath(testfile)):
  69. return os.path.abspath(testfile)
  70. else:
  71. attempts.append(os.path.abspath(testfile))
  72. else:
  73. raise Exception("Could not resolve file %s. Tried: %s" % (filename, attempts))
  74. def do_compile(inputfile, grammarfile, visitors=[], include_paths = []):
  75. import os.path
  76. global working_file
  77. working_file = os.path.abspath(inputfile)
  78. result = do_parse(inputfile, grammarfile)
  79. error = result["status"] != Parser.Constants.Success
  80. if error:
  81. msg = "%s:%s:%s: %s" % (inputfile, result["line"], result["column"], result["text"])
  82. raise Exception(msg)
  83. else:
  84. for child in result["tree"].tail:
  85. child.inputfile = inputfile
  86. included = set()
  87. while True:
  88. for i, v in enumerate(result["tree"].tail):
  89. if v.head == "include":
  90. # Expand this node
  91. for j in v.tail:
  92. if j.head == "STRVALUE":
  93. f = str(j.tail[0])[1:-1]
  94. if f in included:
  95. subtree = []
  96. else:
  97. name = str(j.tail[0])[1:-1]
  98. subtree = do_parse(find_file(name, include_paths), grammarfile)["tree"].tail
  99. if subtree is None:
  100. raise Exception("Parsing error for included file %s" % find_file(name, include_paths))
  101. for t in subtree:
  102. t.inputfile = name
  103. included.add(f)
  104. # Found the string value, so break from the inner for ("searching for element")
  105. break
  106. # Merge all nodes in
  107. before = result["tree"].tail[:i]
  108. after = result["tree"].tail[i+1:]
  109. result["tree"].tail = before + subtree + after
  110. # Found an include node, but to prevent corruption of the tree, we need to start over again, so break from the outer for loop
  111. break
  112. else:
  113. # The outer for finally finished, so there were no includes remaining, thus terminate the infinite while loop
  114. break
  115. result["tree"].fix_tracability(inputfile)
  116. for visitor in visitors:
  117. visitor.visit(result["tree"])
  118. if visitors:
  119. return visitors[-1].dump()
  120. def main(input_file, grammar_file, mode, args=[], symbols=None):
  121. from prettyprint_visitor import PrettyPrintVisitor
  122. from prettyprint_visitor import PrintVisitor
  123. from semantics_visitor import SemanticsVisitor
  124. from bootstrap_visitor import BootstrapVisitor
  125. from primitives_visitor import PrimitivesVisitor
  126. from primitives_object_visitor import PrimitivesObjectVisitor
  127. from constructors_visitor import ConstructorsVisitor
  128. from constructors_object_visitor import ConstructorsObjectVisitor
  129. from model_visitor import ModelVisitor
  130. from model_object_visitor import ModelObjectVisitor
  131. modes = {
  132. "N" : [],
  133. "P" : [PrintVisitor],
  134. "PP" : [PrettyPrintVisitor],
  135. "S" : [SemanticsVisitor],
  136. "PS" : [SemanticsVisitor, PrimitivesVisitor],
  137. "PO" : [SemanticsVisitor, PrimitivesObjectVisitor],
  138. "BS" : [SemanticsVisitor, BootstrapVisitor],
  139. "CS" : [SemanticsVisitor, ConstructorsVisitor],
  140. "CO" : [SemanticsVisitor, ConstructorsObjectVisitor],
  141. "M" : [ModelVisitor],
  142. "MO" : [ModelObjectVisitor],
  143. }
  144. visitors = [v(args) for v in modes[mode]]
  145. result = do_compile(input_file, grammar_file, visitors)
  146. if symbols is not None and getattr(visitors[-1], "object_symbols", None) is not None:
  147. symbols.update(visitors[-1].object_symbols)
  148. return result
  149. if __name__ == "__main__":
  150. if len(sys.argv) <= 2:
  151. print("Invocation: ")
  152. print(" %s input_file grammar_file mode [mode_params]*" % sys.argv[0])
  153. sys.exit(1)
  154. else:
  155. value = main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:])
  156. if value is not None:
  157. print(value)