compiler.py 6.8 KB

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