PageRenderTime 59ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/external/antlr/antlr-3.4/runtime/Python/antlr3/main.py

https://gitlab.com/brian0218/rk3188_r-box_android4.2.2_sdk
Python | 305 lines | 217 code | 58 blank | 30 comment | 26 complexity | 30baf22bd9c7f36bc7bfe67846dcc75b MD5 | raw file
  1. """ANTLR3 runtime package"""
  2. # begin[licence]
  3. #
  4. # [The "BSD licence"]
  5. # Copyright (c) 2005-2008 Terence Parr
  6. # All rights reserved.
  7. #
  8. # Redistribution and use in source and binary forms, with or without
  9. # modification, are permitted provided that the following conditions
  10. # are met:
  11. # 1. Redistributions of source code must retain the above copyright
  12. # notice, this list of conditions and the following disclaimer.
  13. # 2. Redistributions in binary form must reproduce the above copyright
  14. # notice, this list of conditions and the following disclaimer in the
  15. # documentation and/or other materials provided with the distribution.
  16. # 3. The name of the author may not be used to endorse or promote products
  17. # derived from this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  20. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  21. # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  22. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  23. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  24. # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  28. # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. #
  30. # end[licence]
  31. import sys
  32. import optparse
  33. import antlr3
  34. class _Main(object):
  35. def __init__(self):
  36. self.stdin = sys.stdin
  37. self.stdout = sys.stdout
  38. self.stderr = sys.stderr
  39. def parseOptions(self, argv):
  40. optParser = optparse.OptionParser()
  41. optParser.add_option(
  42. "--encoding",
  43. action="store",
  44. type="string",
  45. dest="encoding"
  46. )
  47. optParser.add_option(
  48. "--input",
  49. action="store",
  50. type="string",
  51. dest="input"
  52. )
  53. optParser.add_option(
  54. "--interactive", "-i",
  55. action="store_true",
  56. dest="interactive"
  57. )
  58. optParser.add_option(
  59. "--no-output",
  60. action="store_true",
  61. dest="no_output"
  62. )
  63. optParser.add_option(
  64. "--profile",
  65. action="store_true",
  66. dest="profile"
  67. )
  68. optParser.add_option(
  69. "--hotshot",
  70. action="store_true",
  71. dest="hotshot"
  72. )
  73. optParser.add_option(
  74. "--port",
  75. type="int",
  76. dest="port",
  77. default=None
  78. )
  79. optParser.add_option(
  80. "--debug-socket",
  81. action='store_true',
  82. dest="debug_socket",
  83. default=None
  84. )
  85. self.setupOptions(optParser)
  86. return optParser.parse_args(argv[1:])
  87. def setupOptions(self, optParser):
  88. pass
  89. def execute(self, argv):
  90. options, args = self.parseOptions(argv)
  91. self.setUp(options)
  92. if options.interactive:
  93. while True:
  94. try:
  95. input = raw_input(">>> ")
  96. except (EOFError, KeyboardInterrupt):
  97. self.stdout.write("\nBye.\n")
  98. break
  99. inStream = antlr3.ANTLRStringStream(input)
  100. self.parseStream(options, inStream)
  101. else:
  102. if options.input is not None:
  103. inStream = antlr3.ANTLRStringStream(options.input)
  104. elif len(args) == 1 and args[0] != '-':
  105. inStream = antlr3.ANTLRFileStream(
  106. args[0], encoding=options.encoding
  107. )
  108. else:
  109. inStream = antlr3.ANTLRInputStream(
  110. self.stdin, encoding=options.encoding
  111. )
  112. if options.profile:
  113. try:
  114. import cProfile as profile
  115. except ImportError:
  116. import profile
  117. profile.runctx(
  118. 'self.parseStream(options, inStream)',
  119. globals(),
  120. locals(),
  121. 'profile.dat'
  122. )
  123. import pstats
  124. stats = pstats.Stats('profile.dat')
  125. stats.strip_dirs()
  126. stats.sort_stats('time')
  127. stats.print_stats(100)
  128. elif options.hotshot:
  129. import hotshot
  130. profiler = hotshot.Profile('hotshot.dat')
  131. profiler.runctx(
  132. 'self.parseStream(options, inStream)',
  133. globals(),
  134. locals()
  135. )
  136. else:
  137. self.parseStream(options, inStream)
  138. def setUp(self, options):
  139. pass
  140. def parseStream(self, options, inStream):
  141. raise NotImplementedError
  142. def write(self, options, text):
  143. if not options.no_output:
  144. self.stdout.write(text)
  145. def writeln(self, options, text):
  146. self.write(options, text + '\n')
  147. class LexerMain(_Main):
  148. def __init__(self, lexerClass):
  149. _Main.__init__(self)
  150. self.lexerClass = lexerClass
  151. def parseStream(self, options, inStream):
  152. lexer = self.lexerClass(inStream)
  153. for token in lexer:
  154. self.writeln(options, str(token))
  155. class ParserMain(_Main):
  156. def __init__(self, lexerClassName, parserClass):
  157. _Main.__init__(self)
  158. self.lexerClassName = lexerClassName
  159. self.lexerClass = None
  160. self.parserClass = parserClass
  161. def setupOptions(self, optParser):
  162. optParser.add_option(
  163. "--lexer",
  164. action="store",
  165. type="string",
  166. dest="lexerClass",
  167. default=self.lexerClassName
  168. )
  169. optParser.add_option(
  170. "--rule",
  171. action="store",
  172. type="string",
  173. dest="parserRule"
  174. )
  175. def setUp(self, options):
  176. lexerMod = __import__(options.lexerClass)
  177. self.lexerClass = getattr(lexerMod, options.lexerClass)
  178. def parseStream(self, options, inStream):
  179. kwargs = {}
  180. if options.port is not None:
  181. kwargs['port'] = options.port
  182. if options.debug_socket is not None:
  183. kwargs['debug_socket'] = sys.stderr
  184. lexer = self.lexerClass(inStream)
  185. tokenStream = antlr3.CommonTokenStream(lexer)
  186. parser = self.parserClass(tokenStream, **kwargs)
  187. result = getattr(parser, options.parserRule)()
  188. if result is not None:
  189. if hasattr(result, 'tree') and result.tree is not None:
  190. self.writeln(options, result.tree.toStringTree())
  191. else:
  192. self.writeln(options, repr(result))
  193. class WalkerMain(_Main):
  194. def __init__(self, walkerClass):
  195. _Main.__init__(self)
  196. self.lexerClass = None
  197. self.parserClass = None
  198. self.walkerClass = walkerClass
  199. def setupOptions(self, optParser):
  200. optParser.add_option(
  201. "--lexer",
  202. action="store",
  203. type="string",
  204. dest="lexerClass",
  205. default=None
  206. )
  207. optParser.add_option(
  208. "--parser",
  209. action="store",
  210. type="string",
  211. dest="parserClass",
  212. default=None
  213. )
  214. optParser.add_option(
  215. "--parser-rule",
  216. action="store",
  217. type="string",
  218. dest="parserRule",
  219. default=None
  220. )
  221. optParser.add_option(
  222. "--rule",
  223. action="store",
  224. type="string",
  225. dest="walkerRule"
  226. )
  227. def setUp(self, options):
  228. lexerMod = __import__(options.lexerClass)
  229. self.lexerClass = getattr(lexerMod, options.lexerClass)
  230. parserMod = __import__(options.parserClass)
  231. self.parserClass = getattr(parserMod, options.parserClass)
  232. def parseStream(self, options, inStream):
  233. lexer = self.lexerClass(inStream)
  234. tokenStream = antlr3.CommonTokenStream(lexer)
  235. parser = self.parserClass(tokenStream)
  236. result = getattr(parser, options.parserRule)()
  237. if result is not None:
  238. assert hasattr(result, 'tree'), "Parser did not return an AST"
  239. nodeStream = antlr3.tree.CommonTreeNodeStream(result.tree)
  240. nodeStream.setTokenStream(tokenStream)
  241. walker = self.walkerClass(nodeStream)
  242. result = getattr(walker, options.walkerRule)()
  243. if result is not None:
  244. if hasattr(result, 'tree'):
  245. self.writeln(options, result.tree.toStringTree())
  246. else:
  247. self.writeln(options, repr(result))