PageRenderTime 50ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/lib_pypy/cffi/_pycparser/ply/lex.py

https://bitbucket.org/halgari/pypy
Python | 1058 lines | 944 code | 37 blank | 77 comment | 55 complexity | 07ed71ab870ff673ee9e8214655d608f MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, AGPL-3.0
  1. # -----------------------------------------------------------------------------
  2. # ply: lex.py
  3. #
  4. # Copyright (C) 2001-2011,
  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. __version__ = "3.4"
  34. __tabversion__ = "3.2" # Version of table file used
  35. import re, sys, types, copy, os
  36. # This tuple contains known string types
  37. try:
  38. # Python 2.6
  39. StringTypes = (types.StringType, types.UnicodeType)
  40. except AttributeError:
  41. # Python 3.0
  42. StringTypes = (str, bytes)
  43. # Extract the code attribute of a function. Different implementations
  44. # are for Python 2/3 compatibility.
  45. if sys.version_info[0] < 3:
  46. def func_code(f):
  47. return f.func_code
  48. else:
  49. def func_code(f):
  50. return f.__code__
  51. # This regular expression is used to match valid token names
  52. _is_identifier = re.compile(r'^[a-zA-Z0-9_]+$')
  53. # Exception thrown when invalid token encountered and no default error
  54. # handler is defined.
  55. class LexError(Exception):
  56. def __init__(self,message,s):
  57. self.args = (message,)
  58. self.text = s
  59. # Token class. This class is used to represent the tokens produced.
  60. class LexToken(object):
  61. def __str__(self):
  62. return "LexToken(%s,%r,%d,%d)" % (self.type,self.value,self.lineno,self.lexpos)
  63. def __repr__(self):
  64. return str(self)
  65. # This object is a stand-in for a logging object created by the
  66. # logging module.
  67. class PlyLogger(object):
  68. def __init__(self,f):
  69. self.f = f
  70. def critical(self,msg,*args,**kwargs):
  71. self.f.write((msg % args) + "\n")
  72. def warning(self,msg,*args,**kwargs):
  73. self.f.write("WARNING: "+ (msg % args) + "\n")
  74. def error(self,msg,*args,**kwargs):
  75. self.f.write("ERROR: " + (msg % args) + "\n")
  76. info = critical
  77. debug = critical
  78. # Null logger is used when no output is generated. Does nothing.
  79. class NullLogger(object):
  80. def __getattribute__(self,name):
  81. return self
  82. def __call__(self,*args,**kwargs):
  83. return self
  84. # -----------------------------------------------------------------------------
  85. # === Lexing Engine ===
  86. #
  87. # The following Lexer class implements the lexer runtime. There are only
  88. # a few public methods and attributes:
  89. #
  90. # input() - Store a new string in the lexer
  91. # token() - Get the next token
  92. # clone() - Clone the lexer
  93. #
  94. # lineno - Current line number
  95. # lexpos - Current position in the input string
  96. # -----------------------------------------------------------------------------
  97. class Lexer:
  98. def __init__(self):
  99. self.lexre = None # Master regular expression. This is a list of
  100. # tuples (re,findex) where re is a compiled
  101. # regular expression and findex is a list
  102. # mapping regex group numbers to rules
  103. self.lexretext = None # Current regular expression strings
  104. self.lexstatere = {} # Dictionary mapping lexer states to master regexs
  105. self.lexstateretext = {} # Dictionary mapping lexer states to regex strings
  106. self.lexstaterenames = {} # Dictionary mapping lexer states to symbol names
  107. self.lexstate = "INITIAL" # Current lexer state
  108. self.lexstatestack = [] # Stack of lexer states
  109. self.lexstateinfo = None # State information
  110. self.lexstateignore = {} # Dictionary of ignored characters for each state
  111. self.lexstateerrorf = {} # Dictionary of error functions for each state
  112. self.lexreflags = 0 # Optional re compile flags
  113. self.lexdata = None # Actual input data (as a string)
  114. self.lexpos = 0 # Current position in input text
  115. self.lexlen = 0 # Length of the input text
  116. self.lexerrorf = None # Error rule (if any)
  117. self.lextokens = None # List of valid tokens
  118. self.lexignore = "" # Ignored characters
  119. self.lexliterals = "" # Literal characters that can be passed through
  120. self.lexmodule = None # Module
  121. self.lineno = 1 # Current line number
  122. self.lexoptimize = 0 # Optimized mode
  123. def clone(self,object=None):
  124. c = copy.copy(self)
  125. # If the object parameter has been supplied, it means we are attaching the
  126. # lexer to a new object. In this case, we have to rebind all methods in
  127. # the lexstatere and lexstateerrorf tables.
  128. if object:
  129. newtab = { }
  130. for key, ritem in self.lexstatere.items():
  131. newre = []
  132. for cre, findex in ritem:
  133. newfindex = []
  134. for f in findex:
  135. if not f or not f[0]:
  136. newfindex.append(f)
  137. continue
  138. newfindex.append((getattr(object,f[0].__name__),f[1]))
  139. newre.append((cre,newfindex))
  140. newtab[key] = newre
  141. c.lexstatere = newtab
  142. c.lexstateerrorf = { }
  143. for key, ef in self.lexstateerrorf.items():
  144. c.lexstateerrorf[key] = getattr(object,ef.__name__)
  145. c.lexmodule = object
  146. return c
  147. # ------------------------------------------------------------
  148. # writetab() - Write lexer information to a table file
  149. # ------------------------------------------------------------
  150. def writetab(self,tabfile,outputdir=""):
  151. if isinstance(tabfile,types.ModuleType):
  152. return
  153. basetabfilename = tabfile.split(".")[-1]
  154. filename = os.path.join(outputdir,basetabfilename)+".py"
  155. tf = open(filename,"w")
  156. tf.write("# %s.py. This file automatically created by PLY (version %s). Don't edit!\n" % (tabfile,__version__))
  157. tf.write("_tabversion = %s\n" % repr(__version__))
  158. tf.write("_lextokens = %s\n" % repr(self.lextokens))
  159. tf.write("_lexreflags = %s\n" % repr(self.lexreflags))
  160. tf.write("_lexliterals = %s\n" % repr(self.lexliterals))
  161. tf.write("_lexstateinfo = %s\n" % repr(self.lexstateinfo))
  162. tabre = { }
  163. # Collect all functions in the initial state
  164. initial = self.lexstatere["INITIAL"]
  165. initialfuncs = []
  166. for part in initial:
  167. for f in part[1]:
  168. if f and f[0]:
  169. initialfuncs.append(f)
  170. for key, lre in self.lexstatere.items():
  171. titem = []
  172. for i in range(len(lre)):
  173. titem.append((self.lexstateretext[key][i],_funcs_to_names(lre[i][1],self.lexstaterenames[key][i])))
  174. tabre[key] = titem
  175. tf.write("_lexstatere = %s\n" % repr(tabre))
  176. tf.write("_lexstateignore = %s\n" % repr(self.lexstateignore))
  177. taberr = { }
  178. for key, ef in self.lexstateerrorf.items():
  179. if ef:
  180. taberr[key] = ef.__name__
  181. else:
  182. taberr[key] = None
  183. tf.write("_lexstateerrorf = %s\n" % repr(taberr))
  184. tf.close()
  185. # ------------------------------------------------------------
  186. # readtab() - Read lexer information from a tab file
  187. # ------------------------------------------------------------
  188. def readtab(self,tabfile,fdict):
  189. if isinstance(tabfile,types.ModuleType):
  190. lextab = tabfile
  191. else:
  192. if sys.version_info[0] < 3:
  193. exec("import %s as lextab" % tabfile)
  194. else:
  195. env = { }
  196. exec("import %s as lextab" % tabfile, env,env)
  197. lextab = env['lextab']
  198. if getattr(lextab,"_tabversion","0.0") != __version__:
  199. raise ImportError("Inconsistent PLY version")
  200. self.lextokens = lextab._lextokens
  201. self.lexreflags = lextab._lexreflags
  202. self.lexliterals = lextab._lexliterals
  203. self.lexstateinfo = lextab._lexstateinfo
  204. self.lexstateignore = lextab._lexstateignore
  205. self.lexstatere = { }
  206. self.lexstateretext = { }
  207. for key,lre in lextab._lexstatere.items():
  208. titem = []
  209. txtitem = []
  210. for i in range(len(lre)):
  211. titem.append((re.compile(lre[i][0],lextab._lexreflags | re.VERBOSE),_names_to_funcs(lre[i][1],fdict)))
  212. txtitem.append(lre[i][0])
  213. self.lexstatere[key] = titem
  214. self.lexstateretext[key] = txtitem
  215. self.lexstateerrorf = { }
  216. for key,ef in lextab._lexstateerrorf.items():
  217. self.lexstateerrorf[key] = fdict[ef]
  218. self.begin('INITIAL')
  219. # ------------------------------------------------------------
  220. # input() - Push a new string into the lexer
  221. # ------------------------------------------------------------
  222. def input(self,s):
  223. # Pull off the first character to see if s looks like a string
  224. c = s[:1]
  225. if not isinstance(c,StringTypes):
  226. raise ValueError("Expected a string")
  227. self.lexdata = s
  228. self.lexpos = 0
  229. self.lexlen = len(s)
  230. # ------------------------------------------------------------
  231. # begin() - Changes the lexing state
  232. # ------------------------------------------------------------
  233. def begin(self,state):
  234. if not state in self.lexstatere:
  235. raise ValueError("Undefined state")
  236. self.lexre = self.lexstatere[state]
  237. self.lexretext = self.lexstateretext[state]
  238. self.lexignore = self.lexstateignore.get(state,"")
  239. self.lexerrorf = self.lexstateerrorf.get(state,None)
  240. self.lexstate = state
  241. # ------------------------------------------------------------
  242. # push_state() - Changes the lexing state and saves old on stack
  243. # ------------------------------------------------------------
  244. def push_state(self,state):
  245. self.lexstatestack.append(self.lexstate)
  246. self.begin(state)
  247. # ------------------------------------------------------------
  248. # pop_state() - Restores the previous state
  249. # ------------------------------------------------------------
  250. def pop_state(self):
  251. self.begin(self.lexstatestack.pop())
  252. # ------------------------------------------------------------
  253. # current_state() - Returns the current lexing state
  254. # ------------------------------------------------------------
  255. def current_state(self):
  256. return self.lexstate
  257. # ------------------------------------------------------------
  258. # skip() - Skip ahead n characters
  259. # ------------------------------------------------------------
  260. def skip(self,n):
  261. self.lexpos += n
  262. # ------------------------------------------------------------
  263. # opttoken() - Return the next token from the Lexer
  264. #
  265. # Note: This function has been carefully implemented to be as fast
  266. # as possible. Don't make changes unless you really know what
  267. # you are doing
  268. # ------------------------------------------------------------
  269. def token(self):
  270. # Make local copies of frequently referenced attributes
  271. lexpos = self.lexpos
  272. lexlen = self.lexlen
  273. lexignore = self.lexignore
  274. lexdata = self.lexdata
  275. while lexpos < lexlen:
  276. # This code provides some short-circuit code for whitespace, tabs, and other ignored characters
  277. if lexdata[lexpos] in lexignore:
  278. lexpos += 1
  279. continue
  280. # Look for a regular expression match
  281. for lexre,lexindexfunc in self.lexre:
  282. m = lexre.match(lexdata,lexpos)
  283. if not m: continue
  284. # Create a token for return
  285. tok = LexToken()
  286. tok.value = m.group()
  287. tok.lineno = self.lineno
  288. tok.lexpos = lexpos
  289. i = m.lastindex
  290. func,tok.type = lexindexfunc[i]
  291. if not func:
  292. # If no token type was set, it's an ignored token
  293. if tok.type:
  294. self.lexpos = m.end()
  295. return tok
  296. else:
  297. lexpos = m.end()
  298. break
  299. lexpos = m.end()
  300. # If token is processed by a function, call it
  301. tok.lexer = self # Set additional attributes useful in token rules
  302. self.lexmatch = m
  303. self.lexpos = lexpos
  304. newtok = func(tok)
  305. # Every function must return a token, if nothing, we just move to next token
  306. if not newtok:
  307. lexpos = self.lexpos # This is here in case user has updated lexpos.
  308. lexignore = self.lexignore # This is here in case there was a state change
  309. break
  310. # Verify type of the token. If not in the token map, raise an error
  311. if not self.lexoptimize:
  312. if not newtok.type in self.lextokens:
  313. raise LexError("%s:%d: Rule '%s' returned an unknown token type '%s'" % (
  314. func_code(func).co_filename, func_code(func).co_firstlineno,
  315. func.__name__, newtok.type),lexdata[lexpos:])
  316. return newtok
  317. else:
  318. # No match, see if in literals
  319. if lexdata[lexpos] in self.lexliterals:
  320. tok = LexToken()
  321. tok.value = lexdata[lexpos]
  322. tok.lineno = self.lineno
  323. tok.type = tok.value
  324. tok.lexpos = lexpos
  325. self.lexpos = lexpos + 1
  326. return tok
  327. # No match. Call t_error() if defined.
  328. if self.lexerrorf:
  329. tok = LexToken()
  330. tok.value = self.lexdata[lexpos:]
  331. tok.lineno = self.lineno
  332. tok.type = "error"
  333. tok.lexer = self
  334. tok.lexpos = lexpos
  335. self.lexpos = lexpos
  336. newtok = self.lexerrorf(tok)
  337. if lexpos == self.lexpos:
  338. # Error method didn't change text position at all. This is an error.
  339. raise LexError("Scanning error. Illegal character '%s'" % (lexdata[lexpos]), lexdata[lexpos:])
  340. lexpos = self.lexpos
  341. if not newtok: continue
  342. return newtok
  343. self.lexpos = lexpos
  344. raise LexError("Illegal character '%s' at index %d" % (lexdata[lexpos],lexpos), lexdata[lexpos:])
  345. self.lexpos = lexpos + 1
  346. if self.lexdata is None:
  347. raise RuntimeError("No input string given with input()")
  348. return None
  349. # Iterator interface
  350. def __iter__(self):
  351. return self
  352. def next(self):
  353. t = self.token()
  354. if t is None:
  355. raise StopIteration
  356. return t
  357. __next__ = next
  358. # -----------------------------------------------------------------------------
  359. # ==== Lex Builder ===
  360. #
  361. # The functions and classes below are used to collect lexing information
  362. # and build a Lexer object from it.
  363. # -----------------------------------------------------------------------------
  364. # -----------------------------------------------------------------------------
  365. # get_caller_module_dict()
  366. #
  367. # This function returns a dictionary containing all of the symbols defined within
  368. # a caller further down the call stack. This is used to get the environment
  369. # associated with the yacc() call if none was provided.
  370. # -----------------------------------------------------------------------------
  371. def get_caller_module_dict(levels):
  372. try:
  373. raise RuntimeError
  374. except RuntimeError:
  375. e,b,t = sys.exc_info()
  376. f = t.tb_frame
  377. while levels > 0:
  378. f = f.f_back
  379. levels -= 1
  380. ldict = f.f_globals.copy()
  381. if f.f_globals != f.f_locals:
  382. ldict.update(f.f_locals)
  383. return ldict
  384. # -----------------------------------------------------------------------------
  385. # _funcs_to_names()
  386. #
  387. # Given a list of regular expression functions, this converts it to a list
  388. # suitable for output to a table file
  389. # -----------------------------------------------------------------------------
  390. def _funcs_to_names(funclist,namelist):
  391. result = []
  392. for f,name in zip(funclist,namelist):
  393. if f and f[0]:
  394. result.append((name, f[1]))
  395. else:
  396. result.append(f)
  397. return result
  398. # -----------------------------------------------------------------------------
  399. # _names_to_funcs()
  400. #
  401. # Given a list of regular expression function names, this converts it back to
  402. # functions.
  403. # -----------------------------------------------------------------------------
  404. def _names_to_funcs(namelist,fdict):
  405. result = []
  406. for n in namelist:
  407. if n and n[0]:
  408. result.append((fdict[n[0]],n[1]))
  409. else:
  410. result.append(n)
  411. return result
  412. # -----------------------------------------------------------------------------
  413. # _form_master_re()
  414. #
  415. # This function takes a list of all of the regex components and attempts to
  416. # form the master regular expression. Given limitations in the Python re
  417. # module, it may be necessary to break the master regex into separate expressions.
  418. # -----------------------------------------------------------------------------
  419. def _form_master_re(relist,reflags,ldict,toknames):
  420. if not relist: return []
  421. regex = "|".join(relist)
  422. try:
  423. lexre = re.compile(regex,re.VERBOSE | reflags)
  424. # Build the index to function map for the matching engine
  425. lexindexfunc = [ None ] * (max(lexre.groupindex.values())+1)
  426. lexindexnames = lexindexfunc[:]
  427. for f,i in lexre.groupindex.items():
  428. handle = ldict.get(f,None)
  429. if type(handle) in (types.FunctionType, types.MethodType):
  430. lexindexfunc[i] = (handle,toknames[f])
  431. lexindexnames[i] = f
  432. elif handle is not None:
  433. lexindexnames[i] = f
  434. if f.find("ignore_") > 0:
  435. lexindexfunc[i] = (None,None)
  436. else:
  437. lexindexfunc[i] = (None, toknames[f])
  438. return [(lexre,lexindexfunc)],[regex],[lexindexnames]
  439. except Exception:
  440. m = int(len(relist)/2)
  441. if m == 0: m = 1
  442. llist, lre, lnames = _form_master_re(relist[:m],reflags,ldict,toknames)
  443. rlist, rre, rnames = _form_master_re(relist[m:],reflags,ldict,toknames)
  444. return llist+rlist, lre+rre, lnames+rnames
  445. # -----------------------------------------------------------------------------
  446. # def _statetoken(s,names)
  447. #
  448. # Given a declaration name s of the form "t_" and a dictionary whose keys are
  449. # state names, this function returns a tuple (states,tokenname) where states
  450. # is a tuple of state names and tokenname is the name of the token. For example,
  451. # calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM')
  452. # -----------------------------------------------------------------------------
  453. def _statetoken(s,names):
  454. nonstate = 1
  455. parts = s.split("_")
  456. for i in range(1,len(parts)):
  457. if not parts[i] in names and parts[i] != 'ANY': break
  458. if i > 1:
  459. states = tuple(parts[1:i])
  460. else:
  461. states = ('INITIAL',)
  462. if 'ANY' in states:
  463. states = tuple(names)
  464. tokenname = "_".join(parts[i:])
  465. return (states,tokenname)
  466. # -----------------------------------------------------------------------------
  467. # LexerReflect()
  468. #
  469. # This class represents information needed to build a lexer as extracted from a
  470. # user's input file.
  471. # -----------------------------------------------------------------------------
  472. class LexerReflect(object):
  473. def __init__(self,ldict,log=None,reflags=0):
  474. self.ldict = ldict
  475. self.error_func = None
  476. self.tokens = []
  477. self.reflags = reflags
  478. self.stateinfo = { 'INITIAL' : 'inclusive'}
  479. self.files = {}
  480. self.error = 0
  481. if log is None:
  482. self.log = PlyLogger(sys.stderr)
  483. else:
  484. self.log = log
  485. # Get all of the basic information
  486. def get_all(self):
  487. self.get_tokens()
  488. self.get_literals()
  489. self.get_states()
  490. self.get_rules()
  491. # Validate all of the information
  492. def validate_all(self):
  493. self.validate_tokens()
  494. self.validate_literals()
  495. self.validate_rules()
  496. return self.error
  497. # Get the tokens map
  498. def get_tokens(self):
  499. tokens = self.ldict.get("tokens",None)
  500. if not tokens:
  501. self.log.error("No token list is defined")
  502. self.error = 1
  503. return
  504. if not isinstance(tokens,(list, tuple)):
  505. self.log.error("tokens must be a list or tuple")
  506. self.error = 1
  507. return
  508. if not tokens:
  509. self.log.error("tokens is empty")
  510. self.error = 1
  511. return
  512. self.tokens = tokens
  513. # Validate the tokens
  514. def validate_tokens(self):
  515. terminals = {}
  516. for n in self.tokens:
  517. if not _is_identifier.match(n):
  518. self.log.error("Bad token name '%s'",n)
  519. self.error = 1
  520. if n in terminals:
  521. self.log.warning("Token '%s' multiply defined", n)
  522. terminals[n] = 1
  523. # Get the literals specifier
  524. def get_literals(self):
  525. self.literals = self.ldict.get("literals","")
  526. # Validate literals
  527. def validate_literals(self):
  528. try:
  529. for c in self.literals:
  530. if not isinstance(c,StringTypes) or len(c) > 1:
  531. self.log.error("Invalid literal %s. Must be a single character", repr(c))
  532. self.error = 1
  533. continue
  534. except TypeError:
  535. self.log.error("Invalid literals specification. literals must be a sequence of characters")
  536. self.error = 1
  537. def get_states(self):
  538. self.states = self.ldict.get("states",None)
  539. # Build statemap
  540. if self.states:
  541. if not isinstance(self.states,(tuple,list)):
  542. self.log.error("states must be defined as a tuple or list")
  543. self.error = 1
  544. else:
  545. for s in self.states:
  546. if not isinstance(s,tuple) or len(s) != 2:
  547. self.log.error("Invalid state specifier %s. Must be a tuple (statename,'exclusive|inclusive')",repr(s))
  548. self.error = 1
  549. continue
  550. name, statetype = s
  551. if not isinstance(name,StringTypes):
  552. self.log.error("State name %s must be a string", repr(name))
  553. self.error = 1
  554. continue
  555. if not (statetype == 'inclusive' or statetype == 'exclusive'):
  556. self.log.error("State type for state %s must be 'inclusive' or 'exclusive'",name)
  557. self.error = 1
  558. continue
  559. if name in self.stateinfo:
  560. self.log.error("State '%s' already defined",name)
  561. self.error = 1
  562. continue
  563. self.stateinfo[name] = statetype
  564. # Get all of the symbols with a t_ prefix and sort them into various
  565. # categories (functions, strings, error functions, and ignore characters)
  566. def get_rules(self):
  567. tsymbols = [f for f in self.ldict if f[:2] == 't_' ]
  568. # Now build up a list of functions and a list of strings
  569. self.toknames = { } # Mapping of symbols to token names
  570. self.funcsym = { } # Symbols defined as functions
  571. self.strsym = { } # Symbols defined as strings
  572. self.ignore = { } # Ignore strings by state
  573. self.errorf = { } # Error functions by state
  574. for s in self.stateinfo:
  575. self.funcsym[s] = []
  576. self.strsym[s] = []
  577. if len(tsymbols) == 0:
  578. self.log.error("No rules of the form t_rulename are defined")
  579. self.error = 1
  580. return
  581. for f in tsymbols:
  582. t = self.ldict[f]
  583. states, tokname = _statetoken(f,self.stateinfo)
  584. self.toknames[f] = tokname
  585. if hasattr(t,"__call__"):
  586. if tokname == 'error':
  587. for s in states:
  588. self.errorf[s] = t
  589. elif tokname == 'ignore':
  590. line = func_code(t).co_firstlineno
  591. file = func_code(t).co_filename
  592. self.log.error("%s:%d: Rule '%s' must be defined as a string",file,line,t.__name__)
  593. self.error = 1
  594. else:
  595. for s in states:
  596. self.funcsym[s].append((f,t))
  597. elif isinstance(t, StringTypes):
  598. if tokname == 'ignore':
  599. for s in states:
  600. self.ignore[s] = t
  601. if "\\" in t:
  602. self.log.warning("%s contains a literal backslash '\\'",f)
  603. elif tokname == 'error':
  604. self.log.error("Rule '%s' must be defined as a function", f)
  605. self.error = 1
  606. else:
  607. for s in states:
  608. self.strsym[s].append((f,t))
  609. else:
  610. self.log.error("%s not defined as a function or string", f)
  611. self.error = 1
  612. # Sort the functions by line number
  613. for f in self.funcsym.values():
  614. if sys.version_info[0] < 3:
  615. f.sort(lambda x,y: cmp(func_code(x[1]).co_firstlineno,func_code(y[1]).co_firstlineno))
  616. else:
  617. # Python 3.0
  618. f.sort(key=lambda x: func_code(x[1]).co_firstlineno)
  619. # Sort the strings by regular expression length
  620. for s in self.strsym.values():
  621. if sys.version_info[0] < 3:
  622. s.sort(lambda x,y: (len(x[1]) < len(y[1])) - (len(x[1]) > len(y[1])))
  623. else:
  624. # Python 3.0
  625. s.sort(key=lambda x: len(x[1]),reverse=True)
  626. # Validate all of the t_rules collected
  627. def validate_rules(self):
  628. for state in self.stateinfo:
  629. # Validate all rules defined by functions
  630. for fname, f in self.funcsym[state]:
  631. line = func_code(f).co_firstlineno
  632. file = func_code(f).co_filename
  633. self.files[file] = 1
  634. tokname = self.toknames[fname]
  635. if isinstance(f, types.MethodType):
  636. reqargs = 2
  637. else:
  638. reqargs = 1
  639. nargs = func_code(f).co_argcount
  640. if nargs > reqargs:
  641. self.log.error("%s:%d: Rule '%s' has too many arguments",file,line,f.__name__)
  642. self.error = 1
  643. continue
  644. if nargs < reqargs:
  645. self.log.error("%s:%d: Rule '%s' requires an argument", file,line,f.__name__)
  646. self.error = 1
  647. continue
  648. if not f.__doc__:
  649. self.log.error("%s:%d: No regular expression defined for rule '%s'",file,line,f.__name__)
  650. self.error = 1
  651. continue
  652. try:
  653. c = re.compile("(?P<%s>%s)" % (fname,f.__doc__), re.VERBOSE | self.reflags)
  654. if c.match(""):
  655. self.log.error("%s:%d: Regular expression for rule '%s' matches empty string", file,line,f.__name__)
  656. self.error = 1
  657. except re.error:
  658. _etype, e, _etrace = sys.exc_info()
  659. self.log.error("%s:%d: Invalid regular expression for rule '%s'. %s", file,line,f.__name__,e)
  660. if '#' in f.__doc__:
  661. self.log.error("%s:%d. Make sure '#' in rule '%s' is escaped with '\\#'",file,line, f.__name__)
  662. self.error = 1
  663. # Validate all rules defined by strings
  664. for name,r in self.strsym[state]:
  665. tokname = self.toknames[name]
  666. if tokname == 'error':
  667. self.log.error("Rule '%s' must be defined as a function", name)
  668. self.error = 1
  669. continue
  670. if not tokname in self.tokens and tokname.find("ignore_") < 0:
  671. self.log.error("Rule '%s' defined for an unspecified token %s",name,tokname)
  672. self.error = 1
  673. continue
  674. try:
  675. c = re.compile("(?P<%s>%s)" % (name,r),re.VERBOSE | self.reflags)
  676. if (c.match("")):
  677. self.log.error("Regular expression for rule '%s' matches empty string",name)
  678. self.error = 1
  679. except re.error:
  680. _etype, e, _etrace = sys.exc_info()
  681. self.log.error("Invalid regular expression for rule '%s'. %s",name,e)
  682. if '#' in r:
  683. self.log.error("Make sure '#' in rule '%s' is escaped with '\\#'",name)
  684. self.error = 1
  685. if not self.funcsym[state] and not self.strsym[state]:
  686. self.log.error("No rules defined for state '%s'",state)
  687. self.error = 1
  688. # Validate the error function
  689. efunc = self.errorf.get(state,None)
  690. if efunc:
  691. f = efunc
  692. line = func_code(f).co_firstlineno
  693. file = func_code(f).co_filename
  694. self.files[file] = 1
  695. if isinstance(f, types.MethodType):
  696. reqargs = 2
  697. else:
  698. reqargs = 1
  699. nargs = func_code(f).co_argcount
  700. if nargs > reqargs:
  701. self.log.error("%s:%d: Rule '%s' has too many arguments",file,line,f.__name__)
  702. self.error = 1
  703. if nargs < reqargs:
  704. self.log.error("%s:%d: Rule '%s' requires an argument", file,line,f.__name__)
  705. self.error = 1
  706. for f in self.files:
  707. self.validate_file(f)
  708. # -----------------------------------------------------------------------------
  709. # validate_file()
  710. #
  711. # This checks to see if there are duplicated t_rulename() functions or strings
  712. # in the parser input file. This is done using a simple regular expression
  713. # match on each line in the given file.
  714. # -----------------------------------------------------------------------------
  715. def validate_file(self,filename):
  716. import os.path
  717. base,ext = os.path.splitext(filename)
  718. if ext != '.py': return # No idea what the file is. Return OK
  719. try:
  720. f = open(filename)
  721. lines = f.readlines()
  722. f.close()
  723. except IOError:
  724. return # Couldn't find the file. Don't worry about it
  725. fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(')
  726. sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=')
  727. counthash = { }
  728. linen = 1
  729. for l in lines:
  730. m = fre.match(l)
  731. if not m:
  732. m = sre.match(l)
  733. if m:
  734. name = m.group(1)
  735. prev = counthash.get(name)
  736. if not prev:
  737. counthash[name] = linen
  738. else:
  739. self.log.error("%s:%d: Rule %s redefined. Previously defined on line %d",filename,linen,name,prev)
  740. self.error = 1
  741. linen += 1
  742. # -----------------------------------------------------------------------------
  743. # lex(module)
  744. #
  745. # Build all of the regular expression rules from definitions in the supplied module
  746. # -----------------------------------------------------------------------------
  747. def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,nowarn=0,outputdir="", debuglog=None, errorlog=None):
  748. global lexer
  749. ldict = None
  750. stateinfo = { 'INITIAL' : 'inclusive'}
  751. lexobj = Lexer()
  752. lexobj.lexoptimize = optimize
  753. global token,input
  754. if errorlog is None:
  755. errorlog = PlyLogger(sys.stderr)
  756. if debug:
  757. if debuglog is None:
  758. debuglog = PlyLogger(sys.stderr)
  759. # Get the module dictionary used for the lexer
  760. if object: module = object
  761. if module:
  762. _items = [(k,getattr(module,k)) for k in dir(module)]
  763. ldict = dict(_items)
  764. else:
  765. ldict = get_caller_module_dict(2)
  766. # Collect parser information from the dictionary
  767. linfo = LexerReflect(ldict,log=errorlog,reflags=reflags)
  768. linfo.get_all()
  769. if not optimize:
  770. if linfo.validate_all():
  771. raise SyntaxError("Can't build lexer")
  772. if optimize and lextab:
  773. try:
  774. lexobj.readtab(lextab,ldict)
  775. token = lexobj.token
  776. input = lexobj.input
  777. lexer = lexobj
  778. return lexobj
  779. except ImportError:
  780. pass
  781. # Dump some basic debugging information
  782. if debug:
  783. debuglog.info("lex: tokens = %r", linfo.tokens)
  784. debuglog.info("lex: literals = %r", linfo.literals)
  785. debuglog.info("lex: states = %r", linfo.stateinfo)
  786. # Build a dictionary of valid token names
  787. lexobj.lextokens = { }
  788. for n in linfo.tokens:
  789. lexobj.lextokens[n] = 1
  790. # Get literals specification
  791. if isinstance(linfo.literals,(list,tuple)):
  792. lexobj.lexliterals = type(linfo.literals[0])().join(linfo.literals)
  793. else:
  794. lexobj.lexliterals = linfo.literals
  795. # Get the stateinfo dictionary
  796. stateinfo = linfo.stateinfo
  797. regexs = { }
  798. # Build the master regular expressions
  799. for state in stateinfo:
  800. regex_list = []
  801. # Add rules defined by functions first
  802. for fname, f in linfo.funcsym[state]:
  803. line = func_code(f).co_firstlineno
  804. file = func_code(f).co_filename
  805. regex_list.append("(?P<%s>%s)" % (fname,f.__doc__))
  806. if debug:
  807. debuglog.info("lex: Adding rule %s -> '%s' (state '%s')",fname,f.__doc__, state)
  808. # Now add all of the simple rules
  809. for name,r in linfo.strsym[state]:
  810. regex_list.append("(?P<%s>%s)" % (name,r))
  811. if debug:
  812. debuglog.info("lex: Adding rule %s -> '%s' (state '%s')",name,r, state)
  813. regexs[state] = regex_list
  814. # Build the master regular expressions
  815. if debug:
  816. debuglog.info("lex: ==== MASTER REGEXS FOLLOW ====")
  817. for state in regexs:
  818. lexre, re_text, re_names = _form_master_re(regexs[state],reflags,ldict,linfo.toknames)
  819. lexobj.lexstatere[state] = lexre
  820. lexobj.lexstateretext[state] = re_text
  821. lexobj.lexstaterenames[state] = re_names
  822. if debug:
  823. for i in range(len(re_text)):
  824. debuglog.info("lex: state '%s' : regex[%d] = '%s'",state, i, re_text[i])
  825. # For inclusive states, we need to add the regular expressions from the INITIAL state
  826. for state,stype in stateinfo.items():
  827. if state != "INITIAL" and stype == 'inclusive':
  828. lexobj.lexstatere[state].extend(lexobj.lexstatere['INITIAL'])
  829. lexobj.lexstateretext[state].extend(lexobj.lexstateretext['INITIAL'])
  830. lexobj.lexstaterenames[state].extend(lexobj.lexstaterenames['INITIAL'])
  831. lexobj.lexstateinfo = stateinfo
  832. lexobj.lexre = lexobj.lexstatere["INITIAL"]
  833. lexobj.lexretext = lexobj.lexstateretext["INITIAL"]
  834. lexobj.lexreflags = reflags
  835. # Set up ignore variables
  836. lexobj.lexstateignore = linfo.ignore
  837. lexobj.lexignore = lexobj.lexstateignore.get("INITIAL","")
  838. # Set up error functions
  839. lexobj.lexstateerrorf = linfo.errorf
  840. lexobj.lexerrorf = linfo.errorf.get("INITIAL",None)
  841. if not lexobj.lexerrorf:
  842. errorlog.warning("No t_error rule is defined")
  843. # Check state information for ignore and error rules
  844. for s,stype in stateinfo.items():
  845. if stype == 'exclusive':
  846. if not s in linfo.errorf:
  847. errorlog.warning("No error rule is defined for exclusive state '%s'", s)
  848. if not s in linfo.ignore and lexobj.lexignore:
  849. errorlog.warning("No ignore rule is defined for exclusive state '%s'", s)
  850. elif stype == 'inclusive':
  851. if not s in linfo.errorf:
  852. linfo.errorf[s] = linfo.errorf.get("INITIAL",None)
  853. if not s in linfo.ignore:
  854. linfo.ignore[s] = linfo.ignore.get("INITIAL","")
  855. # Create global versions of the token() and input() functions
  856. token = lexobj.token
  857. input = lexobj.input
  858. lexer = lexobj
  859. # If in optimize mode, we write the lextab
  860. if lextab and optimize:
  861. lexobj.writetab(lextab,outputdir)
  862. return lexobj
  863. # -----------------------------------------------------------------------------
  864. # runmain()
  865. #
  866. # This runs the lexer as a main program
  867. # -----------------------------------------------------------------------------
  868. def runmain(lexer=None,data=None):
  869. if not data:
  870. try:
  871. filename = sys.argv[1]
  872. f = open(filename)
  873. data = f.read()
  874. f.close()
  875. except IndexError:
  876. sys.stdout.write("Reading from standard input (type EOF to end):\n")
  877. data = sys.stdin.read()
  878. if lexer:
  879. _input = lexer.input
  880. else:
  881. _input = input
  882. _input(data)
  883. if lexer:
  884. _token = lexer.token
  885. else:
  886. _token = token
  887. while 1:
  888. tok = _token()
  889. if not tok: break
  890. sys.stdout.write("(%s,%r,%d,%d)\n" % (tok.type, tok.value, tok.lineno,tok.lexpos))
  891. # -----------------------------------------------------------------------------
  892. # @TOKEN(regex)
  893. #
  894. # This decorator function can be used to set the regex expression on a function
  895. # when its docstring might need to be set in an alternative way
  896. # -----------------------------------------------------------------------------
  897. def TOKEN(r):
  898. def set_doc(f):
  899. if hasattr(r,"__call__"):
  900. f.__doc__ = r.__doc__
  901. else:
  902. f.__doc__ = r
  903. return f
  904. return set_doc
  905. # Alternative spelling of the TOKEN decorator
  906. Token = TOKEN