compiler.py 7.0 KB

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