PageRenderTime 76ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/ext/ply/ply/yacc.py

https://bitbucket.org/musleh123/ece565
Python | 3276 lines | 2373 code | 289 blank | 614 comment | 324 complexity | 9154ae6bd469cb728532dc7bcca1d1a0 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, WTFPL
  1. # -----------------------------------------------------------------------------
  2. # ply: yacc.py
  3. #
  4. # Copyright (C) 2001-2009,
  5. # David M. Beazley (Dabeaz LLC)
  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 are
  10. # met:
  11. #
  12. # * Redistributions of source code must retain the above copyright notice,
  13. # this list of conditions and the following disclaimer.
  14. # * Redistributions in binary form must reproduce the above copyright notice,
  15. # this list of conditions and the following disclaimer in the documentation
  16. # and/or other materials provided with the distribution.
  17. # * Neither the name of the David Beazley or Dabeaz LLC may be used to
  18. # endorse or promote products derived from this software without
  19. # specific prior written permission.
  20. #
  21. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. # -----------------------------------------------------------------------------
  33. #
  34. # This implements an LR parser that is constructed from grammar rules defined
  35. # as Python functions. The grammer is specified by supplying the BNF inside
  36. # Python documentation strings. The inspiration for this technique was borrowed
  37. # from John Aycock's Spark parsing system. PLY might be viewed as cross between
  38. # Spark and the GNU bison utility.
  39. #
  40. # The current implementation is only somewhat object-oriented. The
  41. # LR parser itself is defined in terms of an object (which allows multiple
  42. # parsers to co-exist). However, most of the variables used during table
  43. # construction are defined in terms of global variables. Users shouldn't
  44. # notice unless they are trying to define multiple parsers at the same
  45. # time using threads (in which case they should have their head examined).
  46. #
  47. # This implementation supports both SLR and LALR(1) parsing. LALR(1)
  48. # support was originally implemented by Elias Ioup (ezioup@alumni.uchicago.edu),
  49. # using the algorithm found in Aho, Sethi, and Ullman "Compilers: Principles,
  50. # Techniques, and Tools" (The Dragon Book). LALR(1) has since been replaced
  51. # by the more efficient DeRemer and Pennello algorithm.
  52. #
  53. # :::::::: WARNING :::::::
  54. #
  55. # Construction of LR parsing tables is fairly complicated and expensive.
  56. # To make this module run fast, a *LOT* of work has been put into
  57. # optimization---often at the expensive of readability and what might
  58. # consider to be good Python "coding style." Modify the code at your
  59. # own risk!
  60. # ----------------------------------------------------------------------------
  61. __version__ = "3.2"
  62. __tabversion__ = "3.2" # Table version
  63. #-----------------------------------------------------------------------------
  64. # === User configurable parameters ===
  65. #
  66. # Change these to modify the default behavior of yacc (if you wish)
  67. #-----------------------------------------------------------------------------
  68. yaccdebug = 1 # Debugging mode. If set, yacc generates a
  69. # a 'parser.out' file in the current directory
  70. debug_file = 'parser.out' # Default name of the debugging file
  71. tab_module = 'parsetab' # Default name of the table module
  72. default_lr = 'LALR' # Default LR table generation method
  73. error_count = 3 # Number of symbols that must be shifted to leave recovery mode
  74. yaccdevel = 0 # Set to True if developing yacc. This turns off optimized
  75. # implementations of certain functions.
  76. resultlimit = 40 # Size limit of results when running in debug mode.
  77. pickle_protocol = 0 # Protocol to use when writing pickle files
  78. import re, types, sys, os.path
  79. # Compatibility function for python 2.6/3.0
  80. if sys.version_info[0] < 3:
  81. def func_code(f):
  82. return f.func_code
  83. else:
  84. def func_code(f):
  85. return f.__code__
  86. # Compatibility
  87. try:
  88. MAXINT = sys.maxint
  89. except AttributeError:
  90. MAXINT = sys.maxsize
  91. # Python 2.x/3.0 compatibility.
  92. def load_ply_lex():
  93. if sys.version_info[0] < 3:
  94. import lex
  95. else:
  96. import ply.lex as lex
  97. return lex
  98. # This object is a stand-in for a logging object created by the
  99. # logging module. PLY will use this by default to create things
  100. # such as the parser.out file. If a user wants more detailed
  101. # information, they can create their own logging object and pass
  102. # it into PLY.
  103. class PlyLogger(object):
  104. def __init__(self,f):
  105. self.f = f
  106. def debug(self,msg,*args,**kwargs):
  107. self.f.write((msg % args) + "\n")
  108. info = debug
  109. def warning(self,msg,*args,**kwargs):
  110. self.f.write("WARNING: "+ (msg % args) + "\n")
  111. def error(self,msg,*args,**kwargs):
  112. self.f.write("ERROR: " + (msg % args) + "\n")
  113. critical = debug
  114. # Null logger is used when no output is generated. Does nothing.
  115. class NullLogger(object):
  116. def __getattribute__(self,name):
  117. return self
  118. def __call__(self,*args,**kwargs):
  119. return self
  120. # Exception raised for yacc-related errors
  121. class YaccError(Exception): pass
  122. # Format the result message that the parser produces when running in debug mode.
  123. def format_result(r):
  124. repr_str = repr(r)
  125. if '\n' in repr_str: repr_str = repr(repr_str)
  126. if len(repr_str) > resultlimit:
  127. repr_str = repr_str[:resultlimit]+" ..."
  128. result = "<%s @ 0x%x> (%s)" % (type(r).__name__,id(r),repr_str)
  129. return result
  130. # Format stack entries when the parser is running in debug mode
  131. def format_stack_entry(r):
  132. repr_str = repr(r)
  133. if '\n' in repr_str: repr_str = repr(repr_str)
  134. if len(repr_str) < 16:
  135. return repr_str
  136. else:
  137. return "<%s @ 0x%x>" % (type(r).__name__,id(r))
  138. #-----------------------------------------------------------------------------
  139. # === LR Parsing Engine ===
  140. #
  141. # The following classes are used for the LR parser itself. These are not
  142. # used during table construction and are independent of the actual LR
  143. # table generation algorithm
  144. #-----------------------------------------------------------------------------
  145. # This class is used to hold non-terminal grammar symbols during parsing.
  146. # It normally has the following attributes set:
  147. # .type = Grammar symbol type
  148. # .value = Symbol value
  149. # .lineno = Starting line number
  150. # .endlineno = Ending line number (optional, set automatically)
  151. # .lexpos = Starting lex position
  152. # .endlexpos = Ending lex position (optional, set automatically)
  153. class YaccSymbol:
  154. def __str__(self): return self.type
  155. def __repr__(self): return str(self)
  156. # This class is a wrapper around the objects actually passed to each
  157. # grammar rule. Index lookup and assignment actually assign the
  158. # .value attribute of the underlying YaccSymbol object.
  159. # The lineno() method returns the line number of a given
  160. # item (or 0 if not defined). The linespan() method returns
  161. # a tuple of (startline,endline) representing the range of lines
  162. # for a symbol. The lexspan() method returns a tuple (lexpos,endlexpos)
  163. # representing the range of positional information for a symbol.
  164. class YaccProduction:
  165. def __init__(self,s,stack=None):
  166. self.slice = s
  167. self.stack = stack
  168. self.lexer = None
  169. self.parser= None
  170. def __getitem__(self,n):
  171. if n >= 0: return self.slice[n].value
  172. else: return self.stack[n].value
  173. def __setitem__(self,n,v):
  174. self.slice[n].value = v
  175. def __getslice__(self,i,j):
  176. return [s.value for s in self.slice[i:j]]
  177. def __len__(self):
  178. return len(self.slice)
  179. def lineno(self,n):
  180. return getattr(self.slice[n],"lineno",0)
  181. def set_lineno(self,n,lineno):
  182. self.slice[n].lineno = n
  183. def linespan(self,n):
  184. startline = getattr(self.slice[n],"lineno",0)
  185. endline = getattr(self.slice[n],"endlineno",startline)
  186. return startline,endline
  187. def lexpos(self,n):
  188. return getattr(self.slice[n],"lexpos",0)
  189. def lexspan(self,n):
  190. startpos = getattr(self.slice[n],"lexpos",0)
  191. endpos = getattr(self.slice[n],"endlexpos",startpos)
  192. return startpos,endpos
  193. def error(self):
  194. raise SyntaxError
  195. # -----------------------------------------------------------------------------
  196. # == LRParser ==
  197. #
  198. # The LR Parsing engine.
  199. # -----------------------------------------------------------------------------
  200. class LRParser:
  201. def __init__(self,lrtab,errorf):
  202. self.productions = lrtab.lr_productions
  203. self.action = lrtab.lr_action
  204. self.goto = lrtab.lr_goto
  205. self.errorfunc = errorf
  206. def errok(self):
  207. self.errorok = 1
  208. def restart(self):
  209. del self.statestack[:]
  210. del self.symstack[:]
  211. sym = YaccSymbol()
  212. sym.type = '$end'
  213. self.symstack.append(sym)
  214. self.statestack.append(0)
  215. def parse(self,input=None,lexer=None,debug=0,tracking=0,tokenfunc=None):
  216. if debug or yaccdevel:
  217. if isinstance(debug,int):
  218. debug = PlyLogger(sys.stderr)
  219. return self.parsedebug(input,lexer,debug,tracking,tokenfunc)
  220. elif tracking:
  221. return self.parseopt(input,lexer,debug,tracking,tokenfunc)
  222. else:
  223. return self.parseopt_notrack(input,lexer,debug,tracking,tokenfunc)
  224. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  225. # parsedebug().
  226. #
  227. # This is the debugging enabled version of parse(). All changes made to the
  228. # parsing engine should be made here. For the non-debugging version,
  229. # copy this code to a method parseopt() and delete all of the sections
  230. # enclosed in:
  231. #
  232. # #--! DEBUG
  233. # statements
  234. # #--! DEBUG
  235. #
  236. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  237. def parsedebug(self,input=None,lexer=None,debug=None,tracking=0,tokenfunc=None):
  238. lookahead = None # Current lookahead symbol
  239. lookaheadstack = [ ] # Stack of lookahead symbols
  240. actions = self.action # Local reference to action table (to avoid lookup on self.)
  241. goto = self.goto # Local reference to goto table (to avoid lookup on self.)
  242. prod = self.productions # Local reference to production list (to avoid lookup on self.)
  243. pslice = YaccProduction(None) # Production object passed to grammar rules
  244. errorcount = 0 # Used during error recovery
  245. # --! DEBUG
  246. debug.info("PLY: PARSE DEBUG START")
  247. # --! DEBUG
  248. # If no lexer was given, we will try to use the lex module
  249. if not lexer:
  250. lex = load_ply_lex()
  251. lexer = lex.lexer
  252. # Set up the lexer and parser objects on pslice
  253. pslice.lexer = lexer
  254. pslice.parser = self
  255. # If input was supplied, pass to lexer
  256. if input is not None:
  257. lexer.input(input)
  258. if tokenfunc is None:
  259. # Tokenize function
  260. get_token = lexer.token
  261. else:
  262. get_token = tokenfunc
  263. # Set up the state and symbol stacks
  264. statestack = [ ] # Stack of parsing states
  265. self.statestack = statestack
  266. symstack = [ ] # Stack of grammar symbols
  267. self.symstack = symstack
  268. pslice.stack = symstack # Put in the production
  269. errtoken = None # Err token
  270. # The start state is assumed to be (0,$end)
  271. statestack.append(0)
  272. sym = YaccSymbol()
  273. sym.type = "$end"
  274. symstack.append(sym)
  275. state = 0
  276. while 1:
  277. # Get the next symbol on the input. If a lookahead symbol
  278. # is already set, we just use that. Otherwise, we'll pull
  279. # the next token off of the lookaheadstack or from the lexer
  280. # --! DEBUG
  281. debug.debug('')
  282. debug.debug('State : %s', state)
  283. # --! DEBUG
  284. if not lookahead:
  285. if not lookaheadstack:
  286. lookahead = get_token() # Get the next token
  287. else:
  288. lookahead = lookaheadstack.pop()
  289. if not lookahead:
  290. lookahead = YaccSymbol()
  291. lookahead.type = "$end"
  292. # --! DEBUG
  293. debug.debug('Stack : %s',
  294. ("%s . %s" % (" ".join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip())
  295. # --! DEBUG
  296. # Check the action table
  297. ltype = lookahead.type
  298. t = actions[state].get(ltype)
  299. if t is not None:
  300. if t > 0:
  301. # shift a symbol on the stack
  302. statestack.append(t)
  303. state = t
  304. # --! DEBUG
  305. debug.debug("Action : Shift and goto state %s", t)
  306. # --! DEBUG
  307. symstack.append(lookahead)
  308. lookahead = None
  309. # Decrease error count on successful shift
  310. if errorcount: errorcount -=1
  311. continue
  312. if t < 0:
  313. # reduce a symbol on the stack, emit a production
  314. p = prod[-t]
  315. pname = p.name
  316. plen = p.len
  317. # Get production function
  318. sym = YaccSymbol()
  319. sym.type = pname # Production name
  320. sym.value = None
  321. # --! DEBUG
  322. if plen:
  323. debug.info("Action : Reduce rule [%s] with %s and goto state %d", p.str, "["+",".join([format_stack_entry(_v.value) for _v in symstack[-plen:]])+"]",-t)
  324. else:
  325. debug.info("Action : Reduce rule [%s] with %s and goto state %d", p.str, [],-t)
  326. # --! DEBUG
  327. if plen:
  328. targ = symstack[-plen-1:]
  329. targ[0] = sym
  330. # --! TRACKING
  331. if tracking:
  332. t1 = targ[1]
  333. sym.lineno = t1.lineno
  334. sym.lexpos = t1.lexpos
  335. t1 = targ[-1]
  336. sym.endlineno = getattr(t1,"endlineno",t1.lineno)
  337. sym.endlexpos = getattr(t1,"endlexpos",t1.lexpos)
  338. # --! TRACKING
  339. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  340. # The code enclosed in this section is duplicated
  341. # below as a performance optimization. Make sure
  342. # changes get made in both locations.
  343. pslice.slice = targ
  344. try:
  345. # Call the grammar rule with our special slice object
  346. del symstack[-plen:]
  347. del statestack[-plen:]
  348. p.callable(pslice)
  349. # --! DEBUG
  350. debug.info("Result : %s", format_result(pslice[0]))
  351. # --! DEBUG
  352. symstack.append(sym)
  353. state = goto[statestack[-1]][pname]
  354. statestack.append(state)
  355. except SyntaxError:
  356. # If an error was set. Enter error recovery state
  357. lookaheadstack.append(lookahead)
  358. symstack.pop()
  359. statestack.pop()
  360. state = statestack[-1]
  361. sym.type = 'error'
  362. lookahead = sym
  363. errorcount = error_count
  364. self.errorok = 0
  365. continue
  366. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  367. else:
  368. # --! TRACKING
  369. if tracking:
  370. sym.lineno = lexer.lineno
  371. sym.lexpos = lexer.lexpos
  372. # --! TRACKING
  373. targ = [ sym ]
  374. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  375. # The code enclosed in this section is duplicated
  376. # above as a performance optimization. Make sure
  377. # changes get made in both locations.
  378. pslice.slice = targ
  379. try:
  380. # Call the grammar rule with our special slice object
  381. p.callable(pslice)
  382. # --! DEBUG
  383. debug.info("Result : %s", format_result(pslice[0]))
  384. # --! DEBUG
  385. symstack.append(sym)
  386. state = goto[statestack[-1]][pname]
  387. statestack.append(state)
  388. except SyntaxError:
  389. # If an error was set. Enter error recovery state
  390. lookaheadstack.append(lookahead)
  391. symstack.pop()
  392. statestack.pop()
  393. state = statestack[-1]
  394. sym.type = 'error'
  395. lookahead = sym
  396. errorcount = error_count
  397. self.errorok = 0
  398. continue
  399. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  400. if t == 0:
  401. n = symstack[-1]
  402. result = getattr(n,"value",None)
  403. # --! DEBUG
  404. debug.info("Done : Returning %s", format_result(result))
  405. debug.info("PLY: PARSE DEBUG END")
  406. # --! DEBUG
  407. return result
  408. if t == None:
  409. # --! DEBUG
  410. debug.error('Error : %s',
  411. ("%s . %s" % (" ".join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip())
  412. # --! DEBUG
  413. # We have some kind of parsing error here. To handle
  414. # this, we are going to push the current token onto
  415. # the tokenstack and replace it with an 'error' token.
  416. # If there are any synchronization rules, they may
  417. # catch it.
  418. #
  419. # In addition to pushing the error token, we call call
  420. # the user defined p_error() function if this is the
  421. # first syntax error. This function is only called if
  422. # errorcount == 0.
  423. if errorcount == 0 or self.errorok:
  424. errorcount = error_count
  425. self.errorok = 0
  426. errtoken = lookahead
  427. if errtoken.type == "$end":
  428. errtoken = None # End of file!
  429. if self.errorfunc:
  430. global errok,token,restart
  431. errok = self.errok # Set some special functions available in error recovery
  432. token = get_token
  433. restart = self.restart
  434. if errtoken and not hasattr(errtoken,'lexer'):
  435. errtoken.lexer = lexer
  436. tok = self.errorfunc(errtoken)
  437. del errok, token, restart # Delete special functions
  438. if self.errorok:
  439. # User must have done some kind of panic
  440. # mode recovery on their own. The
  441. # returned token is the next lookahead
  442. lookahead = tok
  443. errtoken = None
  444. continue
  445. else:
  446. if errtoken:
  447. if hasattr(errtoken,"lineno"): lineno = lookahead.lineno
  448. else: lineno = 0
  449. if lineno:
  450. sys.stderr.write("yacc: Syntax error at line %d, token=%s\n" % (lineno, errtoken.type))
  451. else:
  452. sys.stderr.write("yacc: Syntax error, token=%s" % errtoken.type)
  453. else:
  454. sys.stderr.write("yacc: Parse error in input. EOF\n")
  455. return
  456. else:
  457. errorcount = error_count
  458. # case 1: the statestack only has 1 entry on it. If we're in this state, the
  459. # entire parse has been rolled back and we're completely hosed. The token is
  460. # discarded and we just keep going.
  461. if len(statestack) <= 1 and lookahead.type != "$end":
  462. lookahead = None
  463. errtoken = None
  464. state = 0
  465. # Nuke the pushback stack
  466. del lookaheadstack[:]
  467. continue
  468. # case 2: the statestack has a couple of entries on it, but we're
  469. # at the end of the file. nuke the top entry and generate an error token
  470. # Start nuking entries on the stack
  471. if lookahead.type == "$end":
  472. # Whoa. We're really hosed here. Bail out
  473. return
  474. if lookahead.type != 'error':
  475. sym = symstack[-1]
  476. if sym.type == 'error':
  477. # Hmmm. Error is on top of stack, we'll just nuke input
  478. # symbol and continue
  479. lookahead = None
  480. continue
  481. t = YaccSymbol()
  482. t.type = 'error'
  483. if hasattr(lookahead,"lineno"):
  484. t.lineno = lookahead.lineno
  485. t.value = lookahead
  486. lookaheadstack.append(lookahead)
  487. lookahead = t
  488. else:
  489. symstack.pop()
  490. statestack.pop()
  491. state = statestack[-1] # Potential bug fix
  492. continue
  493. # Call an error function here
  494. raise RuntimeError("yacc: internal parser error!!!\n")
  495. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  496. # parseopt().
  497. #
  498. # Optimized version of parse() method. DO NOT EDIT THIS CODE DIRECTLY.
  499. # Edit the debug version above, then copy any modifications to the method
  500. # below while removing #--! DEBUG sections.
  501. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  502. def parseopt(self,input=None,lexer=None,debug=0,tracking=0,tokenfunc=None):
  503. lookahead = None # Current lookahead symbol
  504. lookaheadstack = [ ] # Stack of lookahead symbols
  505. actions = self.action # Local reference to action table (to avoid lookup on self.)
  506. goto = self.goto # Local reference to goto table (to avoid lookup on self.)
  507. prod = self.productions # Local reference to production list (to avoid lookup on self.)
  508. pslice = YaccProduction(None) # Production object passed to grammar rules
  509. errorcount = 0 # Used during error recovery
  510. # If no lexer was given, we will try to use the lex module
  511. if not lexer:
  512. lex = load_ply_lex()
  513. lexer = lex.lexer
  514. # Set up the lexer and parser objects on pslice
  515. pslice.lexer = lexer
  516. pslice.parser = self
  517. # If input was supplied, pass to lexer
  518. if input is not None:
  519. lexer.input(input)
  520. if tokenfunc is None:
  521. # Tokenize function
  522. get_token = lexer.token
  523. else:
  524. get_token = tokenfunc
  525. # Set up the state and symbol stacks
  526. statestack = [ ] # Stack of parsing states
  527. self.statestack = statestack
  528. symstack = [ ] # Stack of grammar symbols
  529. self.symstack = symstack
  530. pslice.stack = symstack # Put in the production
  531. errtoken = None # Err token
  532. # The start state is assumed to be (0,$end)
  533. statestack.append(0)
  534. sym = YaccSymbol()
  535. sym.type = '$end'
  536. symstack.append(sym)
  537. state = 0
  538. while 1:
  539. # Get the next symbol on the input. If a lookahead symbol
  540. # is already set, we just use that. Otherwise, we'll pull
  541. # the next token off of the lookaheadstack or from the lexer
  542. if not lookahead:
  543. if not lookaheadstack:
  544. lookahead = get_token() # Get the next token
  545. else:
  546. lookahead = lookaheadstack.pop()
  547. if not lookahead:
  548. lookahead = YaccSymbol()
  549. lookahead.type = '$end'
  550. # Check the action table
  551. ltype = lookahead.type
  552. t = actions[state].get(ltype)
  553. if t is not None:
  554. if t > 0:
  555. # shift a symbol on the stack
  556. statestack.append(t)
  557. state = t
  558. symstack.append(lookahead)
  559. lookahead = None
  560. # Decrease error count on successful shift
  561. if errorcount: errorcount -=1
  562. continue
  563. if t < 0:
  564. # reduce a symbol on the stack, emit a production
  565. p = prod[-t]
  566. pname = p.name
  567. plen = p.len
  568. # Get production function
  569. sym = YaccSymbol()
  570. sym.type = pname # Production name
  571. sym.value = None
  572. if plen:
  573. targ = symstack[-plen-1:]
  574. targ[0] = sym
  575. # --! TRACKING
  576. if tracking:
  577. t1 = targ[1]
  578. sym.lineno = t1.lineno
  579. sym.lexpos = t1.lexpos
  580. t1 = targ[-1]
  581. sym.endlineno = getattr(t1,"endlineno",t1.lineno)
  582. sym.endlexpos = getattr(t1,"endlexpos",t1.lexpos)
  583. # --! TRACKING
  584. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  585. # The code enclosed in this section is duplicated
  586. # below as a performance optimization. Make sure
  587. # changes get made in both locations.
  588. pslice.slice = targ
  589. try:
  590. # Call the grammar rule with our special slice object
  591. del symstack[-plen:]
  592. del statestack[-plen:]
  593. p.callable(pslice)
  594. symstack.append(sym)
  595. state = goto[statestack[-1]][pname]
  596. statestack.append(state)
  597. except SyntaxError:
  598. # If an error was set. Enter error recovery state
  599. lookaheadstack.append(lookahead)
  600. symstack.pop()
  601. statestack.pop()
  602. state = statestack[-1]
  603. sym.type = 'error'
  604. lookahead = sym
  605. errorcount = error_count
  606. self.errorok = 0
  607. continue
  608. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  609. else:
  610. # --! TRACKING
  611. if tracking:
  612. sym.lineno = lexer.lineno
  613. sym.lexpos = lexer.lexpos
  614. # --! TRACKING
  615. targ = [ sym ]
  616. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  617. # The code enclosed in this section is duplicated
  618. # above as a performance optimization. Make sure
  619. # changes get made in both locations.
  620. pslice.slice = targ
  621. try:
  622. # Call the grammar rule with our special slice object
  623. p.callable(pslice)
  624. symstack.append(sym)
  625. state = goto[statestack[-1]][pname]
  626. statestack.append(state)
  627. except SyntaxError:
  628. # If an error was set. Enter error recovery state
  629. lookaheadstack.append(lookahead)
  630. symstack.pop()
  631. statestack.pop()
  632. state = statestack[-1]
  633. sym.type = 'error'
  634. lookahead = sym
  635. errorcount = error_count
  636. self.errorok = 0
  637. continue
  638. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  639. if t == 0:
  640. n = symstack[-1]
  641. return getattr(n,"value",None)
  642. if t == None:
  643. # We have some kind of parsing error here. To handle
  644. # this, we are going to push the current token onto
  645. # the tokenstack and replace it with an 'error' token.
  646. # If there are any synchronization rules, they may
  647. # catch it.
  648. #
  649. # In addition to pushing the error token, we call call
  650. # the user defined p_error() function if this is the
  651. # first syntax error. This function is only called if
  652. # errorcount == 0.
  653. if errorcount == 0 or self.errorok:
  654. errorcount = error_count
  655. self.errorok = 0
  656. errtoken = lookahead
  657. if errtoken.type == '$end':
  658. errtoken = None # End of file!
  659. if self.errorfunc:
  660. global errok,token,restart
  661. errok = self.errok # Set some special functions available in error recovery
  662. token = get_token
  663. restart = self.restart
  664. if errtoken and not hasattr(errtoken,'lexer'):
  665. errtoken.lexer = lexer
  666. tok = self.errorfunc(errtoken)
  667. del errok, token, restart # Delete special functions
  668. if self.errorok:
  669. # User must have done some kind of panic
  670. # mode recovery on their own. The
  671. # returned token is the next lookahead
  672. lookahead = tok
  673. errtoken = None
  674. continue
  675. else:
  676. if errtoken:
  677. if hasattr(errtoken,"lineno"): lineno = lookahead.lineno
  678. else: lineno = 0
  679. if lineno:
  680. sys.stderr.write("yacc: Syntax error at line %d, token=%s\n" % (lineno, errtoken.type))
  681. else:
  682. sys.stderr.write("yacc: Syntax error, token=%s" % errtoken.type)
  683. else:
  684. sys.stderr.write("yacc: Parse error in input. EOF\n")
  685. return
  686. else:
  687. errorcount = error_count
  688. # case 1: the statestack only has 1 entry on it. If we're in this state, the
  689. # entire parse has been rolled back and we're completely hosed. The token is
  690. # discarded and we just keep going.
  691. if len(statestack) <= 1 and lookahead.type != '$end':
  692. lookahead = None
  693. errtoken = None
  694. state = 0
  695. # Nuke the pushback stack
  696. del lookaheadstack[:]
  697. continue
  698. # case 2: the statestack has a couple of entries on it, but we're
  699. # at the end of the file. nuke the top entry and generate an error token
  700. # Start nuking entries on the stack
  701. if lookahead.type == '$end':
  702. # Whoa. We're really hosed here. Bail out
  703. return
  704. if lookahead.type != 'error':
  705. sym = symstack[-1]
  706. if sym.type == 'error':
  707. # Hmmm. Error is on top of stack, we'll just nuke input
  708. # symbol and continue
  709. lookahead = None
  710. continue
  711. t = YaccSymbol()
  712. t.type = 'error'
  713. if hasattr(lookahead,"lineno"):
  714. t.lineno = lookahead.lineno
  715. t.value = lookahead
  716. lookaheadstack.append(lookahead)
  717. lookahead = t
  718. else:
  719. symstack.pop()
  720. statestack.pop()
  721. state = statestack[-1] # Potential bug fix
  722. continue
  723. # Call an error function here
  724. raise RuntimeError("yacc: internal parser error!!!\n")
  725. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  726. # parseopt_notrack().
  727. #
  728. # Optimized version of parseopt() with line number tracking removed.
  729. # DO NOT EDIT THIS CODE DIRECTLY. Copy the optimized version and remove
  730. # code in the #--! TRACKING sections
  731. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  732. def parseopt_notrack(self,input=None,lexer=None,debug=0,tracking=0,tokenfunc=None):
  733. lookahead = None # Current lookahead symbol
  734. lookaheadstack = [ ] # Stack of lookahead symbols
  735. actions = self.action # Local reference to action table (to avoid lookup on self.)
  736. goto = self.goto # Local reference to goto table (to avoid lookup on self.)
  737. prod = self.productions # Local reference to production list (to avoid lookup on self.)
  738. pslice = YaccProduction(None) # Production object passed to grammar rules
  739. errorcount = 0 # Used during error recovery
  740. # If no lexer was given, we will try to use the lex module
  741. if not lexer:
  742. lex = load_ply_lex()
  743. lexer = lex.lexer
  744. # Set up the lexer and parser objects on pslice
  745. pslice.lexer = lexer
  746. pslice.parser = self
  747. # If input was supplied, pass to lexer
  748. if input is not None:
  749. lexer.input(input)
  750. if tokenfunc is None:
  751. # Tokenize function
  752. get_token = lexer.token
  753. else:
  754. get_token = tokenfunc
  755. # Set up the state and symbol stacks
  756. statestack = [ ] # Stack of parsing states
  757. self.statestack = statestack
  758. symstack = [ ] # Stack of grammar symbols
  759. self.symstack = symstack
  760. pslice.stack = symstack # Put in the production
  761. errtoken = None # Err token
  762. # The start state is assumed to be (0,$end)
  763. statestack.append(0)
  764. sym = YaccSymbol()
  765. sym.type = '$end'
  766. symstack.append(sym)
  767. state = 0
  768. while 1:
  769. # Get the next symbol on the input. If a lookahead symbol
  770. # is already set, we just use that. Otherwise, we'll pull
  771. # the next token off of the lookaheadstack or from the lexer
  772. if not lookahead:
  773. if not lookaheadstack:
  774. lookahead = get_token() # Get the next token
  775. else:
  776. lookahead = lookaheadstack.pop()
  777. if not lookahead:
  778. lookahead = YaccSymbol()
  779. lookahead.type = '$end'
  780. # Check the action table
  781. ltype = lookahead.type
  782. t = actions[state].get(ltype)
  783. if t is not None:
  784. if t > 0:
  785. # shift a symbol on the stack
  786. statestack.append(t)
  787. state = t
  788. symstack.append(lookahead)
  789. lookahead = None
  790. # Decrease error count on successful shift
  791. if errorcount: errorcount -=1
  792. continue
  793. if t < 0:
  794. # reduce a symbol on the stack, emit a production
  795. p = prod[-t]
  796. pname = p.name
  797. plen = p.len
  798. # Get production function
  799. sym = YaccSymbol()
  800. sym.type = pname # Production name
  801. sym.value = None
  802. if plen:
  803. targ = symstack[-plen-1:]
  804. targ[0] = sym
  805. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  806. # The code enclosed in this section is duplicated
  807. # below as a performance optimization. Make sure
  808. # changes get made in both locations.
  809. pslice.slice = targ
  810. try:
  811. # Call the grammar rule with our special slice object
  812. del symstack[-plen:]
  813. del statestack[-plen:]
  814. p.callable(pslice)
  815. symstack.append(sym)
  816. state = goto[statestack[-1]][pname]
  817. statestack.append(state)
  818. except SyntaxError:
  819. # If an error was set. Enter error recovery state
  820. lookaheadstack.append(lookahead)
  821. symstack.pop()
  822. statestack.pop()
  823. state = statestack[-1]
  824. sym.type = 'error'
  825. lookahead = sym
  826. errorcount = error_count
  827. self.errorok = 0
  828. continue
  829. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  830. else:
  831. targ = [ sym ]
  832. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  833. # The code enclosed in this section is duplicated
  834. # above as a performance optimization. Make sure
  835. # changes get made in both locations.
  836. pslice.slice = targ
  837. try:
  838. # Call the grammar rule with our special slice object
  839. p.callable(pslice)
  840. symstack.append(sym)
  841. state = goto[statestack[-1]][pname]
  842. statestack.append(state)
  843. except SyntaxError:
  844. # If an error was set. Enter error recovery state
  845. lookaheadstack.append(lookahead)
  846. symstack.pop()
  847. statestack.pop()
  848. state = statestack[-1]
  849. sym.type = 'error'
  850. lookahead = sym
  851. errorcount = error_count
  852. self.errorok = 0
  853. continue
  854. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  855. if t == 0:
  856. n = symstack[-1]
  857. return getattr(n,"value",None)
  858. if t == None:
  859. # We have some kind of parsing error here. To handle
  860. # this, we are going to push the current token onto
  861. # the tokenstack and replace it with an 'error' token.
  862. # If there are any synchronization rules, they may
  863. # catch it.
  864. #
  865. # In addition to pushing the error token, we call call
  866. # the user defined p_error() function if this is the
  867. # first syntax error. This function is only called if
  868. # errorcount == 0.
  869. if errorcount == 0 or self.errorok:
  870. errorcount = error_count
  871. self.errorok = 0
  872. errtoken = lookahead
  873. if errtoken.type == '$end':
  874. errtoken = None # End of file!
  875. if self.errorfunc:
  876. global errok,token,restart
  877. errok = self.errok # Set some special functions available in error recovery
  878. token = get_token
  879. restart = self.restart
  880. if errtoken and not hasattr(errtoken,'lexer'):
  881. errtoken.lexer = lexer
  882. tok = self.errorfunc(errtoken)
  883. del errok, token, restart # Delete special functions
  884. if self.errorok:
  885. # User must have done some kind of panic
  886. # mode recovery on their own. The
  887. # returned token is the next lookahead
  888. lookahead = tok
  889. errtoken = None
  890. continue
  891. else:
  892. if errtoken:
  893. if hasattr(errtoken,"lineno"): lineno = lookahead.lineno
  894. else: lineno = 0
  895. if lineno:
  896. sys.stderr.write("yacc: Syntax error at line %d, token=%s\n" % (lineno, errtoken.type))
  897. else:
  898. sys.stderr.write("yacc: Syntax error, token=%s" % errtoken.type)
  899. else:
  900. sys.stderr.write("yacc: Parse error in input. EOF\n")
  901. return
  902. else:
  903. errorcount = error_count
  904. # case 1: the statestack only has 1 entry on it. If we're in this state, the
  905. # entire parse has been rolled back and we're completely hosed. The token is
  906. # discarded and we just keep going.
  907. if len(statestack) <= 1 and lookahead.type != '$end':
  908. lookahead = None
  909. errtoken = None
  910. state = 0
  911. # Nuke the pushback stack
  912. del lookaheadstack[:]
  913. continue
  914. # case 2: the statestack has a couple of entries on it, but we're
  915. # at the end of the file. nuke the top entry and generate an error token
  916. # Start nuking entries on the stack
  917. if lookahead.type == '$end':
  918. # Whoa. We're really hosed here. Bail out
  919. return
  920. if lookahead.type != 'error':
  921. sym = symstack[-1]
  922. if sym.type == 'error':
  923. # Hmmm. Error is on top of stack, we'll just nuke input
  924. # symbol and continue
  925. lookahead = None
  926. continue
  927. t = YaccSymbol()
  928. t.type = 'error'
  929. if hasattr(lookahead,"lineno"):
  930. t.lineno = lookahead.lineno
  931. t.value = lookahead
  932. lookaheadstack.append(lookahead)
  933. lookahead = t
  934. else:
  935. symstack.pop()
  936. statestack.pop()
  937. state = statestack[-1] # Potential bug fix
  938. continue
  939. # Call an error function here
  940. raise RuntimeError("yacc: internal parser error!!!\n")
  941. # -----------------------------------------------------------------------------
  942. # === Grammar Representation ===
  943. #
  944. # The following functions, classes, and variables are used to represent and
  945. # manipulate the rules that make up a grammar.
  946. # -----------------------------------------------------------------------------
  947. import re
  948. # regex matching identifiers
  949. _is_identifier = re.compile(r'^[a-zA-Z0-9_-]+$')
  950. # -----------------------------------------------------------------------------
  951. # class Production:
  952. #
  953. # This class stores the raw information about a single production or grammar rule.
  954. # A grammar rule refers to a specification such as this:
  955. #
  956. # expr : expr PLUS term
  957. #
  958. # Here are the basic attributes defined on all productions
  959. #
  960. # name - Name of the production. For example 'expr'
  961. # prod - A list of symbols on the right side ['expr','PLUS','term']
  962. # prec - Production precedence level
  963. # number - Production number.
  964. # func - Function that executes on reduce
  965. # file - File where production function is defined
  966. # lineno - Line number where production function is defined
  967. #
  968. # The following attributes are defined or optional.
  969. #
  970. # len - Length of the production (number of symbols on right hand side)
  971. # usyms - Set of unique symbols found in the production
  972. # -----------------------------------------------------------------------------
  973. class Production(object):
  974. reduced = 0
  975. def __init__(self,number,name,prod,precedence=('right',0),func=None,file='',line=0):
  976. self.name = name
  977. self.prod = tuple(prod)
  978. self.number = number
  979. self.func = func
  980. self.callable = None
  981. self.file = file
  982. self.line = line
  983. self.prec = precedence
  984. # Internal settings used during table construction
  985. self.len = len(self.prod) # Length of the production
  986. # Create a list of unique production symbols used in the production
  987. self.usyms = [ ]
  988. for s in self.prod:
  989. if s not in self.usyms:
  990. self.usyms.append(s)
  991. # List of all LR items for the production
  992. self.lr_items = []
  993. self.lr_next = None
  994. # Create a string representation
  995. if self.prod:
  996. self.str = "%s -> %s" % (self.name," ".join(self.prod))
  997. else:
  998. self.str = "%s -> <empty>" % self.name
  999. def __str__(self):
  1000. return self.str
  1001. def __repr__(self):
  1002. return "Production("+str(self)+")"
  1003. def __len__(self):
  1004. return len(self.prod)
  1005. def __nonzero__(self):
  1006. return 1
  1007. def __getitem__(self,index):
  1008. return self.prod[index]
  1009. # Return the nth lr_item from the production (or None if at the end)
  1010. def lr_item(self,n):
  1011. if n > len(self.prod): return None
  1012. p = LRItem(self,n)
  1013. # Precompute the list of productions immediately following. Hack. Remove later
  1014. try:
  1015. p.lr_after = Prodnames[p.prod[n+1]]
  1016. except (IndexError,KeyError):
  1017. p.lr_after = []
  1018. try:
  1019. p.lr_before = p.prod[n-1]
  1020. except IndexError:
  1021. p.lr_before = None
  1022. return p
  1023. # Bind the production function name to a callable
  1024. def bind(self,pdict):
  1025. if self.func:
  1026. self.callable = pdict[self.func]
  1027. # This class serves as a minimal standin for Production objects when
  1028. # reading table data from files. It only contains information
  1029. # actually used by the LR parsing engine, plus some additional
  1030. # debugging information.
  1031. class MiniProduction(object):
  1032. def __init__(self,str,name,len,func,file,line):
  1033. self.name = name
  1034. self.len = len
  1035. self.func = func
  1036. self.callable = None
  1037. self.file = file
  1038. self.line = line
  1039. self.str = str
  1040. def __str__(self):
  1041. return self.str
  1042. def __repr__(self):
  1043. return "MiniProduction(%s)" % self.str
  1044. # Bind the production function name to a callable
  1045. def bind(self,pdict):
  1046. if self.func:
  1047. self.callable = pdict[self.func]
  1048. # -----------------------------------------------------------------------------
  1049. # class LRItem
  1050. #
  1051. # This class represents a specific stage of parsing a production rule. For
  1052. # example:
  1053. #
  1054. # expr : expr . PLUS term
  1055. #
  1056. # In the above, the "." represents the current location of the parse. Here
  1057. # basic attributes:
  1058. #
  1059. # name - Name of the production. For example 'expr'
  1060. # prod - A list of symbols on the right side ['expr','.', 'PLUS','term']
  1061. # number - Production number.
  1062. #
  1063. # lr_next Next LR item. Example, if we are ' expr -> expr . PLUS term'
  1064. # then lr_next refers to 'expr -> expr PLUS . term'
  1065. # lr_index - LR item index (location of the ".") in the prod list.
  1066. # lookaheads - LALR lookahead symbols for this item
  1067. # len - Length of the production (number of symbols on right hand side)
  1068. # lr_after - List of all productions that immediately follow
  1069. # lr_before - Grammar symbol immediately before
  1070. # -----------------------------------------------------------------------------
  1071. class LRItem(object):
  1072. def __init__(self,p,n):
  1073. self.name = p.name
  1074. self.prod = list(p.prod)
  1075. self.number = p.number
  1076. self.lr_index = n
  1077. self.lookaheads = { }
  1078. self.prod.insert(n,".")
  1079. self.prod = tuple(self.prod)
  1080. self.len = len(self.prod)
  1081. self.usyms = p.usyms
  1082. def __str__(self):
  1083. if self.prod:
  1084. s = "%s -> %s" % (self.name," ".join(self.prod))
  1085. else:
  1086. s = "%s -> <empty>" % self.name
  1087. return s
  1088. def __repr__(self):
  1089. return "LRItem("+str(self)+")"
  1090. # -----------------------------------------------------------------------------
  1091. # rightmost_terminal()
  1092. #
  1093. # Return the rightmost terminal from a list of symbols. Used in add_production()
  1094. # -----------------------------------------------------------------------------
  1095. def rightmost_terminal(symbols, terminals):
  1096. i = len(symbols) - 1
  1097. while i >= 0:
  1098. if symbols[i] in terminals:
  1099. return symbols[i]
  1100. i -= 1
  1101. return None
  1102. # -----------------------------------------------------------------------------
  1103. # === GRAMMAR CLASS ===
  1104. #
  1105. # The following class represents the contents of the specified grammar along
  1106. # with various computed properties such as first sets, follow sets, LR items, etc.
  1107. # This data is used for critical parts of the table generation process later.
  1108. # -----------------------------------------------------------------------------
  1109. class GrammarError(YaccError): pass
  1110. class Grammar(object):
  1111. def __init__(self,terminals):
  1112. self.Productions = [None] # A list of all of the productions. The first
  1113. # entry is always reserved for the purpose of
  1114. # building an augmented grammar
  1115. self.Prodnames = { } # A dictionary mapping the names of nonterminals to a list of all
  1116. # productions of that nonterminal.
  1117. self.Prodmap = { } # A dictionary that is only used to detect duplicate
  1118. # productions.
  1119. self.Terminals = { } # A dictionary mapping the names of terminal symbols to a
  1120. # list of the rules where they are used.
  1121. for term in terminals:
  1122. self.Terminals[term] = []
  1123. self.Terminals['error'] = []
  1124. self.Nonterminals = { } # A dictionary mapping names of nonterminals to a list
  1125. # of rule numbers where they are used.
  1126. self.First = { } # A dictionary of precomputed FIRST(x) symbols
  1127. self.Follow = { } # A dictionary of precomputed FOLLOW(x) symbols
  1128. self.Precedence = { } # Precedence rules for each terminal. Contains tuples of the
  1129. # form ('right',level) or ('nonassoc', level) or ('left',level)
  1130. self.UsedPrecedence = { } # Precedence rules that were actually used by the grammer.
  1131. # This is only used to provide error checking and to generate
  1132. # a warning about unused precedence rules.
  1133. self.Start = None # Starting symbol for the grammar
  1134. def __len__(self):
  1135. return len(self.Productions)
  1136. def __getitem__(self,index):
  1137. return self.Productions[index]
  1138. # -----------------------------------------------------------------------------
  1139. # set_precedence()
  1140. #
  1141. # Sets the precedence for a given terminal. assoc is the associativity such as
  1142. # 'left','right', or 'nonassoc'. level is a numeric level.
  1143. #
  1144. # -----------------------------------------------------------------------------
  1145. def set_precedence(self,term,assoc,level):
  1146. assert self.Productions == [None],"Must call set_precedence() before add_production()"
  1147. if term in self.Precedence:
  1148. raise GrammarError("Precedence already specified for terminal '%s'" % term)
  1149. if assoc not in ['left','right','nonassoc']:
  1150. raise GrammarError("Associativity must be one of 'left','right', or 'nonassoc'")
  1151. self.Precedence[term] = (assoc,level)
  1152. # -----------------------------------------------------------------------------
  1153. # add_production()
  1154. #
  1155. # Given an action function, this function assembles a production rule and
  1156. # computes its precedence level.
  1157. #
  1158. # The production rule is supplied as a list of symbols. For example,
  1159. # a rule such as 'expr : expr PLUS term' has a production name of 'expr' and
  1160. # symbols ['expr','PLUS','term'].
  1161. #
  1162. # Precedence is determined by the precedence of the right-most non-terminal
  1163. # or the precedence of a terminal specified by %prec.
  1164. #
  1165. # A variety of error checks are performed to make sure production symbols
  1166. # are valid and that %prec is used correctly.
  1167. # -----------------------------------------------------------------------------
  1168. def add_production(self,prodname,syms,func=None,file='',line=0):
  1169. if prodname in self.Terminals:
  1170. raise GrammarError("%s:%d: Illegal rule name '%s'. Already defined as a token" % (file,line,prodname))
  1171. if prodname == 'error':
  1172. raise GrammarError("%s:%d: Illegal rule name '%s'. error is a reserved word" % (file,line,prodname))
  1173. if not _is_identifier.match(prodname):
  1174. raise GrammarError("%s:%d: Illegal rule name '%s'" % (file,line,prodname))
  1175. # Look for literal tokens
  1176. for n,s in enumerate(syms):
  1177. if s[0] in "'\"":
  1178. try:
  1179. c = eval(s)
  1180. if (len(c) > 1):
  1181. raise GrammarError("%s:%d: Literal token %s in rule '%s' may only be a single character" % (file,line,s, prodname))
  1182. if not c in self.Terminals:
  1183. self.Terminals[c] = []
  1184. syms[n] = c
  1185. continue
  1186. except SyntaxError:
  1187. pass
  1188. if not _is_identifier.match(s) and s != '%prec':
  1189. raise GrammarError("%s:%d: Illegal name '%s' in rule '%s'" % (file,line,s, prodname))
  1190. # Determine the precedence level
  1191. if '%prec' in syms:
  1192. if syms[-1] == '%prec':
  1193. raise GrammarError("%s:%d: Syntax error. Nothing follows %%prec" % (file,line))
  1194. if syms[-2] != '%prec':
  1195. raise GrammarError("%s:%d: Syntax error. %%prec can only appear at the end of a grammar rule" % (file,line))
  1196. precname = syms[-1]
  1197. prodprec = self.Precedence.get(precname,None)
  1198. if not prodprec:
  1199. raise GrammarError("%s:%d: Nothing known about the precedence of '%s'" % (file,line,precname))
  1200. else:
  1201. self.UsedPrecedence[precname] = 1
  1202. del syms[-2:] # Drop %prec from the rule
  1203. else:
  1204. # If no %prec, precedence is determined by the rightmost terminal symbol
  1205. precname = rightmost_terminal(syms,self.Terminals)
  1206. prodprec = self.Precedence.get(precname,('right',0))
  1207. # See if the rule is already in the rulemap
  1208. map = "%s -> %s" % (prodname,syms)
  1209. if map in self.Prodmap:
  1210. m = self.Prodmap[map]
  1211. raise GrammarError("%s:%d: Duplicate rule %s. " % (file,line, m) +
  1212. "Previous definition at %s:%d" % (m.file, m.line))
  1213. # From this point on, everything is valid. Create a new Production instance
  1214. pnumber = len(self.Productions)
  1215. if not prodname in self.Nonterminals:
  1216. self.Nonterminals[prodname] = [ ]
  1217. # Add the production number to Terminals and Nonterminals
  1218. for t in syms:
  1219. if t in self.Terminals:
  1220. self.Terminals[t].append(pnumber)
  1221. else:
  1222. if not t in self.Nonterminals:
  1223. self.Nonterminals[t] = [ ]
  1224. self.Nonterminals[t].append(pnumber)
  1225. # Create a production and add it to the list of productions
  1226. p = Production(pnumber,prodname,syms,prodprec,func,file,line)
  1227. self.Productions.append(p)
  1228. self.Prodmap[map] = p
  1229. # Add to the global productions list
  1230. try:
  1231. self.Prodnames[prodname].append(p)
  1232. except KeyError:
  1233. self.Prodnames[prodname] = [ p ]
  1234. return 0
  1235. # -----------------------------------------------------------------------------
  1236. # set_start()
  1237. #
  1238. # Sets the starting symbol and creates the augmented grammar. Production
  1239. # rule 0 is S' -> start where start is the start symbol.
  1240. # -----------------------------------------------------------------------------
  1241. def set_start(self,start=None):
  1242. if not start:
  1243. start = self.Productions[1].name
  1244. if start not in self.Nonterminals:
  1245. raise GrammarError("start symbol %s undefined" % start)
  1246. self.Productions[0] = Production(0,"S'",[start])
  1247. self.Nonterminals[start].append(0)
  1248. self.Start = start
  1249. # -----------------------------------------------------------------------------
  1250. # find_unreachable()
  1251. #
  1252. # Find all of the nonterminal symbols that can't be reached from the starting
  1253. # symbol. Returns a list of nonterminals that can't be reached.
  1254. # -----------------------------------------------------------------------------
  1255. def find_unreachable(self):
  1256. # Mark all symbols that are reachable from a symbol s
  1257. def mark_reachable_from(s):
  1258. if reachable[s]:
  1259. # We've already reached symbol s.
  1260. return
  1261. reachable[s] = 1
  1262. for p in self.Prodnames.get(s,[]):
  1263. for r in p.prod:
  1264. mark_reachable_from(r)
  1265. reachable = { }
  1266. for s in list(self.Terminals) + list(self.Nonterminals):
  1267. reachable[s] = 0
  1268. mark_reachable_from( self.Productions[0].prod[0] )
  1269. return [s for s in list(self.Nonterminals)
  1270. if not reachable[s]]
  1271. # -----------------------------------------------------------------------------
  1272. # infinite_cycles()
  1273. #
  1274. # This function looks at the various parsing rules and tries to detect
  1275. # infinite recursion cycles (grammar rules where there is no possible way
  1276. # to derive a string of only terminals).
  1277. # -----------------------------------------------------------------------------
  1278. def infinite_cycles(self):
  1279. terminates = {}
  1280. # Terminals:
  1281. for t in self.Terminals:
  1282. terminates[t] = 1
  1283. terminates['$end'] = 1
  1284. # Nonterminals:
  1285. # Initialize to false:
  1286. for n in self.Nonterminals:
  1287. terminates[n] = 0
  1288. # Then propagate termination until no change:
  1289. while 1:
  1290. some_change = 0
  1291. for (n,pl) in self.Prodnames.items():
  1292. # Nonterminal n terminates iff any of its productions terminates.
  1293. for p in pl:
  1294. # Production p terminates iff all of its rhs symbols terminate.
  1295. for s in p.prod:
  1296. if not terminates[s]:
  1297. # The symbol s does not terminate,
  1298. # so production p does not terminate.
  1299. p_terminates = 0
  1300. break
  1301. else:
  1302. # didn't break from the loop,
  1303. # so every symbol s terminates
  1304. # so production p terminates.
  1305. p_terminates = 1
  1306. if p_terminates:
  1307. # symbol n terminates!
  1308. if not terminates[n]:
  1309. terminates[n] = 1
  1310. some_change = 1
  1311. # Don't need to consider any more productions for this n.
  1312. break
  1313. if not some_change:
  1314. break
  1315. infinite = []
  1316. for (s,term) in terminates.items():
  1317. if not term:
  1318. if not s in self.Prodnames and not s in self.Terminals and s != 'error':
  1319. # s is used-but-not-defined, and we've already warned of that,
  1320. # so it would be overkill to say that it's also non-terminating.
  1321. pass
  1322. else:
  1323. infinite.append(s)
  1324. return infinite
  1325. # -----------------------------------------------------------------------------
  1326. # undefined_symbols()
  1327. #
  1328. # Find all symbols that were used the grammar, but not defined as tokens or
  1329. # grammar rules. Returns a list of tuples (sym, prod) where sym in the symbol
  1330. # and prod is the production where the symbol was used.
  1331. # -----------------------------------------------------------------------------
  1332. def undefined_symbols(self):
  1333. result = []
  1334. for p in self.Productions:
  1335. if not p: continue
  1336. for s in p.prod:
  1337. if not s in self.Prodnames and not s in self.Terminals and s != 'error':
  1338. result.append((s,p))
  1339. return result
  1340. # -----------------------------------------------------------------------------
  1341. # unused_terminals()
  1342. #
  1343. # Find all terminals that were defined, but not used by the grammar. Returns
  1344. # a list of all symbols.
  1345. # -----------------------------------------------------------------------------
  1346. def unused_terminals(self):
  1347. unused_tok = []
  1348. for s,v in self.Terminals.items():
  1349. if s != 'error' and not v:
  1350. unused_tok.append(s)
  1351. return unused_tok
  1352. # ------------------------------------------------------------------------------
  1353. # unused_rules()
  1354. #
  1355. # Find all grammar rules that were defined, but not used (maybe not reachable)
  1356. # Returns a list of productions.
  1357. # ------------------------------------------------------------------------------
  1358. def unused_rules(self):
  1359. unused_prod = []
  1360. for s,v in self.Nonterminals.items():
  1361. if not v:
  1362. p = self.Prodnames[s][0]
  1363. unused_prod.append(p)
  1364. return unused_prod
  1365. # -----------------------------------------------------------------------------
  1366. # unused_precedence()
  1367. #
  1368. # Returns a list of tuples (term,precedence) corresponding to precedence
  1369. # rules that were never used by the grammar. term is the name of the terminal
  1370. # on which precedence was applied and precedence is a string such as 'left' or
  1371. # 'right' corresponding to the type of precedence.
  1372. # -----------------------------------------------------------------------------
  1373. def unused_precedence(self):
  1374. unused = []
  1375. for termname in self.Precedence:
  1376. if not (termname in self.Terminals or termname in self.UsedPrecedence):
  1377. unused.append((termname,self.Precedence[termname][0]))
  1378. return unused
  1379. # -------------------------------------------------------------------------
  1380. # _first()
  1381. #
  1382. # Compute the value of FIRST1(beta) where beta is a tuple of symbols.
  1383. #
  1384. # During execution of compute_first1, the result may be incomplete.
  1385. # Afterward (e.g., when called from compute_follow()), it will be complete.
  1386. # -------------------------------------------------------------------------
  1387. def _first(self,beta):
  1388. # We are computing First(x1,x2,x3,...,xn)
  1389. result = [ ]
  1390. for x in beta:
  1391. x_produces_empty = 0
  1392. # Add all the non-<empty> symbols of First[x] to the result.
  1393. for f in self.First[x]:
  1394. if f == '<empty>':
  1395. x_produces_empty = 1
  1396. else:
  1397. if f not in result: result.append(f)
  1398. if x_produces_empty:
  1399. # We have to consider the next x in beta,
  1400. # i.e. stay in the loop.
  1401. pass
  1402. else:
  1403. # We don't have to consider any further symbols in beta.
  1404. break
  1405. else:
  1406. # There was no 'break' from the loop,
  1407. # so x_produces_empty was true for all x in beta,
  1408. # so beta produces empty as well.
  1409. result.append('<empty>')
  1410. return result
  1411. # -------------------------------------------------------------------------
  1412. # compute_first()
  1413. #
  1414. # Compute the value of FIRST1(X) for all symbols
  1415. # -------------------------------------------------------------------------
  1416. def compute_first(self):
  1417. if self.First:
  1418. return self.First
  1419. # Terminals:
  1420. for t in self.Terminals:
  1421. self.First[t] = [t]
  1422. self.First['$end'] = ['$end']
  1423. # Nonterminals:
  1424. # Initialize to the empty set:
  1425. for n in self.Nonterminals:
  1426. self.First[n] = []
  1427. # Then propagate symbols until no change:
  1428. while 1:
  1429. some_change = 0
  1430. for n in self.Nonterminals:
  1431. for p in self.Prodnames[n]:
  1432. for f in self._first(p.prod):
  1433. if f not in self.First[n]:
  1434. self.First[n].append( f )
  1435. some_change = 1
  1436. if not some_change:
  1437. break
  1438. return self.First
  1439. # ---------------------------------------------------------------------
  1440. # compute_follow()
  1441. #
  1442. # Computes all of the follow sets for every non-terminal symbol. The
  1443. # follow set is the set of all symbols that might follow a given
  1444. # non-terminal. See the Dragon book, 2nd Ed. p. 189.
  1445. # ---------------------------------------------------------------------
  1446. def compute_follow(self,start=None):
  1447. # If already computed, return the result
  1448. if self.Follow:
  1449. return self.Follow
  1450. # If first sets not computed yet, do that first.
  1451. if not self.First:
  1452. self.compute_first()
  1453. # Add '$end' to the follow list of the start symbol
  1454. for k in self.Nonterminals:
  1455. self.Follow[k] = [ ]
  1456. if not start:
  1457. start = self.Productions[1].name
  1458. self.Follow[start] = [ '$end' ]
  1459. while 1:
  1460. didadd = 0
  1461. for p in self.Productions[1:]:
  1462. # Here is the production set
  1463. for i in range(len(p.prod)):
  1464. B = p.prod[i]
  1465. if B in self.Nonterminals:
  1466. # Okay. We got a non-terminal in a production
  1467. fst = self._first(p.prod[i+1:])
  1468. hasempty = 0
  1469. for f in fst:
  1470. if f != '<empty>' and f not in self.Follow[B]:
  1471. self.Follow[B].append(f)
  1472. didadd = 1
  1473. if f == '<empty>':
  1474. hasempty = 1
  1475. if hasempty or i == (len(p.prod)-1):
  1476. # Add elements of follow(a) to follow(b)
  1477. for f in self.Follow[p.name]:
  1478. if f not in self.Follow[B]:
  1479. self.Follow[B].append(f)
  1480. didadd = 1
  1481. if not didadd: break
  1482. return self.Follow
  1483. # -----------------------------------------------------------------------------
  1484. # build_lritems()
  1485. #
  1486. # This function walks the list of productions and builds a complete set of the
  1487. # LR items. The LR items are stored in two ways: First, they are uniquely
  1488. # numbered and placed in the list _lritems. Second, a linked list of LR items
  1489. # is built for each production. For example:
  1490. #
  1491. # E -> E PLUS E
  1492. #
  1493. # Creates the list
  1494. #
  1495. # [E -> . E PLUS E, E -> E . PLUS E, E -> E PLUS . E, E -> E PLUS E . ]
  1496. # -----------------------------------------------------------------------------
  1497. def build_lritems(self):
  1498. for p in self.Productions:
  1499. lastlri = p
  1500. i = 0
  1501. lr_items = []
  1502. while 1:
  1503. if i > len(p):
  1504. lri = None
  1505. else:
  1506. lri = LRItem(p,i)
  1507. # Precompute the list of productions immediately following
  1508. try:
  1509. lri.lr_after = self.Prodnames[lri.prod[i+1]]
  1510. except (IndexError,KeyError):
  1511. lri.lr_after = []
  1512. try:
  1513. lri.lr_before = lri.prod[i-1]
  1514. except IndexError:
  1515. lri.lr_before = None
  1516. lastlri.lr_next = lri
  1517. if not lri: break
  1518. lr_items.append(lri)
  1519. lastlri = lri
  1520. i += 1
  1521. p.lr_items = lr_items
  1522. # -----------------------------------------------------------------------------
  1523. # == Class LRTable ==
  1524. #
  1525. # This basic class represents a basic table of LR parsing information.
  1526. # Methods for generating the tables are not defined here. They are defined
  1527. # in the derived class LRGeneratedTable.
  1528. # -----------------------------------------------------------------------------
  1529. class VersionError(YaccError): pass
  1530. class LRTable(object):
  1531. def __init__(self):
  1532. self.lr_action = None
  1533. self.lr_goto = None
  1534. self.lr_productions = None
  1535. self.lr_method = None
  1536. def read_table(self,module):
  1537. if isinstance(module,types.ModuleType):
  1538. parsetab = module
  1539. else:
  1540. if sys.version_info[0] < 3:
  1541. exec("import %s as parsetab" % module)
  1542. else:
  1543. env = { }
  1544. exec("import %s as parsetab" % module, env, env)
  1545. parsetab = env['parsetab']
  1546. if parsetab._tabversion != __tabversion__:
  1547. raise VersionError("yacc table file version is out of date")
  1548. self.lr_action = parsetab._lr_action
  1549. self.lr_goto = parsetab._lr_goto
  1550. self.lr_productions = []
  1551. for p in parsetab._lr_productions:
  1552. self.lr_productions.append(MiniProduction(*p))
  1553. self.lr_method = parsetab._lr_method
  1554. return parsetab._lr_signature
  1555. def read_pickle(self,filename):
  1556. try:
  1557. import cPickle as pickle
  1558. except ImportError:
  1559. import pickle
  1560. in_f = open(filename,"rb")
  1561. tabversion = pickle.load(in_f)
  1562. if tabversion != __tabversion__:
  1563. raise VersionError("yacc table file version is out of date")
  1564. self.lr_method = pickle.load(in_f)
  1565. signature = pickle.load(in_f)
  1566. self.lr_action = pickle.load(in_f)
  1567. self.lr_goto = pickle.load(in_f)
  1568. productions = pickle.load(in_f)
  1569. self.lr_productions = []
  1570. for p in productions:
  1571. self.lr_productions.append(MiniProduction(*p))
  1572. in_f.close()
  1573. return signature
  1574. # Bind all production function names to callable objects in pdict
  1575. def bind_callables(self,pdict):
  1576. for p in self.lr_productions:
  1577. p.bind(pdict)
  1578. # -----------------------------------------------------------------------------
  1579. # === LR Generator ===
  1580. #
  1581. # The following classes and functions are used to generate LR parsing tables on
  1582. # a grammar.
  1583. # -----------------------------------------------------------------------------
  1584. # -----------------------------------------------------------------------------
  1585. # digraph()
  1586. # traverse()
  1587. #
  1588. # The following two functions are used to compute set valued functions
  1589. # of the form:
  1590. #
  1591. # F(x) = F'(x) U U{F(y) | x R y}
  1592. #
  1593. # This is used to compute the values of Read() sets as well as FOLLOW sets
  1594. # in LALR(1) generation.
  1595. #
  1596. # Inputs: X - An input set
  1597. # R - A relation
  1598. # FP - Set-valued function
  1599. # ------------------------------------------------------------------------------
  1600. def digraph(X,R,FP):
  1601. N = { }
  1602. for x in X:
  1603. N[x] = 0
  1604. stack = []
  1605. F = { }
  1606. for x in X:
  1607. if N[x] == 0: traverse(x,N,stack,F,X,R,FP)
  1608. return F
  1609. def traverse(x,N,stack,F,X,R,FP):
  1610. stack.append(x)
  1611. d = len(stack)
  1612. N[x] = d
  1613. F[x] = FP(x) # F(X) <- F'(x)
  1614. rel = R(x) # Get y's related to x
  1615. for y in rel:
  1616. if N[y] == 0:
  1617. traverse(y,N,stack,F,X,R,FP)
  1618. N[x] = min(N[x],N[y])
  1619. for a in F.get(y,[]):
  1620. if a not in F[x]: F[x].append(a)
  1621. if N[x] == d:
  1622. N[stack[-1]] = MAXINT
  1623. F[stack[-1]] = F[x]
  1624. element = stack.pop()
  1625. while element != x:
  1626. N[stack[-1]] = MAXINT
  1627. F[stack[-1]] = F[x]
  1628. element = stack.pop()
  1629. class LALRError(YaccError): pass
  1630. # -----------------------------------------------------------------------------
  1631. # == LRGeneratedTable ==
  1632. #
  1633. # This class implements the LR table generation algorithm. There are no
  1634. # public methods except for write()
  1635. # -----------------------------------------------------------------------------
  1636. class LRGeneratedTable(LRTable):
  1637. def __init__(self,grammar,method='LALR',log=None):
  1638. if method not in ['SLR','LALR']:
  1639. raise LALRError("Unsupported method %s" % method)
  1640. self.grammar = grammar
  1641. self.lr_method = method
  1642. # Set up the logger
  1643. if not log:
  1644. log = NullLogger()
  1645. self.log = log
  1646. # Internal attributes
  1647. self.lr_action = {} # Action table
  1648. self.lr_goto = {} # Goto table
  1649. self.lr_productions = grammar.Productions # Copy of grammar Production array
  1650. self.lr_goto_cache = {} # Cache of computed gotos
  1651. self.lr0_cidhash = {} # Cache of closures
  1652. self._add_count = 0 # Internal counter used to detect cycles
  1653. # Diagonistic information filled in by the table generator
  1654. self.sr_conflict = 0
  1655. self.rr_conflict = 0
  1656. self.conflicts = [] # List of conflicts
  1657. self.sr_conflicts = []
  1658. self.rr_conflicts = []
  1659. # Build the tables
  1660. self.grammar.build_lritems()
  1661. self.grammar.compute_first()
  1662. self.grammar.compute_follow()
  1663. self.lr_parse_table()
  1664. # Compute the LR(0) closure operation on I, where I is a set of LR(0) items.
  1665. def lr0_closure(self,I):
  1666. self._add_count += 1
  1667. # Add everything in I to J
  1668. J = I[:]
  1669. didadd = 1
  1670. while didadd:
  1671. didadd = 0
  1672. for j in J:
  1673. for x in j.lr_after:
  1674. if getattr(x,"lr0_added",0) == self._add_count: continue
  1675. # Add B --> .G to J
  1676. J.append(x.lr_next)
  1677. x.lr0_added = self._add_count
  1678. didadd = 1
  1679. return J
  1680. # Compute the LR(0) goto function goto(I,X) where I is a set
  1681. # of LR(0) items and X is a grammar symbol. This function is written
  1682. # in a way that guarantees uniqueness of the generated goto sets
  1683. # (i.e. the same goto set will never be returned as two different Python
  1684. # objects). With uniqueness, we can later do fast set comparisons using
  1685. # id(obj) instead of element-wise comparison.
  1686. def lr0_goto(self,I,x):
  1687. # First we look for a previously cached entry
  1688. g = self.lr_goto_cache.get((id(I),x),None)
  1689. if g: return g
  1690. # Now we generate the goto set in a way that guarantees uniqueness
  1691. # of the result
  1692. s = self.lr_goto_cache.get(x,None)
  1693. if not s:
  1694. s = { }
  1695. self.lr_goto_cache[x] = s
  1696. gs = [ ]
  1697. for p in I:
  1698. n = p.lr_next
  1699. if n and n.lr_before == x:
  1700. s1 = s.get(id(n),None)
  1701. if not s1:
  1702. s1 = { }
  1703. s[id(n)] = s1
  1704. gs.append(n)
  1705. s = s1
  1706. g = s.get('$end',None)
  1707. if not g:
  1708. if gs:
  1709. g = self.lr0_closure(gs)
  1710. s['$end'] = g
  1711. else:
  1712. s['$end'] = gs
  1713. self.lr_goto_cache[(id(I),x)] = g
  1714. return g
  1715. # Compute the LR(0) sets of item function
  1716. def lr0_items(self):
  1717. C = [ self.lr0_closure([self.grammar.Productions[0].lr_next]) ]
  1718. i = 0
  1719. for I in C:
  1720. self.lr0_cidhash[id(I)] = i
  1721. i += 1
  1722. # Loop over the items in C and each grammar symbols
  1723. i = 0
  1724. while i < len(C):
  1725. I = C[i]
  1726. i += 1
  1727. # Collect all of the symbols that could possibly be in the goto(I,X) sets
  1728. asyms = { }
  1729. for ii in I:
  1730. for s in ii.usyms:
  1731. asyms[s] = None
  1732. for x in asyms:
  1733. g = self.lr0_goto(I,x)
  1734. if not g: continue
  1735. if id(g) in self.lr0_cidhash: continue
  1736. self.lr0_cidhash[id(g)] = len(C)
  1737. C.append(g)
  1738. return C
  1739. # -----------------------------------------------------------------------------
  1740. # ==== LALR(1) Parsing ====
  1741. #
  1742. # LALR(1) parsing is almost exactly the same as SLR except that instead of
  1743. # relying upon Follow() sets when performing reductions, a more selective
  1744. # lookahead set that incorporates the state of the LR(0) machine is utilized.
  1745. # Thus, we mainly just have to focus on calculating the lookahead sets.
  1746. #
  1747. # The method used here is due to DeRemer and Pennelo (1982).
  1748. #
  1749. # DeRemer, F. L., and T. J. Pennelo: "Efficient Computation of LALR(1)
  1750. # Lookahead Sets", ACM Transactions on Programming Languages and Systems,
  1751. # Vol. 4, No. 4, Oct. 1982, pp. 615-649
  1752. #
  1753. # Further details can also be found in:
  1754. #
  1755. # J. Tremblay and P. Sorenson, "The Theory and Practice of Compiler Writing",
  1756. # McGraw-Hill Book Company, (1985).
  1757. #
  1758. # -----------------------------------------------------------------------------
  1759. # -----------------------------------------------------------------------------
  1760. # compute_nullable_nonterminals()
  1761. #
  1762. # Creates a dictionary containing all of the non-terminals that might produce
  1763. # an empty production.
  1764. # -----------------------------------------------------------------------------
  1765. def compute_nullable_nonterminals(self):
  1766. nullable = {}
  1767. num_nullable = 0
  1768. while 1:
  1769. for p in self.grammar.Productions[1:]:
  1770. if p.len == 0:
  1771. nullable[p.name] = 1
  1772. continue
  1773. for t in p.prod:
  1774. if not t in nullable: break
  1775. else:
  1776. nullable[p.name] = 1
  1777. if len(nullable) == num_nullable: break
  1778. num_nullable = len(nullable)
  1779. return nullable
  1780. # -----------------------------------------------------------------------------
  1781. # find_nonterminal_trans(C)
  1782. #
  1783. # Given a set of LR(0) items, this functions finds all of the non-terminal
  1784. # transitions. These are transitions in which a dot appears immediately before
  1785. # a non-terminal. Returns a list of tuples of the form (state,N) where state
  1786. # is the state number and N is the nonterminal symbol.
  1787. #
  1788. # The input C is the set of LR(0) items.
  1789. # -----------------------------------------------------------------------------
  1790. def find_nonterminal_transitions(self,C):
  1791. trans = []
  1792. for state in range(len(C)):
  1793. for p in C[state]:
  1794. if p.lr_index < p.len - 1:
  1795. t = (state,p.prod[p.lr_index+1])
  1796. if t[1] in self.grammar.Nonterminals:
  1797. if t not in trans: trans.append(t)
  1798. state = state + 1
  1799. return trans
  1800. # -----------------------------------------------------------------------------
  1801. # dr_relation()
  1802. #
  1803. # Computes the DR(p,A) relationships for non-terminal transitions. The input
  1804. # is a tuple (state,N) where state is a number and N is a nonterminal symbol.
  1805. #
  1806. # Returns a list of terminals.
  1807. # -----------------------------------------------------------------------------
  1808. def dr_relation(self,C,trans,nullable):
  1809. dr_set = { }
  1810. state,N = trans
  1811. terms = []
  1812. g = self.lr0_goto(C[state],N)
  1813. for p in g:
  1814. if p.lr_index < p.len - 1:
  1815. a = p.prod[p.lr_index+1]
  1816. if a in self.grammar.Terminals:
  1817. if a not in terms: terms.append(a)
  1818. # This extra bit is to handle the start state
  1819. if state == 0 and N == self.grammar.Productions[0].prod[0]:
  1820. terms.append('$end')
  1821. return terms
  1822. # -----------------------------------------------------------------------------
  1823. # reads_relation()
  1824. #
  1825. # Computes the READS() relation (p,A) READS (t,C).
  1826. # -----------------------------------------------------------------------------
  1827. def reads_relation(self,C, trans, empty):
  1828. # Look for empty transitions
  1829. rel = []
  1830. state, N = trans
  1831. g = self.lr0_goto(C[state],N)
  1832. j = self.lr0_cidhash.get(id(g),-1)
  1833. for p in g:
  1834. if p.lr_index < p.len - 1:
  1835. a = p.prod[p.lr_index + 1]
  1836. if a in empty:
  1837. rel.append((j,a))
  1838. return rel
  1839. # -----------------------------------------------------------------------------
  1840. # compute_lookback_includes()
  1841. #
  1842. # Determines the lookback and includes relations
  1843. #
  1844. # LOOKBACK:
  1845. #
  1846. # This relation is determined by running the LR(0) state machine forward.
  1847. # For example, starting with a production "N : . A B C", we run it forward
  1848. # to obtain "N : A B C ." We then build a relationship between this final
  1849. # state and the starting state. These relationships are stored in a dictionary
  1850. # lookdict.
  1851. #
  1852. # INCLUDES:
  1853. #
  1854. # Computes the INCLUDE() relation (p,A) INCLUDES (p',B).
  1855. #
  1856. # This relation is used to determine non-terminal transitions that occur
  1857. # inside of other non-terminal transition states. (p,A) INCLUDES (p', B)
  1858. # if the following holds:
  1859. #
  1860. # B -> LAT, where T -> epsilon and p' -L-> p
  1861. #
  1862. # L is essentially a prefix (which may be empty), T is a suffix that must be
  1863. # able to derive an empty string. State p' must lead to state p with the string L.
  1864. #
  1865. # -----------------------------------------------------------------------------
  1866. def compute_lookback_includes(self,C,trans,nullable):
  1867. lookdict = {} # Dictionary of lookback relations
  1868. includedict = {} # Dictionary of include relations
  1869. # Make a dictionary of non-terminal transitions
  1870. dtrans = {}
  1871. for t in trans:
  1872. dtrans[t] = 1
  1873. # Loop over all transitions and compute lookbacks and includes
  1874. for state,N in trans:
  1875. lookb = []
  1876. includes = []
  1877. for p in C[state]:
  1878. if p.name != N: continue
  1879. # Okay, we have a name match. We now follow the production all the way
  1880. # through the state machine until we get the . on the right hand side
  1881. lr_index = p.lr_index
  1882. j = state
  1883. while lr_index < p.len - 1:
  1884. lr_index = lr_index + 1
  1885. t = p.prod[lr_index]
  1886. # Check to see if this symbol and state are a non-terminal transition
  1887. if (j,t) in dtrans:
  1888. # Yes. Okay, there is some chance that this is an includes relation
  1889. # the only way to know for certain is whether the rest of the
  1890. # production derives empty
  1891. li = lr_index + 1
  1892. while li < p.len:
  1893. if p.prod[li] in self.grammar.Terminals: break # No forget it
  1894. if not p.prod[li] in nullable: break
  1895. li = li + 1
  1896. else:
  1897. # Appears to be a relation between (j,t) and (state,N)
  1898. includes.append((j,t))
  1899. g = self.lr0_goto(C[j],t) # Go to next set
  1900. j = self.lr0_cidhash.get(id(g),-1) # Go to next state
  1901. # When we get here, j is the final state, now we have to locate the production
  1902. for r in C[j]:
  1903. if r.name != p.name: continue
  1904. if r.len != p.len: continue
  1905. i = 0
  1906. # This look is comparing a production ". A B C" with "A B C ."
  1907. while i < r.lr_index:
  1908. if r.prod[i] != p.prod[i+1]: break
  1909. i = i + 1
  1910. else:
  1911. lookb.append((j,r))
  1912. for i in includes:
  1913. if not i in includedict: includedict[i] = []
  1914. includedict[i].append((state,N))
  1915. lookdict[(state,N)] = lookb
  1916. return lookdict,includedict
  1917. # -----------------------------------------------------------------------------
  1918. # compute_read_sets()
  1919. #
  1920. # Given a set of LR(0) items, this function computes the read sets.
  1921. #
  1922. # Inputs: C = Set of LR(0) items
  1923. # ntrans = Set of nonterminal transitions
  1924. # nullable = Set of empty transitions
  1925. #
  1926. # Returns a set containing the read sets
  1927. # -----------------------------------------------------------------------------
  1928. def compute_read_sets(self,C, ntrans, nullable):
  1929. FP = lambda x: self.dr_relation(C,x,nullable)
  1930. R = lambda x: self.reads_relation(C,x,nullable)
  1931. F = digraph(ntrans,R,FP)
  1932. return F
  1933. # -----------------------------------------------------------------------------
  1934. # compute_follow_sets()
  1935. #
  1936. # Given a set of LR(0) items, a set of non-terminal transitions, a readset,
  1937. # and an include set, this function computes the follow sets
  1938. #
  1939. # Follow(p,A) = Read(p,A) U U {Follow(p',B) | (p,A) INCLUDES (p',B)}
  1940. #
  1941. # Inputs:
  1942. # ntrans = Set of nonterminal transitions
  1943. # readsets = Readset (previously computed)
  1944. # inclsets = Include sets (previously computed)
  1945. #
  1946. # Returns a set containing the follow sets
  1947. # -----------------------------------------------------------------------------
  1948. def compute_follow_sets(self,ntrans,readsets,inclsets):
  1949. FP = lambda x: readsets[x]
  1950. R = lambda x: inclsets.get(x,[])
  1951. F = digraph(ntrans,R,FP)
  1952. return F
  1953. # -----------------------------------------------------------------------------
  1954. # add_lookaheads()
  1955. #
  1956. # Attaches the lookahead symbols to grammar rules.
  1957. #
  1958. # Inputs: lookbacks - Set of lookback relations
  1959. # followset - Computed follow set
  1960. #
  1961. # This function directly attaches the lookaheads to productions contained
  1962. # in the lookbacks set
  1963. # -----------------------------------------------------------------------------
  1964. def add_lookaheads(self,lookbacks,followset):
  1965. for trans,lb in lookbacks.items():
  1966. # Loop over productions in lookback
  1967. for state,p in lb:
  1968. if not state in p.lookaheads:
  1969. p.lookaheads[state] = []
  1970. f = followset.get(trans,[])
  1971. for a in f:
  1972. if a not in p.lookaheads[state]: p.lookaheads[state].append(a)
  1973. # -----------------------------------------------------------------------------
  1974. # add_lalr_lookaheads()
  1975. #
  1976. # This function does all of the work of adding lookahead information for use
  1977. # with LALR parsing
  1978. # -----------------------------------------------------------------------------
  1979. def add_lalr_lookaheads(self,C):
  1980. # Determine all of the nullable nonterminals
  1981. nullable = self.compute_nullable_nonterminals()
  1982. # Find all non-terminal transitions
  1983. trans = self.find_nonterminal_transitions(C)
  1984. # Compute read sets
  1985. readsets = self.compute_read_sets(C,trans,nullable)
  1986. # Compute lookback/includes relations
  1987. lookd, included = self.compute_lookback_includes(C,trans,nullable)
  1988. # Compute LALR FOLLOW sets
  1989. followsets = self.compute_follow_sets(trans,readsets,included)
  1990. # Add all of the lookaheads
  1991. self.add_lookaheads(lookd,followsets)
  1992. # -----------------------------------------------------------------------------
  1993. # lr_parse_table()
  1994. #
  1995. # This function constructs the parse tables for SLR or LALR
  1996. # -----------------------------------------------------------------------------
  1997. def lr_parse_table(self):
  1998. Productions = self.grammar.Productions
  1999. Precedence = self.grammar.Precedence
  2000. goto = self.lr_goto # Goto array
  2001. action = self.lr_action # Action array
  2002. log = self.log # Logger for output
  2003. actionp = { } # Action production array (temporary)
  2004. log.info("Parsing method: %s", self.lr_method)
  2005. # Step 1: Construct C = { I0, I1, ... IN}, collection of LR(0) items
  2006. # This determines the number of states
  2007. C = self.lr0_items()
  2008. if self.lr_method == 'LALR':
  2009. self.add_lalr_lookaheads(C)
  2010. # Build the parser table, state by state
  2011. st = 0
  2012. for I in C:
  2013. # Loop over each production in I
  2014. actlist = [ ] # List of actions
  2015. st_action = { }
  2016. st_actionp = { }
  2017. st_goto = { }
  2018. log.info("")
  2019. log.info("state %d", st)
  2020. log.info("")
  2021. for p in I:
  2022. log.info(" (%d) %s", p.number, str(p))
  2023. log.info("")
  2024. for p in I:
  2025. if p.len == p.lr_index + 1:
  2026. if p.name == "S'":
  2027. # Start symbol. Accept!
  2028. st_action["$end"] = 0
  2029. st_actionp["$end"] = p
  2030. else:
  2031. # We are at the end of a production. Reduce!
  2032. if self.lr_method == 'LALR':
  2033. laheads = p.lookaheads[st]
  2034. else:
  2035. laheads = self.grammar.Follow[p.name]
  2036. for a in laheads:
  2037. actlist.append((a,p,"reduce using rule %d (%s)" % (p.number,p)))
  2038. r = st_action.get(a,None)
  2039. if r is not None:
  2040. # Whoa. Have a shift/reduce or reduce/reduce conflict
  2041. if r > 0:
  2042. # Need to decide on shift or reduce here
  2043. # By default we favor shifting. Need to add
  2044. # some precedence rules here.
  2045. sprec,slevel = Productions[st_actionp[a].number].prec
  2046. rprec,rlevel = Precedence.get(a,('right',0))
  2047. if (slevel < rlevel) or ((slevel == rlevel) and (rprec == 'left')):
  2048. # We really need to reduce here.
  2049. st_action[a] = -p.number
  2050. st_actionp[a] = p
  2051. if not slevel and not rlevel:
  2052. log.info(" ! shift/reduce conflict for %s resolved as reduce",a)
  2053. self.sr_conflicts.append((st,a,'reduce'))
  2054. Productions[p.number].reduced += 1
  2055. elif (slevel == rlevel) and (rprec == 'nonassoc'):
  2056. st_action[a] = None
  2057. else:
  2058. # Hmmm. Guess we'll keep the shift
  2059. if not rlevel:
  2060. log.info(" ! shift/reduce conflict for %s resolved as shift",a)
  2061. self.sr_conflicts.append((st,a,'shift'))
  2062. elif r < 0:
  2063. # Reduce/reduce conflict. In this case, we favor the rule
  2064. # that was defined first in the grammar file
  2065. oldp = Productions[-r]
  2066. pp = Productions[p.number]
  2067. if oldp.line > pp.line:
  2068. st_action[a] = -p.number
  2069. st_actionp[a] = p
  2070. chosenp,rejectp = pp,oldp
  2071. Productions[p.number].reduced += 1
  2072. Productions[oldp.number].reduced -= 1
  2073. else:
  2074. chosenp,rejectp = oldp,pp
  2075. self.rr_conflicts.append((st,chosenp,rejectp))
  2076. log.info(" ! reduce/reduce conflict for %s resolved using rule %d (%s)", a,st_actionp[a].number, st_actionp[a])
  2077. else:
  2078. raise LALRError("Unknown conflict in state %d" % st)
  2079. else:
  2080. st_action[a] = -p.number
  2081. st_actionp[a] = p
  2082. Productions[p.number].reduced += 1
  2083. else:
  2084. i = p.lr_index
  2085. a = p.prod[i+1] # Get symbol right after the "."
  2086. if a in self.grammar.Terminals:
  2087. g = self.lr0_goto(I,a)
  2088. j = self.lr0_cidhash.get(id(g),-1)
  2089. if j >= 0:
  2090. # We are in a shift state
  2091. actlist.append((a,p,"shift and go to state %d" % j))
  2092. r = st_action.get(a,None)
  2093. if r is not None:
  2094. # Whoa have a shift/reduce or shift/shift conflict
  2095. if r > 0:
  2096. if r != j:
  2097. raise LALRError("Shift/shift conflict in state %d" % st)
  2098. elif r < 0:
  2099. # Do a precedence check.
  2100. # - if precedence of reduce rule is higher, we reduce.
  2101. # - if precedence of reduce is same and left assoc, we reduce.
  2102. # - otherwise we shift
  2103. rprec,rlevel = Productions[st_actionp[a].number].prec
  2104. sprec,slevel = Precedence.get(a,('right',0))
  2105. if (slevel > rlevel) or ((slevel == rlevel) and (rprec == 'right')):
  2106. # We decide to shift here... highest precedence to shift
  2107. Productions[st_actionp[a].number].reduced -= 1
  2108. st_action[a] = j
  2109. st_actionp[a] = p
  2110. if not rlevel:
  2111. log.info(" ! shift/reduce conflict for %s resolved as shift",a)
  2112. self.sr_conflicts.append((st,a,'shift'))
  2113. elif (slevel == rlevel) and (rprec == 'nonassoc'):
  2114. st_action[a] = None
  2115. else:
  2116. # Hmmm. Guess we'll keep the reduce
  2117. if not slevel and not rlevel:
  2118. log.info(" ! shift/reduce conflict for %s resolved as reduce",a)
  2119. self.sr_conflicts.append((st,a,'reduce'))
  2120. else:
  2121. raise LALRError("Unknown conflict in state %d" % st)
  2122. else:
  2123. st_action[a] = j
  2124. st_actionp[a] = p
  2125. # Print the actions associated with each terminal
  2126. _actprint = { }
  2127. for a,p,m in actlist:
  2128. if a in st_action:
  2129. if p is st_actionp[a]:
  2130. log.info(" %-15s %s",a,m)
  2131. _actprint[(a,m)] = 1
  2132. log.info("")
  2133. # Print the actions that were not used. (debugging)
  2134. not_used = 0
  2135. for a,p,m in actlist:
  2136. if a in st_action:
  2137. if p is not st_actionp[a]:
  2138. if not (a,m) in _actprint:
  2139. log.debug(" ! %-15s [ %s ]",a,m)
  2140. not_used = 1
  2141. _actprint[(a,m)] = 1
  2142. if not_used:
  2143. log.debug("")
  2144. # Construct the goto table for this state
  2145. nkeys = { }
  2146. for ii in I:
  2147. for s in ii.usyms:
  2148. if s in self.grammar.Nonterminals:
  2149. nkeys[s] = None
  2150. for n in nkeys:
  2151. g = self.lr0_goto(I,n)
  2152. j = self.lr0_cidhash.get(id(g),-1)
  2153. if j >= 0:
  2154. st_goto[n] = j
  2155. log.info(" %-30s shift and go to state %d",n,j)
  2156. action[st] = st_action
  2157. actionp[st] = st_actionp
  2158. goto[st] = st_goto
  2159. st += 1
  2160. # -----------------------------------------------------------------------------
  2161. # write()
  2162. #
  2163. # This function writes the LR parsing tables to a file
  2164. # -----------------------------------------------------------------------------
  2165. def write_table(self,modulename,outputdir='',signature=""):
  2166. basemodulename = modulename.split(".")[-1]
  2167. filename = os.path.join(outputdir,basemodulename) + ".py"
  2168. try:
  2169. f = open(filename,"w")
  2170. f.write("""
  2171. # %s
  2172. # This file is automatically generated. Do not edit.
  2173. _tabversion = %r
  2174. _lr_method = %r
  2175. _lr_signature = %r
  2176. """ % (filename, __tabversion__, self.lr_method, signature))
  2177. # Change smaller to 0 to go back to original tables
  2178. smaller = 1
  2179. # Factor out names to try and make smaller
  2180. if smaller:
  2181. items = { }
  2182. for s,nd in self.lr_action.items():
  2183. for name,v in nd.items():
  2184. i = items.get(name)
  2185. if not i:
  2186. i = ([],[])
  2187. items[name] = i
  2188. i[0].append(s)
  2189. i[1].append(v)
  2190. f.write("\n_lr_action_items = {")
  2191. for k,v in items.items():
  2192. f.write("%r:([" % k)
  2193. for i in v[0]:
  2194. f.write("%r," % i)
  2195. f.write("],[")
  2196. for i in v[1]:
  2197. f.write("%r," % i)
  2198. f.write("]),")
  2199. f.write("}\n")
  2200. f.write("""
  2201. _lr_action = { }
  2202. for _k, _v in _lr_action_items.items():
  2203. for _x,_y in zip(_v[0],_v[1]):
  2204. if not _x in _lr_action: _lr_action[_x] = { }
  2205. _lr_action[_x][_k] = _y
  2206. del _lr_action_items
  2207. """)
  2208. else:
  2209. f.write("\n_lr_action = { ");
  2210. for k,v in self.lr_action.items():
  2211. f.write("(%r,%r):%r," % (k[0],k[1],v))
  2212. f.write("}\n");
  2213. if smaller:
  2214. # Factor out names to try and make smaller
  2215. items = { }
  2216. for s,nd in self.lr_goto.items():
  2217. for name,v in nd.items():
  2218. i = items.get(name)
  2219. if not i:
  2220. i = ([],[])
  2221. items[name] = i
  2222. i[0].append(s)
  2223. i[1].append(v)
  2224. f.write("\n_lr_goto_items = {")
  2225. for k,v in items.items():
  2226. f.write("%r:([" % k)
  2227. for i in v[0]:
  2228. f.write("%r," % i)
  2229. f.write("],[")
  2230. for i in v[1]:
  2231. f.write("%r," % i)
  2232. f.write("]),")
  2233. f.write("}\n")
  2234. f.write("""
  2235. _lr_goto = { }
  2236. for _k, _v in _lr_goto_items.items():
  2237. for _x,_y in zip(_v[0],_v[1]):
  2238. if not _x in _lr_goto: _lr_goto[_x] = { }
  2239. _lr_goto[_x][_k] = _y
  2240. del _lr_goto_items
  2241. """)
  2242. else:
  2243. f.write("\n_lr_goto = { ");
  2244. for k,v in self.lr_goto.items():
  2245. f.write("(%r,%r):%r," % (k[0],k[1],v))
  2246. f.write("}\n");
  2247. # Write production table
  2248. f.write("_lr_productions = [\n")
  2249. for p in self.lr_productions:
  2250. if p.func:
  2251. f.write(" (%r,%r,%d,%r,%r,%d),\n" % (p.str,p.name, p.len, p.func,p.file,p.line))
  2252. else:
  2253. f.write(" (%r,%r,%d,None,None,None),\n" % (str(p),p.name, p.len))
  2254. f.write("]\n")
  2255. f.close()
  2256. except IOError:
  2257. e = sys.exc_info()[1]
  2258. sys.stderr.write("Unable to create '%s'\n" % filename)
  2259. sys.stderr.write(str(e)+"\n")
  2260. return
  2261. # -----------------------------------------------------------------------------
  2262. # pickle_table()
  2263. #
  2264. # This function pickles the LR parsing tables to a supplied file object
  2265. # -----------------------------------------------------------------------------
  2266. def pickle_table(self,filename,signature=""):
  2267. try:
  2268. import cPickle as pickle
  2269. except ImportError:
  2270. import pickle
  2271. outf = open(filename,"wb")
  2272. pickle.dump(__tabversion__,outf,pickle_protocol)
  2273. pickle.dump(self.lr_method,outf,pickle_protocol)
  2274. pickle.dump(signature,outf,pickle_protocol)
  2275. pickle.dump(self.lr_action,outf,pickle_protocol)
  2276. pickle.dump(self.lr_goto,outf,pickle_protocol)
  2277. outp = []
  2278. for p in self.lr_productions:
  2279. if p.func:
  2280. outp.append((p.str,p.name, p.len, p.func,p.file,p.line))
  2281. else:
  2282. outp.append((str(p),p.name,p.len,None,None,None))
  2283. pickle.dump(outp,outf,pickle_protocol)
  2284. outf.close()
  2285. # -----------------------------------------------------------------------------
  2286. # === INTROSPECTION ===
  2287. #
  2288. # The following functions and classes are used to implement the PLY
  2289. # introspection features followed by the yacc() function itself.
  2290. # -----------------------------------------------------------------------------
  2291. # -----------------------------------------------------------------------------
  2292. # get_caller_module_dict()
  2293. #
  2294. # This function returns a dictionary containing all of the symbols defined within
  2295. # a caller further down the call stack. This is used to get the environment
  2296. # associated with the yacc() call if none was provided.
  2297. # -----------------------------------------------------------------------------
  2298. def get_caller_module_dict(levels):
  2299. try:
  2300. raise RuntimeError
  2301. except RuntimeError:
  2302. e,b,t = sys.exc_info()
  2303. f = t.tb_frame
  2304. while levels > 0:
  2305. f = f.f_back
  2306. levels -= 1
  2307. ldict = f.f_globals.copy()
  2308. if f.f_globals != f.f_locals:
  2309. ldict.update(f.f_locals)
  2310. return ldict
  2311. # -----------------------------------------------------------------------------
  2312. # parse_grammar()
  2313. #
  2314. # This takes a raw grammar rule string and parses it into production data
  2315. # -----------------------------------------------------------------------------
  2316. def parse_grammar(doc,file,line):
  2317. grammar = []
  2318. # Split the doc string into lines
  2319. pstrings = doc.splitlines()
  2320. lastp = None
  2321. dline = line
  2322. for ps in pstrings:
  2323. dline += 1
  2324. p = ps.split()
  2325. if not p: continue
  2326. try:
  2327. if p[0] == '|':
  2328. # This is a continuation of a previous rule
  2329. if not lastp:
  2330. raise SyntaxError("%s:%d: Misplaced '|'" % (file,dline))
  2331. prodname = lastp
  2332. syms = p[1:]
  2333. else:
  2334. prodname = p[0]
  2335. lastp = prodname
  2336. syms = p[2:]
  2337. assign = p[1]
  2338. if assign != ':' and assign != '::=':
  2339. raise SyntaxError("%s:%d: Syntax error. Expected ':'" % (file,dline))
  2340. grammar.append((file,dline,prodname,syms))
  2341. except SyntaxError:
  2342. raise
  2343. except Exception:
  2344. raise SyntaxError("%s:%d: Syntax error in rule '%s'" % (file,dline,ps.strip()))
  2345. return grammar
  2346. # -----------------------------------------------------------------------------
  2347. # ParserReflect()
  2348. #
  2349. # This class represents information extracted for building a parser including
  2350. # start symbol, error function, tokens, precedence list, action functions,
  2351. # etc.
  2352. # -----------------------------------------------------------------------------
  2353. class ParserReflect(object):
  2354. def __init__(self,pdict,log=None):
  2355. self.pdict = pdict
  2356. self.start = None
  2357. self.error_func = None
  2358. self.tokens = None
  2359. self.files = {}
  2360. self.grammar = []
  2361. self.error = 0
  2362. if log is None:
  2363. self.log = PlyLogger(sys.stderr)
  2364. else:
  2365. self.log = log
  2366. # Get all of the basic information
  2367. def get_all(self):
  2368. self.get_start()
  2369. self.get_error_func()
  2370. self.get_tokens()
  2371. self.get_precedence()
  2372. self.get_pfunctions()
  2373. # Validate all of the information
  2374. def validate_all(self):
  2375. self.validate_start()
  2376. self.validate_error_func()
  2377. self.validate_tokens()
  2378. self.validate_precedence()
  2379. self.validate_pfunctions()
  2380. self.validate_files()
  2381. return self.error
  2382. # Compute a signature over the grammar
  2383. def signature(self):
  2384. try:
  2385. from hashlib import md5
  2386. except ImportError:
  2387. from md5 import md5
  2388. try:
  2389. sig = md5()
  2390. if self.start:
  2391. sig.update(self.start.encode('latin-1'))
  2392. if self.prec:
  2393. sig.update("".join(["".join(p) for p in self.prec]).encode('latin-1'))
  2394. if self.tokens:
  2395. sig.update(" ".join(self.tokens).encode('latin-1'))
  2396. for f in self.pfuncs:
  2397. if f[3]:
  2398. sig.update(f[3].encode('latin-1'))
  2399. except (TypeError,ValueError):
  2400. pass
  2401. return sig.digest()
  2402. # -----------------------------------------------------------------------------
  2403. # validate_file()
  2404. #
  2405. # This method checks to see if there are duplicated p_rulename() functions
  2406. # in the parser module file. Without this function, it is really easy for
  2407. # users to make mistakes by cutting and pasting code fragments (and it's a real
  2408. # bugger to try and figure out why the resulting parser doesn't work). Therefore,
  2409. # we just do a little regular expression pattern matching of def statements
  2410. # to try and detect duplicates.
  2411. # -----------------------------------------------------------------------------
  2412. def validate_files(self):
  2413. # Match def p_funcname(
  2414. fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(')
  2415. for filename in self.files.keys():
  2416. base,ext = os.path.splitext(filename)
  2417. if ext != '.py': return 1 # No idea. Assume it's okay.
  2418. try:
  2419. f = open(filename)
  2420. lines = f.readlines()
  2421. f.close()
  2422. except IOError:
  2423. continue
  2424. counthash = { }
  2425. for linen,l in enumerate(lines):
  2426. linen += 1
  2427. m = fre.match(l)
  2428. if m:
  2429. name = m.group(1)
  2430. prev = counthash.get(name)
  2431. if not prev:
  2432. counthash[name] = linen
  2433. else:
  2434. self.log.warning("%s:%d: Function %s redefined. Previously defined on line %d", filename,linen,name,prev)
  2435. # Get the start symbol
  2436. def get_start(self):
  2437. self.start = self.pdict.get('start')
  2438. # Validate the start symbol
  2439. def validate_start(self):
  2440. if self.start is not None:
  2441. if not isinstance(self.start,str):
  2442. self.log.error("'start' must be a string")
  2443. # Look for error handler
  2444. def get_error_func(self):
  2445. self.error_func = self.pdict.get('p_error')
  2446. # Validate the error function
  2447. def validate_error_func(self):
  2448. if self.error_func:
  2449. if isinstance(self.error_func,types.FunctionType):
  2450. ismethod = 0
  2451. elif isinstance(self.error_func, types.MethodType):
  2452. ismethod = 1
  2453. else:
  2454. self.log.error("'p_error' defined, but is not a function or method")
  2455. self.error = 1
  2456. return
  2457. eline = func_code(self.error_func).co_firstlineno
  2458. efile = func_code(self.error_func).co_filename
  2459. self.files[efile] = 1
  2460. if (func_code(self.error_func).co_argcount != 1+ismethod):
  2461. self.log.error("%s:%d: p_error() requires 1 argument",efile,eline)
  2462. self.error = 1
  2463. # Get the tokens map
  2464. def get_tokens(self):
  2465. tokens = self.pdict.get("tokens",None)
  2466. if not tokens:
  2467. self.log.error("No token list is defined")
  2468. self.error = 1
  2469. return
  2470. if not isinstance(tokens,(list, tuple)):
  2471. self.log.error("tokens must be a list or tuple")
  2472. self.error = 1
  2473. return
  2474. if not tokens:
  2475. self.log.error("tokens is empty")
  2476. self.error = 1
  2477. return
  2478. self.tokens = tokens
  2479. # Validate the tokens
  2480. def validate_tokens(self):
  2481. # Validate the tokens.
  2482. if 'error' in self.tokens:
  2483. self.log.error("Illegal token name 'error'. Is a reserved word")
  2484. self.error = 1
  2485. return
  2486. terminals = {}
  2487. for n in self.tokens:
  2488. if n in terminals:
  2489. self.log.warning("Token '%s' multiply defined", n)
  2490. terminals[n] = 1
  2491. # Get the precedence map (if any)
  2492. def get_precedence(self):
  2493. self.prec = self.pdict.get("precedence",None)
  2494. # Validate and parse the precedence map
  2495. def validate_precedence(self):
  2496. preclist = []
  2497. if self.prec:
  2498. if not isinstance(self.prec,(list,tuple)):
  2499. self.log.error("precedence must be a list or tuple")
  2500. self.error = 1
  2501. return
  2502. for level,p in enumerate(self.prec):
  2503. if not isinstance(p,(list,tuple)):
  2504. self.log.error("Bad precedence table")
  2505. self.error = 1
  2506. return
  2507. if len(p) < 2:
  2508. self.log.error("Malformed precedence entry %s. Must be (assoc, term, ..., term)",p)
  2509. self.error = 1
  2510. return
  2511. assoc = p[0]
  2512. if not isinstance(assoc,str):
  2513. self.log.error("precedence associativity must be a string")
  2514. self.error = 1
  2515. return
  2516. for term in p[1:]:
  2517. if not isinstance(term,str):
  2518. self.log.error("precedence items must be strings")
  2519. self.error = 1
  2520. return
  2521. preclist.append((term,assoc,level+1))
  2522. self.preclist = preclist
  2523. # Get all p_functions from the grammar
  2524. def get_pfunctions(self):
  2525. p_functions = []
  2526. for name, item in self.pdict.items():
  2527. if name[:2] != 'p_': continue
  2528. if name == 'p_error': continue
  2529. if isinstance(item,(types.FunctionType,types.MethodType)):
  2530. line = func_code(item).co_firstlineno
  2531. file = func_code(item).co_filename
  2532. p_functions.append((line,file,name,item.__doc__))
  2533. # Sort all of the actions by line number
  2534. p_functions.sort()
  2535. self.pfuncs = p_functions
  2536. # Validate all of the p_functions
  2537. def validate_pfunctions(self):
  2538. grammar = []
  2539. # Check for non-empty symbols
  2540. if len(self.pfuncs) == 0:
  2541. self.log.error("no rules of the form p_rulename are defined")
  2542. self.error = 1
  2543. return
  2544. for line, file, name, doc in self.pfuncs:
  2545. func = self.pdict[name]
  2546. if isinstance(func, types.MethodType):
  2547. reqargs = 2
  2548. else:
  2549. reqargs = 1
  2550. if func_code(func).co_argcount > reqargs:
  2551. self.log.error("%s:%d: Rule '%s' has too many arguments",file,line,func.__name__)
  2552. self.error = 1
  2553. elif func_code(func).co_argcount < reqargs:
  2554. self.log.error("%s:%d: Rule '%s' requires an argument",file,line,func.__name__)
  2555. self.error = 1
  2556. elif not func.__doc__:
  2557. self.log.warning("%s:%d: No documentation string specified in function '%s' (ignored)",file,line,func.__name__)
  2558. else:
  2559. try:
  2560. parsed_g = parse_grammar(doc,file,line)
  2561. for g in parsed_g:
  2562. grammar.append((name, g))
  2563. except SyntaxError:
  2564. e = sys.exc_info()[1]
  2565. self.log.error(str(e))
  2566. self.error = 1
  2567. # Looks like a valid grammar rule
  2568. # Mark the file in which defined.
  2569. self.files[file] = 1
  2570. # Secondary validation step that looks for p_ definitions that are not functions
  2571. # or functions that look like they might be grammar rules.
  2572. for n,v in self.pdict.items():
  2573. if n[0:2] == 'p_' and isinstance(v, (types.FunctionType, types.MethodType)): continue
  2574. if n[0:2] == 't_': continue
  2575. if n[0:2] == 'p_' and n != 'p_error':
  2576. self.log.warning("'%s' not defined as a function", n)
  2577. if ((isinstance(v,types.FunctionType) and func_code(v).co_argcount == 1) or
  2578. (isinstance(v,types.MethodType) and func_code(v).co_argcount == 2)):
  2579. try:
  2580. doc = v.__doc__.split(" ")
  2581. if doc[1] == ':':
  2582. self.log.warning("%s:%d: Possible grammar rule '%s' defined without p_ prefix",
  2583. func_code(v).co_filename, func_code(v).co_firstlineno,n)
  2584. except Exception:
  2585. pass
  2586. self.grammar = grammar
  2587. # -----------------------------------------------------------------------------
  2588. # yacc(module)
  2589. #
  2590. # Build a parser
  2591. # -----------------------------------------------------------------------------
  2592. def yacc(method='LALR', debug=yaccdebug, module=None, tabmodule=tab_module, start=None,
  2593. check_recursion=1, optimize=0, write_tables=1, debugfile=debug_file,outputdir='',
  2594. debuglog=None, errorlog = None, picklefile=None):
  2595. global parse # Reference to the parsing method of the last built parser
  2596. # If pickling is enabled, table files are not created
  2597. if picklefile:
  2598. write_tables = 0
  2599. if errorlog is None:
  2600. errorlog = PlyLogger(sys.stderr)
  2601. # Get the module dictionary used for the parser
  2602. if module:
  2603. _items = [(k,getattr(module,k)) for k in dir(module)]
  2604. pdict = dict(_items)
  2605. else:
  2606. pdict = get_caller_module_dict(2)
  2607. # Collect parser information from the dictionary
  2608. pinfo = ParserReflect(pdict,log=errorlog)
  2609. pinfo.get_all()
  2610. if pinfo.error:
  2611. raise YaccError("Unable to build parser")
  2612. # Check signature against table files (if any)
  2613. signature = pinfo.signature()
  2614. # Read the tables
  2615. try:
  2616. lr = LRTable()
  2617. if picklefile:
  2618. read_signature = lr.read_pickle(picklefile)
  2619. else:
  2620. read_signature = lr.read_table(tabmodule)
  2621. if optimize or (read_signature == signature):
  2622. try:
  2623. lr.bind_callables(pinfo.pdict)
  2624. parser = LRParser(lr,pinfo.error_func)
  2625. parse = parser.parse
  2626. return parser
  2627. except Exception:
  2628. e = sys.exc_info()[1]
  2629. errorlog.warning("There was a problem loading the table file: %s", repr(e))
  2630. except VersionError:
  2631. e = sys.exc_info()
  2632. errorlog.warning(str(e))
  2633. except Exception:
  2634. pass
  2635. if debuglog is None:
  2636. if debug:
  2637. debuglog = PlyLogger(open(debugfile,"w"))
  2638. else:
  2639. debuglog = NullLogger()
  2640. debuglog.info("Created by PLY version %s (http://www.dabeaz.com/ply)", __version__)
  2641. errors = 0
  2642. # Validate the parser information
  2643. if pinfo.validate_all():
  2644. raise YaccError("Unable to build parser")
  2645. if not pinfo.error_func:
  2646. errorlog.warning("no p_error() function is defined")
  2647. # Create a grammar object
  2648. grammar = Grammar(pinfo.tokens)
  2649. # Set precedence level for terminals
  2650. for term, assoc, level in pinfo.preclist:
  2651. try:
  2652. grammar.set_precedence(term,assoc,level)
  2653. except GrammarError:
  2654. e = sys.exc_info()[1]
  2655. errorlog.warning("%s",str(e))
  2656. # Add productions to the grammar
  2657. for funcname, gram in pinfo.grammar:
  2658. file, line, prodname, syms = gram
  2659. try:
  2660. grammar.add_production(prodname,syms,funcname,file,line)
  2661. except GrammarError:
  2662. e = sys.exc_info()[1]
  2663. errorlog.error("%s",str(e))
  2664. errors = 1
  2665. # Set the grammar start symbols
  2666. try:
  2667. if start is None:
  2668. grammar.set_start(pinfo.start)
  2669. else:
  2670. grammar.set_start(start)
  2671. except GrammarError:
  2672. e = sys.exc_info()[1]
  2673. errorlog.error(str(e))
  2674. errors = 1
  2675. if errors:
  2676. raise YaccError("Unable to build parser")
  2677. # Verify the grammar structure
  2678. undefined_symbols = grammar.undefined_symbols()
  2679. for sym, prod in undefined_symbols:
  2680. errorlog.error("%s:%d: Symbol '%s' used, but not defined as a token or a rule",prod.file,prod.line,sym)
  2681. errors = 1
  2682. unused_terminals = grammar.unused_terminals()
  2683. if unused_terminals:
  2684. debuglog.info("")
  2685. debuglog.info("Unused terminals:")
  2686. debuglog.info("")
  2687. for term in unused_terminals:
  2688. errorlog.warning("Token '%s' defined, but not used", term)
  2689. debuglog.info(" %s", term)
  2690. # Print out all productions to the debug log
  2691. if debug:
  2692. debuglog.info("")
  2693. debuglog.info("Grammar")
  2694. debuglog.info("")
  2695. for n,p in enumerate(grammar.Productions):
  2696. debuglog.info("Rule %-5d %s", n, p)
  2697. # Find unused non-terminals
  2698. unused_rules = grammar.unused_rules()
  2699. for prod in unused_rules:
  2700. errorlog.warning("%s:%d: Rule '%s' defined, but not used", prod.file, prod.line, prod.name)
  2701. if len(unused_terminals) == 1:
  2702. errorlog.warning("There is 1 unused token")
  2703. if len(unused_terminals) > 1:
  2704. errorlog.warning("There are %d unused tokens", len(unused_terminals))
  2705. if len(unused_rules) == 1:
  2706. errorlog.warning("There is 1 unused rule")
  2707. if len(unused_rules) > 1:
  2708. errorlog.warning("There are %d unused rules", len(unused_rules))
  2709. if debug:
  2710. debuglog.info("")
  2711. debuglog.info("Terminals, with rules where they appear")
  2712. debuglog.info("")
  2713. terms = list(grammar.Terminals)
  2714. terms.sort()
  2715. for term in terms:
  2716. debuglog.info("%-20s : %s", term, " ".join([str(s) for s in grammar.Terminals[term]]))
  2717. debuglog.info("")
  2718. debuglog.info("Nonterminals, with rules where they appear")
  2719. debuglog.info("")
  2720. nonterms = list(grammar.Nonterminals)
  2721. nonterms.sort()
  2722. for nonterm in nonterms:
  2723. debuglog.info("%-20s : %s", nonterm, " ".join([str(s) for s in grammar.Nonterminals[nonterm]]))
  2724. debuglog.info("")
  2725. if check_recursion:
  2726. unreachable = grammar.find_unreachable()
  2727. for u in unreachable:
  2728. errorlog.warning("Symbol '%s' is unreachable",u)
  2729. infinite = grammar.infinite_cycles()
  2730. for inf in infinite:
  2731. errorlog.error("Infinite recursion detected for symbol '%s'", inf)
  2732. errors = 1
  2733. unused_prec = grammar.unused_precedence()
  2734. for term, assoc in unused_prec:
  2735. errorlog.error("Precedence rule '%s' defined for unknown symbol '%s'", assoc, term)
  2736. errors = 1
  2737. if errors:
  2738. raise YaccError("Unable to build parser")
  2739. # Run the LRGeneratedTable on the grammar
  2740. if debug:
  2741. errorlog.debug("Generating %s tables", method)
  2742. lr = LRGeneratedTable(grammar,method,debuglog)
  2743. if debug:
  2744. num_sr = len(lr.sr_conflicts)
  2745. # Report shift/reduce and reduce/reduce conflicts
  2746. if num_sr == 1:
  2747. errorlog.warning("1 shift/reduce conflict")
  2748. elif num_sr > 1:
  2749. errorlog.warning("%d shift/reduce conflicts", num_sr)
  2750. num_rr = len(lr.rr_conflicts)
  2751. if num_rr == 1:
  2752. errorlog.warning("1 reduce/reduce conflict")
  2753. elif num_rr > 1:
  2754. errorlog.warning("%d reduce/reduce conflicts", num_rr)
  2755. # Write out conflicts to the output file
  2756. if debug and (lr.sr_conflicts or lr.rr_conflicts):
  2757. debuglog.warning("")
  2758. debuglog.warning("Conflicts:")
  2759. debuglog.warning("")
  2760. for state, tok, resolution in lr.sr_conflicts:
  2761. debuglog.warning("shift/reduce conflict for %s in state %d resolved as %s", tok, state, resolution)
  2762. already_reported = {}
  2763. for state, rule, rejected in lr.rr_conflicts:
  2764. if (state,id(rule),id(rejected)) in already_reported:
  2765. continue
  2766. debuglog.warning("reduce/reduce conflict in state %d resolved using rule (%s)", state, rule)
  2767. debuglog.warning("rejected rule (%s) in state %d", rejected,state)
  2768. errorlog.warning("reduce/reduce conflict in state %d resolved using rule (%s)", state, rule)
  2769. errorlog.warning("rejected rule (%s) in state %d", rejected, state)
  2770. already_reported[state,id(rule),id(rejected)] = 1
  2771. warned_never = []
  2772. for state, rule, rejected in lr.rr_conflicts:
  2773. if not rejected.reduced and (rejected not in warned_never):
  2774. debuglog.warning("Rule (%s) is never reduced", rejected)
  2775. errorlog.warning("Rule (%s) is never reduced", rejected)
  2776. warned_never.append(rejected)
  2777. # Write the table file if requested
  2778. if write_tables:
  2779. lr.write_table(tabmodule,outputdir,signature)
  2780. # Write a pickled version of the tables
  2781. if picklefile:
  2782. lr.pickle_table(picklefile,signature)
  2783. # Build the parser
  2784. lr.bind_callables(pinfo.pdict)
  2785. parser = LRParser(lr,pinfo.error_func)
  2786. parse = parser.parse
  2787. return parser