compiler.py 7.8 KB

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