compiler.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import cPickle as pickle
  2. import os
  3. import sys
  4. import time
  5. from grammar_compiler_visitor import GrammarCompilerVisitor
  6. from hutnparser import Parser, Tree
  7. from meta_grammar import Grammar
  8. from cached_exception import CachedException
  9. import hashlib
  10. global parsers
  11. parsers = {}
  12. sys.setrecursionlimit(2000)
  13. def read(filename):
  14. with open(filename, 'r') as f:
  15. return f.read()
  16. def md5digest(data):
  17. hasher = hashlib.md5()
  18. hasher.update(data)
  19. return hasher.hexdigest()
  20. def fetch_cached(data, mode=None):
  21. try:
  22. md5 = md5digest(data)
  23. cache_folder = os.path.abspath("%s/../caches/" % (os.path.dirname(os.path.abspath(__file__))))
  24. if mode is None:
  25. picklefile = cache_folder + "/%s.pickle" % md5
  26. else:
  27. picklefile = cache_folder + "/%s_%s.pickle" % (mode, md5)
  28. with open(picklefile, "rb") as f:
  29. return pickle.load(f)
  30. except:
  31. return None
  32. def make_cached(original_data, data, mode=None):
  33. md5 = md5digest(original_data)
  34. cache_folder = os.path.abspath("%s/../caches/" % (os.path.dirname(os.path.abspath(__file__))))
  35. if mode is None:
  36. picklefile = cache_folder + "/%s.pickle" % md5
  37. else:
  38. picklefile = cache_folder + "/%s_%s.pickle" % (mode, md5)
  39. with open(picklefile, "wb") as f:
  40. pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
  41. def do_parse(inputfile, grammarfile):
  42. if grammarfile not in parsers:
  43. grammar = fetch_cached(read(grammarfile))
  44. if grammar is None:
  45. result = parser = Parser(Grammar(), hide_implicit = True).parse(read(grammarfile))
  46. if result['status'] != Parser.Constants.Success:
  47. print 'not a valid grammar!'
  48. print result
  49. tree = result['tree']
  50. visitor = GrammarCompilerVisitor()
  51. structure = visitor.visit(tree)
  52. grammar = Grammar()
  53. grammar.rules = structure['rules']
  54. grammar.tokens = structure['tokens']
  55. make_cached(read(grammarfile), grammar)
  56. parsers[grammarfile] = grammar
  57. else:
  58. grammar = parsers[grammarfile]
  59. result = fetch_cached(read(inputfile))
  60. if result is None:
  61. result = Parser(grammar, line_position = True).parse(read(inputfile))
  62. if result['status'] != Parser.Constants.Success:
  63. lines = open(inputfile, 'r').readlines()
  64. begin_line = max(result["line"] - 3, 0)
  65. end_line = min(result["line"] + 3, len(lines))
  66. lines = lines[begin_line:end_line]
  67. lines = ["%s: %s" % (begin_line + i + 1, line) for i, line in enumerate(lines)]
  68. lines = "".join(lines)
  69. msg = "%s:%s:%s: %s\nContext:\n%s" % (inputfile, result["line"], result["column"], result["text"], lines)
  70. raise Exception(msg)
  71. make_cached(read(inputfile), result)
  72. return result
  73. def find_file(filename, include_paths):
  74. import os.path
  75. include_paths = ["."] + \
  76. [os.path.abspath(os.path.dirname(working_file))] + \
  77. [os.path.abspath("%s/../includes/" % (os.path.dirname(os.path.abspath(__file__))))] + \
  78. include_paths + \
  79. []
  80. attempts = []
  81. for include in include_paths:
  82. testfile = include + os.sep + filename
  83. if os.path.isfile(os.path.abspath(testfile)):
  84. return os.path.abspath(testfile)
  85. else:
  86. attempts.append(os.path.abspath(testfile))
  87. else:
  88. raise Exception("Could not resolve file %s. Tried: %s" % (filename, attempts))
  89. def do_compile(inputfile, grammarfile, visitors=[], include_paths = [], mode=""):
  90. import os.path
  91. global working_file
  92. working_file = os.path.abspath(inputfile)
  93. result = do_parse(inputfile, grammarfile)
  94. error = result["status"] != Parser.Constants.Success
  95. if error:
  96. lines = open(working_file, 'r').readlines()
  97. begin_line = max(result["line"] - 3, 0)
  98. end_line = max(result["line"] + 3, len(lines))
  99. lines = lines[begin_line:end_line]
  100. lines = ["%s: %s" % (begin_line + i + 1, line) for i, line in enumerate(lines)]
  101. lines = "".join(lines)
  102. msg = "%s:%s:%s: %s\nContext:\n%s" % (inputfile, result["line"], result["column"], result["text"], lines)
  103. raise Exception(msg)
  104. else:
  105. for child in result["tree"].tail:
  106. child.inputfile = inputfile
  107. included = set()
  108. while True:
  109. for i, v in enumerate(result["tree"].tail):
  110. if v.head == "include":
  111. # Expand this node
  112. for j in v.tail:
  113. if j.head == "STRVALUE":
  114. f = str(j.tail[0])[1:-1]
  115. if f in included:
  116. subtree = []
  117. else:
  118. name = str(j.tail[0])[1:-1]
  119. subtree = do_parse(find_file(name, include_paths), grammarfile)["tree"].tail
  120. if subtree is None:
  121. raise Exception("Parsing error for included file %s" % find_file(name, include_paths))
  122. for t in subtree:
  123. t.inputfile = name
  124. included.add(f)
  125. # Found the string value, so break from the inner for ("searching for element")
  126. break
  127. # Merge all nodes in
  128. before = result["tree"].tail[:i]
  129. after = result["tree"].tail[i+1:]
  130. result["tree"].tail = before + subtree + after
  131. # Found an include node, but to prevent corruption of the tree, we need to start over again, so break from the outer for loop
  132. break
  133. else:
  134. # The outer for finally finished, so there were no includes remaining, thus terminate the infinite while loop
  135. break
  136. tree_data = pickle.dumps(result["tree"], pickle.HIGHEST_PROTOCOL)
  137. new_result = fetch_cached(tree_data, mode)
  138. if new_result is None:
  139. result["tree"].fix_tracability(inputfile)
  140. for visitor in visitors:
  141. visitor.visit(result["tree"])
  142. if visitors:
  143. result = visitors[-1].dump()
  144. make_cached(tree_data, result, mode)
  145. else:
  146. result = new_result
  147. if visitors:
  148. return result
  149. def main(input_file, grammar_file, mode, args=[]):
  150. from prettyprint_visitor import PrettyPrintVisitor
  151. from prettyprint_visitor import PrintVisitor
  152. from semantics_visitor import SemanticsVisitor
  153. from bootstrap_visitor import BootstrapVisitor
  154. from constructors_visitor import ConstructorsVisitor
  155. from model_visitor import ModelVisitor
  156. from model_bootstrap_visitor import ModelBootstrapVisitor
  157. modes = {
  158. "N" : [],
  159. "P" : [PrintVisitor],
  160. "PP" : [PrettyPrintVisitor],
  161. "BS" : [SemanticsVisitor, BootstrapVisitor],
  162. "CS" : [SemanticsVisitor, ConstructorsVisitor],
  163. "M" : [ModelVisitor],
  164. "MB" : [ModelBootstrapVisitor],
  165. }
  166. try:
  167. visitors = [v(args) for v in modes[mode]]
  168. result = do_compile(input_file, grammar_file, visitors, mode=mode)
  169. except CachedException:
  170. return True
  171. return result
  172. if __name__ == "__main__":
  173. if len(sys.argv) <= 2:
  174. print("Invocation: ")
  175. print(" %s input_file grammar_file mode [mode_params]*" % sys.argv[0])
  176. sys.exit(1)
  177. else:
  178. value = main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:])
  179. if value is not None:
  180. print(value)