Debian Codegraph @

tools/wraptypes/lex.py

raw symbols SCIP
1 from __future__ import print_function
2 #-----------------------------------------------------------------------------
3 # ply: lex.py
4 #
5 # Author: David M. Beazley ([email protected])
6 # Modification for pyglet by Alex Holkner ([email protected])
7 #
8 # Copyright (C) 2001-2006, David M. Beazley
9 #
10 # This library is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU Lesser General Public
12 # License as published by the Free Software Foundation; either
13 # version 2.1 of the License, or (at your option) any later version.
14 #
15 # This library is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 # Lesser General Public License for more details.
19 #
20 # You should have received a copy of the GNU Lesser General Public
21 # License along with this library; if not, write to the Free Software
22 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #
24 # See the file LICENSE for a complete copy of the LGPL.
25 #-----------------------------------------------------------------------------
26
27 __version__ = "2.2"
28
29 import re, sys, types
30
31 # Regular expression used to match valid token names
32 _is_identifier = re.compile(r'^[a-zA-Z0-9_]+$')
33
34 # Available instance types. This is used when lexers are defined by a class.
35 # It's a little funky because I want to preserve backwards compatibility
36 # with Python 2.0 where types.ObjectType is undefined.
37
38 try:
39 _INSTANCETYPE = (types.InstanceType, types.ObjectType)
40 except AttributeError:
41 _INSTANCETYPE = types.InstanceType
42 class object: pass # Note: needed if no new-style classes present
43
44 # Exception thrown when invalid token encountered and no default error
45 # handler is defined.
46 class LexError(Exception):
47 def __init__(self,message,s):
48 self.args = (message,)
49 self.text = s
50
51 # Token class
52 class LexToken(object):
53 def __str__(self):
54 return "LexToken(%s,%r,%d,%d)" % (self.type,self.value,self.lineno,self.lexpos)
55 def __repr__(self):
56 return str(self)
57 def skip(self,n):
58 self.lexer.skip(n)
59
60 # -----------------------------------------------------------------------------
61 # Lexer class
62 #
63 # This class encapsulates all of the methods and data associated with a lexer.
64 #
65 # input() - Store a new string in the lexer
66 # token() - Get the next token
67 # -----------------------------------------------------------------------------
68
69 class Lexer:
70 def __init__(self):
71 self.lexre = None # Master regular expression. This is a list of
72 # tuples (re,findex) where re is a compiled
73 # regular expression and findex is a list
74 # mapping regex group numbers to rules
75 self.lexretext = None # Current regular expression strings
76 self.lexstatere = {} # Dictionary mapping lexer states to master regexs
77 self.lexstateretext = {} # Dictionary mapping lexer states to regex strings
78 self.lexstate = "INITIAL" # Current lexer state
79 self.lexstatestack = [] # Stack of lexer states
80 self.lexstateinfo = None # State information
81 self.lexstateignore = {} # Dictionary of ignored characters for each state
82 self.lexstateerrorf = {} # Dictionary of error functions for each state
83 self.lexreflags = 0 # Optional re compile flags
84 self.lexdata = None # Actual input data (as a string)
85 self.lexpos = 0 # Current position in input text
86 self.lexlen = 0 # Length of the input text
87 self.lexerrorf = None # Error rule (if any)
88 self.lextokens = None # List of valid tokens
89 self.lexignore = "" # Ignored characters
90 self.lexliterals = "" # Literal characters that can be passed through
91 self.lexmodule = None # Module
92 self.lineno = 1 # Current line number
93 self.lexdebug = 0 # Debugging mode
94 self.lexoptimize = 0 # Optimized mode
95
96 def clone(self,object=None):
97 c = Lexer()
98 c.lexstatere = self.lexstatere
99 c.lexstateinfo = self.lexstateinfo
100 c.lexstateretext = self.lexstateretext
101 c.lexstate = self.lexstate
102 c.lexstatestack = self.lexstatestack
103 c.lexstateignore = self.lexstateignore
104 c.lexstateerrorf = self.lexstateerrorf
105 c.lexreflags = self.lexreflags
106 c.lexdata = self.lexdata
107 c.lexpos = self.lexpos
108 c.lexlen = self.lexlen
109 c.lextokens = self.lextokens
110 c.lexdebug = self.lexdebug
111 c.lineno = self.lineno
112 c.lexoptimize = self.lexoptimize
113 c.lexliterals = self.lexliterals
114 c.lexmodule = self.lexmodule
115
116 # If the object parameter has been supplied, it means we are attaching the
117 # lexer to a new object. In this case, we have to rebind all methods in
118 # the lexstatere and lexstateerrorf tables.
119
120 if object:
121 newtab = { }
122 for key, ritem in self.lexstatere.items():
123 newre = []
124 for cre, findex in ritem:
125 newfindex = []
126 for f in findex:
127 if not f or not f[0]:
128 newfindex.append(f)
129 continue
130 newfindex.append((getattr(object,f[0].__name__),f[1]))
131 newre.append((cre,newfindex))
132 newtab[key] = newre
133 c.lexstatere = newtab
134 c.lexstateerrorf = { }
135 for key, ef in self.lexstateerrorf.items():
136 c.lexstateerrorf[key] = getattr(object,ef.__name__)
137 c.lexmodule = object
138
139 # Set up other attributes
140 c.begin(c.lexstate)
141 return c
142
143 # ------------------------------------------------------------
144 # writetab() - Write lexer information to a table file
145 # ------------------------------------------------------------
146 def writetab(self,tabfile):
147 tf = open(tabfile+".py","w")
148 tf.write("# %s.py. This file automatically created by PLY (version %s). Don't edit!\n" % (tabfile,__version__))
149 tf.write("_lextokens = %s\n" % repr(self.lextokens))
150 tf.write("_lexreflags = %s\n" % repr(self.lexreflags))
151 tf.write("_lexliterals = %s\n" % repr(self.lexliterals))
152 tf.write("_lexstateinfo = %s\n" % repr(self.lexstateinfo))
153
154 tabre = { }
155 for key, lre in self.lexstatere.items():
156 titem = []
157 for i in range(len(lre)):
158 titem.append((self.lexstateretext[key][i],_funcs_to_names(lre[i][1])))
159 tabre[key] = titem
160
161 tf.write("_lexstatere = %s\n" % repr(tabre))
162 tf.write("_lexstateignore = %s\n" % repr(self.lexstateignore))
163
164 taberr = { }
165 for key, ef in self.lexstateerrorf.items():
166 if ef:
167 taberr[key] = ef.__name__
168 else:
169 taberr[key] = None
170 tf.write("_lexstateerrorf = %s\n" % repr(taberr))
171 tf.close()
172
173 # ------------------------------------------------------------
174 # readtab() - Read lexer information from a tab file
175 # ------------------------------------------------------------
176 def readtab(self,tabfile,fdict):
177 exec("import %s as lextab" % tabfile)
178 global lextab # declare the name of the imported module
179 self.lextokens = lextab._lextokens
180 self.lexreflags = lextab._lexreflags
181 self.lexliterals = lextab._lexliterals
182 self.lexstateinfo = lextab._lexstateinfo
183 self.lexstateignore = lextab._lexstateignore
184 self.lexstatere = { }
185 self.lexstateretext = { }
186 for key,lre in lextab._lexstatere.items():
187 titem = []
188 txtitem = []
189 for i in range(len(lre)):
190 titem.append((re.compile(lre[i][0],lextab._lexreflags),_names_to_funcs(lre[i][1],fdict)))
191 txtitem.append(lre[i][0])
192 self.lexstatere[key] = titem
193 self.lexstateretext[key] = txtitem
194 self.lexstateerrorf = { }
195 for key,ef in lextab._lexstateerrorf.items():
196 self.lexstateerrorf[key] = fdict[ef]
197 self.begin('INITIAL')
198
199 # ------------------------------------------------------------
200 # input() - Push a new string into the lexer
201 # ------------------------------------------------------------
202 def input(self,s):
203 if not (isinstance(s,types.StringType) or isinstance(s,types.UnicodeType)):
204 raise ValueError("Expected a string")
205 self.lexdata = s
206 self.lexpos = 0
207 self.lexlen = len(s)
208
209 # ------------------------------------------------------------
210 # begin() - Changes the lexing state
211 # ------------------------------------------------------------
212 def begin(self,state):
213 if not self.lexstatere.has_key(state):
214 raise ValueError("Undefined state")
215 self.lexre = self.lexstatere[state]
216 self.lexretext = self.lexstateretext[state]
217 self.lexignore = self.lexstateignore.get(state,"")
218 self.lexerrorf = self.lexstateerrorf.get(state,None)
219 self.lexstate = state
220
221 # ------------------------------------------------------------
222 # push_state() - Changes the lexing state and saves old on stack
223 # ------------------------------------------------------------
224 def push_state(self,state):
225 self.lexstatestack.append(self.lexstate)
226 self.begin(state)
227
228 # ------------------------------------------------------------
229 # pop_state() - Restores the previous state
230 # ------------------------------------------------------------
231 def pop_state(self):
232 self.begin(self.lexstatestack.pop())
233
234 # ------------------------------------------------------------
235 # current_state() - Returns the current lexing state
236 # ------------------------------------------------------------
237 def current_state(self):
238 return self.lexstate
239
240 # ------------------------------------------------------------
241 # skip() - Skip ahead n characters
242 # ------------------------------------------------------------
243 def skip(self,n):
244 self.lexpos += n
245
246 # ------------------------------------------------------------
247 # token() - Return the next token from the Lexer
248 #
249 # Note: This function has been carefully implemented to be as fast
250 # as possible. Don't make changes unless you really know what
251 # you are doing
252 # ------------------------------------------------------------
253 def token(self):
254 # Make local copies of frequently referenced attributes
255 lexpos = self.lexpos
256 lexlen = self.lexlen
257 lexignore = self.lexignore
258 lexdata = self.lexdata
259
260 while lexpos < lexlen:
261 # This code provides some short-circuit code for whitespace, tabs, and other ignored characters
262 if lexdata[lexpos] in lexignore:
263 lexpos += 1
264 continue
265
266 # Look for a regular expression match
267 for lexre,lexindexfunc in self.lexre:
268 m = lexre.match(lexdata,lexpos)
269 if not m: continue
270
271 # Set last match in lexer so that rules can access it if they want
272 self.lexmatch = m
273
274 # Create a token for return
275 tok = LexToken()
276 tok.value = m.group()
277 tok.lineno = self.lineno
278 tok.lexpos = lexpos
279 tok.lexer = self
280
281 lexpos = m.end()
282 i = m.lastindex
283 func,tok.type = lexindexfunc[i]
284 self.lexpos = lexpos
285
286 if not func:
287 # If no token type was set, it's an ignored token
288 if tok.type: return tok
289 break
290
291 # if func not callable, it means it's an ignored token
292 if not callable(func):
293 break
294
295 # If token is processed by a function, call it
296 newtok = func(tok)
297
298 # Every function must return a token, if nothing, we just move to next token
299 if not newtok:
300 lexpos = self.lexpos # This is here in case user has updated lexpos.
301
302 # Added for pyglet/tools/wrapper/cparser.py by Alex
303 # Holkner on 20/Jan/2007
304 lexdata = self.lexdata
305 break
306
307 # Verify type of the token. If not in the token map, raise an error
308 if not self.lexoptimize:
309 # Allow any single-character literal also for
310 # pyglet/tools/wrapper/cparser.py by Alex Holkner on
311 # 20/Jan/2007
312 if not self.lextokens.has_key(newtok.type) and len(newtok.type) > 1:
313 raise LexError("%s:%d: Rule '%s' returned an unknown token type '%s'" % (
314 func.func_code.co_filename, func.func_code.co_firstlineno,
315 func.__name__, newtok.type),lexdata[lexpos:])
316
317 return newtok
318 else:
319 # No match, see if in literals
320 if lexdata[lexpos] in self.lexliterals:
321 tok = LexToken()
322 tok.value = lexdata[lexpos]
323 tok.lineno = self.lineno
324 tok.lexer = self
325 tok.type = tok.value
326 tok.lexpos = lexpos
327 self.lexpos = lexpos + 1
328 return tok
329
330 # No match. Call t_error() if defined.
331 if self.lexerrorf:
332 tok = LexToken()
333 tok.value = self.lexdata[lexpos:]
334 tok.lineno = self.lineno
335 tok.type = "error"
336 tok.lexer = self
337 tok.lexpos = lexpos
338 self.lexpos = lexpos
339 newtok = self.lexerrorf(tok)
340 if lexpos == self.lexpos:
341 # Error method didn't change text position at all. This is an error.
342 raise LexError("Scanning error. Illegal character '%s'" % (lexdata[lexpos]), lexdata[lexpos:])
343 lexpos = self.lexpos
344 if not newtok: continue
345 return newtok
346
347 self.lexpos = lexpos
348 raise LexError("Illegal character '%s' at index %d" % (lexdata[lexpos],lexpos), lexdata[lexpos:])
349
350 self.lexpos = lexpos + 1
351 if self.lexdata is None:
352 raise RuntimeError("No input string given with input()")
353 return None
354
355 # -----------------------------------------------------------------------------
356 # _validate_file()
357 #
358 # This checks to see if there are duplicated t_rulename() functions or strings
359 # in the parser input file. This is done using a simple regular expression
360 # match on each line in the filename.
361 # -----------------------------------------------------------------------------
362
363 def _validate_file(filename):
364 import os.path
365 base,ext = os.path.splitext(filename)
366 if ext != '.py': return 1 # No idea what the file is. Return OK
367
368 try:
369 f = open(filename)
370 lines = f.readlines()
371 f.close()
372 except IOError:
373 return 1 # Oh well
374
375 fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(')
376 sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=')
377 counthash = { }
378 linen = 1
379 noerror = 1
380 for l in lines:
381 m = fre.match(l)
382 if not m:
383 m = sre.match(l)
384 if m:
385 name = m.group(1)
386 prev = counthash.get(name)
387 if not prev:
388 counthash[name] = linen
389 else:
390 print("%s:%d: Rule %s redefined. Previously defined on line %d" % (filename,linen,name,prev))
391 noerror = 0
392 linen += 1
393 return noerror
394
395 # -----------------------------------------------------------------------------
396 # _funcs_to_names()
397 #
398 # Given a list of regular expression functions, this converts it to a list
399 # suitable for output to a table file
400 # -----------------------------------------------------------------------------
401
402 def _funcs_to_names(funclist):
403 result = []
404 for f in funclist:
405 if f and f[0]:
406 result.append((f[0].__name__,f[1]))
407 else:
408 result.append(f)
409 return result
410
411 # -----------------------------------------------------------------------------
412 # _names_to_funcs()
413 #
414 # Given a list of regular expression function names, this converts it back to
415 # functions.
416 # -----------------------------------------------------------------------------
417
418 def _names_to_funcs(namelist,fdict):
419 result = []
420 for n in namelist:
421 if n and n[0]:
422 result.append((fdict[n[0]],n[1]))
423 else:
424 result.append(n)
425 return result
426
427 # -----------------------------------------------------------------------------
428 # _form_master_re()
429 #
430 # This function takes a list of all of the regex components and attempts to
431 # form the master regular expression. Given limitations in the Python re
432 # module, it may be necessary to break the master regex into separate expressions.
433 # -----------------------------------------------------------------------------
434
435 def _form_master_re(relist,reflags,ldict):
436 if not relist: return []
437 regex = "|".join(relist)
438 try:
439 lexre = re.compile(regex,re.VERBOSE | reflags)
440
441 # Build the index to function map for the matching engine
442 lexindexfunc = [ None ] * (max(lexre.groupindex.values())+1)
443 for f,i in lexre.groupindex.items():
444 handle = ldict.get(f,None)
445 if type(handle) in (types.FunctionType, types.MethodType):
446 lexindexfunc[i] = (handle,handle.__name__[2:])
447 elif handle is not None:
448 # If rule was specified as a string, we build an anonymous
449 # callback function to carry out the action
450 if f.find("ignore_") > 0:
451 lexindexfunc[i] = (None,None)
452 print("IGNORE", f)
453 else:
454 lexindexfunc[i] = (None, f[2:])
455
456 return [(lexre,lexindexfunc)],[regex]
457 except Exception as e:
458 m = int(len(relist)/2)
459 if m == 0: m = 1
460 llist, lre = _form_master_re(relist[:m],reflags,ldict)
461 rlist, rre = _form_master_re(relist[m:],reflags,ldict)
462 return llist+rlist, lre+rre
463
464 # -----------------------------------------------------------------------------
465 # def _statetoken(s,names)
466 #
467 # Given a declaration name s of the form "t_" and a dictionary whose keys are
468 # state names, this function returns a tuple (states,tokenname) where states
469 # is a tuple of state names and tokenname is the name of the token. For example,
470 # calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM')
471 # -----------------------------------------------------------------------------
472
473 def _statetoken(s,names):
474 nonstate = 1
475 parts = s.split("_")
476 for i in range(1,len(parts)):
477 if not names.has_key(parts[i]) and parts[i] != 'ANY': break
478 if i > 1:
479 states = tuple(parts[1:i])
480 else:
481 states = ('INITIAL',)
482
483 if 'ANY' in states:
484 states = tuple(names.keys())
485
486 tokenname = "_".join(parts[i:])
487 return (states,tokenname)
488
489 # -----------------------------------------------------------------------------
490 # lex(module)
491 #
492 # Build all of the regular expression rules from definitions in the supplied module
493 # -----------------------------------------------------------------------------
494 # cls added for pyglet/tools/wrapper/cparser.py by Alex Holkner on 22/Jan/2007
495 def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,nowarn=0,cls=Lexer):
496 global lexer
497 ldict = None
498 stateinfo = { 'INITIAL' : 'inclusive'}
499 error = 0
500 files = { }
501 lexobj = cls()
502 lexobj.lexdebug = debug
503 lexobj.lexoptimize = optimize
504 global token,input
505
506 if nowarn: warn = 0
507 else: warn = 1
508
509 if object: module = object
510
511 if module:
512 # User supplied a module object.
513 if isinstance(module, types.ModuleType):
514 ldict = module.__dict__
515 elif isinstance(module, _INSTANCETYPE):
516 _items = [(k,getattr(module,k)) for k in dir(module)]
517 ldict = { }
518 for (i,v) in _items:
519 ldict[i] = v
520 else:
521 raise ValueError("Expected a module or instance")
522 lexobj.lexmodule = module
523
524 else:
525 # No module given. We might be able to get information from the caller.
526 try:
527 raise RuntimeError
528 except RuntimeError:
529 e,b,t = sys.exc_info()
530 f = t.tb_frame
531 f = f.f_back # Walk out to our calling function
532 ldict = f.f_globals # Grab its globals dictionary
533
534 if optimize and lextab:
535 try:
536 lexobj.readtab(lextab,ldict)
537 token = lexobj.token
538 input = lexobj.input
539 lexer = lexobj
540 return lexobj
541
542 except ImportError:
543 pass
544
545 # Get the tokens, states, and literals variables (if any)
546 if (module and isinstance(module,_INSTANCETYPE)):
547 tokens = getattr(module,"tokens",None)
548 states = getattr(module,"states",None)
549 literals = getattr(module,"literals","")
550 else:
551 tokens = ldict.get("tokens",None)
552 states = ldict.get("states",None)
553 literals = ldict.get("literals","")
554
555 if not tokens:
556 raise SyntaxError("lex: module does not define 'tokens'")
557 if not (isinstance(tokens,types.ListType) or isinstance(tokens,types.TupleType)):
558 raise SyntaxError("lex: tokens must be a list or tuple.")
559
560 # Build a dictionary of valid token names
561 lexobj.lextokens = { }
562 if not optimize:
563 for n in tokens:
564 if not _is_identifier.match(n):
565 print("lex: Bad token name '%s'" % n)
566 error = 1
567 if warn and lexobj.lextokens.has_key(n):
568 print("lex: Warning. Token '%s' multiply defined." % n)
569 lexobj.lextokens[n] = None
570 else:
571 for n in tokens: lexobj.lextokens[n] = None
572
573 if debug:
574 print("lex: tokens = '%s'" % lexobj.lextokens.keys())
575
576 try:
577 for c in literals:
578 if not (isinstance(c,types.StringType) or isinstance(c,types.UnicodeType)) or len(c) > 1:
579 print("lex: Invalid literal %s. Must be a single character" % repr(c))
580 error = 1
581 continue
582
583 except TypeError:
584 print("lex: Invalid literals specification. literals must be a sequence of characters.")
585 error = 1
586
587 lexobj.lexliterals = literals
588
589 # Build statemap
590 if states:
591 if not (isinstance(states,types.TupleType) or isinstance(states,types.ListType)):
592 print("lex: states must be defined as a tuple or list.")
593 error = 1
594 else:
595 for s in states:
596 if not isinstance(s,types.TupleType) or len(s) != 2:
597 print("lex: invalid state specifier %s. Must be a tuple (statename,'exclusive|inclusive')" % repr(s))
598 error = 1
599 continue
600 name, statetype = s
601 if not isinstance(name,types.StringType):
602 print("lex: state name %s must be a string" % repr(name))
603 error = 1
604 continue
605 if not (statetype == 'inclusive' or statetype == 'exclusive'):
606 print("lex: state type for state %s must be 'inclusive' or 'exclusive'" % name)
607 error = 1
608 continue
609 if stateinfo.has_key(name):
610 print("lex: state '%s' already defined." % name)
611 error = 1
612 continue
613 stateinfo[name] = statetype
614
615 # Get a list of symbols with the t_ or s_ prefix
616 tsymbols = [f for f in ldict.keys() if f[:2] == 't_' ]
617
618 # Now build up a list of functions and a list of strings
619
620 funcsym = { } # Symbols defined as functions
621 strsym = { } # Symbols defined as strings
622 toknames = { } # Mapping of symbols to token names
623
624 for s in stateinfo.keys():
625 funcsym[s] = []
626 strsym[s] = []
627
628 ignore = { } # Ignore strings by state
629 errorf = { } # Error functions by state
630
631 if len(tsymbols) == 0:
632 raise SyntaxError("lex: no rules of the form t_rulename are defined.")
633
634 for f in tsymbols:
635 t = ldict[f]
636 states, tokname = _statetoken(f,stateinfo)
637 toknames[f] = tokname
638
639 if callable(t):
640 for s in states: funcsym[s].append((f,t))
641 elif (isinstance(t, types.StringType) or isinstance(t,types.UnicodeType)):
642 for s in states: strsym[s].append((f,t))
643 else:
644 print("lex: %s not defined as a function or string" % f)
645 error = 1
646
647 # Sort the functions by line number
648 for f in funcsym.values():
649 f.sort(key=lambda func: func[1].__code__.co_firstlineno)
650
651 # Sort the strings by regular expression length
652 for s in strsym.values():
653 s.sort(lambda x,y: (len(x[1]) < len(y[1])) - (len(x[1]) > len(y[1])))
654
655 regexs = { }
656
657 # Build the master regular expressions
658 for state in stateinfo.keys():
659 regex_list = []
660
661 # Add rules defined by functions first
662 for fname, f in funcsym[state]:
663 line = f.func_code.co_firstlineno
664 file = f.func_code.co_filename
665 files[file] = None
666 tokname = toknames[fname]
667
668 ismethod = isinstance(f, types.MethodType)
669
670 if not optimize:
671 nargs = f.func_code.co_argcount
672 if ismethod:
673 reqargs = 2
674 else:
675 reqargs = 1
676 if nargs > reqargs:
677 print("%s:%d: Rule '%s' has too many arguments." % (file,line,f.__name__))
678 error = 1
679 continue
680
681 if nargs < reqargs:
682 print("%s:%d: Rule '%s' requires an argument." % (file,line,f.__name__))
683 error = 1
684 continue
685
686 if tokname == 'ignore':
687 print("%s:%d: Rule '%s' must be defined as a string." % (file,line,f.__name__))
688 error = 1
689 continue
690
691 if tokname == 'error':
692 errorf[state] = f
693 continue
694
695 if f.__doc__:
696 if not optimize:
697 try:
698 c = re.compile("(?P<%s>%s)" % (f.__name__,f.__doc__), re.VERBOSE | reflags)
699 if c.match(""):
700 print("%s:%d: Regular expression for rule '%s' matches empty string." % (file,line,f.__name__))
701 error = 1
702 continue
703 except re.error as e:
704 print("%s:%d: Invalid regular expression for rule '%s'. %s" % (file,line,f.__name__,e))
705 if '#' in f.__doc__:
706 print("%s:%d. Make sure '#' in rule '%s' is escaped with '\\#'." % (file,line, f.__name__))
707 error = 1
708 continue
709
710 if debug:
711 print("lex: Adding rule %s -> '%s' (state '%s')" % (f.__name__,f.__doc__, state))
712
713 # Okay. The regular expression seemed okay. Let's append it to the master regular
714 # expression we're building
715
716 regex_list.append("(?P<%s>%s)" % (f.__name__,f.__doc__))
717 else:
718 print("%s:%d: No regular expression defined for rule '%s'" % (file,line,f.__name__))
719
720 # Now add all of the simple rules
721 for name,r in strsym[state]:
722 tokname = toknames[name]
723
724 if tokname == 'ignore':
725 ignore[state] = r
726 continue
727
728 if not optimize:
729 if tokname == 'error':
730 raise SyntaxError("lex: Rule '%s' must be defined as a function" % name)
731 error = 1
732 continue
733
734 if not lexobj.lextokens.has_key(tokname) and tokname.find("ignore_") < 0:
735 print("lex: Rule '%s' defined for an unspecified token %s." % (name,tokname))
736 error = 1
737 continue
738 try:
739 c = re.compile("(?P<%s>%s)" % (name,r),re.VERBOSE | reflags)
740 if (c.match("")):
741 print("lex: Regular expression for rule '%s' matches empty string." % name)
742 error = 1
743 continue
744 except re.error as e:
745 print("lex: Invalid regular expression for rule '%s'. %s" % (name,e))
746 if '#' in r:
747 print("lex: Make sure '#' in rule '%s' is escaped with '\\#'." % name)
748
749 error = 1
750 continue
751 if debug:
752 print("lex: Adding rule %s -> '%s' (state '%s')" % (name,r,state))
753
754 regex_list.append("(?P<%s>%s)" % (name,r))
755
756 if not regex_list:
757 print("lex: No rules defined for state '%s'" % state)
758 error = 1
759
760 regexs[state] = regex_list
761
762
763 if not optimize:
764 for f in files.keys():
765 if not _validate_file(f):
766 error = 1
767
768 if error:
769 raise SyntaxError("lex: Unable to build lexer.")
770
771 # From this point forward, we're reasonably confident that we can build the lexer.
772 # No more errors will be generated, but there might be some warning messages.
773
774 # Build the master regular expressions
775
776 for state in regexs.keys():
777 lexre, re_text = _form_master_re(regexs[state],reflags,ldict)
778 lexobj.lexstatere[state] = lexre
779 lexobj.lexstateretext[state] = re_text
780 if debug:
781 for i in range(len(re_text)):
782 print("lex: state '%s'. regex[%d] = '%s'" % (state, i, re_text[i]))
783
784 # For inclusive states, we need to add the INITIAL state
785 for state,type in stateinfo.items():
786 if state != "INITIAL" and type == 'inclusive':
787 lexobj.lexstatere[state].extend(lexobj.lexstatere['INITIAL'])
788 lexobj.lexstateretext[state].extend(lexobj.lexstateretext['INITIAL'])
789
790 lexobj.lexstateinfo = stateinfo
791 lexobj.lexre = lexobj.lexstatere["INITIAL"]
792 lexobj.lexretext = lexobj.lexstateretext["INITIAL"]
793
794 # Set up ignore variables
795 lexobj.lexstateignore = ignore
796 lexobj.lexignore = lexobj.lexstateignore.get("INITIAL","")
797
798 # Set up error functions
799 lexobj.lexstateerrorf = errorf
800 lexobj.lexerrorf = errorf.get("INITIAL",None)
801 if warn and not lexobj.lexerrorf:
802 print("lex: Warning. no t_error rule is defined.")
803
804 # Check state information for ignore and error rules
805 for s,stype in stateinfo.items():
806 if stype == 'exclusive':
807 if warn and not errorf.has_key(s):
808 print("lex: Warning. no error rule is defined for exclusive state '%s'" % s)
809 if warn and not ignore.has_key(s) and lexobj.lexignore:
810 print("lex: Warning. no ignore rule is defined for exclusive state '%s'" % s)
811 elif stype == 'inclusive':
812 if not errorf.has_key(s):
813 errorf[s] = errorf.get("INITIAL",None)
814 if not ignore.has_key(s):
815 ignore[s] = ignore.get("INITIAL","")
816
817
818 # Create global versions of the token() and input() functions
819 token = lexobj.token
820 input = lexobj.input
821 lexer = lexobj
822
823 # If in optimize mode, we write the lextab
824 if lextab and optimize:
825 lexobj.writetab(lextab)
826
827 return lexobj
828
829 # -----------------------------------------------------------------------------
830 # runmain()
831 #
832 # This runs the lexer as a main program
833 # -----------------------------------------------------------------------------
834
835 def runmain(lexer=None,data=None):
836 if not data:
837 try:
838 filename = sys.argv[1]
839 f = open(filename)
840 data = f.read()
841 f.close()
842 except IndexError:
843 print("Reading from standard input (type EOF to end):")
844 data = sys.stdin.read()
845
846 if lexer:
847 _input = lexer.input
848 else:
849 _input = input
850 _input(data)
851 if lexer:
852 _token = lexer.token
853 else:
854 _token = token
855
856 while 1:
857 tok = _token()
858 if not tok: break
859 print("(%s,%r,%d,%d)" % (tok.type, tok.value, tok.lineno,tok.lexpos))
860
861
862 # -----------------------------------------------------------------------------
863 # @TOKEN(regex)
864 #
865 # This decorator function can be used to set the regex expression on a function
866 # when its docstring might need to be set in an alternative way
867 # -----------------------------------------------------------------------------
868
869 def TOKEN(r):
870 def set_doc(f):
871 f.__doc__ = r
872 return f
873 return set_doc
874
875 # Alternative spelling of the TOKEN decorator
876 Token = TOKEN
877