compiler.py 6.4 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. 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):
  21. try:
  22. md5 = md5digest(filename)
  23. cache_folder = os.path.abspath("%s/../caches/" % (os.path.dirname(os.path.abspath(__file__))))
  24. picklefile = cache_folder + "/%s.pickle" % md5
  25. with open(picklefile, "rb") as f:
  26. return pickle.load(f)
  27. except:
  28. return None
  29. def make_cached(filename, data):
  30. md5 = md5digest(filename)
  31. cache_folder = os.path.abspath("%s/../caches/" % (os.path.dirname(os.path.abspath(__file__))))
  32. picklefile = cache_folder + "/%s.pickle" % md5
  33. with open(picklefile, "wb") as f:
  34. pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
  35. def do_parse(inputfile, grammarfile):
  36. if grammarfile not in parsers:
  37. grammar = fetch_cached(grammarfile)
  38. if grammar is None:
  39. result = parser = Parser(Grammar(), hide_implicit = True).parse(read(grammarfile))
  40. if result['status'] != Parser.Constants.Success:
  41. print 'not a valid grammar!'
  42. print result
  43. tree = result['tree']
  44. visitor = GrammarCompilerVisitor()
  45. structure = visitor.visit(tree)
  46. grammar = Grammar()
  47. grammar.rules = structure['rules']
  48. grammar.tokens = structure['tokens']
  49. make_cached(grammarfile, grammar)
  50. parsers[grammarfile] = grammar
  51. else:
  52. grammar = parsers[grammarfile]
  53. result = fetch_cached(inputfile)
  54. if result is None:
  55. result = Parser(grammar, line_position = True).parse(read(inputfile))
  56. if result['status'] != Parser.Constants.Success:
  57. msg = "%s:%s:%s: %s" % (inputfile, result["line"], result["column"], result["text"])
  58. raise Exception(msg)
  59. make_cached(inputfile, result)
  60. return result
  61. def find_file(filename, include_paths):
  62. import os.path
  63. include_paths = ["."] + \
  64. [os.path.abspath(os.path.dirname(working_file))] + \
  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 = os.path.abspath(inputfile)
  81. result = do_parse(inputfile, grammarfile)
  82. error = result["status"] != Parser.Constants.Success
  83. if error:
  84. msg = "%s:%s:%s: %s" % (inputfile, result["line"], result["column"], result["text"])
  85. raise Exception(msg)
  86. else:
  87. for child in result["tree"].tail:
  88. child.inputfile = inputfile
  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 = str(j.tail[0])[1:-1]
  101. subtree = do_parse(find_file(name, include_paths), grammarfile)["tree"].tail
  102. if subtree is None:
  103. raise Exception("Parsing error for included file %s" % find_file(name, include_paths))
  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(inputfile)
  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=[]):
  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 constructors_visitor import ConstructorsVisitor
  129. from model_visitor import ModelVisitor
  130. from model_bootstrap_visitor import ModelBootstrapVisitor
  131. modes = {
  132. "N" : [],
  133. "P" : [PrintVisitor],
  134. "PP" : [PrettyPrintVisitor],
  135. "BS" : [SemanticsVisitor, BootstrapVisitor],
  136. "CS" : [SemanticsVisitor, ConstructorsVisitor],
  137. "M" : [ModelVisitor],
  138. "MB" : [ModelBootstrapVisitor],
  139. }
  140. try:
  141. visitors = [v(args) for v in modes[mode]]
  142. result = do_compile(input_file, grammar_file, visitors)
  143. except CachedException:
  144. return True
  145. return result
  146. if __name__ == "__main__":
  147. if len(sys.argv) <= 2:
  148. print("Invocation: ")
  149. print(" %s input_file grammar_file mode [mode_params]*" % sys.argv[0])
  150. sys.exit(1)
  151. else:
  152. value = main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:])
  153. if value is not None:
  154. print(value)