abcjs 6.3.0 → 6.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +4 -0
  2. package/RELEASE.md +52 -0
  3. package/dist/abcjs-basic-min.js +2 -2
  4. package/dist/abcjs-basic.js +1031 -622
  5. package/dist/abcjs-basic.js.map +1 -1
  6. package/dist/abcjs-plugin-min.js +2 -2
  7. package/index.js +1 -0
  8. package/package.json +1 -1
  9. package/src/api/tune-metrics.js +18 -0
  10. package/src/data/abc_tune.js +13 -2
  11. package/src/edit/abc_editarea.js +4 -1
  12. package/src/parse/abc_parse.js +2 -0
  13. package/src/parse/abc_parse_directive.js +6 -0
  14. package/src/synth/abc_midi_flattener.js +40 -462
  15. package/src/synth/abc_midi_sequencer.js +25 -10
  16. package/src/synth/chord-track.js +565 -0
  17. package/src/synth/create-note-map.js +2 -1
  18. package/src/synth/create-synth.js +91 -42
  19. package/src/test/abc_parser_lint.js +1 -0
  20. package/src/write/creation/abstract-engraver.js +4 -1
  21. package/src/write/creation/decoration.js +3 -2
  22. package/src/write/creation/elements/tie-element.js +23 -0
  23. package/src/write/draw/draw.js +1 -1
  24. package/src/write/engraver-controller.js +9 -5
  25. package/src/write/interactive/create-analysis.js +50 -0
  26. package/src/write/interactive/find-selectable-element.js +24 -0
  27. package/src/write/interactive/selection.js +5 -45
  28. package/src/write/layout/layout-in-grid.js +83 -0
  29. package/src/write/layout/layout.js +29 -24
  30. package/src/write/layout/set-upper-and-lower-elements.js +2 -0
  31. package/src/write/layout/staff-group.js +2 -2
  32. package/src/write/layout/voice-elements.js +1 -1
  33. package/src/write/layout/voice.js +1 -1
  34. package/src/write/renderer.js +3 -0
  35. package/types/index.d.ts +96 -32
  36. package/version.js +1 -1
  37. package/abc2xml_239/abc2xml.html +0 -769
  38. package/abc2xml_239/abc2xml.py +0 -2248
  39. package/abc2xml_239/abc2xml_changelog.html +0 -124
  40. package/abc2xml_239/lazy-river.abc +0 -26
  41. package/abc2xml_239/lazy-river.xml +0 -3698
  42. package/abc2xml_239/mean-to-me.abc +0 -22
  43. package/abc2xml_239/mean-to-me.xml +0 -2954
  44. package/abc2xml_239/pyparsing.py +0 -3672
  45. package/abc2xml_239/pyparsing.pyc +0 -0
  46. package/temp.txt +0 -50
@@ -1,3672 +0,0 @@
1
- # module pyparsing.py
2
- #
3
- # Copyright (c) 2003-2013 Paul T. McGuire
4
- #
5
- # Permission is hereby granted, free of charge, to any person obtaining
6
- # a copy of this software and associated documentation files (the
7
- # "Software"), to deal in the Software without restriction, including
8
- # without limitation the rights to use, copy, modify, merge, publish,
9
- # distribute, sublicense, and/or sell copies of the Software, and to
10
- # permit persons to whom the Software is furnished to do so, subject to
11
- # the following conditions:
12
- #
13
- # The above copyright notice and this permission notice shall be
14
- # included in all copies or substantial portions of the Software.
15
- #
16
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
- # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
- # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
- # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
- # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
- # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
- # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
- #
24
-
25
- __doc__ = \
26
- """
27
- pyparsing module - Classes and methods to define and execute parsing grammars
28
-
29
- The pyparsing module is an alternative approach to creating and executing simple grammars,
30
- vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
31
- don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
32
- provides a library of classes that you use to construct the grammar directly in Python.
33
-
34
- Here is a program to parse "Hello, World!" (or any greeting of the form C{"<salutation>, <addressee>!"})::
35
-
36
- from pyparsing import Word, alphas
37
-
38
- # define grammar of a greeting
39
- greet = Word( alphas ) + "," + Word( alphas ) + "!"
40
-
41
- hello = "Hello, World!"
42
- print (hello, "->", greet.parseString( hello ))
43
-
44
- The program outputs the following::
45
-
46
- Hello, World! -> ['Hello', ',', 'World', '!']
47
-
48
- The Python representation of the grammar is quite readable, owing to the self-explanatory
49
- class names, and the use of '+', '|' and '^' operators.
50
-
51
- The parsed results returned from C{parseString()} can be accessed as a nested list, a dictionary, or an
52
- object with named attributes.
53
-
54
- The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
55
- - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.)
56
- - quoted strings
57
- - embedded comments
58
- """
59
-
60
- __version__ = "2.0.1"
61
- __versionTime__ = "16 July 2013 22:22"
62
- __author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
63
-
64
- import string
65
- from weakref import ref as wkref
66
- import copy
67
- import sys
68
- import warnings
69
- import re
70
- import sre_constants
71
- import collections
72
- #~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
73
-
74
- __all__ = [
75
- 'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
76
- 'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
77
- 'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
78
- 'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
79
- 'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
80
- 'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter', 'Upcase',
81
- 'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore',
82
- 'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
83
- 'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
84
- 'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'hexnums',
85
- 'htmlComment', 'javaStyleComment', 'keepOriginalText', 'line', 'lineEnd', 'lineStart', 'lineno',
86
- 'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
87
- 'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
88
- 'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
89
- 'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
90
- 'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
91
- 'indentedBlock', 'originalTextFor', 'ungroup', 'infixNotation',
92
- ]
93
-
94
- PY_3 = sys.version.startswith('3')
95
- if PY_3:
96
- _MAX_INT = sys.maxsize
97
- basestring = str
98
- unichr = chr
99
- _ustr = str
100
-
101
- # build list of single arg builtins, that can be used as parse actions
102
- singleArgBuiltins = [sum, len, sorted, reversed, list, tuple, set, any, all, min, max]
103
-
104
- else:
105
- _MAX_INT = sys.maxint
106
- range = xrange
107
-
108
- def _ustr(obj):
109
- """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
110
- str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
111
- then < returns the unicode object | encodes it with the default encoding | ... >.
112
- """
113
- if isinstance(obj,unicode):
114
- return obj
115
-
116
- try:
117
- # If this works, then _ustr(obj) has the same behaviour as str(obj), so
118
- # it won't break any existing code.
119
- return str(obj)
120
-
121
- except UnicodeEncodeError:
122
- # The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
123
- # state that "The return value must be a string object". However, does a
124
- # unicode object (being a subclass of basestring) count as a "string
125
- # object"?
126
- # If so, then return a unicode object:
127
- return unicode(obj)
128
- # Else encode it... but how? There are many choices... :)
129
- # Replace unprintables with escape codes?
130
- #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors')
131
- # Replace unprintables with question marks?
132
- #return unicode(obj).encode(sys.getdefaultencoding(), 'replace')
133
- # ...
134
-
135
- # build list of single arg builtins, tolerant of Python version, that can be used as parse actions
136
- singleArgBuiltins = []
137
- import __builtin__
138
- for fname in "sum len sorted reversed list tuple set any all min max".split():
139
- try:
140
- singleArgBuiltins.append(getattr(__builtin__,fname))
141
- except AttributeError:
142
- continue
143
-
144
-
145
- def _xml_escape(data):
146
- """Escape &, <, >, ", ', etc. in a string of data."""
147
-
148
- # ampersand must be replaced first
149
- from_symbols = '&><"\''
150
- to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split())
151
- for from_,to_ in zip(from_symbols, to_symbols):
152
- data = data.replace(from_, to_)
153
- return data
154
-
155
- class _Constants(object):
156
- pass
157
-
158
- alphas = string.ascii_lowercase + string.ascii_uppercase
159
- nums = "0123456789"
160
- hexnums = nums + "ABCDEFabcdef"
161
- alphanums = alphas + nums
162
- _bslash = chr(92)
163
- printables = "".join(c for c in string.printable if c not in string.whitespace)
164
-
165
- class ParseBaseException(Exception):
166
- """base exception class for all parsing runtime exceptions"""
167
- # Performance tuning: we construct a *lot* of these, so keep this
168
- # constructor as small and fast as possible
169
- def __init__( self, pstr, loc=0, msg=None, elem=None ):
170
- self.loc = loc
171
- if msg is None:
172
- self.msg = pstr
173
- self.pstr = ""
174
- else:
175
- self.msg = msg
176
- self.pstr = pstr
177
- self.parserElement = elem
178
-
179
- def __getattr__( self, aname ):
180
- """supported attributes by name are:
181
- - lineno - returns the line number of the exception text
182
- - col - returns the column number of the exception text
183
- - line - returns the line containing the exception text
184
- """
185
- if( aname == "lineno" ):
186
- return lineno( self.loc, self.pstr )
187
- elif( aname in ("col", "column") ):
188
- return col( self.loc, self.pstr )
189
- elif( aname == "line" ):
190
- return line( self.loc, self.pstr )
191
- else:
192
- raise AttributeError(aname)
193
-
194
- def __str__( self ):
195
- return "%s (at char %d), (line:%d, col:%d)" % \
196
- ( self.msg, self.loc, self.lineno, self.column )
197
- def __repr__( self ):
198
- return _ustr(self)
199
- def markInputline( self, markerString = ">!<" ):
200
- """Extracts the exception line from the input string, and marks
201
- the location of the exception with a special symbol.
202
- """
203
- line_str = self.line
204
- line_column = self.column - 1
205
- if markerString:
206
- line_str = "".join(line_str[:line_column],
207
- markerString, line_str[line_column:])
208
- return line_str.strip()
209
- def __dir__(self):
210
- return "loc msg pstr parserElement lineno col line " \
211
- "markInputline __str__ __repr__".split()
212
-
213
- class ParseException(ParseBaseException):
214
- """exception thrown when parse expressions don't match class;
215
- supported attributes by name are:
216
- - lineno - returns the line number of the exception text
217
- - col - returns the column number of the exception text
218
- - line - returns the line containing the exception text
219
- """
220
- pass
221
-
222
- class ParseFatalException(ParseBaseException):
223
- """user-throwable exception thrown when inconsistent parse content
224
- is found; stops all parsing immediately"""
225
- pass
226
-
227
- class ParseSyntaxException(ParseFatalException):
228
- """just like C{L{ParseFatalException}}, but thrown internally when an
229
- C{L{ErrorStop<And._ErrorStop>}} ('-' operator) indicates that parsing is to stop immediately because
230
- an unbacktrackable syntax error has been found"""
231
- def __init__(self, pe):
232
- super(ParseSyntaxException, self).__init__(
233
- pe.pstr, pe.loc, pe.msg, pe.parserElement)
234
-
235
- #~ class ReparseException(ParseBaseException):
236
- #~ """Experimental class - parse actions can raise this exception to cause
237
- #~ pyparsing to reparse the input string:
238
- #~ - with a modified input string, and/or
239
- #~ - with a modified start location
240
- #~ Set the values of the ReparseException in the constructor, and raise the
241
- #~ exception in a parse action to cause pyparsing to use the new string/location.
242
- #~ Setting the values as None causes no change to be made.
243
- #~ """
244
- #~ def __init_( self, newstring, restartLoc ):
245
- #~ self.newParseText = newstring
246
- #~ self.reparseLoc = restartLoc
247
-
248
- class RecursiveGrammarException(Exception):
249
- """exception thrown by C{validate()} if the grammar could be improperly recursive"""
250
- def __init__( self, parseElementList ):
251
- self.parseElementTrace = parseElementList
252
-
253
- def __str__( self ):
254
- return "RecursiveGrammarException: %s" % self.parseElementTrace
255
-
256
- class _ParseResultsWithOffset(object):
257
- def __init__(self,p1,p2):
258
- self.tup = (p1,p2)
259
- def __getitem__(self,i):
260
- return self.tup[i]
261
- def __repr__(self):
262
- return repr(self.tup)
263
- def setOffset(self,i):
264
- self.tup = (self.tup[0],i)
265
-
266
- class ParseResults(object):
267
- """Structured parse results, to provide multiple means of access to the parsed data:
268
- - as a list (C{len(results)})
269
- - by list index (C{results[0], results[1]}, etc.)
270
- - by attribute (C{results.<resultsName>})
271
- """
272
- #~ __slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__accumNames", "__weakref__" )
273
- def __new__(cls, toklist, name=None, asList=True, modal=True ):
274
- if isinstance(toklist, cls):
275
- return toklist
276
- retobj = object.__new__(cls)
277
- retobj.__doinit = True
278
- return retobj
279
-
280
- # Performance tuning: we construct a *lot* of these, so keep this
281
- # constructor as small and fast as possible
282
- def __init__( self, toklist, name=None, asList=True, modal=True, isinstance=isinstance ):
283
- if self.__doinit:
284
- self.__doinit = False
285
- self.__name = None
286
- self.__parent = None
287
- self.__accumNames = {}
288
- if isinstance(toklist, list):
289
- self.__toklist = toklist[:]
290
- else:
291
- self.__toklist = [toklist]
292
- self.__tokdict = dict()
293
-
294
- if name is not None and name:
295
- if not modal:
296
- self.__accumNames[name] = 0
297
- if isinstance(name,int):
298
- name = _ustr(name) # will always return a str, but use _ustr for consistency
299
- self.__name = name
300
- if not toklist in (None,'',[]):
301
- if isinstance(toklist,basestring):
302
- toklist = [ toklist ]
303
- if asList:
304
- if isinstance(toklist,ParseResults):
305
- self[name] = _ParseResultsWithOffset(toklist.copy(),0)
306
- else:
307
- self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),0)
308
- self[name].__name = name
309
- else:
310
- try:
311
- self[name] = toklist[0]
312
- except (KeyError,TypeError,IndexError):
313
- self[name] = toklist
314
-
315
- def __getitem__( self, i ):
316
- if isinstance( i, (int,slice) ):
317
- return self.__toklist[i]
318
- else:
319
- if i not in self.__accumNames:
320
- return self.__tokdict[i][-1][0]
321
- else:
322
- return ParseResults([ v[0] for v in self.__tokdict[i] ])
323
-
324
- def __setitem__( self, k, v, isinstance=isinstance ):
325
- if isinstance(v,_ParseResultsWithOffset):
326
- self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
327
- sub = v[0]
328
- elif isinstance(k,int):
329
- self.__toklist[k] = v
330
- sub = v
331
- else:
332
- self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)]
333
- sub = v
334
- if isinstance(sub,ParseResults):
335
- sub.__parent = wkref(self)
336
-
337
- def __delitem__( self, i ):
338
- if isinstance(i,(int,slice)):
339
- mylen = len( self.__toklist )
340
- del self.__toklist[i]
341
-
342
- # convert int to slice
343
- if isinstance(i, int):
344
- if i < 0:
345
- i += mylen
346
- i = slice(i, i+1)
347
- # get removed indices
348
- removed = list(range(*i.indices(mylen)))
349
- removed.reverse()
350
- # fixup indices in token dictionary
351
- for name in self.__tokdict:
352
- occurrences = self.__tokdict[name]
353
- for j in removed:
354
- for k, (value, position) in enumerate(occurrences):
355
- occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
356
- else:
357
- del self.__tokdict[i]
358
-
359
- def __contains__( self, k ):
360
- return k in self.__tokdict
361
-
362
- def __len__( self ): return len( self.__toklist )
363
- def __bool__(self): return len( self.__toklist ) > 0
364
- __nonzero__ = __bool__
365
- def __iter__( self ): return iter( self.__toklist )
366
- def __reversed__( self ): return iter( self.__toklist[::-1] )
367
- def keys( self ):
368
- """Returns all named result keys."""
369
- return self.__tokdict.keys()
370
-
371
- def pop( self, index=-1 ):
372
- """Removes and returns item at specified index (default=last).
373
- Will work with either numeric indices or dict-key indicies."""
374
- ret = self[index]
375
- del self[index]
376
- return ret
377
-
378
- def get(self, key, defaultValue=None):
379
- """Returns named result matching the given key, or if there is no
380
- such name, then returns the given C{defaultValue} or C{None} if no
381
- C{defaultValue} is specified."""
382
- if key in self:
383
- return self[key]
384
- else:
385
- return defaultValue
386
-
387
- def insert( self, index, insStr ):
388
- """Inserts new element at location index in the list of parsed tokens."""
389
- self.__toklist.insert(index, insStr)
390
- # fixup indices in token dictionary
391
- for name in self.__tokdict:
392
- occurrences = self.__tokdict[name]
393
- for k, (value, position) in enumerate(occurrences):
394
- occurrences[k] = _ParseResultsWithOffset(value, position + (position > index))
395
-
396
- def items( self ):
397
- """Returns all named result keys and values as a list of tuples."""
398
- return [(k,self[k]) for k in self.__tokdict]
399
-
400
- def values( self ):
401
- """Returns all named result values."""
402
- return [ v[-1][0] for v in self.__tokdict.values() ]
403
-
404
- def __getattr__( self, name ):
405
- if True: #name not in self.__slots__:
406
- if name in self.__tokdict:
407
- if name not in self.__accumNames:
408
- return self.__tokdict[name][-1][0]
409
- else:
410
- return ParseResults([ v[0] for v in self.__tokdict[name] ])
411
- else:
412
- return ""
413
- return None
414
-
415
- def __add__( self, other ):
416
- ret = self.copy()
417
- ret += other
418
- return ret
419
-
420
- def __iadd__( self, other ):
421
- if other.__tokdict:
422
- offset = len(self.__toklist)
423
- addoffset = ( lambda a: (a<0 and offset) or (a+offset) )
424
- otheritems = other.__tokdict.items()
425
- otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) )
426
- for (k,vlist) in otheritems for v in vlist]
427
- for k,v in otherdictitems:
428
- self[k] = v
429
- if isinstance(v[0],ParseResults):
430
- v[0].__parent = wkref(self)
431
-
432
- self.__toklist += other.__toklist
433
- self.__accumNames.update( other.__accumNames )
434
- return self
435
-
436
- def __radd__(self, other):
437
- if isinstance(other,int) and other == 0:
438
- return self.copy()
439
-
440
- def __repr__( self ):
441
- return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
442
-
443
- def __str__( self ):
444
- out = []
445
- for i in self.__toklist:
446
- if isinstance(i, ParseResults):
447
- out.append(_ustr(i))
448
- else:
449
- out.append(repr(i))
450
- return '[' + ', '.join(out) + ']'
451
-
452
- def _asStringList( self, sep='' ):
453
- out = []
454
- for item in self.__toklist:
455
- if out and sep:
456
- out.append(sep)
457
- if isinstance( item, ParseResults ):
458
- out += item._asStringList()
459
- else:
460
- out.append( _ustr(item) )
461
- return out
462
-
463
- def asList( self ):
464
- """Returns the parse results as a nested list of matching tokens, all converted to strings."""
465
- out = []
466
- for res in self.__toklist:
467
- if isinstance(res,ParseResults):
468
- out.append( res.asList() )
469
- else:
470
- out.append( res )
471
- return out
472
-
473
- def asDict( self ):
474
- """Returns the named parse results as dictionary."""
475
- return dict( self.items() )
476
-
477
- def copy( self ):
478
- """Returns a new copy of a C{ParseResults} object."""
479
- ret = ParseResults( self.__toklist )
480
- ret.__tokdict = self.__tokdict.copy()
481
- ret.__parent = self.__parent
482
- ret.__accumNames.update( self.__accumNames )
483
- ret.__name = self.__name
484
- return ret
485
-
486
- def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
487
- """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names."""
488
- nl = "\n"
489
- out = []
490
- namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items()
491
- for v in vlist)
492
- nextLevelIndent = indent + " "
493
-
494
- # collapse out indents if formatting is not desired
495
- if not formatted:
496
- indent = ""
497
- nextLevelIndent = ""
498
- nl = ""
499
-
500
- selfTag = None
501
- if doctag is not None:
502
- selfTag = doctag
503
- else:
504
- if self.__name:
505
- selfTag = self.__name
506
-
507
- if not selfTag:
508
- if namedItemsOnly:
509
- return ""
510
- else:
511
- selfTag = "ITEM"
512
-
513
- out += [ nl, indent, "<", selfTag, ">" ]
514
-
515
- worklist = self.__toklist
516
- for i,res in enumerate(worklist):
517
- if isinstance(res,ParseResults):
518
- if i in namedItems:
519
- out += [ res.asXML(namedItems[i],
520
- namedItemsOnly and doctag is None,
521
- nextLevelIndent,
522
- formatted)]
523
- else:
524
- out += [ res.asXML(None,
525
- namedItemsOnly and doctag is None,
526
- nextLevelIndent,
527
- formatted)]
528
- else:
529
- # individual token, see if there is a name for it
530
- resTag = None
531
- if i in namedItems:
532
- resTag = namedItems[i]
533
- if not resTag:
534
- if namedItemsOnly:
535
- continue
536
- else:
537
- resTag = "ITEM"
538
- xmlBodyText = _xml_escape(_ustr(res))
539
- out += [ nl, nextLevelIndent, "<", resTag, ">",
540
- xmlBodyText,
541
- "</", resTag, ">" ]
542
-
543
- out += [ nl, indent, "</", selfTag, ">" ]
544
- return "".join(out)
545
-
546
- def __lookup(self,sub):
547
- for k,vlist in self.__tokdict.items():
548
- for v,loc in vlist:
549
- if sub is v:
550
- return k
551
- return None
552
-
553
- def getName(self):
554
- """Returns the results name for this token expression."""
555
- if self.__name:
556
- return self.__name
557
- elif self.__parent:
558
- par = self.__parent()
559
- if par:
560
- return par.__lookup(self)
561
- else:
562
- return None
563
- elif (len(self) == 1 and
564
- len(self.__tokdict) == 1 and
565
- self.__tokdict.values()[0][0][1] in (0,-1)):
566
- return self.__tokdict.keys()[0]
567
- else:
568
- return None
569
-
570
- def dump(self,indent='',depth=0):
571
- """Diagnostic method for listing out the contents of a C{ParseResults}.
572
- Accepts an optional C{indent} argument so that this string can be embedded
573
- in a nested display of other data."""
574
- out = []
575
- out.append( indent+_ustr(self.asList()) )
576
- keys = self.items()
577
- keys.sort()
578
- for k,v in keys:
579
- if out:
580
- out.append('\n')
581
- out.append( "%s%s- %s: " % (indent,(' '*depth), k) )
582
- if isinstance(v,ParseResults):
583
- if v.keys():
584
- out.append( v.dump(indent,depth+1) )
585
- else:
586
- out.append(_ustr(v))
587
- else:
588
- out.append(_ustr(v))
589
- return "".join(out)
590
-
591
- # add support for pickle protocol
592
- def __getstate__(self):
593
- return ( self.__toklist,
594
- ( self.__tokdict.copy(),
595
- self.__parent is not None and self.__parent() or None,
596
- self.__accumNames,
597
- self.__name ) )
598
-
599
- def __setstate__(self,state):
600
- self.__toklist = state[0]
601
- (self.__tokdict,
602
- par,
603
- inAccumNames,
604
- self.__name) = state[1]
605
- self.__accumNames = {}
606
- self.__accumNames.update(inAccumNames)
607
- if par is not None:
608
- self.__parent = wkref(par)
609
- else:
610
- self.__parent = None
611
-
612
- def __dir__(self):
613
- return dir(super(ParseResults,self)) + list(self.keys())
614
-
615
- if hasattr (collections, 'MutableMapping'):
616
- collections.MutableMapping.register(ParseResults)
617
- else:
618
- from collections.abc import MutableMapping
619
- MutableMapping.register (ParseResults)
620
-
621
- def col (loc,strg):
622
- """Returns current column within a string, counting newlines as line separators.
623
- The first column is number 1.
624
-
625
- Note: the default parsing behavior is to expand tabs in the input string
626
- before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
627
- on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
628
- consistent view of the parsed string, the parse location, and line and column
629
- positions within the parsed string.
630
- """
631
- return (loc<len(strg) and strg[loc] == '\n') and 1 or loc - strg.rfind("\n", 0, loc)
632
-
633
- def lineno(loc,strg):
634
- """Returns current line number within a string, counting newlines as line separators.
635
- The first line is number 1.
636
-
637
- Note: the default parsing behavior is to expand tabs in the input string
638
- before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
639
- on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
640
- consistent view of the parsed string, the parse location, and line and column
641
- positions within the parsed string.
642
- """
643
- return strg.count("\n",0,loc) + 1
644
-
645
- def line( loc, strg ):
646
- """Returns the line of text containing loc within a string, counting newlines as line separators.
647
- """
648
- lastCR = strg.rfind("\n", 0, loc)
649
- nextCR = strg.find("\n", loc)
650
- if nextCR >= 0:
651
- return strg[lastCR+1:nextCR]
652
- else:
653
- return strg[lastCR+1:]
654
-
655
- def _defaultStartDebugAction( instring, loc, expr ):
656
- print (("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )))
657
-
658
- def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
659
- print ("Matched " + _ustr(expr) + " -> " + str(toks.asList()))
660
-
661
- def _defaultExceptionDebugAction( instring, loc, expr, exc ):
662
- print ("Exception raised:" + _ustr(exc))
663
-
664
- def nullDebugAction(*args):
665
- """'Do-nothing' debug action, to suppress debugging output during parsing."""
666
- pass
667
-
668
- # Only works on Python 3.x - nonlocal is toxic to Python 2 installs
669
- #~ 'decorator to trim function calls to match the arity of the target'
670
- #~ def _trim_arity(func, maxargs=3):
671
- #~ if func in singleArgBuiltins:
672
- #~ return lambda s,l,t: func(t)
673
- #~ limit = 0
674
- #~ foundArity = False
675
- #~ def wrapper(*args):
676
- #~ nonlocal limit,foundArity
677
- #~ while 1:
678
- #~ try:
679
- #~ ret = func(*args[limit:])
680
- #~ foundArity = True
681
- #~ return ret
682
- #~ except TypeError:
683
- #~ if limit == maxargs or foundArity:
684
- #~ raise
685
- #~ limit += 1
686
- #~ continue
687
- #~ return wrapper
688
-
689
- # this version is Python 2.x-3.x cross-compatible
690
- 'decorator to trim function calls to match the arity of the target'
691
- def _trim_arity(func, maxargs=2):
692
- if func in singleArgBuiltins:
693
- return lambda s,l,t: func(t)
694
- limit = [0]
695
- foundArity = [False]
696
- def wrapper(*args):
697
- while 1:
698
- try:
699
- ret = func(*args[limit[0]:])
700
- foundArity[0] = True
701
- return ret
702
- except TypeError:
703
- if limit[0] <= maxargs and not foundArity[0]:
704
- limit[0] += 1
705
- continue
706
- raise
707
- return wrapper
708
-
709
- class ParserElement(object):
710
- """Abstract base level parser element class."""
711
- DEFAULT_WHITE_CHARS = " \n\t\r"
712
- verbose_stacktrace = False
713
-
714
- def setDefaultWhitespaceChars( chars ):
715
- """Overrides the default whitespace chars
716
- """
717
- ParserElement.DEFAULT_WHITE_CHARS = chars
718
- setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars)
719
-
720
- def inlineLiteralsUsing(cls):
721
- """
722
- Set class to be used for inclusion of string literals into a parser.
723
- """
724
- ParserElement.literalStringClass = cls
725
- inlineLiteralsUsing = staticmethod(inlineLiteralsUsing)
726
-
727
- def __init__( self, savelist=False ):
728
- self.parseAction = list()
729
- self.failAction = None
730
- #~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall
731
- self.strRepr = None
732
- self.resultsName = None
733
- self.saveAsList = savelist
734
- self.skipWhitespace = True
735
- self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
736
- self.copyDefaultWhiteChars = True
737
- self.mayReturnEmpty = False # used when checking for left-recursion
738
- self.keepTabs = False
739
- self.ignoreExprs = list()
740
- self.debug = False
741
- self.streamlined = False
742
- self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
743
- self.errmsg = ""
744
- self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all)
745
- self.debugActions = ( None, None, None ) #custom debug actions
746
- self.re = None
747
- self.callPreparse = True # used to avoid redundant calls to preParse
748
- self.callDuringTry = False
749
-
750
- def copy( self ):
751
- """Make a copy of this C{ParserElement}. Useful for defining different parse actions
752
- for the same parsing pattern, using copies of the original parse element."""
753
- cpy = copy.copy( self )
754
- cpy.parseAction = self.parseAction[:]
755
- cpy.ignoreExprs = self.ignoreExprs[:]
756
- if self.copyDefaultWhiteChars:
757
- cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
758
- return cpy
759
-
760
- def setName( self, name ):
761
- """Define name for this expression, for use in debugging."""
762
- self.name = name
763
- self.errmsg = "Expected " + self.name
764
- if hasattr(self,"exception"):
765
- self.exception.msg = self.errmsg
766
- return self
767
-
768
- def setResultsName( self, name, listAllMatches=False ):
769
- """Define name for referencing matching tokens as a nested attribute
770
- of the returned parse results.
771
- NOTE: this returns a *copy* of the original C{ParserElement} object;
772
- this is so that the client can define a basic element, such as an
773
- integer, and reference it in multiple places with different names.
774
-
775
- You can also set results names using the abbreviated syntax,
776
- C{expr("name")} in place of C{expr.setResultsName("name")} -
777
- see L{I{__call__}<__call__>}.
778
- """
779
- newself = self.copy()
780
- if name.endswith("*"):
781
- name = name[:-1]
782
- listAllMatches=True
783
- newself.resultsName = name
784
- newself.modalResults = not listAllMatches
785
- return newself
786
-
787
- def setBreak(self,breakFlag = True):
788
- """Method to invoke the Python pdb debugger when this element is
789
- about to be parsed. Set C{breakFlag} to True to enable, False to
790
- disable.
791
- """
792
- if breakFlag:
793
- _parseMethod = self._parse
794
- def breaker(instring, loc, doActions=True, callPreParse=True):
795
- import pdb
796
- pdb.set_trace()
797
- return _parseMethod( instring, loc, doActions, callPreParse )
798
- breaker._originalParseMethod = _parseMethod
799
- self._parse = breaker
800
- else:
801
- if hasattr(self._parse,"_originalParseMethod"):
802
- self._parse = self._parse._originalParseMethod
803
- return self
804
-
805
- def setParseAction( self, *fns, **kwargs ):
806
- """Define action to perform when successfully matching parse element definition.
807
- Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
808
- C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
809
- - s = the original string being parsed (see note below)
810
- - loc = the location of the matching substring
811
- - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
812
- If the functions in fns modify the tokens, they can return them as the return
813
- value from fn, and the modified list of tokens will replace the original.
814
- Otherwise, fn does not need to return any value.
815
-
816
- Note: the default parsing behavior is to expand tabs in the input string
817
- before starting the parsing process. See L{I{parseString}<parseString>} for more information
818
- on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
819
- consistent view of the parsed string, the parse location, and line and column
820
- positions within the parsed string.
821
- """
822
- self.parseAction = list(map(_trim_arity, list(fns)))
823
- self.callDuringTry = ("callDuringTry" in kwargs and kwargs["callDuringTry"])
824
- return self
825
-
826
- def addParseAction( self, *fns, **kwargs ):
827
- """Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}."""
828
- self.parseAction += list(map(_trim_arity, list(fns)))
829
- self.callDuringTry = self.callDuringTry or ("callDuringTry" in kwargs and kwargs["callDuringTry"])
830
- return self
831
-
832
- def setFailAction( self, fn ):
833
- """Define action to perform if parsing fails at this expression.
834
- Fail acton fn is a callable function that takes the arguments
835
- C{fn(s,loc,expr,err)} where:
836
- - s = string being parsed
837
- - loc = location where expression match was attempted and failed
838
- - expr = the parse expression that failed
839
- - err = the exception thrown
840
- The function returns no value. It may throw C{L{ParseFatalException}}
841
- if it is desired to stop parsing immediately."""
842
- self.failAction = fn
843
- return self
844
-
845
- def _skipIgnorables( self, instring, loc ):
846
- exprsFound = True
847
- while exprsFound:
848
- exprsFound = False
849
- for e in self.ignoreExprs:
850
- try:
851
- while 1:
852
- loc,dummy = e._parse( instring, loc )
853
- exprsFound = True
854
- except ParseException:
855
- pass
856
- return loc
857
-
858
- def preParse( self, instring, loc ):
859
- if self.ignoreExprs:
860
- loc = self._skipIgnorables( instring, loc )
861
-
862
- if self.skipWhitespace:
863
- wt = self.whiteChars
864
- instrlen = len(instring)
865
- while loc < instrlen and instring[loc] in wt:
866
- loc += 1
867
-
868
- return loc
869
-
870
- def parseImpl( self, instring, loc, doActions=True ):
871
- return loc, []
872
-
873
- def postParse( self, instring, loc, tokenlist ):
874
- return tokenlist
875
-
876
- #~ @profile
877
- def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
878
- debugging = ( self.debug ) #and doActions )
879
-
880
- if debugging or self.failAction:
881
- #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
882
- if (self.debugActions[0] ):
883
- self.debugActions[0]( instring, loc, self )
884
- if callPreParse and self.callPreparse:
885
- preloc = self.preParse( instring, loc )
886
- else:
887
- preloc = loc
888
- tokensStart = preloc
889
- try:
890
- try:
891
- loc,tokens = self.parseImpl( instring, preloc, doActions )
892
- except IndexError:
893
- raise ParseException( instring, len(instring), self.errmsg, self )
894
- except ParseBaseException as err:
895
- #~ print ("Exception raised:", err)
896
- if self.debugActions[2]:
897
- self.debugActions[2]( instring, tokensStart, self, err )
898
- if self.failAction:
899
- self.failAction( instring, tokensStart, self, err )
900
- raise
901
- else:
902
- if callPreParse and self.callPreparse:
903
- preloc = self.preParse( instring, loc )
904
- else:
905
- preloc = loc
906
- tokensStart = preloc
907
- if self.mayIndexError or loc >= len(instring):
908
- try:
909
- loc,tokens = self.parseImpl( instring, preloc, doActions )
910
- except IndexError:
911
- raise ParseException( instring, len(instring), self.errmsg, self )
912
- else:
913
- loc,tokens = self.parseImpl( instring, preloc, doActions )
914
-
915
- tokens = self.postParse( instring, loc, tokens )
916
-
917
- retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
918
- if self.parseAction and (doActions or self.callDuringTry):
919
- if debugging:
920
- try:
921
- for fn in self.parseAction:
922
- tokens = fn( instring, tokensStart, retTokens )
923
- if tokens is not None:
924
- retTokens = ParseResults( tokens,
925
- self.resultsName,
926
- asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
927
- modal=self.modalResults )
928
- except ParseBaseException as err:
929
- #~ print "Exception raised in user parse action:", err
930
- if (self.debugActions[2] ):
931
- self.debugActions[2]( instring, tokensStart, self, err )
932
- raise
933
- else:
934
- for fn in self.parseAction:
935
- tokens = fn( instring, tokensStart, retTokens )
936
- if tokens is not None:
937
- retTokens = ParseResults( tokens,
938
- self.resultsName,
939
- asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
940
- modal=self.modalResults )
941
-
942
- if debugging:
943
- #~ print ("Matched",self,"->",retTokens.asList())
944
- if (self.debugActions[1] ):
945
- self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
946
-
947
- return loc, retTokens
948
-
949
- def tryParse( self, instring, loc ):
950
- try:
951
- return self._parse( instring, loc, doActions=False )[0]
952
- except ParseFatalException:
953
- raise ParseException( instring, loc, self.errmsg, self)
954
-
955
- # this method gets repeatedly called during backtracking with the same arguments -
956
- # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
957
- def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
958
- lookup = (self,instring,loc,callPreParse,doActions)
959
- if lookup in ParserElement._exprArgCache:
960
- value = ParserElement._exprArgCache[ lookup ]
961
- if isinstance(value, Exception):
962
- raise value
963
- return (value[0],value[1].copy())
964
- else:
965
- try:
966
- value = self._parseNoCache( instring, loc, doActions, callPreParse )
967
- ParserElement._exprArgCache[ lookup ] = (value[0],value[1].copy())
968
- return value
969
- except ParseBaseException as pe:
970
- pe.__traceback__ = None
971
- ParserElement._exprArgCache[ lookup ] = pe
972
- raise
973
-
974
- _parse = _parseNoCache
975
-
976
- # argument cache for optimizing repeated calls when backtracking through recursive expressions
977
- _exprArgCache = {}
978
- def resetCache():
979
- ParserElement._exprArgCache.clear()
980
- resetCache = staticmethod(resetCache)
981
-
982
- _packratEnabled = False
983
- def enablePackrat():
984
- """Enables "packrat" parsing, which adds memoizing to the parsing logic.
985
- Repeated parse attempts at the same string location (which happens
986
- often in many complex grammars) can immediately return a cached value,
987
- instead of re-executing parsing/validating code. Memoizing is done of
988
- both valid results and parsing exceptions.
989
-
990
- This speedup may break existing programs that use parse actions that
991
- have side-effects. For this reason, packrat parsing is disabled when
992
- you first import pyparsing. To activate the packrat feature, your
993
- program must call the class method C{ParserElement.enablePackrat()}. If
994
- your program uses C{psyco} to "compile as you go", you must call
995
- C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
996
- Python will crash. For best results, call C{enablePackrat()} immediately
997
- after importing pyparsing.
998
- """
999
- if not ParserElement._packratEnabled:
1000
- ParserElement._packratEnabled = True
1001
- ParserElement._parse = ParserElement._parseCache
1002
- enablePackrat = staticmethod(enablePackrat)
1003
-
1004
- def parseString( self, instring, parseAll=False ):
1005
- """Execute the parse expression with the given string.
1006
- This is the main interface to the client code, once the complete
1007
- expression has been built.
1008
-
1009
- If you want the grammar to require that the entire input string be
1010
- successfully parsed, then set C{parseAll} to True (equivalent to ending
1011
- the grammar with C{L{StringEnd()}}).
1012
-
1013
- Note: C{parseString} implicitly calls C{expandtabs()} on the input string,
1014
- in order to report proper column numbers in parse actions.
1015
- If the input string contains tabs and
1016
- the grammar uses parse actions that use the C{loc} argument to index into the
1017
- string being parsed, you can ensure you have a consistent view of the input
1018
- string by:
1019
- - calling C{parseWithTabs} on your grammar before calling C{parseString}
1020
- (see L{I{parseWithTabs}<parseWithTabs>})
1021
- - define your parse action using the full C{(s,loc,toks)} signature, and
1022
- reference the input string using the parse action's C{s} argument
1023
- - explictly expand the tabs in your input string before calling
1024
- C{parseString}
1025
- """
1026
- ParserElement.resetCache()
1027
- if not self.streamlined:
1028
- self.streamline()
1029
- #~ self.saveAsList = True
1030
- for e in self.ignoreExprs:
1031
- e.streamline()
1032
- if not self.keepTabs:
1033
- instring = instring.expandtabs()
1034
- try:
1035
- loc, tokens = self._parse( instring, 0 )
1036
- if parseAll:
1037
- loc = self.preParse( instring, loc )
1038
- se = Empty() + StringEnd()
1039
- se._parse( instring, loc )
1040
- except ParseBaseException as exc:
1041
- if ParserElement.verbose_stacktrace:
1042
- raise
1043
- else:
1044
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
1045
- raise exc
1046
- else:
1047
- return tokens
1048
-
1049
- def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ):
1050
- """Scan the input string for expression matches. Each match will return the
1051
- matching tokens, start location, and end location. May be called with optional
1052
- C{maxMatches} argument, to clip scanning after 'n' matches are found. If
1053
- C{overlap} is specified, then overlapping matches will be reported.
1054
-
1055
- Note that the start and end locations are reported relative to the string
1056
- being parsed. See L{I{parseString}<parseString>} for more information on parsing
1057
- strings with embedded tabs."""
1058
- if not self.streamlined:
1059
- self.streamline()
1060
- for e in self.ignoreExprs:
1061
- e.streamline()
1062
-
1063
- if not self.keepTabs:
1064
- instring = _ustr(instring).expandtabs()
1065
- instrlen = len(instring)
1066
- loc = 0
1067
- preparseFn = self.preParse
1068
- parseFn = self._parse
1069
- ParserElement.resetCache()
1070
- matches = 0
1071
- try:
1072
- while loc <= instrlen and matches < maxMatches:
1073
- try:
1074
- preloc = preparseFn( instring, loc )
1075
- nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
1076
- except ParseException:
1077
- loc = preloc+1
1078
- else:
1079
- if nextLoc > loc:
1080
- matches += 1
1081
- yield tokens, preloc, nextLoc
1082
- if overlap:
1083
- nextloc = preparseFn( instring, loc )
1084
- if nextloc > loc:
1085
- loc = nextLoc
1086
- else:
1087
- loc += 1
1088
- else:
1089
- loc = nextLoc
1090
- else:
1091
- loc = preloc+1
1092
- except ParseBaseException as exc:
1093
- if ParserElement.verbose_stacktrace:
1094
- raise
1095
- else:
1096
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
1097
- raise exc
1098
-
1099
- def transformString( self, instring ):
1100
- """Extension to C{L{scanString}}, to modify matching text with modified tokens that may
1101
- be returned from a parse action. To use C{transformString}, define a grammar and
1102
- attach a parse action to it that modifies the returned token list.
1103
- Invoking C{transformString()} on a target string will then scan for matches,
1104
- and replace the matched text patterns according to the logic in the parse
1105
- action. C{transformString()} returns the resulting transformed string."""
1106
- out = []
1107
- lastE = 0
1108
- # force preservation of <TAB>s, to minimize unwanted transformation of string, and to
1109
- # keep string locs straight between transformString and scanString
1110
- self.keepTabs = True
1111
- try:
1112
- for t,s,e in self.scanString( instring ):
1113
- out.append( instring[lastE:s] )
1114
- if t:
1115
- if isinstance(t,ParseResults):
1116
- out += t.asList()
1117
- elif isinstance(t,list):
1118
- out += t
1119
- else:
1120
- out.append(t)
1121
- lastE = e
1122
- out.append(instring[lastE:])
1123
- out = [o for o in out if o]
1124
- return "".join(map(_ustr,_flatten(out)))
1125
- except ParseBaseException as exc:
1126
- if ParserElement.verbose_stacktrace:
1127
- raise
1128
- else:
1129
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
1130
- raise exc
1131
-
1132
- def searchString( self, instring, maxMatches=_MAX_INT ):
1133
- """Another extension to C{L{scanString}}, simplifying the access to the tokens found
1134
- to match the given parse expression. May be called with optional
1135
- C{maxMatches} argument, to clip searching after 'n' matches are found.
1136
- """
1137
- try:
1138
- return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
1139
- except ParseBaseException as exc:
1140
- if ParserElement.verbose_stacktrace:
1141
- raise
1142
- else:
1143
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
1144
- raise exc
1145
-
1146
- def __add__(self, other ):
1147
- """Implementation of + operator - returns C{L{And}}"""
1148
- if isinstance( other, basestring ):
1149
- other = ParserElement.literalStringClass( other )
1150
- if not isinstance( other, ParserElement ):
1151
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1152
- SyntaxWarning, stacklevel=2)
1153
- return None
1154
- return And( [ self, other ] )
1155
-
1156
- def __radd__(self, other ):
1157
- """Implementation of + operator when left operand is not a C{L{ParserElement}}"""
1158
- if isinstance( other, basestring ):
1159
- other = ParserElement.literalStringClass( other )
1160
- if not isinstance( other, ParserElement ):
1161
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1162
- SyntaxWarning, stacklevel=2)
1163
- return None
1164
- return other + self
1165
-
1166
- def __sub__(self, other):
1167
- """Implementation of - operator, returns C{L{And}} with error stop"""
1168
- if isinstance( other, basestring ):
1169
- other = ParserElement.literalStringClass( other )
1170
- if not isinstance( other, ParserElement ):
1171
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1172
- SyntaxWarning, stacklevel=2)
1173
- return None
1174
- return And( [ self, And._ErrorStop(), other ] )
1175
-
1176
- def __rsub__(self, other ):
1177
- """Implementation of - operator when left operand is not a C{L{ParserElement}}"""
1178
- if isinstance( other, basestring ):
1179
- other = ParserElement.literalStringClass( other )
1180
- if not isinstance( other, ParserElement ):
1181
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1182
- SyntaxWarning, stacklevel=2)
1183
- return None
1184
- return other - self
1185
-
1186
- def __mul__(self,other):
1187
- """Implementation of * operator, allows use of C{expr * 3} in place of
1188
- C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
1189
- tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
1190
- may also include C{None} as in:
1191
- - C{expr*(n,None)} or C{expr*(n,)} is equivalent
1192
- to C{expr*n + L{ZeroOrMore}(expr)}
1193
- (read as "at least n instances of C{expr}")
1194
- - C{expr*(None,n)} is equivalent to C{expr*(0,n)}
1195
- (read as "0 to n instances of C{expr}")
1196
- - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
1197
- - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
1198
-
1199
- Note that C{expr*(None,n)} does not raise an exception if
1200
- more than n exprs exist in the input stream; that is,
1201
- C{expr*(None,n)} does not enforce a maximum number of expr
1202
- occurrences. If this behavior is desired, then write
1203
- C{expr*(None,n) + ~expr}
1204
-
1205
- """
1206
- if isinstance(other,int):
1207
- minElements, optElements = other,0
1208
- elif isinstance(other,tuple):
1209
- other = (other + (None, None))[:2]
1210
- if other[0] is None:
1211
- other = (0, other[1])
1212
- if isinstance(other[0],int) and other[1] is None:
1213
- if other[0] == 0:
1214
- return ZeroOrMore(self)
1215
- if other[0] == 1:
1216
- return OneOrMore(self)
1217
- else:
1218
- return self*other[0] + ZeroOrMore(self)
1219
- elif isinstance(other[0],int) and isinstance(other[1],int):
1220
- minElements, optElements = other
1221
- optElements -= minElements
1222
- else:
1223
- raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
1224
- else:
1225
- raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
1226
-
1227
- if minElements < 0:
1228
- raise ValueError("cannot multiply ParserElement by negative value")
1229
- if optElements < 0:
1230
- raise ValueError("second tuple value must be greater or equal to first tuple value")
1231
- if minElements == optElements == 0:
1232
- raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
1233
-
1234
- if (optElements):
1235
- def makeOptionalList(n):
1236
- if n>1:
1237
- return Optional(self + makeOptionalList(n-1))
1238
- else:
1239
- return Optional(self)
1240
- if minElements:
1241
- if minElements == 1:
1242
- ret = self + makeOptionalList(optElements)
1243
- else:
1244
- ret = And([self]*minElements) + makeOptionalList(optElements)
1245
- else:
1246
- ret = makeOptionalList(optElements)
1247
- else:
1248
- if minElements == 1:
1249
- ret = self
1250
- else:
1251
- ret = And([self]*minElements)
1252
- return ret
1253
-
1254
- def __rmul__(self, other):
1255
- return self.__mul__(other)
1256
-
1257
- def __or__(self, other ):
1258
- """Implementation of | operator - returns C{L{MatchFirst}}"""
1259
- if isinstance( other, basestring ):
1260
- other = ParserElement.literalStringClass( other )
1261
- if not isinstance( other, ParserElement ):
1262
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1263
- SyntaxWarning, stacklevel=2)
1264
- return None
1265
- return MatchFirst( [ self, other ] )
1266
-
1267
- def __ror__(self, other ):
1268
- """Implementation of | operator when left operand is not a C{L{ParserElement}}"""
1269
- if isinstance( other, basestring ):
1270
- other = ParserElement.literalStringClass( other )
1271
- if not isinstance( other, ParserElement ):
1272
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1273
- SyntaxWarning, stacklevel=2)
1274
- return None
1275
- return other | self
1276
-
1277
- def __xor__(self, other ):
1278
- """Implementation of ^ operator - returns C{L{Or}}"""
1279
- if isinstance( other, basestring ):
1280
- other = ParserElement.literalStringClass( other )
1281
- if not isinstance( other, ParserElement ):
1282
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1283
- SyntaxWarning, stacklevel=2)
1284
- return None
1285
- return Or( [ self, other ] )
1286
-
1287
- def __rxor__(self, other ):
1288
- """Implementation of ^ operator when left operand is not a C{L{ParserElement}}"""
1289
- if isinstance( other, basestring ):
1290
- other = ParserElement.literalStringClass( other )
1291
- if not isinstance( other, ParserElement ):
1292
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1293
- SyntaxWarning, stacklevel=2)
1294
- return None
1295
- return other ^ self
1296
-
1297
- def __and__(self, other ):
1298
- """Implementation of & operator - returns C{L{Each}}"""
1299
- if isinstance( other, basestring ):
1300
- other = ParserElement.literalStringClass( other )
1301
- if not isinstance( other, ParserElement ):
1302
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1303
- SyntaxWarning, stacklevel=2)
1304
- return None
1305
- return Each( [ self, other ] )
1306
-
1307
- def __rand__(self, other ):
1308
- """Implementation of & operator when left operand is not a C{L{ParserElement}}"""
1309
- if isinstance( other, basestring ):
1310
- other = ParserElement.literalStringClass( other )
1311
- if not isinstance( other, ParserElement ):
1312
- warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
1313
- SyntaxWarning, stacklevel=2)
1314
- return None
1315
- return other & self
1316
-
1317
- def __invert__( self ):
1318
- """Implementation of ~ operator - returns C{L{NotAny}}"""
1319
- return NotAny( self )
1320
-
1321
- def __call__(self, name):
1322
- """Shortcut for C{L{setResultsName}}, with C{listAllMatches=default}::
1323
- userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
1324
- could be written as::
1325
- userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
1326
-
1327
- If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
1328
- passed as C{True}.
1329
- """
1330
- return self.setResultsName(name)
1331
-
1332
- def suppress( self ):
1333
- """Suppresses the output of this C{ParserElement}; useful to keep punctuation from
1334
- cluttering up returned output.
1335
- """
1336
- return Suppress( self )
1337
-
1338
- def leaveWhitespace( self ):
1339
- """Disables the skipping of whitespace before matching the characters in the
1340
- C{ParserElement}'s defined pattern. This is normally only used internally by
1341
- the pyparsing module, but may be needed in some whitespace-sensitive grammars.
1342
- """
1343
- self.skipWhitespace = False
1344
- return self
1345
-
1346
- def setWhitespaceChars( self, chars ):
1347
- """Overrides the default whitespace chars
1348
- """
1349
- self.skipWhitespace = True
1350
- self.whiteChars = chars
1351
- self.copyDefaultWhiteChars = False
1352
- return self
1353
-
1354
- def parseWithTabs( self ):
1355
- """Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
1356
- Must be called before C{parseString} when the input grammar contains elements that
1357
- match C{<TAB>} characters."""
1358
- self.keepTabs = True
1359
- return self
1360
-
1361
- def ignore( self, other ):
1362
- """Define expression to be ignored (e.g., comments) while doing pattern
1363
- matching; may be called repeatedly, to define multiple comment or other
1364
- ignorable patterns.
1365
- """
1366
- if isinstance( other, Suppress ):
1367
- if other not in self.ignoreExprs:
1368
- self.ignoreExprs.append( other.copy() )
1369
- else:
1370
- self.ignoreExprs.append( Suppress( other.copy() ) )
1371
- return self
1372
-
1373
- def setDebugActions( self, startAction, successAction, exceptionAction ):
1374
- """Enable display of debugging messages while doing pattern matching."""
1375
- self.debugActions = (startAction or _defaultStartDebugAction,
1376
- successAction or _defaultSuccessDebugAction,
1377
- exceptionAction or _defaultExceptionDebugAction)
1378
- self.debug = True
1379
- return self
1380
-
1381
- def setDebug( self, flag=True ):
1382
- """Enable display of debugging messages while doing pattern matching.
1383
- Set C{flag} to True to enable, False to disable."""
1384
- if flag:
1385
- self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
1386
- else:
1387
- self.debug = False
1388
- return self
1389
-
1390
- def __str__( self ):
1391
- return self.name
1392
-
1393
- def __repr__( self ):
1394
- return _ustr(self)
1395
-
1396
- def streamline( self ):
1397
- self.streamlined = True
1398
- self.strRepr = None
1399
- return self
1400
-
1401
- def checkRecursion( self, parseElementList ):
1402
- pass
1403
-
1404
- def validate( self, validateTrace=[] ):
1405
- """Check defined expressions for valid structure, check for infinite recursive definitions."""
1406
- self.checkRecursion( [] )
1407
-
1408
- def parseFile( self, file_or_filename, parseAll=False ):
1409
- """Execute the parse expression on the given file or filename.
1410
- If a filename is specified (instead of a file object),
1411
- the entire file is opened, read, and closed before parsing.
1412
- """
1413
- try:
1414
- file_contents = file_or_filename.read()
1415
- except AttributeError:
1416
- f = open(file_or_filename, "r")
1417
- file_contents = f.read()
1418
- f.close()
1419
- try:
1420
- return self.parseString(file_contents, parseAll)
1421
- except ParseBaseException as exc:
1422
- if ParserElement.verbose_stacktrace:
1423
- raise
1424
- else:
1425
- # catch and re-raise exception from here, clears out pyparsing internal stack trace
1426
- raise exc
1427
-
1428
- def __eq__(self,other):
1429
- if isinstance(other, ParserElement):
1430
- return self is other or self.__dict__ == other.__dict__
1431
- elif isinstance(other, basestring):
1432
- try:
1433
- self.parseString(_ustr(other), parseAll=True)
1434
- return True
1435
- except ParseBaseException:
1436
- return False
1437
- else:
1438
- return super(ParserElement,self)==other
1439
-
1440
- def __ne__(self,other):
1441
- return not (self == other)
1442
-
1443
- def __hash__(self):
1444
- return hash(id(self))
1445
-
1446
- def __req__(self,other):
1447
- return self == other
1448
-
1449
- def __rne__(self,other):
1450
- return not (self == other)
1451
-
1452
-
1453
- class Token(ParserElement):
1454
- """Abstract C{ParserElement} subclass, for defining atomic matching patterns."""
1455
- def __init__( self ):
1456
- super(Token,self).__init__( savelist=False )
1457
-
1458
- def setName(self, name):
1459
- s = super(Token,self).setName(name)
1460
- self.errmsg = "Expected " + self.name
1461
- return s
1462
-
1463
-
1464
- class Empty(Token):
1465
- """An empty token, will always match."""
1466
- def __init__( self ):
1467
- super(Empty,self).__init__()
1468
- self.name = "Empty"
1469
- self.mayReturnEmpty = True
1470
- self.mayIndexError = False
1471
-
1472
-
1473
- class NoMatch(Token):
1474
- """A token that will never match."""
1475
- def __init__( self ):
1476
- super(NoMatch,self).__init__()
1477
- self.name = "NoMatch"
1478
- self.mayReturnEmpty = True
1479
- self.mayIndexError = False
1480
- self.errmsg = "Unmatchable token"
1481
-
1482
- def parseImpl( self, instring, loc, doActions=True ):
1483
- raise ParseException(instring, loc, self.errmsg, self)
1484
-
1485
-
1486
- class Literal(Token):
1487
- """Token to exactly match a specified string."""
1488
- def __init__( self, matchString ):
1489
- super(Literal,self).__init__()
1490
- self.match = matchString
1491
- self.matchLen = len(matchString)
1492
- try:
1493
- self.firstMatchChar = matchString[0]
1494
- except IndexError:
1495
- warnings.warn("null string passed to Literal; use Empty() instead",
1496
- SyntaxWarning, stacklevel=2)
1497
- self.__class__ = Empty
1498
- self.name = '"%s"' % _ustr(self.match)
1499
- self.errmsg = "Expected " + self.name
1500
- self.mayReturnEmpty = False
1501
- self.mayIndexError = False
1502
-
1503
- # Performance tuning: this routine gets called a *lot*
1504
- # if this is a single character match string and the first character matches,
1505
- # short-circuit as quickly as possible, and avoid calling startswith
1506
- #~ @profile
1507
- def parseImpl( self, instring, loc, doActions=True ):
1508
- if (instring[loc] == self.firstMatchChar and
1509
- (self.matchLen==1 or instring.startswith(self.match,loc)) ):
1510
- return loc+self.matchLen, self.match
1511
- raise ParseException(instring, loc, self.errmsg, self)
1512
- _L = Literal
1513
- ParserElement.literalStringClass = Literal
1514
-
1515
- class Keyword(Token):
1516
- """Token to exactly match a specified string as a keyword, that is, it must be
1517
- immediately followed by a non-keyword character. Compare with C{L{Literal}}::
1518
- Literal("if") will match the leading C{'if'} in C{'ifAndOnlyIf'}.
1519
- Keyword("if") will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'}
1520
- Accepts two optional constructor arguments in addition to the keyword string:
1521
- C{identChars} is a string of characters that would be valid identifier characters,
1522
- defaulting to all alphanumerics + "_" and "$"; C{caseless} allows case-insensitive
1523
- matching, default is C{False}.
1524
- """
1525
- DEFAULT_KEYWORD_CHARS = alphanums+"_$"
1526
-
1527
- def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ):
1528
- super(Keyword,self).__init__()
1529
- self.match = matchString
1530
- self.matchLen = len(matchString)
1531
- try:
1532
- self.firstMatchChar = matchString[0]
1533
- except IndexError:
1534
- warnings.warn("null string passed to Keyword; use Empty() instead",
1535
- SyntaxWarning, stacklevel=2)
1536
- self.name = '"%s"' % self.match
1537
- self.errmsg = "Expected " + self.name
1538
- self.mayReturnEmpty = False
1539
- self.mayIndexError = False
1540
- self.caseless = caseless
1541
- if caseless:
1542
- self.caselessmatch = matchString.upper()
1543
- identChars = identChars.upper()
1544
- self.identChars = set(identChars)
1545
-
1546
- def parseImpl( self, instring, loc, doActions=True ):
1547
- if self.caseless:
1548
- if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
1549
- (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
1550
- (loc == 0 or instring[loc-1].upper() not in self.identChars) ):
1551
- return loc+self.matchLen, self.match
1552
- else:
1553
- if (instring[loc] == self.firstMatchChar and
1554
- (self.matchLen==1 or instring.startswith(self.match,loc)) and
1555
- (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
1556
- (loc == 0 or instring[loc-1] not in self.identChars) ):
1557
- return loc+self.matchLen, self.match
1558
- raise ParseException(instring, loc, self.errmsg, self)
1559
-
1560
- def copy(self):
1561
- c = super(Keyword,self).copy()
1562
- c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
1563
- return c
1564
-
1565
- def setDefaultKeywordChars( chars ):
1566
- """Overrides the default Keyword chars
1567
- """
1568
- Keyword.DEFAULT_KEYWORD_CHARS = chars
1569
- setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)
1570
-
1571
- class CaselessLiteral(Literal):
1572
- """Token to match a specified string, ignoring case of letters.
1573
- Note: the matched results will always be in the case of the given
1574
- match string, NOT the case of the input text.
1575
- """
1576
- def __init__( self, matchString ):
1577
- super(CaselessLiteral,self).__init__( matchString.upper() )
1578
- # Preserve the defining literal.
1579
- self.returnString = matchString
1580
- self.name = "'%s'" % self.returnString
1581
- self.errmsg = "Expected " + self.name
1582
-
1583
- def parseImpl( self, instring, loc, doActions=True ):
1584
- if instring[ loc:loc+self.matchLen ].upper() == self.match:
1585
- return loc+self.matchLen, self.returnString
1586
- raise ParseException(instring, loc, self.errmsg, self)
1587
-
1588
- class CaselessKeyword(Keyword):
1589
- def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ):
1590
- super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
1591
-
1592
- def parseImpl( self, instring, loc, doActions=True ):
1593
- if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
1594
- (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
1595
- return loc+self.matchLen, self.match
1596
- raise ParseException(instring, loc, self.errmsg, self)
1597
-
1598
- class Word(Token):
1599
- """Token for matching words composed of allowed character sets.
1600
- Defined with string containing all allowed initial characters,
1601
- an optional string containing allowed body characters (if omitted,
1602
- defaults to the initial character set), and an optional minimum,
1603
- maximum, and/or exact length. The default value for C{min} is 1 (a
1604
- minimum value < 1 is not valid); the default values for C{max} and C{exact}
1605
- are 0, meaning no maximum or exact length restriction. An optional
1606
- C{exclude} parameter can list characters that might be found in
1607
- the input C{bodyChars} string; useful to define a word of all printables
1608
- except for one or two characters, for instance.
1609
- """
1610
- def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None ):
1611
- super(Word,self).__init__()
1612
- if excludeChars:
1613
- initChars = ''.join(c for c in initChars if c not in excludeChars)
1614
- if bodyChars:
1615
- bodyChars = ''.join(c for c in bodyChars if c not in excludeChars)
1616
- self.initCharsOrig = initChars
1617
- self.initChars = set(initChars)
1618
- if bodyChars :
1619
- self.bodyCharsOrig = bodyChars
1620
- self.bodyChars = set(bodyChars)
1621
- else:
1622
- self.bodyCharsOrig = initChars
1623
- self.bodyChars = set(initChars)
1624
-
1625
- self.maxSpecified = max > 0
1626
-
1627
- if min < 1:
1628
- raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted")
1629
-
1630
- self.minLen = min
1631
-
1632
- if max > 0:
1633
- self.maxLen = max
1634
- else:
1635
- self.maxLen = _MAX_INT
1636
-
1637
- if exact > 0:
1638
- self.maxLen = exact
1639
- self.minLen = exact
1640
-
1641
- self.name = _ustr(self)
1642
- self.errmsg = "Expected " + self.name
1643
- self.mayIndexError = False
1644
- self.asKeyword = asKeyword
1645
-
1646
- if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
1647
- if self.bodyCharsOrig == self.initCharsOrig:
1648
- self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
1649
- elif len(self.bodyCharsOrig) == 1:
1650
- self.reString = "%s[%s]*" % \
1651
- (re.escape(self.initCharsOrig),
1652
- _escapeRegexRangeChars(self.bodyCharsOrig),)
1653
- else:
1654
- self.reString = "[%s][%s]*" % \
1655
- (_escapeRegexRangeChars(self.initCharsOrig),
1656
- _escapeRegexRangeChars(self.bodyCharsOrig),)
1657
- if self.asKeyword:
1658
- self.reString = r"\b"+self.reString+r"\b"
1659
- try:
1660
- self.re = re.compile( self.reString )
1661
- except:
1662
- self.re = None
1663
-
1664
- def parseImpl( self, instring, loc, doActions=True ):
1665
- if self.re:
1666
- result = self.re.match(instring,loc)
1667
- if not result:
1668
- raise ParseException(instring, loc, self.errmsg, self)
1669
-
1670
- loc = result.end()
1671
- return loc, result.group()
1672
-
1673
- if not(instring[ loc ] in self.initChars):
1674
- raise ParseException(instring, loc, self.errmsg, self)
1675
-
1676
- start = loc
1677
- loc += 1
1678
- instrlen = len(instring)
1679
- bodychars = self.bodyChars
1680
- maxloc = start + self.maxLen
1681
- maxloc = min( maxloc, instrlen )
1682
- while loc < maxloc and instring[loc] in bodychars:
1683
- loc += 1
1684
-
1685
- throwException = False
1686
- if loc - start < self.minLen:
1687
- throwException = True
1688
- if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
1689
- throwException = True
1690
- if self.asKeyword:
1691
- if (start>0 and instring[start-1] in bodychars) or (loc<instrlen and instring[loc] in bodychars):
1692
- throwException = True
1693
-
1694
- if throwException:
1695
- raise ParseException(instring, loc, self.errmsg, self)
1696
-
1697
- return loc, instring[start:loc]
1698
-
1699
- def __str__( self ):
1700
- try:
1701
- return super(Word,self).__str__()
1702
- except:
1703
- pass
1704
-
1705
-
1706
- if self.strRepr is None:
1707
-
1708
- def charsAsStr(s):
1709
- if len(s)>4:
1710
- return s[:4]+"..."
1711
- else:
1712
- return s
1713
-
1714
- if ( self.initCharsOrig != self.bodyCharsOrig ):
1715
- self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
1716
- else:
1717
- self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
1718
-
1719
- return self.strRepr
1720
-
1721
-
1722
- class Regex(Token):
1723
- """Token for matching strings that match a given regular expression.
1724
- Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.
1725
- """
1726
- compiledREtype = type(re.compile("[A-Z]"))
1727
- def __init__( self, pattern, flags=0):
1728
- """The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags."""
1729
- super(Regex,self).__init__()
1730
-
1731
- if isinstance(pattern, basestring):
1732
- if len(pattern) == 0:
1733
- warnings.warn("null string passed to Regex; use Empty() instead",
1734
- SyntaxWarning, stacklevel=2)
1735
-
1736
- self.pattern = pattern
1737
- self.flags = flags
1738
-
1739
- try:
1740
- self.re = re.compile(self.pattern, self.flags)
1741
- self.reString = self.pattern
1742
- except sre_constants.error:
1743
- warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
1744
- SyntaxWarning, stacklevel=2)
1745
- raise
1746
-
1747
- elif isinstance(pattern, Regex.compiledREtype):
1748
- self.re = pattern
1749
- self.pattern = \
1750
- self.reString = str(pattern)
1751
- self.flags = flags
1752
-
1753
- else:
1754
- raise ValueError("Regex may only be constructed with a string or a compiled RE object")
1755
-
1756
- self.name = _ustr(self)
1757
- self.errmsg = "Expected " + self.name
1758
- self.mayIndexError = False
1759
- self.mayReturnEmpty = True
1760
-
1761
- def parseImpl( self, instring, loc, doActions=True ):
1762
- result = self.re.match(instring,loc)
1763
- if not result:
1764
- raise ParseException(instring, loc, self.errmsg, self)
1765
-
1766
- loc = result.end()
1767
- d = result.groupdict()
1768
- ret = ParseResults(result.group())
1769
- if d:
1770
- for k in d:
1771
- ret[k] = d[k]
1772
- return loc,ret
1773
-
1774
- def __str__( self ):
1775
- try:
1776
- return super(Regex,self).__str__()
1777
- except:
1778
- pass
1779
-
1780
- if self.strRepr is None:
1781
- self.strRepr = "Re:(%s)" % repr(self.pattern)
1782
-
1783
- return self.strRepr
1784
-
1785
-
1786
- class QuotedString(Token):
1787
- """Token for matching strings that are delimited by quoting characters.
1788
- """
1789
- def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None):
1790
- """
1791
- Defined with the following parameters:
1792
- - quoteChar - string of one or more characters defining the quote delimiting string
1793
- - escChar - character to escape quotes, typically backslash (default=None)
1794
- - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None)
1795
- - multiline - boolean indicating whether quotes can span multiple lines (default=C{False})
1796
- - unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True})
1797
- - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar)
1798
- """
1799
- super(QuotedString,self).__init__()
1800
-
1801
- # remove white space from quote chars - wont work anyway
1802
- quoteChar = quoteChar.strip()
1803
- if len(quoteChar) == 0:
1804
- warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
1805
- raise SyntaxError()
1806
-
1807
- if endQuoteChar is None:
1808
- endQuoteChar = quoteChar
1809
- else:
1810
- endQuoteChar = endQuoteChar.strip()
1811
- if len(endQuoteChar) == 0:
1812
- warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
1813
- raise SyntaxError()
1814
-
1815
- self.quoteChar = quoteChar
1816
- self.quoteCharLen = len(quoteChar)
1817
- self.firstQuoteChar = quoteChar[0]
1818
- self.endQuoteChar = endQuoteChar
1819
- self.endQuoteCharLen = len(endQuoteChar)
1820
- self.escChar = escChar
1821
- self.escQuote = escQuote
1822
- self.unquoteResults = unquoteResults
1823
-
1824
- if multiline:
1825
- self.flags = re.MULTILINE | re.DOTALL
1826
- self.pattern = r'%s(?:[^%s%s]' % \
1827
- ( re.escape(self.quoteChar),
1828
- _escapeRegexRangeChars(self.endQuoteChar[0]),
1829
- (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
1830
- else:
1831
- self.flags = 0
1832
- self.pattern = r'%s(?:[^%s\n\r%s]' % \
1833
- ( re.escape(self.quoteChar),
1834
- _escapeRegexRangeChars(self.endQuoteChar[0]),
1835
- (escChar is not None and _escapeRegexRangeChars(escChar) or '') )
1836
- if len(self.endQuoteChar) > 1:
1837
- self.pattern += (
1838
- '|(?:' + ')|(?:'.join("%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
1839
- _escapeRegexRangeChars(self.endQuoteChar[i]))
1840
- for i in range(len(self.endQuoteChar)-1,0,-1)) + ')'
1841
- )
1842
- if escQuote:
1843
- self.pattern += (r'|(?:%s)' % re.escape(escQuote))
1844
- if escChar:
1845
- self.pattern += (r'|(?:%s.)' % re.escape(escChar))
1846
- charset = ''.join(set(self.quoteChar[0]+self.endQuoteChar[0])).replace('^',r'\^').replace('-',r'\-')
1847
- self.escCharReplacePattern = re.escape(self.escChar)+("([%s])" % charset)
1848
- self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
1849
-
1850
- try:
1851
- self.re = re.compile(self.pattern, self.flags)
1852
- self.reString = self.pattern
1853
- except sre_constants.error:
1854
- warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
1855
- SyntaxWarning, stacklevel=2)
1856
- raise
1857
-
1858
- self.name = _ustr(self)
1859
- self.errmsg = "Expected " + self.name
1860
- self.mayIndexError = False
1861
- self.mayReturnEmpty = True
1862
-
1863
- def parseImpl( self, instring, loc, doActions=True ):
1864
- result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None
1865
- if not result:
1866
- raise ParseException(instring, loc, self.errmsg, self)
1867
-
1868
- loc = result.end()
1869
- ret = result.group()
1870
-
1871
- if self.unquoteResults:
1872
-
1873
- # strip off quotes
1874
- ret = ret[self.quoteCharLen:-self.endQuoteCharLen]
1875
-
1876
- if isinstance(ret,basestring):
1877
- # replace escaped characters
1878
- if self.escChar:
1879
- ret = re.sub(self.escCharReplacePattern,"\g<1>",ret)
1880
-
1881
- # replace escaped quotes
1882
- if self.escQuote:
1883
- ret = ret.replace(self.escQuote, self.endQuoteChar)
1884
-
1885
- return loc, ret
1886
-
1887
- def __str__( self ):
1888
- try:
1889
- return super(QuotedString,self).__str__()
1890
- except:
1891
- pass
1892
-
1893
- if self.strRepr is None:
1894
- self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
1895
-
1896
- return self.strRepr
1897
-
1898
-
1899
- class CharsNotIn(Token):
1900
- """Token for matching words composed of characters *not* in a given set.
1901
- Defined with string containing all disallowed characters, and an optional
1902
- minimum, maximum, and/or exact length. The default value for C{min} is 1 (a
1903
- minimum value < 1 is not valid); the default values for C{max} and C{exact}
1904
- are 0, meaning no maximum or exact length restriction.
1905
- """
1906
- def __init__( self, notChars, min=1, max=0, exact=0 ):
1907
- super(CharsNotIn,self).__init__()
1908
- self.skipWhitespace = False
1909
- self.notChars = notChars
1910
-
1911
- if min < 1:
1912
- raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted")
1913
-
1914
- self.minLen = min
1915
-
1916
- if max > 0:
1917
- self.maxLen = max
1918
- else:
1919
- self.maxLen = _MAX_INT
1920
-
1921
- if exact > 0:
1922
- self.maxLen = exact
1923
- self.minLen = exact
1924
-
1925
- self.name = _ustr(self)
1926
- self.errmsg = "Expected " + self.name
1927
- self.mayReturnEmpty = ( self.minLen == 0 )
1928
- self.mayIndexError = False
1929
-
1930
- def parseImpl( self, instring, loc, doActions=True ):
1931
- if instring[loc] in self.notChars:
1932
- raise ParseException(instring, loc, self.errmsg, self)
1933
-
1934
- start = loc
1935
- loc += 1
1936
- notchars = self.notChars
1937
- maxlen = min( start+self.maxLen, len(instring) )
1938
- while loc < maxlen and \
1939
- (instring[loc] not in notchars):
1940
- loc += 1
1941
-
1942
- if loc - start < self.minLen:
1943
- raise ParseException(instring, loc, self.errmsg, self)
1944
-
1945
- return loc, instring[start:loc]
1946
-
1947
- def __str__( self ):
1948
- try:
1949
- return super(CharsNotIn, self).__str__()
1950
- except:
1951
- pass
1952
-
1953
- if self.strRepr is None:
1954
- if len(self.notChars) > 4:
1955
- self.strRepr = "!W:(%s...)" % self.notChars[:4]
1956
- else:
1957
- self.strRepr = "!W:(%s)" % self.notChars
1958
-
1959
- return self.strRepr
1960
-
1961
- class White(Token):
1962
- """Special matching class for matching whitespace. Normally, whitespace is ignored
1963
- by pyparsing grammars. This class is included when some whitespace structures
1964
- are significant. Define with a string containing the whitespace characters to be
1965
- matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments,
1966
- as defined for the C{L{Word}} class."""
1967
- whiteStrs = {
1968
- " " : "<SPC>",
1969
- "\t": "<TAB>",
1970
- "\n": "<LF>",
1971
- "\r": "<CR>",
1972
- "\f": "<FF>",
1973
- }
1974
- def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0):
1975
- super(White,self).__init__()
1976
- self.matchWhite = ws
1977
- self.setWhitespaceChars( "".join(c for c in self.whiteChars if c not in self.matchWhite) )
1978
- #~ self.leaveWhitespace()
1979
- self.name = ("".join(White.whiteStrs[c] for c in self.matchWhite))
1980
- self.mayReturnEmpty = True
1981
- self.errmsg = "Expected " + self.name
1982
-
1983
- self.minLen = min
1984
-
1985
- if max > 0:
1986
- self.maxLen = max
1987
- else:
1988
- self.maxLen = _MAX_INT
1989
-
1990
- if exact > 0:
1991
- self.maxLen = exact
1992
- self.minLen = exact
1993
-
1994
- def parseImpl( self, instring, loc, doActions=True ):
1995
- if not(instring[ loc ] in self.matchWhite):
1996
- raise ParseException(instring, loc, self.errmsg, self)
1997
- start = loc
1998
- loc += 1
1999
- maxloc = start + self.maxLen
2000
- maxloc = min( maxloc, len(instring) )
2001
- while loc < maxloc and instring[loc] in self.matchWhite:
2002
- loc += 1
2003
-
2004
- if loc - start < self.minLen:
2005
- raise ParseException(instring, loc, self.errmsg, self)
2006
-
2007
- return loc, instring[start:loc]
2008
-
2009
-
2010
- class _PositionToken(Token):
2011
- def __init__( self ):
2012
- super(_PositionToken,self).__init__()
2013
- self.name=self.__class__.__name__
2014
- self.mayReturnEmpty = True
2015
- self.mayIndexError = False
2016
-
2017
- class GoToColumn(_PositionToken):
2018
- """Token to advance to a specific column of input text; useful for tabular report scraping."""
2019
- def __init__( self, colno ):
2020
- super(GoToColumn,self).__init__()
2021
- self.col = colno
2022
-
2023
- def preParse( self, instring, loc ):
2024
- if col(loc,instring) != self.col:
2025
- instrlen = len(instring)
2026
- if self.ignoreExprs:
2027
- loc = self._skipIgnorables( instring, loc )
2028
- while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col :
2029
- loc += 1
2030
- return loc
2031
-
2032
- def parseImpl( self, instring, loc, doActions=True ):
2033
- thiscol = col( loc, instring )
2034
- if thiscol > self.col:
2035
- raise ParseException( instring, loc, "Text not in expected column", self )
2036
- newloc = loc + self.col - thiscol
2037
- ret = instring[ loc: newloc ]
2038
- return newloc, ret
2039
-
2040
- class LineStart(_PositionToken):
2041
- """Matches if current position is at the beginning of a line within the parse string"""
2042
- def __init__( self ):
2043
- super(LineStart,self).__init__()
2044
- self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") )
2045
- self.errmsg = "Expected start of line"
2046
-
2047
- def preParse( self, instring, loc ):
2048
- preloc = super(LineStart,self).preParse(instring,loc)
2049
- if instring[preloc] == "\n":
2050
- loc += 1
2051
- return loc
2052
-
2053
- def parseImpl( self, instring, loc, doActions=True ):
2054
- if not( loc==0 or
2055
- (loc == self.preParse( instring, 0 )) or
2056
- (instring[loc-1] == "\n") ): #col(loc, instring) != 1:
2057
- raise ParseException(instring, loc, self.errmsg, self)
2058
- return loc, []
2059
-
2060
- class LineEnd(_PositionToken):
2061
- """Matches if current position is at the end of a line within the parse string"""
2062
- def __init__( self ):
2063
- super(LineEnd,self).__init__()
2064
- self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") )
2065
- self.errmsg = "Expected end of line"
2066
-
2067
- def parseImpl( self, instring, loc, doActions=True ):
2068
- if loc<len(instring):
2069
- if instring[loc] == "\n":
2070
- return loc+1, "\n"
2071
- else:
2072
- raise ParseException(instring, loc, self.errmsg, self)
2073
- elif loc == len(instring):
2074
- return loc+1, []
2075
- else:
2076
- raise ParseException(instring, loc, self.errmsg, self)
2077
-
2078
- class StringStart(_PositionToken):
2079
- """Matches if current position is at the beginning of the parse string"""
2080
- def __init__( self ):
2081
- super(StringStart,self).__init__()
2082
- self.errmsg = "Expected start of text"
2083
-
2084
- def parseImpl( self, instring, loc, doActions=True ):
2085
- if loc != 0:
2086
- # see if entire string up to here is just whitespace and ignoreables
2087
- if loc != self.preParse( instring, 0 ):
2088
- raise ParseException(instring, loc, self.errmsg, self)
2089
- return loc, []
2090
-
2091
- class StringEnd(_PositionToken):
2092
- """Matches if current position is at the end of the parse string"""
2093
- def __init__( self ):
2094
- super(StringEnd,self).__init__()
2095
- self.errmsg = "Expected end of text"
2096
-
2097
- def parseImpl( self, instring, loc, doActions=True ):
2098
- if loc < len(instring):
2099
- raise ParseException(instring, loc, self.errmsg, self)
2100
- elif loc == len(instring):
2101
- return loc+1, []
2102
- elif loc > len(instring):
2103
- return loc, []
2104
- else:
2105
- raise ParseException(instring, loc, self.errmsg, self)
2106
-
2107
- class WordStart(_PositionToken):
2108
- """Matches if the current position is at the beginning of a Word, and
2109
- is not preceded by any character in a given set of C{wordChars}
2110
- (default=C{printables}). To emulate the C{\b} behavior of regular expressions,
2111
- use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of
2112
- the string being parsed, or at the beginning of a line.
2113
- """
2114
- def __init__(self, wordChars = printables):
2115
- super(WordStart,self).__init__()
2116
- self.wordChars = set(wordChars)
2117
- self.errmsg = "Not at the start of a word"
2118
-
2119
- def parseImpl(self, instring, loc, doActions=True ):
2120
- if loc != 0:
2121
- if (instring[loc-1] in self.wordChars or
2122
- instring[loc] not in self.wordChars):
2123
- raise ParseException(instring, loc, self.errmsg, self)
2124
- return loc, []
2125
-
2126
- class WordEnd(_PositionToken):
2127
- """Matches if the current position is at the end of a Word, and
2128
- is not followed by any character in a given set of C{wordChars}
2129
- (default=C{printables}). To emulate the C{\b} behavior of regular expressions,
2130
- use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of
2131
- the string being parsed, or at the end of a line.
2132
- """
2133
- def __init__(self, wordChars = printables):
2134
- super(WordEnd,self).__init__()
2135
- self.wordChars = set(wordChars)
2136
- self.skipWhitespace = False
2137
- self.errmsg = "Not at the end of a word"
2138
-
2139
- def parseImpl(self, instring, loc, doActions=True ):
2140
- instrlen = len(instring)
2141
- if instrlen>0 and loc<instrlen:
2142
- if (instring[loc] in self.wordChars or
2143
- instring[loc-1] not in self.wordChars):
2144
- raise ParseException(instring, loc, self.errmsg, self)
2145
- return loc, []
2146
-
2147
-
2148
- class ParseExpression(ParserElement):
2149
- """Abstract subclass of ParserElement, for combining and post-processing parsed tokens."""
2150
- def __init__( self, exprs, savelist = False ):
2151
- super(ParseExpression,self).__init__(savelist)
2152
- if isinstance( exprs, list ):
2153
- self.exprs = exprs
2154
- elif isinstance( exprs, basestring ):
2155
- self.exprs = [ Literal( exprs ) ]
2156
- else:
2157
- try:
2158
- self.exprs = list( exprs )
2159
- except TypeError:
2160
- self.exprs = [ exprs ]
2161
- self.callPreparse = False
2162
-
2163
- def __getitem__( self, i ):
2164
- return self.exprs[i]
2165
-
2166
- def append( self, other ):
2167
- self.exprs.append( other )
2168
- self.strRepr = None
2169
- return self
2170
-
2171
- def leaveWhitespace( self ):
2172
- """Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
2173
- all contained expressions."""
2174
- self.skipWhitespace = False
2175
- self.exprs = [ e.copy() for e in self.exprs ]
2176
- for e in self.exprs:
2177
- e.leaveWhitespace()
2178
- return self
2179
-
2180
- def ignore( self, other ):
2181
- if isinstance( other, Suppress ):
2182
- if other not in self.ignoreExprs:
2183
- super( ParseExpression, self).ignore( other )
2184
- for e in self.exprs:
2185
- e.ignore( self.ignoreExprs[-1] )
2186
- else:
2187
- super( ParseExpression, self).ignore( other )
2188
- for e in self.exprs:
2189
- e.ignore( self.ignoreExprs[-1] )
2190
- return self
2191
-
2192
- def __str__( self ):
2193
- try:
2194
- return super(ParseExpression,self).__str__()
2195
- except:
2196
- pass
2197
-
2198
- if self.strRepr is None:
2199
- self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) )
2200
- return self.strRepr
2201
-
2202
- def streamline( self ):
2203
- super(ParseExpression,self).streamline()
2204
-
2205
- for e in self.exprs:
2206
- e.streamline()
2207
-
2208
- # collapse nested And's of the form And( And( And( a,b), c), d) to And( a,b,c,d )
2209
- # but only if there are no parse actions or resultsNames on the nested And's
2210
- # (likewise for Or's and MatchFirst's)
2211
- if ( len(self.exprs) == 2 ):
2212
- other = self.exprs[0]
2213
- if ( isinstance( other, self.__class__ ) and
2214
- not(other.parseAction) and
2215
- other.resultsName is None and
2216
- not other.debug ):
2217
- self.exprs = other.exprs[:] + [ self.exprs[1] ]
2218
- self.strRepr = None
2219
- self.mayReturnEmpty |= other.mayReturnEmpty
2220
- self.mayIndexError |= other.mayIndexError
2221
-
2222
- other = self.exprs[-1]
2223
- if ( isinstance( other, self.__class__ ) and
2224
- not(other.parseAction) and
2225
- other.resultsName is None and
2226
- not other.debug ):
2227
- self.exprs = self.exprs[:-1] + other.exprs[:]
2228
- self.strRepr = None
2229
- self.mayReturnEmpty |= other.mayReturnEmpty
2230
- self.mayIndexError |= other.mayIndexError
2231
-
2232
- return self
2233
-
2234
- def setResultsName( self, name, listAllMatches=False ):
2235
- ret = super(ParseExpression,self).setResultsName(name,listAllMatches)
2236
- return ret
2237
-
2238
- def validate( self, validateTrace=[] ):
2239
- tmp = validateTrace[:]+[self]
2240
- for e in self.exprs:
2241
- e.validate(tmp)
2242
- self.checkRecursion( [] )
2243
-
2244
- def copy(self):
2245
- ret = super(ParseExpression,self).copy()
2246
- ret.exprs = [e.copy() for e in self.exprs]
2247
- return ret
2248
-
2249
- class And(ParseExpression):
2250
- """Requires all given C{ParseExpression}s to be found in the given order.
2251
- Expressions may be separated by whitespace.
2252
- May be constructed using the C{'+'} operator.
2253
- """
2254
-
2255
- class _ErrorStop(Empty):
2256
- def __init__(self, *args, **kwargs):
2257
- super(And._ErrorStop,self).__init__(*args, **kwargs)
2258
- self.name = '-'
2259
- self.leaveWhitespace()
2260
-
2261
- def __init__( self, exprs, savelist = True ):
2262
- super(And,self).__init__(exprs, savelist)
2263
- self.mayReturnEmpty = True
2264
- for e in self.exprs:
2265
- if not e.mayReturnEmpty:
2266
- self.mayReturnEmpty = False
2267
- break
2268
- self.setWhitespaceChars( exprs[0].whiteChars )
2269
- self.skipWhitespace = exprs[0].skipWhitespace
2270
- self.callPreparse = True
2271
-
2272
- def parseImpl( self, instring, loc, doActions=True ):
2273
- # pass False as last arg to _parse for first element, since we already
2274
- # pre-parsed the string as part of our And pre-parsing
2275
- loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
2276
- errorStop = False
2277
- for e in self.exprs[1:]:
2278
- if isinstance(e, And._ErrorStop):
2279
- errorStop = True
2280
- continue
2281
- if errorStop:
2282
- try:
2283
- loc, exprtokens = e._parse( instring, loc, doActions )
2284
- except ParseSyntaxException:
2285
- raise
2286
- except ParseBaseException as pe:
2287
- pe.__traceback__ = None
2288
- raise ParseSyntaxException(pe)
2289
- except IndexError:
2290
- raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) )
2291
- else:
2292
- loc, exprtokens = e._parse( instring, loc, doActions )
2293
- if exprtokens or exprtokens.keys():
2294
- resultlist += exprtokens
2295
- return loc, resultlist
2296
-
2297
- def __iadd__(self, other ):
2298
- if isinstance( other, basestring ):
2299
- other = Literal( other )
2300
- return self.append( other ) #And( [ self, other ] )
2301
-
2302
- def checkRecursion( self, parseElementList ):
2303
- subRecCheckList = parseElementList[:] + [ self ]
2304
- for e in self.exprs:
2305
- e.checkRecursion( subRecCheckList )
2306
- if not e.mayReturnEmpty:
2307
- break
2308
-
2309
- def __str__( self ):
2310
- if hasattr(self,"name"):
2311
- return self.name
2312
-
2313
- if self.strRepr is None:
2314
- self.strRepr = "{" + " ".join(_ustr(e) for e in self.exprs) + "}"
2315
-
2316
- return self.strRepr
2317
-
2318
-
2319
- class Or(ParseExpression):
2320
- """Requires that at least one C{ParseExpression} is found.
2321
- If two expressions match, the expression that matches the longest string will be used.
2322
- May be constructed using the C{'^'} operator.
2323
- """
2324
- def __init__( self, exprs, savelist = False ):
2325
- super(Or,self).__init__(exprs, savelist)
2326
- self.mayReturnEmpty = False
2327
- for e in self.exprs:
2328
- if e.mayReturnEmpty:
2329
- self.mayReturnEmpty = True
2330
- break
2331
-
2332
- def parseImpl( self, instring, loc, doActions=True ):
2333
- maxExcLoc = -1
2334
- maxMatchLoc = -1
2335
- maxException = None
2336
- for e in self.exprs:
2337
- try:
2338
- loc2 = e.tryParse( instring, loc )
2339
- except ParseException as err:
2340
- err.__traceback__ = None
2341
- if err.loc > maxExcLoc:
2342
- maxException = err
2343
- maxExcLoc = err.loc
2344
- except IndexError:
2345
- if len(instring) > maxExcLoc:
2346
- maxException = ParseException(instring,len(instring),e.errmsg,self)
2347
- maxExcLoc = len(instring)
2348
- else:
2349
- if loc2 > maxMatchLoc:
2350
- maxMatchLoc = loc2
2351
- maxMatchExp = e
2352
-
2353
- if maxMatchLoc < 0:
2354
- if maxException is not None:
2355
- raise maxException
2356
- else:
2357
- raise ParseException(instring, loc, "no defined alternatives to match", self)
2358
-
2359
- return maxMatchExp._parse( instring, loc, doActions )
2360
-
2361
- def __ixor__(self, other ):
2362
- if isinstance( other, basestring ):
2363
- other = ParserElement.literalStringClass( other )
2364
- return self.append( other ) #Or( [ self, other ] )
2365
-
2366
- def __str__( self ):
2367
- if hasattr(self,"name"):
2368
- return self.name
2369
-
2370
- if self.strRepr is None:
2371
- self.strRepr = "{" + " ^ ".join(_ustr(e) for e in self.exprs) + "}"
2372
-
2373
- return self.strRepr
2374
-
2375
- def checkRecursion( self, parseElementList ):
2376
- subRecCheckList = parseElementList[:] + [ self ]
2377
- for e in self.exprs:
2378
- e.checkRecursion( subRecCheckList )
2379
-
2380
-
2381
- class MatchFirst(ParseExpression):
2382
- """Requires that at least one C{ParseExpression} is found.
2383
- If two expressions match, the first one listed is the one that will match.
2384
- May be constructed using the C{'|'} operator.
2385
- """
2386
- def __init__( self, exprs, savelist = False ):
2387
- super(MatchFirst,self).__init__(exprs, savelist)
2388
- if exprs:
2389
- self.mayReturnEmpty = False
2390
- for e in self.exprs:
2391
- if e.mayReturnEmpty:
2392
- self.mayReturnEmpty = True
2393
- break
2394
- else:
2395
- self.mayReturnEmpty = True
2396
-
2397
- def parseImpl( self, instring, loc, doActions=True ):
2398
- maxExcLoc = -1
2399
- maxException = None
2400
- for e in self.exprs:
2401
- try:
2402
- ret = e._parse( instring, loc, doActions )
2403
- return ret
2404
- except ParseException as err:
2405
- if err.loc > maxExcLoc:
2406
- maxException = err
2407
- maxExcLoc = err.loc
2408
- except IndexError:
2409
- if len(instring) > maxExcLoc:
2410
- maxException = ParseException(instring,len(instring),e.errmsg,self)
2411
- maxExcLoc = len(instring)
2412
-
2413
- # only got here if no expression matched, raise exception for match that made it the furthest
2414
- else:
2415
- if maxException is not None:
2416
- raise maxException
2417
- else:
2418
- raise ParseException(instring, loc, "no defined alternatives to match", self)
2419
-
2420
- def __ior__(self, other ):
2421
- if isinstance( other, basestring ):
2422
- other = ParserElement.literalStringClass( other )
2423
- return self.append( other ) #MatchFirst( [ self, other ] )
2424
-
2425
- def __str__( self ):
2426
- if hasattr(self,"name"):
2427
- return self.name
2428
-
2429
- if self.strRepr is None:
2430
- self.strRepr = "{" + " | ".join(_ustr(e) for e in self.exprs) + "}"
2431
-
2432
- return self.strRepr
2433
-
2434
- def checkRecursion( self, parseElementList ):
2435
- subRecCheckList = parseElementList[:] + [ self ]
2436
- for e in self.exprs:
2437
- e.checkRecursion( subRecCheckList )
2438
-
2439
-
2440
- class Each(ParseExpression):
2441
- """Requires all given C{ParseExpression}s to be found, but in any order.
2442
- Expressions may be separated by whitespace.
2443
- May be constructed using the C{'&'} operator.
2444
- """
2445
- def __init__( self, exprs, savelist = True ):
2446
- super(Each,self).__init__(exprs, savelist)
2447
- self.mayReturnEmpty = True
2448
- for e in self.exprs:
2449
- if not e.mayReturnEmpty:
2450
- self.mayReturnEmpty = False
2451
- break
2452
- self.skipWhitespace = True
2453
- self.initExprGroups = True
2454
-
2455
- def parseImpl( self, instring, loc, doActions=True ):
2456
- if self.initExprGroups:
2457
- opt1 = [ e.expr for e in self.exprs if isinstance(e,Optional) ]
2458
- opt2 = [ e for e in self.exprs if e.mayReturnEmpty and e not in opt1 ]
2459
- self.optionals = opt1 + opt2
2460
- self.multioptionals = [ e.expr for e in self.exprs if isinstance(e,ZeroOrMore) ]
2461
- self.multirequired = [ e.expr for e in self.exprs if isinstance(e,OneOrMore) ]
2462
- self.required = [ e for e in self.exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
2463
- self.required += self.multirequired
2464
- self.initExprGroups = False
2465
- tmpLoc = loc
2466
- tmpReqd = self.required[:]
2467
- tmpOpt = self.optionals[:]
2468
- matchOrder = []
2469
-
2470
- keepMatching = True
2471
- while keepMatching:
2472
- tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
2473
- failed = []
2474
- for e in tmpExprs:
2475
- try:
2476
- tmpLoc = e.tryParse( instring, tmpLoc )
2477
- except ParseException:
2478
- failed.append(e)
2479
- else:
2480
- matchOrder.append(e)
2481
- if e in tmpReqd:
2482
- tmpReqd.remove(e)
2483
- elif e in tmpOpt:
2484
- tmpOpt.remove(e)
2485
- if len(failed) == len(tmpExprs):
2486
- keepMatching = False
2487
-
2488
- if tmpReqd:
2489
- missing = ", ".join(_ustr(e) for e in tmpReqd)
2490
- raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
2491
-
2492
- # add any unmatched Optionals, in case they have default values defined
2493
- matchOrder += [e for e in self.exprs if isinstance(e,Optional) and e.expr in tmpOpt]
2494
-
2495
- resultlist = []
2496
- for e in matchOrder:
2497
- loc,results = e._parse(instring,loc,doActions)
2498
- resultlist.append(results)
2499
-
2500
- finalResults = ParseResults([])
2501
- for r in resultlist:
2502
- dups = {}
2503
- for k in r.keys():
2504
- if k in finalResults.keys():
2505
- tmp = ParseResults(finalResults[k])
2506
- tmp += ParseResults(r[k])
2507
- dups[k] = tmp
2508
- finalResults += ParseResults(r)
2509
- for k,v in dups.items():
2510
- finalResults[k] = v
2511
- return loc, finalResults
2512
-
2513
- def __str__( self ):
2514
- if hasattr(self,"name"):
2515
- return self.name
2516
-
2517
- if self.strRepr is None:
2518
- self.strRepr = "{" + " & ".join(_ustr(e) for e in self.exprs) + "}"
2519
-
2520
- return self.strRepr
2521
-
2522
- def checkRecursion( self, parseElementList ):
2523
- subRecCheckList = parseElementList[:] + [ self ]
2524
- for e in self.exprs:
2525
- e.checkRecursion( subRecCheckList )
2526
-
2527
-
2528
- class ParseElementEnhance(ParserElement):
2529
- """Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens."""
2530
- def __init__( self, expr, savelist=False ):
2531
- super(ParseElementEnhance,self).__init__(savelist)
2532
- if isinstance( expr, basestring ):
2533
- expr = Literal(expr)
2534
- self.expr = expr
2535
- self.strRepr = None
2536
- if expr is not None:
2537
- self.mayIndexError = expr.mayIndexError
2538
- self.mayReturnEmpty = expr.mayReturnEmpty
2539
- self.setWhitespaceChars( expr.whiteChars )
2540
- self.skipWhitespace = expr.skipWhitespace
2541
- self.saveAsList = expr.saveAsList
2542
- self.callPreparse = expr.callPreparse
2543
- self.ignoreExprs.extend(expr.ignoreExprs)
2544
-
2545
- def parseImpl( self, instring, loc, doActions=True ):
2546
- if self.expr is not None:
2547
- return self.expr._parse( instring, loc, doActions, callPreParse=False )
2548
- else:
2549
- raise ParseException("",loc,self.errmsg,self)
2550
-
2551
- def leaveWhitespace( self ):
2552
- self.skipWhitespace = False
2553
- self.expr = self.expr.copy()
2554
- if self.expr is not None:
2555
- self.expr.leaveWhitespace()
2556
- return self
2557
-
2558
- def ignore( self, other ):
2559
- if isinstance( other, Suppress ):
2560
- if other not in self.ignoreExprs:
2561
- super( ParseElementEnhance, self).ignore( other )
2562
- if self.expr is not None:
2563
- self.expr.ignore( self.ignoreExprs[-1] )
2564
- else:
2565
- super( ParseElementEnhance, self).ignore( other )
2566
- if self.expr is not None:
2567
- self.expr.ignore( self.ignoreExprs[-1] )
2568
- return self
2569
-
2570
- def streamline( self ):
2571
- super(ParseElementEnhance,self).streamline()
2572
- if self.expr is not None:
2573
- self.expr.streamline()
2574
- return self
2575
-
2576
- def checkRecursion( self, parseElementList ):
2577
- if self in parseElementList:
2578
- raise RecursiveGrammarException( parseElementList+[self] )
2579
- subRecCheckList = parseElementList[:] + [ self ]
2580
- if self.expr is not None:
2581
- self.expr.checkRecursion( subRecCheckList )
2582
-
2583
- def validate( self, validateTrace=[] ):
2584
- tmp = validateTrace[:]+[self]
2585
- if self.expr is not None:
2586
- self.expr.validate(tmp)
2587
- self.checkRecursion( [] )
2588
-
2589
- def __str__( self ):
2590
- try:
2591
- return super(ParseElementEnhance,self).__str__()
2592
- except:
2593
- pass
2594
-
2595
- if self.strRepr is None and self.expr is not None:
2596
- self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) )
2597
- return self.strRepr
2598
-
2599
-
2600
- class FollowedBy(ParseElementEnhance):
2601
- """Lookahead matching of the given parse expression. C{FollowedBy}
2602
- does *not* advance the parsing position within the input string, it only
2603
- verifies that the specified parse expression matches at the current
2604
- position. C{FollowedBy} always returns a null token list."""
2605
- def __init__( self, expr ):
2606
- super(FollowedBy,self).__init__(expr)
2607
- self.mayReturnEmpty = True
2608
-
2609
- def parseImpl( self, instring, loc, doActions=True ):
2610
- self.expr.tryParse( instring, loc )
2611
- return loc, []
2612
-
2613
-
2614
- class NotAny(ParseElementEnhance):
2615
- """Lookahead to disallow matching with the given parse expression. C{NotAny}
2616
- does *not* advance the parsing position within the input string, it only
2617
- verifies that the specified parse expression does *not* match at the current
2618
- position. Also, C{NotAny} does *not* skip over leading whitespace. C{NotAny}
2619
- always returns a null token list. May be constructed using the '~' operator."""
2620
- def __init__( self, expr ):
2621
- super(NotAny,self).__init__(expr)
2622
- #~ self.leaveWhitespace()
2623
- self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs
2624
- self.mayReturnEmpty = True
2625
- self.errmsg = "Found unwanted token, "+_ustr(self.expr)
2626
-
2627
- def parseImpl( self, instring, loc, doActions=True ):
2628
- try:
2629
- self.expr.tryParse( instring, loc )
2630
- except (ParseException,IndexError):
2631
- pass
2632
- else:
2633
- raise ParseException(instring, loc, self.errmsg, self)
2634
- return loc, []
2635
-
2636
- def __str__( self ):
2637
- if hasattr(self,"name"):
2638
- return self.name
2639
-
2640
- if self.strRepr is None:
2641
- self.strRepr = "~{" + _ustr(self.expr) + "}"
2642
-
2643
- return self.strRepr
2644
-
2645
-
2646
- class ZeroOrMore(ParseElementEnhance):
2647
- """Optional repetition of zero or more of the given expression."""
2648
- def __init__( self, expr ):
2649
- super(ZeroOrMore,self).__init__(expr)
2650
- self.mayReturnEmpty = True
2651
-
2652
- def parseImpl( self, instring, loc, doActions=True ):
2653
- tokens = []
2654
- try:
2655
- loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
2656
- hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
2657
- while 1:
2658
- if hasIgnoreExprs:
2659
- preloc = self._skipIgnorables( instring, loc )
2660
- else:
2661
- preloc = loc
2662
- loc, tmptokens = self.expr._parse( instring, preloc, doActions )
2663
- if tmptokens or tmptokens.keys():
2664
- tokens += tmptokens
2665
- except (ParseException,IndexError):
2666
- pass
2667
-
2668
- return loc, tokens
2669
-
2670
- def __str__( self ):
2671
- if hasattr(self,"name"):
2672
- return self.name
2673
-
2674
- if self.strRepr is None:
2675
- self.strRepr = "[" + _ustr(self.expr) + "]..."
2676
-
2677
- return self.strRepr
2678
-
2679
- def setResultsName( self, name, listAllMatches=False ):
2680
- ret = super(ZeroOrMore,self).setResultsName(name,listAllMatches)
2681
- ret.saveAsList = True
2682
- return ret
2683
-
2684
-
2685
- class OneOrMore(ParseElementEnhance):
2686
- """Repetition of one or more of the given expression."""
2687
- def parseImpl( self, instring, loc, doActions=True ):
2688
- # must be at least one
2689
- loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
2690
- try:
2691
- hasIgnoreExprs = ( len(self.ignoreExprs) > 0 )
2692
- while 1:
2693
- if hasIgnoreExprs:
2694
- preloc = self._skipIgnorables( instring, loc )
2695
- else:
2696
- preloc = loc
2697
- loc, tmptokens = self.expr._parse( instring, preloc, doActions )
2698
- if tmptokens or tmptokens.keys():
2699
- tokens += tmptokens
2700
- except (ParseException,IndexError):
2701
- pass
2702
-
2703
- return loc, tokens
2704
-
2705
- def __str__( self ):
2706
- if hasattr(self,"name"):
2707
- return self.name
2708
-
2709
- if self.strRepr is None:
2710
- self.strRepr = "{" + _ustr(self.expr) + "}..."
2711
-
2712
- return self.strRepr
2713
-
2714
- def setResultsName( self, name, listAllMatches=False ):
2715
- ret = super(OneOrMore,self).setResultsName(name,listAllMatches)
2716
- ret.saveAsList = True
2717
- return ret
2718
-
2719
- class _NullToken(object):
2720
- def __bool__(self):
2721
- return False
2722
- __nonzero__ = __bool__
2723
- def __str__(self):
2724
- return ""
2725
-
2726
- _optionalNotMatched = _NullToken()
2727
- class Optional(ParseElementEnhance):
2728
- """Optional matching of the given expression.
2729
- A default return string can also be specified, if the optional expression
2730
- is not found.
2731
- """
2732
- def __init__( self, exprs, default=_optionalNotMatched ):
2733
- super(Optional,self).__init__( exprs, savelist=False )
2734
- self.defaultValue = default
2735
- self.mayReturnEmpty = True
2736
-
2737
- def parseImpl( self, instring, loc, doActions=True ):
2738
- try:
2739
- loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
2740
- except (ParseException,IndexError):
2741
- if self.defaultValue is not _optionalNotMatched:
2742
- if self.expr.resultsName:
2743
- tokens = ParseResults([ self.defaultValue ])
2744
- tokens[self.expr.resultsName] = self.defaultValue
2745
- else:
2746
- tokens = [ self.defaultValue ]
2747
- else:
2748
- tokens = []
2749
- return loc, tokens
2750
-
2751
- def __str__( self ):
2752
- if hasattr(self,"name"):
2753
- return self.name
2754
-
2755
- if self.strRepr is None:
2756
- self.strRepr = "[" + _ustr(self.expr) + "]"
2757
-
2758
- return self.strRepr
2759
-
2760
-
2761
- class SkipTo(ParseElementEnhance):
2762
- """Token for skipping over all undefined text until the matched expression is found.
2763
- If C{include} is set to true, the matched expression is also parsed (the skipped text
2764
- and matched expression are returned as a 2-element list). The C{ignore}
2765
- argument is used to define grammars (typically quoted strings and comments) that
2766
- might contain false matches.
2767
- """
2768
- def __init__( self, other, include=False, ignore=None, failOn=None ):
2769
- super( SkipTo, self ).__init__( other )
2770
- self.ignoreExpr = ignore
2771
- self.mayReturnEmpty = True
2772
- self.mayIndexError = False
2773
- self.includeMatch = include
2774
- self.asList = False
2775
- if failOn is not None and isinstance(failOn, basestring):
2776
- self.failOn = Literal(failOn)
2777
- else:
2778
- self.failOn = failOn
2779
- self.errmsg = "No match found for "+_ustr(self.expr)
2780
-
2781
- def parseImpl( self, instring, loc, doActions=True ):
2782
- startLoc = loc
2783
- instrlen = len(instring)
2784
- expr = self.expr
2785
- failParse = False
2786
- while loc <= instrlen:
2787
- try:
2788
- if self.failOn:
2789
- try:
2790
- self.failOn.tryParse(instring, loc)
2791
- except ParseBaseException:
2792
- pass
2793
- else:
2794
- failParse = True
2795
- raise ParseException(instring, loc, "Found expression " + str(self.failOn))
2796
- failParse = False
2797
- if self.ignoreExpr is not None:
2798
- while 1:
2799
- try:
2800
- loc = self.ignoreExpr.tryParse(instring,loc)
2801
- # print("found ignoreExpr, advance to", loc)
2802
- except ParseBaseException:
2803
- break
2804
- expr._parse( instring, loc, doActions=False, callPreParse=False )
2805
- skipText = instring[startLoc:loc]
2806
- if self.includeMatch:
2807
- loc,mat = expr._parse(instring,loc,doActions,callPreParse=False)
2808
- if mat:
2809
- skipRes = ParseResults( skipText )
2810
- skipRes += mat
2811
- return loc, [ skipRes ]
2812
- else:
2813
- return loc, [ skipText ]
2814
- else:
2815
- return loc, [ skipText ]
2816
- except (ParseException,IndexError):
2817
- if failParse:
2818
- raise
2819
- else:
2820
- loc += 1
2821
- raise ParseException(instring, loc, self.errmsg, self)
2822
-
2823
- class Forward(ParseElementEnhance):
2824
- """Forward declaration of an expression to be defined later -
2825
- used for recursive grammars, such as algebraic infix notation.
2826
- When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator.
2827
-
2828
- Note: take care when assigning to C{Forward} not to overlook precedence of operators.
2829
- Specifically, '|' has a lower precedence than '<<', so that::
2830
- fwdExpr << a | b | c
2831
- will actually be evaluated as::
2832
- (fwdExpr << a) | b | c
2833
- thereby leaving b and c out as parseable alternatives. It is recommended that you
2834
- explicitly group the values inserted into the C{Forward}::
2835
- fwdExpr << (a | b | c)
2836
- Converting to use the '<<=' operator instead will avoid this problem.
2837
- """
2838
- def __init__( self, other=None ):
2839
- super(Forward,self).__init__( other, savelist=False )
2840
-
2841
- def __ilshift__( self, other ):
2842
- if isinstance( other, basestring ):
2843
- other = ParserElement.literalStringClass(other)
2844
- self.expr = other
2845
- self.mayReturnEmpty = other.mayReturnEmpty
2846
- self.strRepr = None
2847
- self.mayIndexError = self.expr.mayIndexError
2848
- self.mayReturnEmpty = self.expr.mayReturnEmpty
2849
- self.setWhitespaceChars( self.expr.whiteChars )
2850
- self.skipWhitespace = self.expr.skipWhitespace
2851
- self.saveAsList = self.expr.saveAsList
2852
- self.ignoreExprs.extend(self.expr.ignoreExprs)
2853
- return self
2854
-
2855
- def __lshift__(self, other):
2856
- warnings.warn("Operator '<<' is deprecated, use '<<=' instead",
2857
- DeprecationWarning,stacklevel=2)
2858
- self <<= other
2859
- return None
2860
-
2861
- def leaveWhitespace( self ):
2862
- self.skipWhitespace = False
2863
- return self
2864
-
2865
- def streamline( self ):
2866
- if not self.streamlined:
2867
- self.streamlined = True
2868
- if self.expr is not None:
2869
- self.expr.streamline()
2870
- return self
2871
-
2872
- def validate( self, validateTrace=[] ):
2873
- if self not in validateTrace:
2874
- tmp = validateTrace[:]+[self]
2875
- if self.expr is not None:
2876
- self.expr.validate(tmp)
2877
- self.checkRecursion([])
2878
-
2879
- def __str__( self ):
2880
- if hasattr(self,"name"):
2881
- return self.name
2882
-
2883
- self._revertClass = self.__class__
2884
- self.__class__ = _ForwardNoRecurse
2885
- try:
2886
- if self.expr is not None:
2887
- retString = _ustr(self.expr)
2888
- else:
2889
- retString = "None"
2890
- finally:
2891
- self.__class__ = self._revertClass
2892
- return self.__class__.__name__ + ": " + retString
2893
-
2894
- def copy(self):
2895
- if self.expr is not None:
2896
- return super(Forward,self).copy()
2897
- else:
2898
- ret = Forward()
2899
- ret << self
2900
- return ret
2901
-
2902
- class _ForwardNoRecurse(Forward):
2903
- def __str__( self ):
2904
- return "..."
2905
-
2906
- class TokenConverter(ParseElementEnhance):
2907
- """Abstract subclass of C{ParseExpression}, for converting parsed results."""
2908
- def __init__( self, expr, savelist=False ):
2909
- super(TokenConverter,self).__init__( expr )#, savelist )
2910
- self.saveAsList = False
2911
-
2912
- class Upcase(TokenConverter):
2913
- """Converter to upper case all matching tokens."""
2914
- def __init__(self, *args):
2915
- super(Upcase,self).__init__(*args)
2916
- warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead",
2917
- DeprecationWarning,stacklevel=2)
2918
-
2919
- def postParse( self, instring, loc, tokenlist ):
2920
- return list(map( str.upper, tokenlist ))
2921
-
2922
-
2923
- class Combine(TokenConverter):
2924
- """Converter to concatenate all matching tokens to a single string.
2925
- By default, the matching patterns must also be contiguous in the input string;
2926
- this can be disabled by specifying C{'adjacent=False'} in the constructor.
2927
- """
2928
- def __init__( self, expr, joinString="", adjacent=True ):
2929
- super(Combine,self).__init__( expr )
2930
- # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
2931
- if adjacent:
2932
- self.leaveWhitespace()
2933
- self.adjacent = adjacent
2934
- self.skipWhitespace = True
2935
- self.joinString = joinString
2936
- self.callPreparse = True
2937
-
2938
- def ignore( self, other ):
2939
- if self.adjacent:
2940
- ParserElement.ignore(self, other)
2941
- else:
2942
- super( Combine, self).ignore( other )
2943
- return self
2944
-
2945
- def postParse( self, instring, loc, tokenlist ):
2946
- retToks = tokenlist.copy()
2947
- del retToks[:]
2948
- retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults)
2949
-
2950
- if self.resultsName and len(retToks.keys())>0:
2951
- return [ retToks ]
2952
- else:
2953
- return retToks
2954
-
2955
- class Group(TokenConverter):
2956
- """Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions."""
2957
- def __init__( self, expr ):
2958
- super(Group,self).__init__( expr )
2959
- self.saveAsList = True
2960
-
2961
- def postParse( self, instring, loc, tokenlist ):
2962
- return [ tokenlist ]
2963
-
2964
- class Dict(TokenConverter):
2965
- """Converter to return a repetitive expression as a list, but also as a dictionary.
2966
- Each element can also be referenced using the first token in the expression as its key.
2967
- Useful for tabular report scraping when the first column can be used as a item key.
2968
- """
2969
- def __init__( self, exprs ):
2970
- super(Dict,self).__init__( exprs )
2971
- self.saveAsList = True
2972
-
2973
- def postParse( self, instring, loc, tokenlist ):
2974
- for i,tok in enumerate(tokenlist):
2975
- if len(tok) == 0:
2976
- continue
2977
- ikey = tok[0]
2978
- if isinstance(ikey,int):
2979
- ikey = _ustr(tok[0]).strip()
2980
- if len(tok)==1:
2981
- tokenlist[ikey] = _ParseResultsWithOffset("",i)
2982
- elif len(tok)==2 and not isinstance(tok[1],ParseResults):
2983
- tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i)
2984
- else:
2985
- dictvalue = tok.copy() #ParseResults(i)
2986
- del dictvalue[0]
2987
- if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.keys()):
2988
- tokenlist[ikey] = _ParseResultsWithOffset(dictvalue,i)
2989
- else:
2990
- tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0],i)
2991
-
2992
- if self.resultsName:
2993
- return [ tokenlist ]
2994
- else:
2995
- return tokenlist
2996
-
2997
-
2998
- class Suppress(TokenConverter):
2999
- """Converter for ignoring the results of a parsed expression."""
3000
- def postParse( self, instring, loc, tokenlist ):
3001
- return []
3002
-
3003
- def suppress( self ):
3004
- return self
3005
-
3006
-
3007
- class OnlyOnce(object):
3008
- """Wrapper for parse actions, to ensure they are only called once."""
3009
- def __init__(self, methodCall):
3010
- self.callable = _trim_arity(methodCall)
3011
- self.called = False
3012
- def __call__(self,s,l,t):
3013
- if not self.called:
3014
- results = self.callable(s,l,t)
3015
- self.called = True
3016
- return results
3017
- raise ParseException(s,l,"")
3018
- def reset(self):
3019
- self.called = False
3020
-
3021
- def traceParseAction(f):
3022
- """Decorator for debugging parse actions."""
3023
- f = _trim_arity(f)
3024
- def z(*paArgs):
3025
- thisFunc = f.func_name
3026
- s,l,t = paArgs[-3:]
3027
- if len(paArgs)>3:
3028
- thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
3029
- sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) )
3030
- try:
3031
- ret = f(*paArgs)
3032
- except Exception as exc:
3033
- sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
3034
- raise
3035
- sys.stderr.write( "<<leaving %s (ret: %s)\n" % (thisFunc,ret) )
3036
- return ret
3037
- try:
3038
- z.__name__ = f.__name__
3039
- except AttributeError:
3040
- pass
3041
- return z
3042
-
3043
- #
3044
- # global helpers
3045
- #
3046
- def delimitedList( expr, delim=",", combine=False ):
3047
- """Helper to define a delimited list of expressions - the delimiter defaults to ','.
3048
- By default, the list elements and delimiters can have intervening whitespace, and
3049
- comments, but this can be overridden by passing C{combine=True} in the constructor.
3050
- If C{combine} is set to C{True}, the matching tokens are returned as a single token
3051
- string, with the delimiters included; otherwise, the matching tokens are returned
3052
- as a list of tokens, with the delimiters suppressed.
3053
- """
3054
- dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
3055
- if combine:
3056
- return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
3057
- else:
3058
- return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
3059
-
3060
- def countedArray( expr, intExpr=None ):
3061
- """Helper to define a counted list of expressions.
3062
- This helper defines a pattern of the form::
3063
- integer expr expr expr...
3064
- where the leading integer tells how many expr expressions follow.
3065
- The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
3066
- """
3067
- arrayExpr = Forward()
3068
- def countFieldParseAction(s,l,t):
3069
- n = t[0]
3070
- arrayExpr << (n and Group(And([expr]*n)) or Group(empty))
3071
- return []
3072
- if intExpr is None:
3073
- intExpr = Word(nums).setParseAction(lambda t:int(t[0]))
3074
- else:
3075
- intExpr = intExpr.copy()
3076
- intExpr.setName("arrayLen")
3077
- intExpr.addParseAction(countFieldParseAction, callDuringTry=True)
3078
- return ( intExpr + arrayExpr )
3079
-
3080
- def _flatten(L):
3081
- ret = []
3082
- for i in L:
3083
- if isinstance(i,list):
3084
- ret.extend(_flatten(i))
3085
- else:
3086
- ret.append(i)
3087
- return ret
3088
-
3089
- def matchPreviousLiteral(expr):
3090
- """Helper to define an expression that is indirectly defined from
3091
- the tokens matched in a previous expression, that is, it looks
3092
- for a 'repeat' of a previous expression. For example::
3093
- first = Word(nums)
3094
- second = matchPreviousLiteral(first)
3095
- matchExpr = first + ":" + second
3096
- will match C{"1:1"}, but not C{"1:2"}. Because this matches a
3097
- previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
3098
- If this is not desired, use C{matchPreviousExpr}.
3099
- Do *not* use with packrat parsing enabled.
3100
- """
3101
- rep = Forward()
3102
- def copyTokenToRepeater(s,l,t):
3103
- if t:
3104
- if len(t) == 1:
3105
- rep << t[0]
3106
- else:
3107
- # flatten t tokens
3108
- tflat = _flatten(t.asList())
3109
- rep << And( [ Literal(tt) for tt in tflat ] )
3110
- else:
3111
- rep << Empty()
3112
- expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
3113
- return rep
3114
-
3115
- def matchPreviousExpr(expr):
3116
- """Helper to define an expression that is indirectly defined from
3117
- the tokens matched in a previous expression, that is, it looks
3118
- for a 'repeat' of a previous expression. For example::
3119
- first = Word(nums)
3120
- second = matchPreviousExpr(first)
3121
- matchExpr = first + ":" + second
3122
- will match C{"1:1"}, but not C{"1:2"}. Because this matches by
3123
- expressions, will *not* match the leading C{"1:1"} in C{"1:10"};
3124
- the expressions are evaluated first, and then compared, so
3125
- C{"1"} is compared with C{"10"}.
3126
- Do *not* use with packrat parsing enabled.
3127
- """
3128
- rep = Forward()
3129
- e2 = expr.copy()
3130
- rep << e2
3131
- def copyTokenToRepeater(s,l,t):
3132
- matchTokens = _flatten(t.asList())
3133
- def mustMatchTheseTokens(s,l,t):
3134
- theseTokens = _flatten(t.asList())
3135
- if theseTokens != matchTokens:
3136
- raise ParseException("",0,"")
3137
- rep.setParseAction( mustMatchTheseTokens, callDuringTry=True )
3138
- expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
3139
- return rep
3140
-
3141
- def _escapeRegexRangeChars(s):
3142
- #~ escape these chars: ^-]
3143
- for c in r"\^-]":
3144
- s = s.replace(c,_bslash+c)
3145
- s = s.replace("\n",r"\n")
3146
- s = s.replace("\t",r"\t")
3147
- return _ustr(s)
3148
-
3149
- def oneOf( strs, caseless=False, useRegex=True ):
3150
- """Helper to quickly define a set of alternative Literals, and makes sure to do
3151
- longest-first testing when there is a conflict, regardless of the input order,
3152
- but returns a C{L{MatchFirst}} for best performance.
3153
-
3154
- Parameters:
3155
- - strs - a string of space-delimited literals, or a list of string literals
3156
- - caseless - (default=False) - treat all literals as caseless
3157
- - useRegex - (default=True) - as an optimization, will generate a Regex
3158
- object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or
3159
- if creating a C{Regex} raises an exception)
3160
- """
3161
- if caseless:
3162
- isequal = ( lambda a,b: a.upper() == b.upper() )
3163
- masks = ( lambda a,b: b.upper().startswith(a.upper()) )
3164
- parseElementClass = CaselessLiteral
3165
- else:
3166
- isequal = ( lambda a,b: a == b )
3167
- masks = ( lambda a,b: b.startswith(a) )
3168
- parseElementClass = Literal
3169
-
3170
- if isinstance(strs,(list,tuple)):
3171
- symbols = list(strs[:])
3172
- elif isinstance(strs,basestring):
3173
- symbols = strs.split()
3174
- else:
3175
- warnings.warn("Invalid argument to oneOf, expected string or list",
3176
- SyntaxWarning, stacklevel=2)
3177
-
3178
- i = 0
3179
- while i < len(symbols)-1:
3180
- cur = symbols[i]
3181
- for j,other in enumerate(symbols[i+1:]):
3182
- if ( isequal(other, cur) ):
3183
- del symbols[i+j+1]
3184
- break
3185
- elif ( masks(cur, other) ):
3186
- del symbols[i+j+1]
3187
- symbols.insert(i,other)
3188
- cur = other
3189
- break
3190
- else:
3191
- i += 1
3192
-
3193
- if not caseless and useRegex:
3194
- #~ print (strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] ))
3195
- try:
3196
- if len(symbols)==len("".join(symbols)):
3197
- return Regex( "[%s]" % "".join(_escapeRegexRangeChars(sym) for sym in symbols) )
3198
- else:
3199
- return Regex( "|".join(re.escape(sym) for sym in symbols) )
3200
- except:
3201
- warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
3202
- SyntaxWarning, stacklevel=2)
3203
-
3204
-
3205
- # last resort, just use MatchFirst
3206
- return MatchFirst( [ parseElementClass(sym) for sym in symbols ] )
3207
-
3208
- def dictOf( key, value ):
3209
- """Helper to easily and clearly define a dictionary by specifying the respective patterns
3210
- for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
3211
- in the proper order. The key pattern can include delimiting markers or punctuation,
3212
- as long as they are suppressed, thereby leaving the significant key text. The value
3213
- pattern can include named results, so that the C{Dict} results can include named token
3214
- fields.
3215
- """
3216
- return Dict( ZeroOrMore( Group ( key + value ) ) )
3217
-
3218
- def originalTextFor(expr, asString=True):
3219
- """Helper to return the original, untokenized text for a given expression. Useful to
3220
- restore the parsed fields of an HTML start tag into the raw tag text itself, or to
3221
- revert separate tokens with intervening whitespace back to the original matching
3222
- input text. Simpler to use than the parse action C{L{keepOriginalText}}, and does not
3223
- require the inspect module to chase up the call stack. By default, returns a
3224
- string containing the original parsed text.
3225
-
3226
- If the optional C{asString} argument is passed as C{False}, then the return value is a
3227
- C{L{ParseResults}} containing any results names that were originally matched, and a
3228
- single token containing the original matched text from the input string. So if
3229
- the expression passed to C{L{originalTextFor}} contains expressions with defined
3230
- results names, you must set C{asString} to C{False} if you want to preserve those
3231
- results name values."""
3232
- locMarker = Empty().setParseAction(lambda s,loc,t: loc)
3233
- endlocMarker = locMarker.copy()
3234
- endlocMarker.callPreparse = False
3235
- matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
3236
- if asString:
3237
- extractText = lambda s,l,t: s[t._original_start:t._original_end]
3238
- else:
3239
- def extractText(s,l,t):
3240
- del t[:]
3241
- t.insert(0, s[t._original_start:t._original_end])
3242
- del t["_original_start"]
3243
- del t["_original_end"]
3244
- matchExpr.setParseAction(extractText)
3245
- return matchExpr
3246
-
3247
- def ungroup(expr):
3248
- """Helper to undo pyparsing's default grouping of And expressions, even
3249
- if all but one are non-empty."""
3250
- return TokenConverter(expr).setParseAction(lambda t:t[0])
3251
-
3252
- # convenience constants for positional expressions
3253
- empty = Empty().setName("empty")
3254
- lineStart = LineStart().setName("lineStart")
3255
- lineEnd = LineEnd().setName("lineEnd")
3256
- stringStart = StringStart().setName("stringStart")
3257
- stringEnd = StringEnd().setName("stringEnd")
3258
-
3259
- _escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1])
3260
- _escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").setParseAction(lambda s,l,t:unichr(int(t[0].lstrip(r'\0x'),16)))
3261
- _escapedOctChar = Regex(r"\\0[0-7]+").setParseAction(lambda s,l,t:unichr(int(t[0][1:],8)))
3262
- _singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(printables, excludeChars=r'\]', exact=1)
3263
- _charRange = Group(_singleChar + Suppress("-") + _singleChar)
3264
- _reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
3265
-
3266
- _expanded = lambda p: (isinstance(p,ParseResults) and ''.join(unichr(c) for c in range(ord(p[0]),ord(p[1])+1)) or p)
3267
-
3268
- def srange(s):
3269
- r"""Helper to easily define string ranges for use in Word construction. Borrows
3270
- syntax from regexp '[]' string range definitions::
3271
- srange("[0-9]") -> "0123456789"
3272
- srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
3273
- srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
3274
- The input string must be enclosed in []'s, and the returned string is the expanded
3275
- character set joined into a single string.
3276
- The values enclosed in the []'s may be::
3277
- a single character
3278
- an escaped character with a leading backslash (such as \- or \])
3279
- an escaped hex character with a leading '\x' (\x21, which is a '!' character)
3280
- (\0x## is also supported for backwards compatibility)
3281
- an escaped octal character with a leading '\0' (\041, which is a '!' character)
3282
- a range of any of the above, separated by a dash ('a-z', etc.)
3283
- any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.)
3284
- """
3285
- try:
3286
- return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body)
3287
- except:
3288
- return ""
3289
-
3290
- def matchOnlyAtCol(n):
3291
- """Helper method for defining parse actions that require matching at a specific
3292
- column in the input text.
3293
- """
3294
- def verifyCol(strg,locn,toks):
3295
- if col(locn,strg) != n:
3296
- raise ParseException(strg,locn,"matched token not at column %d" % n)
3297
- return verifyCol
3298
-
3299
- def replaceWith(replStr):
3300
- """Helper method for common parse actions that simply return a literal value. Especially
3301
- useful when used with C{L{transformString<ParserElement.transformString>}()}.
3302
- """
3303
- def _replFunc(*args):
3304
- return [replStr]
3305
- return _replFunc
3306
-
3307
- def removeQuotes(s,l,t):
3308
- """Helper parse action for removing quotation marks from parsed quoted strings.
3309
- To use, add this parse action to quoted string using::
3310
- quotedString.setParseAction( removeQuotes )
3311
- """
3312
- return t[0][1:-1]
3313
-
3314
- def upcaseTokens(s,l,t):
3315
- """Helper parse action to convert tokens to upper case."""
3316
- return [ tt.upper() for tt in map(_ustr,t) ]
3317
-
3318
- def downcaseTokens(s,l,t):
3319
- """Helper parse action to convert tokens to lower case."""
3320
- return [ tt.lower() for tt in map(_ustr,t) ]
3321
-
3322
- def keepOriginalText(s,startLoc,t):
3323
- """DEPRECATED - use new helper method C{L{originalTextFor}}.
3324
- Helper parse action to preserve original parsed text,
3325
- overriding any nested parse actions."""
3326
- try:
3327
- endloc = getTokensEndLoc()
3328
- except ParseException:
3329
- raise ParseFatalException("incorrect usage of keepOriginalText - may only be called as a parse action")
3330
- del t[:]
3331
- t += ParseResults(s[startLoc:endloc])
3332
- return t
3333
-
3334
- def getTokensEndLoc():
3335
- """Method to be called from within a parse action to determine the end
3336
- location of the parsed tokens."""
3337
- import inspect
3338
- fstack = inspect.stack()
3339
- try:
3340
- # search up the stack (through intervening argument normalizers) for correct calling routine
3341
- for f in fstack[2:]:
3342
- if f[3] == "_parseNoCache":
3343
- endloc = f[0].f_locals["loc"]
3344
- return endloc
3345
- else:
3346
- raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
3347
- finally:
3348
- del fstack
3349
-
3350
- def _makeTags(tagStr, xml):
3351
- """Internal helper to construct opening and closing tag expressions, given a tag name"""
3352
- if isinstance(tagStr,basestring):
3353
- resname = tagStr
3354
- tagStr = Keyword(tagStr, caseless=not xml)
3355
- else:
3356
- resname = tagStr.name
3357
-
3358
- tagAttrName = Word(alphas,alphanums+"_-:")
3359
- if (xml):
3360
- tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
3361
- openTag = Suppress("<") + tagStr("tag") + \
3362
- Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \
3363
- Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
3364
- else:
3365
- printablesLessRAbrack = "".join(c for c in printables if c not in ">")
3366
- tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)
3367
- openTag = Suppress("<") + tagStr("tag") + \
3368
- Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
3369
- Optional( Suppress("=") + tagAttrValue ) ))) + \
3370
- Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
3371
- closeTag = Combine(_L("</") + tagStr + ">")
3372
-
3373
- openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr)
3374
- closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % tagStr)
3375
- openTag.tag = resname
3376
- closeTag.tag = resname
3377
- return openTag, closeTag
3378
-
3379
- def makeHTMLTags(tagStr):
3380
- """Helper to construct opening and closing tag expressions for HTML, given a tag name"""
3381
- return _makeTags( tagStr, False )
3382
-
3383
- def makeXMLTags(tagStr):
3384
- """Helper to construct opening and closing tag expressions for XML, given a tag name"""
3385
- return _makeTags( tagStr, True )
3386
-
3387
- def withAttribute(*args,**attrDict):
3388
- """Helper to create a validating parse action to be used with start tags created
3389
- with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag
3390
- with a required attribute value, to avoid false matches on common tags such as
3391
- C{<TD>} or C{<DIV>}.
3392
-
3393
- Call C{withAttribute} with a series of attribute names and values. Specify the list
3394
- of filter attributes names and values as:
3395
- - keyword arguments, as in C{(align="right")}, or
3396
- - as an explicit dict with C{**} operator, when an attribute name is also a Python
3397
- reserved word, as in C{**{"class":"Customer", "align":"right"}}
3398
- - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
3399
- For attribute names with a namespace prefix, you must use the second form. Attribute
3400
- names are matched insensitive to upper/lower case.
3401
-
3402
- To verify that the attribute exists, but without specifying a value, pass
3403
- C{withAttribute.ANY_VALUE} as the value.
3404
- """
3405
- if args:
3406
- attrs = args[:]
3407
- else:
3408
- attrs = attrDict.items()
3409
- attrs = [(k,v) for k,v in attrs]
3410
- def pa(s,l,tokens):
3411
- for attrName,attrValue in attrs:
3412
- if attrName not in tokens:
3413
- raise ParseException(s,l,"no matching attribute " + attrName)
3414
- if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
3415
- raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
3416
- (attrName, tokens[attrName], attrValue))
3417
- return pa
3418
- withAttribute.ANY_VALUE = object()
3419
-
3420
- opAssoc = _Constants()
3421
- opAssoc.LEFT = object()
3422
- opAssoc.RIGHT = object()
3423
-
3424
- def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ):
3425
- """Helper method for constructing grammars of expressions made up of
3426
- operators working in a precedence hierarchy. Operators may be unary or
3427
- binary, left- or right-associative. Parse actions can also be attached
3428
- to operator expressions.
3429
-
3430
- Parameters:
3431
- - baseExpr - expression representing the most basic element for the nested
3432
- - opList - list of tuples, one for each operator precedence level in the
3433
- expression grammar; each tuple is of the form
3434
- (opExpr, numTerms, rightLeftAssoc, parseAction), where:
3435
- - opExpr is the pyparsing expression for the operator;
3436
- may also be a string, which will be converted to a Literal;
3437
- if numTerms is 3, opExpr is a tuple of two expressions, for the
3438
- two operators separating the 3 terms
3439
- - numTerms is the number of terms for this operator (must
3440
- be 1, 2, or 3)
3441
- - rightLeftAssoc is the indicator whether the operator is
3442
- right or left associative, using the pyparsing-defined
3443
- constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}.
3444
- - parseAction is the parse action to be associated with
3445
- expressions matching this operator expression (the
3446
- parse action tuple member may be omitted)
3447
- - lpar - expression for matching left-parentheses (default=Suppress('('))
3448
- - rpar - expression for matching right-parentheses (default=Suppress(')'))
3449
- """
3450
- ret = Forward()
3451
- lastExpr = baseExpr | ( lpar + ret + rpar )
3452
- for i,operDef in enumerate(opList):
3453
- opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
3454
- if arity == 3:
3455
- if opExpr is None or len(opExpr) != 2:
3456
- raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions")
3457
- opExpr1, opExpr2 = opExpr
3458
- thisExpr = Forward()#.setName("expr%d" % i)
3459
- if rightLeftAssoc == opAssoc.LEFT:
3460
- if arity == 1:
3461
- matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) )
3462
- elif arity == 2:
3463
- if opExpr is not None:
3464
- matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
3465
- else:
3466
- matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) )
3467
- elif arity == 3:
3468
- matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \
3469
- Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr )
3470
- else:
3471
- raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
3472
- elif rightLeftAssoc == opAssoc.RIGHT:
3473
- if arity == 1:
3474
- # try to avoid LR with this extra test
3475
- if not isinstance(opExpr, Optional):
3476
- opExpr = Optional(opExpr)
3477
- matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr )
3478
- elif arity == 2:
3479
- if opExpr is not None:
3480
- matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
3481
- else:
3482
- matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) )
3483
- elif arity == 3:
3484
- matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \
3485
- Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr )
3486
- else:
3487
- raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
3488
- else:
3489
- raise ValueError("operator must indicate right or left associativity")
3490
- if pa:
3491
- matchExpr.setParseAction( pa )
3492
- thisExpr << ( matchExpr | lastExpr )
3493
- lastExpr = thisExpr
3494
- ret << lastExpr
3495
- return ret
3496
- operatorPrecedence = infixNotation
3497
-
3498
- dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*"').setName("string enclosed in double quotes")
3499
- sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*'").setName("string enclosed in single quotes")
3500
- quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*')''').setName("quotedString using single or double quotes")
3501
- unicodeString = Combine(_L('u') + quotedString.copy())
3502
-
3503
- def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()):
3504
- """Helper method for defining nested lists enclosed in opening and closing
3505
- delimiters ("(" and ")" are the default).
3506
-
3507
- Parameters:
3508
- - opener - opening character for a nested list (default="("); can also be a pyparsing expression
3509
- - closer - closing character for a nested list (default=")"); can also be a pyparsing expression
3510
- - content - expression for items within the nested lists (default=None)
3511
- - ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString)
3512
-
3513
- If an expression is not provided for the content argument, the nested
3514
- expression will capture all whitespace-delimited content between delimiters
3515
- as a list of separate values.
3516
-
3517
- Use the C{ignoreExpr} argument to define expressions that may contain
3518
- opening or closing characters that should not be treated as opening
3519
- or closing characters for nesting, such as quotedString or a comment
3520
- expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}.
3521
- The default is L{quotedString}, but if no expressions are to be ignored,
3522
- then pass C{None} for this argument.
3523
- """
3524
- if opener == closer:
3525
- raise ValueError("opening and closing strings cannot be the same")
3526
- if content is None:
3527
- if isinstance(opener,basestring) and isinstance(closer,basestring):
3528
- if len(opener) == 1 and len(closer)==1:
3529
- if ignoreExpr is not None:
3530
- content = (Combine(OneOrMore(~ignoreExpr +
3531
- CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS,exact=1))
3532
- ).setParseAction(lambda t:t[0].strip()))
3533
- else:
3534
- content = (empty.copy()+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS
3535
- ).setParseAction(lambda t:t[0].strip()))
3536
- else:
3537
- if ignoreExpr is not None:
3538
- content = (Combine(OneOrMore(~ignoreExpr +
3539
- ~Literal(opener) + ~Literal(closer) +
3540
- CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
3541
- ).setParseAction(lambda t:t[0].strip()))
3542
- else:
3543
- content = (Combine(OneOrMore(~Literal(opener) + ~Literal(closer) +
3544
- CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
3545
- ).setParseAction(lambda t:t[0].strip()))
3546
- else:
3547
- raise ValueError("opening and closing arguments must be strings if no content expression is given")
3548
- ret = Forward()
3549
- if ignoreExpr is not None:
3550
- ret << Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) )
3551
- else:
3552
- ret << Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) )
3553
- return ret
3554
-
3555
- def indentedBlock(blockStatementExpr, indentStack, indent=True):
3556
- """Helper method for defining space-delimited indentation blocks, such as
3557
- those used to define block statements in Python source code.
3558
-
3559
- Parameters:
3560
- - blockStatementExpr - expression defining syntax of statement that
3561
- is repeated within the indented block
3562
- - indentStack - list created by caller to manage indentation stack
3563
- (multiple statementWithIndentedBlock expressions within a single grammar
3564
- should share a common indentStack)
3565
- - indent - boolean indicating whether block must be indented beyond the
3566
- the current level; set to False for block of left-most statements
3567
- (default=True)
3568
-
3569
- A valid block must contain at least one C{blockStatement}.
3570
- """
3571
- def checkPeerIndent(s,l,t):
3572
- if l >= len(s): return
3573
- curCol = col(l,s)
3574
- if curCol != indentStack[-1]:
3575
- if curCol > indentStack[-1]:
3576
- raise ParseFatalException(s,l,"illegal nesting")
3577
- raise ParseException(s,l,"not a peer entry")
3578
-
3579
- def checkSubIndent(s,l,t):
3580
- curCol = col(l,s)
3581
- if curCol > indentStack[-1]:
3582
- indentStack.append( curCol )
3583
- else:
3584
- raise ParseException(s,l,"not a subentry")
3585
-
3586
- def checkUnindent(s,l,t):
3587
- if l >= len(s): return
3588
- curCol = col(l,s)
3589
- if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]):
3590
- raise ParseException(s,l,"not an unindent")
3591
- indentStack.pop()
3592
-
3593
- NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress())
3594
- INDENT = Empty() + Empty().setParseAction(checkSubIndent)
3595
- PEER = Empty().setParseAction(checkPeerIndent)
3596
- UNDENT = Empty().setParseAction(checkUnindent)
3597
- if indent:
3598
- smExpr = Group( Optional(NL) +
3599
- #~ FollowedBy(blockStatementExpr) +
3600
- INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT)
3601
- else:
3602
- smExpr = Group( Optional(NL) +
3603
- (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) )
3604
- blockStatementExpr.ignore(_bslash + LineEnd())
3605
- return smExpr
3606
-
3607
- alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
3608
- punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
3609
-
3610
- anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:"))
3611
- commonHTMLEntity = Combine(_L("&") + oneOf("gt lt amp nbsp quot").setResultsName("entity") +";").streamline()
3612
- _htmlEntityMap = dict(zip("gt lt amp nbsp quot".split(),'><& "'))
3613
- replaceHTMLEntity = lambda t : t.entity in _htmlEntityMap and _htmlEntityMap[t.entity] or None
3614
-
3615
- # it's easy to get these comment structures wrong - they're very common, so may as well make them available
3616
- cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment")
3617
-
3618
- htmlComment = Regex(r"<!--[\s\S]*?-->")
3619
- restOfLine = Regex(r".*").leaveWhitespace()
3620
- dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment")
3621
- cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?<!\\)|\Z))").setName("C++ style comment")
3622
-
3623
- javaStyleComment = cppStyleComment
3624
- pythonStyleComment = Regex(r"#.*").setName("Python style comment")
3625
- _commasepitem = Combine(OneOrMore(Word(printables, excludeChars=',') +
3626
- Optional( Word(" \t") +
3627
- ~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem")
3628
- commaSeparatedList = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("commaSeparatedList")
3629
-
3630
-
3631
- if __name__ == "__main__":
3632
-
3633
- def test( teststring ):
3634
- try:
3635
- tokens = simpleSQL.parseString( teststring )
3636
- tokenlist = tokens.asList()
3637
- print (teststring + "->" + str(tokenlist))
3638
- print ("tokens = " + str(tokens))
3639
- print ("tokens.columns = " + str(tokens.columns))
3640
- print ("tokens.tables = " + str(tokens.tables))
3641
- print (tokens.asXML("SQL",True))
3642
- except ParseBaseException as err:
3643
- print (teststring + "->")
3644
- print (err.line)
3645
- print (" "*(err.column-1) + "^")
3646
- print (err)
3647
- print()
3648
-
3649
- selectToken = CaselessLiteral( "select" )
3650
- fromToken = CaselessLiteral( "from" )
3651
-
3652
- ident = Word( alphas, alphanums + "_$" )
3653
- columnName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
3654
- columnNameList = Group( delimitedList( columnName ) )#.setName("columns")
3655
- tableName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens )
3656
- tableNameList = Group( delimitedList( tableName ) )#.setName("tables")
3657
- simpleSQL = ( selectToken + \
3658
- ( '*' | columnNameList ).setResultsName( "columns" ) + \
3659
- fromToken + \
3660
- tableNameList.setResultsName( "tables" ) )
3661
-
3662
- test( "SELECT * from XYZZY, ABC" )
3663
- test( "select * from SYS.XYZZY" )
3664
- test( "Select A from Sys.dual" )
3665
- test( "Select AA,BB,CC from Sys.dual" )
3666
- test( "Select A, B, C from Sys.dual" )
3667
- test( "Select A, B, C from Sys.dual" )
3668
- test( "Xelect A, B, C from Sys.dual" )
3669
- test( "Select A, B, C frox Sys.dual" )
3670
- test( "Select" )
3671
- test( "Select ^^^ frox Sys.dual" )
3672
- test( "Select A, B, C from Sys.dual, Table2 " )