compiler.py 6.9 KB

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