| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# module pyparsing.py |
| 3 |
# |
| 4 |
# |
| 5 |
# Note: We keep pyparsing 2.4 in here because this is what DaCHS |
| 6 |
# assumes, and pyparsing has had some nasty incompatible changes |
| 7 |
# in the past. DaCHS will still use the operating system's pyparsing |
| 8 |
# by default. |
| 9 |
# |
| 10 |
# If DaCHS more complex parsers (in particular ADQL and STC-S) fail with |
| 11 |
# your platform's pyparsing, as a quick fallback define the environment |
| 12 |
# variable (e.g., GAVO_BUILTIN_PYPARSING=1 dachs...; DaCHS will |
| 13 |
# then use this known-good version. |
| 14 |
# |
| 15 |
# |
| 16 |
# Copyright (c) 2003-2019 Paul T. McGuire |
| 17 |
# |
| 18 |
# Permission is hereby granted, free of charge, to any person obtaining |
| 19 |
# a copy of this software and associated documentation files (the |
| 20 |
# "Software"), to deal in the Software without restriction, including |
| 21 |
# without limitation the rights to use, copy, modify, merge, publish, |
| 22 |
# distribute, sublicense, and/or sell copies of the Software, and to |
| 23 |
# permit persons to whom the Software is furnished to do so, subject to |
| 24 |
# the following conditions: |
| 25 |
# |
| 26 |
# The above copyright notice and this permission notice shall be |
| 27 |
# included in all copies or substantial portions of the Software. |
| 28 |
# |
| 29 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 30 |
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 31 |
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 32 |
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| 33 |
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, |
| 34 |
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| 35 |
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 36 |
# |
| 37 |
|
| 38 |
__doc__ = \ |
| 39 |
""" |
| 40 |
pyparsing module - Classes and methods to define and execute parsing grammars |
| 41 |
============================================================================= |
| 42 |
|
| 43 |
The pyparsing module is an alternative approach to creating and |
| 44 |
executing simple grammars, vs. the traditional lex/yacc approach, or the |
| 45 |
use of regular expressions. With pyparsing, you don't need to learn |
| 46 |
a new syntax for defining grammars or matching expressions - the parsing |
| 47 |
module provides a library of classes that you use to construct the |
| 48 |
grammar directly in Python. |
| 49 |
|
| 50 |
Here is a program to parse "Hello, World!" (or any greeting of the form |
| 51 |
``"<salutation>, <addressee>!"``), built up using :class:`Word`, |
| 52 |
:class:`Literal`, and :class:`And` elements |
| 53 |
(the :class:`'+'<ParserElement.__add__>` operators create :class:`And` expressions, |
| 54 |
and the strings are auto-converted to :class:`Literal` expressions):: |
| 55 |
|
| 56 |
from pyparsing import Word, alphas |
| 57 |
|
| 58 |
# define grammar of a greeting |
| 59 |
greet = Word(alphas) + "," + Word(alphas) + "!" |
| 60 |
|
| 61 |
hello = "Hello, World!" |
| 62 |
print (hello, "->", greet.parseString(hello)) |
| 63 |
|
| 64 |
The program outputs the following:: |
| 65 |
|
| 66 |
Hello, World! -> ['Hello', ',', 'World', '!'] |
| 67 |
|
| 68 |
The Python representation of the grammar is quite readable, owing to the |
| 69 |
self-explanatory class names, and the use of '+', '|' and '^' operators. |
| 70 |
|
| 71 |
The :class:`ParseResults` object returned from |
| 72 |
:class:`ParserElement.parseString` can be |
| 73 |
accessed as a nested list, a dictionary, or an object with named |
| 74 |
attributes. |
| 75 |
|
| 76 |
The pyparsing module handles some of the problems that are typically |
| 77 |
vexing when writing text parsers: |
| 78 |
|
| 79 |
- extra or missing whitespace (the above program will also handle |
| 80 |
"Hello,World!", "Hello , World !", etc.) |
| 81 |
- quoted strings |
| 82 |
- embedded comments |
| 83 |
|
| 84 |
|
| 85 |
Getting Started - |
| 86 |
----------------- |
| 87 |
Visit the classes :class:`ParserElement` and :class:`ParseResults` to |
| 88 |
see the base classes that most other pyparsing |
| 89 |
classes inherit from. Use the docstrings for examples of how to: |
| 90 |
|
| 91 |
- construct literal match expressions from :class:`Literal` and |
| 92 |
:class:`CaselessLiteral` classes |
| 93 |
- construct character word-group expressions using the :class:`Word` |
| 94 |
class |
| 95 |
- see how to create repetitive expressions using :class:`ZeroOrMore` |
| 96 |
and :class:`OneOrMore` classes |
| 97 |
- use :class:`'+'<And>`, :class:`'|'<MatchFirst>`, :class:`'^'<Or>`, |
| 98 |
and :class:`'&'<Each>` operators to combine simple expressions into |
| 99 |
more complex ones |
| 100 |
- associate names with your parsed results using |
| 101 |
:class:`ParserElement.setResultsName` |
| 102 |
- access the parsed data, which is returned as a :class:`ParseResults` |
| 103 |
object |
| 104 |
- find some helpful expression short-cuts like :class:`delimitedList` |
| 105 |
and :class:`oneOf` |
| 106 |
- find more useful common expressions in the :class:`pyparsing_common` |
| 107 |
namespace class |
| 108 |
""" |
| 109 |
|
| 110 |
__version__ = "2.4.7" |
| 111 |
__versionTime__ = "30 Mar 2020 00:43 UTC" |
| 112 |
__author__ = "Paul McGuire <[email protected]>" |
| 113 |
|
| 114 |
import string |
| 115 |
from weakref import ref as wkref |
| 116 |
import copy |
| 117 |
import sys |
| 118 |
import warnings |
| 119 |
import re |
| 120 |
import sre_constants |
| 121 |
import collections |
| 122 |
import pprint |
| 123 |
import traceback |
| 124 |
import types |
| 125 |
from datetime import datetime |
| 126 |
from operator import itemgetter |
| 127 |
import itertools |
| 128 |
from functools import wraps |
| 129 |
from contextlib import contextmanager |
| 130 |
|
| 131 |
try: |
| 132 |
# Python 3 |
| 133 |
from itertools import filterfalse |
| 134 |
except ImportError: |
| 135 |
from itertools import ifilterfalse as filterfalse |
| 136 |
|
| 137 |
try: |
| 138 |
from _thread import RLock |
| 139 |
except ImportError: |
| 140 |
from threading import RLock |
| 141 |
|
| 142 |
try: |
| 143 |
# Python 3 |
| 144 |
from collections.abc import Iterable |
| 145 |
from collections.abc import MutableMapping, Mapping |
| 146 |
except ImportError: |
| 147 |
# Python 2.7 |
| 148 |
from collections import Iterable |
| 149 |
from collections import MutableMapping, Mapping |
| 150 |
|
| 151 |
try: |
| 152 |
from collections import OrderedDict as _OrderedDict |
| 153 |
except ImportError: |
| 154 |
try: |
| 155 |
from ordereddict import OrderedDict as _OrderedDict |
| 156 |
except ImportError: |
| 157 |
_OrderedDict = None |
| 158 |
|
| 159 |
try: |
| 160 |
from types import SimpleNamespace |
| 161 |
except ImportError: |
| 162 |
class SimpleNamespace: pass |
| 163 |
|
| 164 |
# version compatibility configuration |
| 165 |
__compat__ = SimpleNamespace() |
| 166 |
__compat__.__doc__ = """ |
| 167 |
A cross-version compatibility configuration for pyparsing features that will be |
| 168 |
released in a future version. By setting values in this configuration to True, |
| 169 |
those features can be enabled in prior versions for compatibility development |
| 170 |
and testing. |
| 171 |
|
| 172 |
- collect_all_And_tokens - flag to enable fix for Issue #63 that fixes erroneous grouping |
| 173 |
of results names when an And expression is nested within an Or or MatchFirst; set to |
| 174 |
True to enable bugfix released in pyparsing 2.3.0, or False to preserve |
| 175 |
pre-2.3.0 handling of named results |
| 176 |
""" |
| 177 |
__compat__.collect_all_And_tokens = True |
| 178 |
|
| 179 |
__diag__ = SimpleNamespace() |
| 180 |
__diag__.__doc__ = """ |
| 181 |
Diagnostic configuration (all default to False) |
| 182 |
- warn_multiple_tokens_in_named_alternation - flag to enable warnings when a results |
| 183 |
name is defined on a MatchFirst or Or expression with one or more And subexpressions |
| 184 |
(only warns if __compat__.collect_all_And_tokens is False) |
| 185 |
- warn_ungrouped_named_tokens_in_collection - flag to enable warnings when a results |
| 186 |
name is defined on a containing expression with ungrouped subexpressions that also |
| 187 |
have results names |
| 188 |
- warn_name_set_on_empty_Forward - flag to enable warnings whan a Forward is defined |
| 189 |
with a results name, but has no contents defined |
| 190 |
- warn_on_multiple_string_args_to_oneof - flag to enable warnings whan oneOf is |
| 191 |
incorrectly called with multiple str arguments |
| 192 |
- enable_debug_on_named_expressions - flag to auto-enable debug on all subsequent |
| 193 |
calls to ParserElement.setName() |
| 194 |
""" |
| 195 |
__diag__.warn_multiple_tokens_in_named_alternation = False |
| 196 |
__diag__.warn_ungrouped_named_tokens_in_collection = False |
| 197 |
__diag__.warn_name_set_on_empty_Forward = False |
| 198 |
__diag__.warn_on_multiple_string_args_to_oneof = False |
| 199 |
__diag__.enable_debug_on_named_expressions = False |
| 200 |
__diag__._all_names = [nm for nm in vars(__diag__) if nm.startswith("enable_") or nm.startswith("warn_")] |
| 201 |
|
| 202 |
def _enable_all_warnings(): |
| 203 |
__diag__.warn_multiple_tokens_in_named_alternation = True |
| 204 |
__diag__.warn_ungrouped_named_tokens_in_collection = True |
| 205 |
__diag__.warn_name_set_on_empty_Forward = True |
| 206 |
__diag__.warn_on_multiple_string_args_to_oneof = True |
| 207 |
__diag__.enable_all_warnings = _enable_all_warnings |
| 208 |
|
| 209 |
|
| 210 |
__all__ = ['__version__', '__versionTime__', '__author__', '__compat__', '__diag__', |
| 211 |
'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty', |
| 212 |
'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal', |
| 213 |
'PrecededBy', 'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or', |
| 214 |
'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException', |
| 215 |
'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException', |
| 216 |
'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter', |
| 217 |
'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore', 'Char', |
| 218 |
'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col', |
| 219 |
'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString', |
| 220 |
'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'hexnums', |
| 221 |
'htmlComment', 'javaStyleComment', 'line', 'lineEnd', 'lineStart', 'lineno', |
| 222 |
'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral', |
| 223 |
'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables', |
| 224 |
'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity', |
| 225 |
'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd', |
| 226 |
'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute', |
| 227 |
'indentedBlock', 'originalTextFor', 'ungroup', 'infixNotation', 'locatedExpr', 'withClass', |
| 228 |
'CloseMatch', 'tokenMap', 'pyparsing_common', 'pyparsing_unicode', 'unicode_set', |
| 229 |
'conditionAsParseAction', 're', |
| 230 |
] |
| 231 |
|
| 232 |
system_version = tuple(sys.version_info)[:3] |
| 233 |
PY_3 = system_version[0] == 3 |
| 234 |
if PY_3: |
| 235 |
_MAX_INT = sys.maxsize |
| 236 |
basestring = str |
| 237 |
unichr = chr |
| 238 |
unicode = str |
| 239 |
_ustr = str |
| 240 |
|
| 241 |
# build list of single arg builtins, that can be used as parse actions |
| 242 |
singleArgBuiltins = [sum, len, sorted, reversed, list, tuple, set, any, all, min, max] |
| 243 |
|
| 244 |
else: |
| 245 |
_MAX_INT = sys.maxint |
| 246 |
range = xrange |
| 247 |
|
| 248 |
def _ustr(obj): |
| 249 |
"""Drop-in replacement for str(obj) that tries to be Unicode |
| 250 |
friendly. It first tries str(obj). If that fails with |
| 251 |
a UnicodeEncodeError, then it tries unicode(obj). It then |
| 252 |
< returns the unicode object | encodes it with the default |
| 253 |
encoding | ... >. |
| 254 |
""" |
| 255 |
if isinstance(obj, unicode): |
| 256 |
return obj |
| 257 |
|
| 258 |
try: |
| 259 |
# If this works, then _ustr(obj) has the same behaviour as str(obj), so |
| 260 |
# it won't break any existing code. |
| 261 |
return str(obj) |
| 262 |
|
| 263 |
except UnicodeEncodeError: |
| 264 |
# Else encode it |
| 265 |
ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace') |
| 266 |
xmlcharref = Regex(r'&#\d+;') |
| 267 |
xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:]) |
| 268 |
return xmlcharref.transformString(ret) |
| 269 |
|
| 270 |
# build list of single arg builtins, tolerant of Python version, that can be used as parse actions |
| 271 |
singleArgBuiltins = [] |
| 272 |
import __builtin__ |
| 273 |
|
| 274 |
for fname in "sum len sorted reversed list tuple set any all min max".split(): |
| 275 |
try: |
| 276 |
singleArgBuiltins.append(getattr(__builtin__, fname)) |
| 277 |
except AttributeError: |
| 278 |
continue |
| 279 |
|
| 280 |
_generatorType = type((y for y in range(1))) |
| 281 |
|
| 282 |
def _xml_escape(data): |
| 283 |
"""Escape &, <, >, ", ', etc. in a string of data.""" |
| 284 |
|
| 285 |
# ampersand must be replaced first |
| 286 |
from_symbols = '&><"\'' |
| 287 |
to_symbols = ('&' + s + ';' for s in "amp gt lt quot apos".split()) |
| 288 |
for from_, to_ in zip(from_symbols, to_symbols): |
| 289 |
data = data.replace(from_, to_) |
| 290 |
return data |
| 291 |
|
| 292 |
alphas = string.ascii_uppercase + string.ascii_lowercase |
| 293 |
nums = "0123456789" |
| 294 |
hexnums = nums + "ABCDEFabcdef" |
| 295 |
alphanums = alphas + nums |
| 296 |
_bslash = chr(92) |
| 297 |
printables = "".join(c for c in string.printable if c not in string.whitespace) |
| 298 |
|
| 299 |
|
| 300 |
def conditionAsParseAction(fn, message=None, fatal=False): |
| 301 |
msg = message if message is not None else "failed user-defined condition" |
| 302 |
exc_type = ParseFatalException if fatal else ParseException |
| 303 |
fn = _trim_arity(fn) |
| 304 |
|
| 305 |
@wraps(fn) |
| 306 |
def pa(s, l, t): |
| 307 |
if not bool(fn(s, l, t)): |
| 308 |
raise exc_type(s, l, msg) |
| 309 |
|
| 310 |
return pa |
| 311 |
|
| 312 |
class ParseBaseException(Exception): |
| 313 |
"""base exception class for all parsing runtime exceptions""" |
| 314 |
# Performance tuning: we construct a *lot* of these, so keep this |
| 315 |
# constructor as small and fast as possible |
| 316 |
def __init__(self, pstr, loc=0, msg=None, elem=None): |
| 317 |
self.loc = loc |
| 318 |
if msg is None: |
| 319 |
self.msg = pstr |
| 320 |
self.pstr = "" |
| 321 |
else: |
| 322 |
self.msg = msg |
| 323 |
self.pstr = pstr |
| 324 |
self.parserElement = elem |
| 325 |
self.args = (pstr, loc, msg) |
| 326 |
|
| 327 |
@classmethod |
| 328 |
def _from_exception(cls, pe): |
| 329 |
""" |
| 330 |
internal factory method to simplify creating one type of ParseException |
| 331 |
from another - avoids having __init__ signature conflicts among subclasses |
| 332 |
""" |
| 333 |
return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) |
| 334 |
|
| 335 |
def __getattr__(self, aname): |
| 336 |
"""supported attributes by name are: |
| 337 |
- lineno - returns the line number of the exception text |
| 338 |
- col - returns the column number of the exception text |
| 339 |
- line - returns the line containing the exception text |
| 340 |
""" |
| 341 |
if aname == "lineno": |
| 342 |
return lineno(self.loc, self.pstr) |
| 343 |
elif aname in ("col", "column"): |
| 344 |
return col(self.loc, self.pstr) |
| 345 |
elif aname == "line": |
| 346 |
return line(self.loc, self.pstr) |
| 347 |
else: |
| 348 |
raise AttributeError(aname) |
| 349 |
|
| 350 |
def __str__(self): |
| 351 |
if self.pstr: |
| 352 |
if self.loc >= len(self.pstr): |
| 353 |
foundstr = ', found end of text' |
| 354 |
else: |
| 355 |
foundstr = (', found %r' % self.pstr[self.loc:self.loc + 1]).replace(r'\\', '\\') |
| 356 |
else: |
| 357 |
foundstr = '' |
| 358 |
return ("%s%s (at char %d), (line:%d, col:%d)" % |
| 359 |
(self.msg, foundstr, self.loc, self.lineno, self.column)) |
| 360 |
def __repr__(self): |
| 361 |
return _ustr(self) |
| 362 |
def markInputline(self, markerString=">!<"): |
| 363 |
"""Extracts the exception line from the input string, and marks |
| 364 |
the location of the exception with a special symbol. |
| 365 |
""" |
| 366 |
line_str = self.line |
| 367 |
line_column = self.column - 1 |
| 368 |
if markerString: |
| 369 |
line_str = "".join((line_str[:line_column], |
| 370 |
markerString, line_str[line_column:])) |
| 371 |
return line_str.strip() |
| 372 |
def __dir__(self): |
| 373 |
return "lineno col line".split() + dir(type(self)) |
| 374 |
|
| 375 |
class ParseException(ParseBaseException): |
| 376 |
""" |
| 377 |
Exception thrown when parse expressions don't match class; |
| 378 |
supported attributes by name are: |
| 379 |
- lineno - returns the line number of the exception text |
| 380 |
- col - returns the column number of the exception text |
| 381 |
- line - returns the line containing the exception text |
| 382 |
|
| 383 |
Example:: |
| 384 |
|
| 385 |
try: |
| 386 |
Word(nums).setName("integer").parseString("ABC") |
| 387 |
except ParseException as pe: |
| 388 |
print(pe) |
| 389 |
print("column: {}".format(pe.col)) |
| 390 |
|
| 391 |
prints:: |
| 392 |
|
| 393 |
Expected integer (at char 0), (line:1, col:1) |
| 394 |
column: 1 |
| 395 |
|
| 396 |
""" |
| 397 |
|
| 398 |
@staticmethod |
| 399 |
def explain(exc, depth=16): |
| 400 |
""" |
| 401 |
Method to take an exception and translate the Python internal traceback into a list |
| 402 |
of the pyparsing expressions that caused the exception to be raised. |
| 403 |
|
| 404 |
Parameters: |
| 405 |
|
| 406 |
- exc - exception raised during parsing (need not be a ParseException, in support |
| 407 |
of Python exceptions that might be raised in a parse action) |
| 408 |
- depth (default=16) - number of levels back in the stack trace to list expression |
| 409 |
and function names; if None, the full stack trace names will be listed; if 0, only |
| 410 |
the failing input line, marker, and exception string will be shown |
| 411 |
|
| 412 |
Returns a multi-line string listing the ParserElements and/or function names in the |
| 413 |
exception's stack trace. |
| 414 |
|
| 415 |
Note: the diagnostic output will include string representations of the expressions |
| 416 |
that failed to parse. These representations will be more helpful if you use `setName` to |
| 417 |
give identifiable names to your expressions. Otherwise they will use the default string |
| 418 |
forms, which may be cryptic to read. |
| 419 |
|
| 420 |
explain() is only supported under Python 3. |
| 421 |
""" |
| 422 |
import inspect |
| 423 |
|
| 424 |
if depth is None: |
| 425 |
depth = sys.getrecursionlimit() |
| 426 |
ret = [] |
| 427 |
if isinstance(exc, ParseBaseException): |
| 428 |
ret.append(exc.line) |
| 429 |
ret.append(' ' * (exc.col - 1) + '^') |
| 430 |
ret.append("{0}: {1}".format(type(exc).__name__, exc)) |
| 431 |
|
| 432 |
if depth > 0: |
| 433 |
callers = inspect.getinnerframes(exc.__traceback__, context=depth) |
| 434 |
seen = set() |
| 435 |
for i, ff in enumerate(callers[-depth:]): |
| 436 |
frm = ff[0] |
| 437 |
|
| 438 |
f_self = frm.f_locals.get('self', None) |
| 439 |
if isinstance(f_self, ParserElement): |
| 440 |
if frm.f_code.co_name not in ('parseImpl', '_parseNoCache'): |
| 441 |
continue |
| 442 |
if f_self in seen: |
| 443 |
continue |
| 444 |
seen.add(f_self) |
| 445 |
|
| 446 |
self_type = type(f_self) |
| 447 |
ret.append("{0}.{1} - {2}".format(self_type.__module__, |
| 448 |
self_type.__name__, |
| 449 |
f_self)) |
| 450 |
elif f_self is not None: |
| 451 |
self_type = type(f_self) |
| 452 |
ret.append("{0}.{1}".format(self_type.__module__, |
| 453 |
self_type.__name__)) |
| 454 |
else: |
| 455 |
code = frm.f_code |
| 456 |
if code.co_name in ('wrapper', '<module>'): |
| 457 |
continue |
| 458 |
|
| 459 |
ret.append("{0}".format(code.co_name)) |
| 460 |
|
| 461 |
depth -= 1 |
| 462 |
if not depth: |
| 463 |
break |
| 464 |
|
| 465 |
return '\n'.join(ret) |
| 466 |
|
| 467 |
|
| 468 |
class ParseFatalException(ParseBaseException): |
| 469 |
"""user-throwable exception thrown when inconsistent parse content |
| 470 |
is found; stops all parsing immediately""" |
| 471 |
pass |
| 472 |
|
| 473 |
class ParseSyntaxException(ParseFatalException): |
| 474 |
"""just like :class:`ParseFatalException`, but thrown internally |
| 475 |
when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates |
| 476 |
that parsing is to stop immediately because an unbacktrackable |
| 477 |
syntax error has been found. |
| 478 |
""" |
| 479 |
pass |
| 480 |
|
| 481 |
#~ class ReparseException(ParseBaseException): |
| 482 |
#~ """Experimental class - parse actions can raise this exception to cause |
| 483 |
#~ pyparsing to reparse the input string: |
| 484 |
#~ - with a modified input string, and/or |
| 485 |
#~ - with a modified start location |
| 486 |
#~ Set the values of the ReparseException in the constructor, and raise the |
| 487 |
#~ exception in a parse action to cause pyparsing to use the new string/location. |
| 488 |
#~ Setting the values as None causes no change to be made. |
| 489 |
#~ """ |
| 490 |
#~ def __init_( self, newstring, restartLoc ): |
| 491 |
#~ self.newParseText = newstring |
| 492 |
#~ self.reparseLoc = restartLoc |
| 493 |
|
| 494 |
class RecursiveGrammarException(Exception): |
| 495 |
"""exception thrown by :class:`ParserElement.validate` if the |
| 496 |
grammar could be improperly recursive |
| 497 |
""" |
| 498 |
def __init__(self, parseElementList): |
| 499 |
self.parseElementTrace = parseElementList |
| 500 |
|
| 501 |
def __str__(self): |
| 502 |
return "RecursiveGrammarException: %s" % self.parseElementTrace |
| 503 |
|
| 504 |
class _ParseResultsWithOffset(object): |
| 505 |
def __init__(self, p1, p2): |
| 506 |
self.tup = (p1, p2) |
| 507 |
def __getitem__(self, i): |
| 508 |
return self.tup[i] |
| 509 |
def __repr__(self): |
| 510 |
return repr(self.tup[0]) |
| 511 |
def setOffset(self, i): |
| 512 |
self.tup = (self.tup[0], i) |
| 513 |
|
| 514 |
class ParseResults(object): |
| 515 |
"""Structured parse results, to provide multiple means of access to |
| 516 |
the parsed data: |
| 517 |
|
| 518 |
- as a list (``len(results)``) |
| 519 |
- by list index (``results[0], results[1]``, etc.) |
| 520 |
- by attribute (``results.<resultsName>`` - see :class:`ParserElement.setResultsName`) |
| 521 |
|
| 522 |
Example:: |
| 523 |
|
| 524 |
integer = Word(nums) |
| 525 |
date_str = (integer.setResultsName("year") + '/' |
| 526 |
+ integer.setResultsName("month") + '/' |
| 527 |
+ integer.setResultsName("day")) |
| 528 |
# equivalent form: |
| 529 |
# date_str = integer("year") + '/' + integer("month") + '/' + integer("day") |
| 530 |
|
| 531 |
# parseString returns a ParseResults object |
| 532 |
result = date_str.parseString("1999/12/31") |
| 533 |
|
| 534 |
def test(s, fn=repr): |
| 535 |
print("%s -> %s" % (s, fn(eval(s)))) |
| 536 |
test("list(result)") |
| 537 |
test("result[0]") |
| 538 |
test("result['month']") |
| 539 |
test("result.day") |
| 540 |
test("'month' in result") |
| 541 |
test("'minutes' in result") |
| 542 |
test("result.dump()", str) |
| 543 |
|
| 544 |
prints:: |
| 545 |
|
| 546 |
list(result) -> ['1999', '/', '12', '/', '31'] |
| 547 |
result[0] -> '1999' |
| 548 |
result['month'] -> '12' |
| 549 |
result.day -> '31' |
| 550 |
'month' in result -> True |
| 551 |
'minutes' in result -> False |
| 552 |
result.dump() -> ['1999', '/', '12', '/', '31'] |
| 553 |
- day: 31 |
| 554 |
- month: 12 |
| 555 |
- year: 1999 |
| 556 |
""" |
| 557 |
def __new__(cls, toklist=None, name=None, asList=True, modal=True): |
| 558 |
if isinstance(toklist, cls): |
| 559 |
return toklist |
| 560 |
retobj = object.__new__(cls) |
| 561 |
retobj.__doinit = True |
| 562 |
return retobj |
| 563 |
|
| 564 |
# Performance tuning: we construct a *lot* of these, so keep this |
| 565 |
# constructor as small and fast as possible |
| 566 |
def __init__(self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance): |
| 567 |
if self.__doinit: |
| 568 |
self.__doinit = False |
| 569 |
self.__name = None |
| 570 |
self.__parent = None |
| 571 |
self.__accumNames = {} |
| 572 |
self.__asList = asList |
| 573 |
self.__modal = modal |
| 574 |
if toklist is None: |
| 575 |
toklist = [] |
| 576 |
if isinstance(toklist, list): |
| 577 |
self.__toklist = toklist[:] |
| 578 |
elif isinstance(toklist, _generatorType): |
| 579 |
self.__toklist = list(toklist) |
| 580 |
else: |
| 581 |
self.__toklist = [toklist] |
| 582 |
self.__tokdict = dict() |
| 583 |
|
| 584 |
if name is not None and name: |
| 585 |
if not modal: |
| 586 |
self.__accumNames[name] = 0 |
| 587 |
if isinstance(name, int): |
| 588 |
name = _ustr(name) # will always return a str, but use _ustr for consistency |
| 589 |
self.__name = name |
| 590 |
if not (isinstance(toklist, (type(None), basestring, list)) and toklist in (None, '', [])): |
| 591 |
if isinstance(toklist, basestring): |
| 592 |
toklist = [toklist] |
| 593 |
if asList: |
| 594 |
if isinstance(toklist, ParseResults): |
| 595 |
self[name] = _ParseResultsWithOffset(ParseResults(toklist.__toklist), 0) |
| 596 |
else: |
| 597 |
self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]), 0) |
| 598 |
self[name].__name = name |
| 599 |
else: |
| 600 |
try: |
| 601 |
self[name] = toklist[0] |
| 602 |
except (KeyError, TypeError, IndexError): |
| 603 |
self[name] = toklist |
| 604 |
|
| 605 |
def __getitem__(self, i): |
| 606 |
if isinstance(i, (int, slice)): |
| 607 |
return self.__toklist[i] |
| 608 |
else: |
| 609 |
if i not in self.__accumNames: |
| 610 |
return self.__tokdict[i][-1][0] |
| 611 |
else: |
| 612 |
return ParseResults([v[0] for v in self.__tokdict[i]]) |
| 613 |
|
| 614 |
def __setitem__(self, k, v, isinstance=isinstance): |
| 615 |
if isinstance(v, _ParseResultsWithOffset): |
| 616 |
self.__tokdict[k] = self.__tokdict.get(k, list()) + [v] |
| 617 |
sub = v[0] |
| 618 |
elif isinstance(k, (int, slice)): |
| 619 |
self.__toklist[k] = v |
| 620 |
sub = v |
| 621 |
else: |
| 622 |
self.__tokdict[k] = self.__tokdict.get(k, list()) + [_ParseResultsWithOffset(v, 0)] |
| 623 |
sub = v |
| 624 |
if isinstance(sub, ParseResults): |
| 625 |
sub.__parent = wkref(self) |
| 626 |
|
| 627 |
def __delitem__(self, i): |
| 628 |
if isinstance(i, (int, slice)): |
| 629 |
mylen = len(self.__toklist) |
| 630 |
del self.__toklist[i] |
| 631 |
|
| 632 |
# convert int to slice |
| 633 |
if isinstance(i, int): |
| 634 |
if i < 0: |
| 635 |
i += mylen |
| 636 |
i = slice(i, i + 1) |
| 637 |
# get removed indices |
| 638 |
removed = list(range(*i.indices(mylen))) |
| 639 |
removed.reverse() |
| 640 |
# fixup indices in token dictionary |
| 641 |
for name, occurrences in self.__tokdict.items(): |
| 642 |
for j in removed: |
| 643 |
for k, (value, position) in enumerate(occurrences): |
| 644 |
occurrences[k] = _ParseResultsWithOffset(value, position - (position > j)) |
| 645 |
else: |
| 646 |
del self.__tokdict[i] |
| 647 |
|
| 648 |
def __contains__(self, k): |
| 649 |
return k in self.__tokdict |
| 650 |
|
| 651 |
def __len__(self): |
| 652 |
return len(self.__toklist) |
| 653 |
|
| 654 |
def __bool__(self): |
| 655 |
return (not not self.__toklist) |
| 656 |
__nonzero__ = __bool__ |
| 657 |
|
| 658 |
def __iter__(self): |
| 659 |
return iter(self.__toklist) |
| 660 |
|
| 661 |
def __reversed__(self): |
| 662 |
return iter(self.__toklist[::-1]) |
| 663 |
|
| 664 |
def _iterkeys(self): |
| 665 |
if hasattr(self.__tokdict, "iterkeys"): |
| 666 |
return self.__tokdict.iterkeys() |
| 667 |
else: |
| 668 |
return iter(self.__tokdict) |
| 669 |
|
| 670 |
def _itervalues(self): |
| 671 |
return (self[k] for k in self._iterkeys()) |
| 672 |
|
| 673 |
def _iteritems(self): |
| 674 |
return ((k, self[k]) for k in self._iterkeys()) |
| 675 |
|
| 676 |
if PY_3: |
| 677 |
keys = _iterkeys |
| 678 |
"""Returns an iterator of all named result keys.""" |
| 679 |
|
| 680 |
values = _itervalues |
| 681 |
"""Returns an iterator of all named result values.""" |
| 682 |
|
| 683 |
items = _iteritems |
| 684 |
"""Returns an iterator of all named result key-value tuples.""" |
| 685 |
|
| 686 |
else: |
| 687 |
iterkeys = _iterkeys |
| 688 |
"""Returns an iterator of all named result keys (Python 2.x only).""" |
| 689 |
|
| 690 |
itervalues = _itervalues |
| 691 |
"""Returns an iterator of all named result values (Python 2.x only).""" |
| 692 |
|
| 693 |
iteritems = _iteritems |
| 694 |
"""Returns an iterator of all named result key-value tuples (Python 2.x only).""" |
| 695 |
|
| 696 |
def keys(self): |
| 697 |
"""Returns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x).""" |
| 698 |
return list(self.iterkeys()) |
| 699 |
|
| 700 |
def values(self): |
| 701 |
"""Returns all named result values (as a list in Python 2.x, as an iterator in Python 3.x).""" |
| 702 |
return list(self.itervalues()) |
| 703 |
|
| 704 |
def items(self): |
| 705 |
"""Returns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x).""" |
| 706 |
return list(self.iteritems()) |
| 707 |
|
| 708 |
def haskeys(self): |
| 709 |
"""Since keys() returns an iterator, this method is helpful in bypassing |
| 710 |
code that looks for the existence of any defined results names.""" |
| 711 |
return bool(self.__tokdict) |
| 712 |
|
| 713 |
def pop(self, *args, **kwargs): |
| 714 |
""" |
| 715 |
Removes and returns item at specified index (default= ``last``). |
| 716 |
Supports both ``list`` and ``dict`` semantics for ``pop()``. If |
| 717 |
passed no argument or an integer argument, it will use ``list`` |
| 718 |
semantics and pop tokens from the list of parsed tokens. If passed |
| 719 |
a non-integer argument (most likely a string), it will use ``dict`` |
| 720 |
semantics and pop the corresponding value from any defined results |
| 721 |
names. A second default return value argument is supported, just as in |
| 722 |
``dict.pop()``. |
| 723 |
|
| 724 |
Example:: |
| 725 |
|
| 726 |
def remove_first(tokens): |
| 727 |
tokens.pop(0) |
| 728 |
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] |
| 729 |
print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] |
| 730 |
|
| 731 |
label = Word(alphas) |
| 732 |
patt = label("LABEL") + OneOrMore(Word(nums)) |
| 733 |
print(patt.parseString("AAB 123 321").dump()) |
| 734 |
|
| 735 |
# Use pop() in a parse action to remove named result (note that corresponding value is not |
| 736 |
# removed from list form of results) |
| 737 |
def remove_LABEL(tokens): |
| 738 |
tokens.pop("LABEL") |
| 739 |
return tokens |
| 740 |
patt.addParseAction(remove_LABEL) |
| 741 |
print(patt.parseString("AAB 123 321").dump()) |
| 742 |
|
| 743 |
prints:: |
| 744 |
|
| 745 |
['AAB', '123', '321'] |
| 746 |
- LABEL: AAB |
| 747 |
|
| 748 |
['AAB', '123', '321'] |
| 749 |
""" |
| 750 |
if not args: |
| 751 |
args = [-1] |
| 752 |
for k, v in kwargs.items(): |
| 753 |
if k == 'default': |
| 754 |
args = (args[0], v) |
| 755 |
else: |
| 756 |
raise TypeError("pop() got an unexpected keyword argument '%s'" % k) |
| 757 |
if (isinstance(args[0], int) |
| 758 |
or len(args) == 1 |
| 759 |
or args[0] in self): |
| 760 |
index = args[0] |
| 761 |
ret = self[index] |
| 762 |
del self[index] |
| 763 |
return ret |
| 764 |
else: |
| 765 |
defaultvalue = args[1] |
| 766 |
return defaultvalue |
| 767 |
|
| 768 |
def get(self, key, defaultValue=None): |
| 769 |
""" |
| 770 |
Returns named result matching the given key, or if there is no |
| 771 |
such name, then returns the given ``defaultValue`` or ``None`` if no |
| 772 |
``defaultValue`` is specified. |
| 773 |
|
| 774 |
Similar to ``dict.get()``. |
| 775 |
|
| 776 |
Example:: |
| 777 |
|
| 778 |
integer = Word(nums) |
| 779 |
date_str = integer("year") + '/' + integer("month") + '/' + integer("day") |
| 780 |
|
| 781 |
result = date_str.parseString("1999/12/31") |
| 782 |
print(result.get("year")) # -> '1999' |
| 783 |
print(result.get("hour", "not specified")) # -> 'not specified' |
| 784 |
print(result.get("hour")) # -> None |
| 785 |
""" |
| 786 |
if key in self: |
| 787 |
return self[key] |
| 788 |
else: |
| 789 |
return defaultValue |
| 790 |
|
| 791 |
def insert(self, index, insStr): |
| 792 |
""" |
| 793 |
Inserts new element at location index in the list of parsed tokens. |
| 794 |
|
| 795 |
Similar to ``list.insert()``. |
| 796 |
|
| 797 |
Example:: |
| 798 |
|
| 799 |
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] |
| 800 |
|
| 801 |
# use a parse action to insert the parse location in the front of the parsed results |
| 802 |
def insert_locn(locn, tokens): |
| 803 |
tokens.insert(0, locn) |
| 804 |
print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321'] |
| 805 |
""" |
| 806 |
self.__toklist.insert(index, insStr) |
| 807 |
# fixup indices in token dictionary |
| 808 |
for name, occurrences in self.__tokdict.items(): |
| 809 |
for k, (value, position) in enumerate(occurrences): |
| 810 |
occurrences[k] = _ParseResultsWithOffset(value, position + (position > index)) |
| 811 |
|
| 812 |
def append(self, item): |
| 813 |
""" |
| 814 |
Add single element to end of ParseResults list of elements. |
| 815 |
|
| 816 |
Example:: |
| 817 |
|
| 818 |
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] |
| 819 |
|
| 820 |
# use a parse action to compute the sum of the parsed integers, and add it to the end |
| 821 |
def append_sum(tokens): |
| 822 |
tokens.append(sum(map(int, tokens))) |
| 823 |
print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444] |
| 824 |
""" |
| 825 |
self.__toklist.append(item) |
| 826 |
|
| 827 |
def extend(self, itemseq): |
| 828 |
""" |
| 829 |
Add sequence of elements to end of ParseResults list of elements. |
| 830 |
|
| 831 |
Example:: |
| 832 |
|
| 833 |
patt = OneOrMore(Word(alphas)) |
| 834 |
|
| 835 |
# use a parse action to append the reverse of the matched strings, to make a palindrome |
| 836 |
def make_palindrome(tokens): |
| 837 |
tokens.extend(reversed([t[::-1] for t in tokens])) |
| 838 |
return ''.join(tokens) |
| 839 |
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' |
| 840 |
""" |
| 841 |
if isinstance(itemseq, ParseResults): |
| 842 |
self.__iadd__(itemseq) |
| 843 |
else: |
| 844 |
self.__toklist.extend(itemseq) |
| 845 |
|
| 846 |
def clear(self): |
| 847 |
""" |
| 848 |
Clear all elements and results names. |
| 849 |
""" |
| 850 |
del self.__toklist[:] |
| 851 |
self.__tokdict.clear() |
| 852 |
|
| 853 |
def __getattr__(self, name): |
| 854 |
try: |
| 855 |
return self[name] |
| 856 |
except KeyError: |
| 857 |
return "" |
| 858 |
|
| 859 |
def __add__(self, other): |
| 860 |
ret = self.copy() |
| 861 |
ret += other |
| 862 |
return ret |
| 863 |
|
| 864 |
def __iadd__(self, other): |
| 865 |
if other.__tokdict: |
| 866 |
offset = len(self.__toklist) |
| 867 |
addoffset = lambda a: offset if a < 0 else a + offset |
| 868 |
otheritems = other.__tokdict.items() |
| 869 |
otherdictitems = [(k, _ParseResultsWithOffset(v[0], addoffset(v[1]))) |
| 870 |
for k, vlist in otheritems for v in vlist] |
| 871 |
for k, v in otherdictitems: |
| 872 |
self[k] = v |
| 873 |
if isinstance(v[0], ParseResults): |
| 874 |
v[0].__parent = wkref(self) |
| 875 |
|
| 876 |
self.__toklist += other.__toklist |
| 877 |
self.__accumNames.update(other.__accumNames) |
| 878 |
return self |
| 879 |
|
| 880 |
def __radd__(self, other): |
| 881 |
if isinstance(other, int) and other == 0: |
| 882 |
# useful for merging many ParseResults using sum() builtin |
| 883 |
return self.copy() |
| 884 |
else: |
| 885 |
# this may raise a TypeError - so be it |
| 886 |
return other + self |
| 887 |
|
| 888 |
def __repr__(self): |
| 889 |
return "(%s, %s)" % (repr(self.__toklist), repr(self.__tokdict)) |
| 890 |
|
| 891 |
def __str__(self): |
| 892 |
return '[' + ', '.join(_ustr(i) if isinstance(i, ParseResults) else repr(i) for i in self.__toklist) + ']' |
| 893 |
|
| 894 |
def _asStringList(self, sep=''): |
| 895 |
out = [] |
| 896 |
for item in self.__toklist: |
| 897 |
if out and sep: |
| 898 |
out.append(sep) |
| 899 |
if isinstance(item, ParseResults): |
| 900 |
out += item._asStringList() |
| 901 |
else: |
| 902 |
out.append(_ustr(item)) |
| 903 |
return out |
| 904 |
|
| 905 |
def asList(self): |
| 906 |
""" |
| 907 |
Returns the parse results as a nested list of matching tokens, all converted to strings. |
| 908 |
|
| 909 |
Example:: |
| 910 |
|
| 911 |
patt = OneOrMore(Word(alphas)) |
| 912 |
result = patt.parseString("sldkj lsdkj sldkj") |
| 913 |
# even though the result prints in string-like form, it is actually a pyparsing ParseResults |
| 914 |
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj'] |
| 915 |
|
| 916 |
# Use asList() to create an actual list |
| 917 |
result_list = result.asList() |
| 918 |
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj'] |
| 919 |
""" |
| 920 |
return [res.asList() if isinstance(res, ParseResults) else res for res in self.__toklist] |
| 921 |
|
| 922 |
def asDict(self): |
| 923 |
""" |
| 924 |
Returns the named parse results as a nested dictionary. |
| 925 |
|
| 926 |
Example:: |
| 927 |
|
| 928 |
integer = Word(nums) |
| 929 |
date_str = integer("year") + '/' + integer("month") + '/' + integer("day") |
| 930 |
|
| 931 |
result = date_str.parseString('12/31/1999') |
| 932 |
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) |
| 933 |
|
| 934 |
result_dict = result.asDict() |
| 935 |
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'} |
| 936 |
|
| 937 |
# even though a ParseResults supports dict-like access, sometime you just need to have a dict |
| 938 |
import json |
| 939 |
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable |
| 940 |
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"} |
| 941 |
""" |
| 942 |
if PY_3: |
| 943 |
item_fn = self.items |
| 944 |
else: |
| 945 |
item_fn = self.iteritems |
| 946 |
|
| 947 |
def toItem(obj): |
| 948 |
if isinstance(obj, ParseResults): |
| 949 |
if obj.haskeys(): |
| 950 |
return obj.asDict() |
| 951 |
else: |
| 952 |
return [toItem(v) for v in obj] |
| 953 |
else: |
| 954 |
return obj |
| 955 |
|
| 956 |
return dict((k, toItem(v)) for k, v in item_fn()) |
| 957 |
|
| 958 |
def copy(self): |
| 959 |
""" |
| 960 |
Returns a new copy of a :class:`ParseResults` object. |
| 961 |
""" |
| 962 |
ret = ParseResults(self.__toklist) |
| 963 |
ret.__tokdict = dict(self.__tokdict.items()) |
| 964 |
ret.__parent = self.__parent |
| 965 |
ret.__accumNames.update(self.__accumNames) |
| 966 |
ret.__name = self.__name |
| 967 |
return ret |
| 968 |
|
| 969 |
def asXML(self, doctag=None, namedItemsOnly=False, indent="", formatted=True): |
| 970 |
""" |
| 971 |
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. |
| 972 |
""" |
| 973 |
nl = "\n" |
| 974 |
out = [] |
| 975 |
namedItems = dict((v[1], k) for (k, vlist) in self.__tokdict.items() |
| 976 |
for v in vlist) |
| 977 |
nextLevelIndent = indent + " " |
| 978 |
|
| 979 |
# collapse out indents if formatting is not desired |
| 980 |
if not formatted: |
| 981 |
indent = "" |
| 982 |
nextLevelIndent = "" |
| 983 |
nl = "" |
| 984 |
|
| 985 |
selfTag = None |
| 986 |
if doctag is not None: |
| 987 |
selfTag = doctag |
| 988 |
else: |
| 989 |
if self.__name: |
| 990 |
selfTag = self.__name |
| 991 |
|
| 992 |
if not selfTag: |
| 993 |
if namedItemsOnly: |
| 994 |
return "" |
| 995 |
else: |
| 996 |
selfTag = "ITEM" |
| 997 |
|
| 998 |
out += [nl, indent, "<", selfTag, ">"] |
| 999 |
|
| 1000 |
for i, res in enumerate(self.__toklist): |
| 1001 |
if isinstance(res, ParseResults): |
| 1002 |
if i in namedItems: |
| 1003 |
out += [res.asXML(namedItems[i], |
| 1004 |
namedItemsOnly and doctag is None, |
| 1005 |
nextLevelIndent, |
| 1006 |
formatted)] |
| 1007 |
else: |
| 1008 |
out += [res.asXML(None, |
| 1009 |
namedItemsOnly and doctag is None, |
| 1010 |
nextLevelIndent, |
| 1011 |
formatted)] |
| 1012 |
else: |
| 1013 |
# individual token, see if there is a name for it |
| 1014 |
resTag = None |
| 1015 |
if i in namedItems: |
| 1016 |
resTag = namedItems[i] |
| 1017 |
if not resTag: |
| 1018 |
if namedItemsOnly: |
| 1019 |
continue |
| 1020 |
else: |
| 1021 |
resTag = "ITEM" |
| 1022 |
xmlBodyText = _xml_escape(_ustr(res)) |
| 1023 |
out += [nl, nextLevelIndent, "<", resTag, ">", |
| 1024 |
xmlBodyText, |
| 1025 |
"</", resTag, ">"] |
| 1026 |
|
| 1027 |
out += [nl, indent, "</", selfTag, ">"] |
| 1028 |
return "".join(out) |
| 1029 |
|
| 1030 |
def __lookup(self, sub): |
| 1031 |
for k, vlist in self.__tokdict.items(): |
| 1032 |
for v, loc in vlist: |
| 1033 |
if sub is v: |
| 1034 |
return k |
| 1035 |
return None |
| 1036 |
|
| 1037 |
def getName(self): |
| 1038 |
r""" |
| 1039 |
Returns the results name for this token expression. Useful when several |
| 1040 |
different expressions might match at a particular location. |
| 1041 |
|
| 1042 |
Example:: |
| 1043 |
|
| 1044 |
integer = Word(nums) |
| 1045 |
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") |
| 1046 |
house_number_expr = Suppress('#') + Word(nums, alphanums) |
| 1047 |
user_data = (Group(house_number_expr)("house_number") |
| 1048 |
| Group(ssn_expr)("ssn") |
| 1049 |
| Group(integer)("age")) |
| 1050 |
user_info = OneOrMore(user_data) |
| 1051 |
|
| 1052 |
result = user_info.parseString("22 111-22-3333 #221B") |
| 1053 |
for item in result: |
| 1054 |
print(item.getName(), ':', item[0]) |
| 1055 |
|
| 1056 |
prints:: |
| 1057 |
|
| 1058 |
age : 22 |
| 1059 |
ssn : 111-22-3333 |
| 1060 |
house_number : 221B |
| 1061 |
""" |
| 1062 |
if self.__name: |
| 1063 |
return self.__name |
| 1064 |
elif self.__parent: |
| 1065 |
par = self.__parent() |
| 1066 |
if par: |
| 1067 |
return par.__lookup(self) |
| 1068 |
else: |
| 1069 |
return None |
| 1070 |
elif (len(self) == 1 |
| 1071 |
and len(self.__tokdict) == 1 |
| 1072 |
and next(iter(self.__tokdict.values()))[0][1] in (0, -1)): |
| 1073 |
return next(iter(self.__tokdict.keys())) |
| 1074 |
else: |
| 1075 |
return None |
| 1076 |
|
| 1077 |
def dump(self, indent='', full=True, include_list=True, _depth=0): |
| 1078 |
""" |
| 1079 |
Diagnostic method for listing out the contents of |
| 1080 |
a :class:`ParseResults`. Accepts an optional ``indent`` argument so |
| 1081 |
that this string can be embedded in a nested display of other data. |
| 1082 |
|
| 1083 |
Example:: |
| 1084 |
|
| 1085 |
integer = Word(nums) |
| 1086 |
date_str = integer("year") + '/' + integer("month") + '/' + integer("day") |
| 1087 |
|
| 1088 |
result = date_str.parseString('12/31/1999') |
| 1089 |
print(result.dump()) |
| 1090 |
|
| 1091 |
prints:: |
| 1092 |
|
| 1093 |
['12', '/', '31', '/', '1999'] |
| 1094 |
- day: 1999 |
| 1095 |
- month: 31 |
| 1096 |
- year: 12 |
| 1097 |
""" |
| 1098 |
out = [] |
| 1099 |
NL = '\n' |
| 1100 |
if include_list: |
| 1101 |
out.append(indent + _ustr(self.asList())) |
| 1102 |
else: |
| 1103 |
out.append('') |
| 1104 |
|
| 1105 |
if full: |
| 1106 |
if self.haskeys(): |
| 1107 |
items = sorted((str(k), v) for k, v in self.items()) |
| 1108 |
for k, v in items: |
| 1109 |
if out: |
| 1110 |
out.append(NL) |
| 1111 |
out.append("%s%s- %s: " % (indent, (' ' * _depth), k)) |
| 1112 |
if isinstance(v, ParseResults): |
| 1113 |
if v: |
| 1114 |
out.append(v.dump(indent=indent, full=full, include_list=include_list, _depth=_depth + 1)) |
| 1115 |
else: |
| 1116 |
out.append(_ustr(v)) |
| 1117 |
else: |
| 1118 |
out.append(repr(v)) |
| 1119 |
elif any(isinstance(vv, ParseResults) for vv in self): |
| 1120 |
v = self |
| 1121 |
for i, vv in enumerate(v): |
| 1122 |
if isinstance(vv, ParseResults): |
| 1123 |
out.append("\n%s%s[%d]:\n%s%s%s" % (indent, |
| 1124 |
(' ' * (_depth)), |
| 1125 |
i, |
| 1126 |
indent, |
| 1127 |
(' ' * (_depth + 1)), |
| 1128 |
vv.dump(indent=indent, |
| 1129 |
full=full, |
| 1130 |
include_list=include_list, |
| 1131 |
_depth=_depth + 1))) |
| 1132 |
else: |
| 1133 |
out.append("\n%s%s[%d]:\n%s%s%s" % (indent, |
| 1134 |
(' ' * (_depth)), |
| 1135 |
i, |
| 1136 |
indent, |
| 1137 |
(' ' * (_depth + 1)), |
| 1138 |
_ustr(vv))) |
| 1139 |
|
| 1140 |
return "".join(out) |
| 1141 |
|
| 1142 |
def pprint(self, *args, **kwargs): |
| 1143 |
""" |
| 1144 |
Pretty-printer for parsed results as a list, using the |
| 1145 |
`pprint <https://docs.python.org/3/library/pprint.html>`_ module. |
| 1146 |
Accepts additional positional or keyword args as defined for |
| 1147 |
`pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ . |
| 1148 |
|
| 1149 |
Example:: |
| 1150 |
|
| 1151 |
ident = Word(alphas, alphanums) |
| 1152 |
num = Word(nums) |
| 1153 |
func = Forward() |
| 1154 |
term = ident | num | Group('(' + func + ')') |
| 1155 |
func <<= ident + Group(Optional(delimitedList(term))) |
| 1156 |
result = func.parseString("fna a,b,(fnb c,d,200),100") |
| 1157 |
result.pprint(width=40) |
| 1158 |
|
| 1159 |
prints:: |
| 1160 |
|
| 1161 |
['fna', |
| 1162 |
['a', |
| 1163 |
'b', |
| 1164 |
['(', 'fnb', ['c', 'd', '200'], ')'], |
| 1165 |
'100']] |
| 1166 |
""" |
| 1167 |
pprint.pprint(self.asList(), *args, **kwargs) |
| 1168 |
|
| 1169 |
# add support for pickle protocol |
| 1170 |
def __getstate__(self): |
| 1171 |
return (self.__toklist, |
| 1172 |
(self.__tokdict.copy(), |
| 1173 |
self.__parent is not None and self.__parent() or None, |
| 1174 |
self.__accumNames, |
| 1175 |
self.__name)) |
| 1176 |
|
| 1177 |
def __setstate__(self, state): |
| 1178 |
self.__toklist = state[0] |
| 1179 |
self.__tokdict, par, inAccumNames, self.__name = state[1] |
| 1180 |
self.__accumNames = {} |
| 1181 |
self.__accumNames.update(inAccumNames) |
| 1182 |
if par is not None: |
| 1183 |
self.__parent = wkref(par) |
| 1184 |
else: |
| 1185 |
self.__parent = None |
| 1186 |
|
| 1187 |
def __getnewargs__(self): |
| 1188 |
return self.__toklist, self.__name, self.__asList, self.__modal |
| 1189 |
|
| 1190 |
def __dir__(self): |
| 1191 |
return dir(type(self)) + list(self.keys()) |
| 1192 |
|
| 1193 |
@classmethod |
| 1194 |
def from_dict(cls, other, name=None): |
| 1195 |
""" |
| 1196 |
Helper classmethod to construct a ParseResults from a dict, preserving the |
| 1197 |
name-value relations as results names. If an optional 'name' argument is |
| 1198 |
given, a nested ParseResults will be returned |
| 1199 |
""" |
| 1200 |
def is_iterable(obj): |
| 1201 |
try: |
| 1202 |
iter(obj) |
| 1203 |
except Exception: |
| 1204 |
return False |
| 1205 |
else: |
| 1206 |
if PY_3: |
| 1207 |
return not isinstance(obj, (str, bytes)) |
| 1208 |
else: |
| 1209 |
return not isinstance(obj, basestring) |
| 1210 |
|
| 1211 |
ret = cls([]) |
| 1212 |
for k, v in other.items(): |
| 1213 |
if isinstance(v, Mapping): |
| 1214 |
ret += cls.from_dict(v, name=k) |
| 1215 |
else: |
| 1216 |
ret += cls([v], name=k, asList=is_iterable(v)) |
| 1217 |
if name is not None: |
| 1218 |
ret = cls([ret], name=name) |
| 1219 |
return ret |
| 1220 |
|
| 1221 |
MutableMapping.register(ParseResults) |
| 1222 |
|
| 1223 |
def col (loc, strg): |
| 1224 |
"""Returns current column within a string, counting newlines as line separators. |
| 1225 |
The first column is number 1. |
| 1226 |
|
| 1227 |
Note: the default parsing behavior is to expand tabs in the input string |
| 1228 |
before starting the parsing process. See |
| 1229 |
:class:`ParserElement.parseString` for more |
| 1230 |
information on parsing strings containing ``<TAB>`` s, and suggested |
| 1231 |
methods to maintain a consistent view of the parsed string, the parse |
| 1232 |
location, and line and column positions within the parsed string. |
| 1233 |
""" |
| 1234 |
s = strg |
| 1235 |
return 1 if 0 < loc < len(s) and s[loc-1] == '\n' else loc - s.rfind("\n", 0, loc) |
| 1236 |
|
| 1237 |
def lineno(loc, strg): |
| 1238 |
"""Returns current line number within a string, counting newlines as line separators. |
| 1239 |
The first line is number 1. |
| 1240 |
|
| 1241 |
Note - the default parsing behavior is to expand tabs in the input string |
| 1242 |
before starting the parsing process. See :class:`ParserElement.parseString` |
| 1243 |
for more information on parsing strings containing ``<TAB>`` s, and |
| 1244 |
suggested methods to maintain a consistent view of the parsed string, the |
| 1245 |
parse location, and line and column positions within the parsed string. |
| 1246 |
""" |
| 1247 |
return strg.count("\n", 0, loc) + 1 |
| 1248 |
|
| 1249 |
def line(loc, strg): |
| 1250 |
"""Returns the line of text containing loc within a string, counting newlines as line separators. |
| 1251 |
""" |
| 1252 |
lastCR = strg.rfind("\n", 0, loc) |
| 1253 |
nextCR = strg.find("\n", loc) |
| 1254 |
if nextCR >= 0: |
| 1255 |
return strg[lastCR + 1:nextCR] |
| 1256 |
else: |
| 1257 |
return strg[lastCR + 1:] |
| 1258 |
|
| 1259 |
def _defaultStartDebugAction(instring, loc, expr): |
| 1260 |
print(("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % (lineno(loc, instring), col(loc, instring)))) |
| 1261 |
|
| 1262 |
def _defaultSuccessDebugAction(instring, startloc, endloc, expr, toks): |
| 1263 |
print("Matched " + _ustr(expr) + " -> " + str(toks.asList())) |
| 1264 |
|
| 1265 |
def _defaultExceptionDebugAction(instring, loc, expr, exc): |
| 1266 |
print("Exception raised:" + _ustr(exc)) |
| 1267 |
|
| 1268 |
def nullDebugAction(*args): |
| 1269 |
"""'Do-nothing' debug action, to suppress debugging output during parsing.""" |
| 1270 |
pass |
| 1271 |
|
| 1272 |
# Only works on Python 3.x - nonlocal is toxic to Python 2 installs |
| 1273 |
#~ 'decorator to trim function calls to match the arity of the target' |
| 1274 |
#~ def _trim_arity(func, maxargs=3): |
| 1275 |
#~ if func in singleArgBuiltins: |
| 1276 |
#~ return lambda s,l,t: func(t) |
| 1277 |
#~ limit = 0 |
| 1278 |
#~ foundArity = False |
| 1279 |
#~ def wrapper(*args): |
| 1280 |
#~ nonlocal limit,foundArity |
| 1281 |
#~ while 1: |
| 1282 |
#~ try: |
| 1283 |
#~ ret = func(*args[limit:]) |
| 1284 |
#~ foundArity = True |
| 1285 |
#~ return ret |
| 1286 |
#~ except TypeError: |
| 1287 |
#~ if limit == maxargs or foundArity: |
| 1288 |
#~ raise |
| 1289 |
#~ limit += 1 |
| 1290 |
#~ continue |
| 1291 |
#~ return wrapper |
| 1292 |
|
| 1293 |
# this version is Python 2.x-3.x cross-compatible |
| 1294 |
'decorator to trim function calls to match the arity of the target' |
| 1295 |
def _trim_arity(func, maxargs=2): |
| 1296 |
if func in singleArgBuiltins: |
| 1297 |
return lambda s, l, t: func(t) |
| 1298 |
limit = [0] |
| 1299 |
foundArity = [False] |
| 1300 |
|
| 1301 |
# traceback return data structure changed in Py3.5 - normalize back to plain tuples |
| 1302 |
if system_version[:2] >= (3, 5): |
| 1303 |
def extract_stack(limit=0): |
| 1304 |
# special handling for Python 3.5.0 - extra deep call stack by 1 |
| 1305 |
offset = -3 if system_version == (3, 5, 0) else -2 |
| 1306 |
frame_summary = traceback.extract_stack(limit=-offset + limit - 1)[offset] |
| 1307 |
return [frame_summary[:2]] |
| 1308 |
def extract_tb(tb, limit=0): |
| 1309 |
frames = traceback.extract_tb(tb, limit=limit) |
| 1310 |
frame_summary = frames[-1] |
| 1311 |
return [frame_summary[:2]] |
| 1312 |
else: |
| 1313 |
extract_stack = traceback.extract_stack |
| 1314 |
extract_tb = traceback.extract_tb |
| 1315 |
|
| 1316 |
# synthesize what would be returned by traceback.extract_stack at the call to |
| 1317 |
# user's parse action 'func', so that we don't incur call penalty at parse time |
| 1318 |
|
| 1319 |
LINE_DIFF = 6 |
| 1320 |
# IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND |
| 1321 |
# THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!! |
| 1322 |
this_line = extract_stack(limit=2)[-1] |
| 1323 |
pa_call_line_synth = (this_line[0], this_line[1] + LINE_DIFF) |
| 1324 |
|
| 1325 |
def wrapper(*args): |
| 1326 |
while 1: |
| 1327 |
try: |
| 1328 |
ret = func(*args[limit[0]:]) |
| 1329 |
foundArity[0] = True |
| 1330 |
return ret |
| 1331 |
except TypeError: |
| 1332 |
# re-raise TypeErrors if they did not come from our arity testing |
| 1333 |
if foundArity[0]: |
| 1334 |
raise |
| 1335 |
else: |
| 1336 |
try: |
| 1337 |
tb = sys.exc_info()[-1] |
| 1338 |
if not extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth: |
| 1339 |
raise |
| 1340 |
finally: |
| 1341 |
try: |
| 1342 |
del tb |
| 1343 |
except NameError: |
| 1344 |
pass |
| 1345 |
|
| 1346 |
if limit[0] <= maxargs: |
| 1347 |
limit[0] += 1 |
| 1348 |
continue |
| 1349 |
raise |
| 1350 |
|
| 1351 |
# copy func name to wrapper for sensible debug output |
| 1352 |
func_name = "<parse action>" |
| 1353 |
try: |
| 1354 |
func_name = getattr(func, '__name__', |
| 1355 |
getattr(func, '__class__').__name__) |
| 1356 |
except Exception: |
| 1357 |
func_name = str(func) |
| 1358 |
wrapper.__name__ = func_name |
| 1359 |
|
| 1360 |
return wrapper |
| 1361 |
|
| 1362 |
|
| 1363 |
class ParserElement(object): |
| 1364 |
"""Abstract base level parser element class.""" |
| 1365 |
DEFAULT_WHITE_CHARS = " \n\t\r" |
| 1366 |
verbose_stacktrace = False |
| 1367 |
|
| 1368 |
@staticmethod |
| 1369 |
def setDefaultWhitespaceChars(chars): |
| 1370 |
r""" |
| 1371 |
Overrides the default whitespace chars |
| 1372 |
|
| 1373 |
Example:: |
| 1374 |
|
| 1375 |
# default whitespace chars are space, <TAB> and newline |
| 1376 |
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] |
| 1377 |
|
| 1378 |
# change to just treat newline as significant |
| 1379 |
ParserElement.setDefaultWhitespaceChars(" \t") |
| 1380 |
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def'] |
| 1381 |
""" |
| 1382 |
ParserElement.DEFAULT_WHITE_CHARS = chars |
| 1383 |
|
| 1384 |
@staticmethod |
| 1385 |
def inlineLiteralsUsing(cls): |
| 1386 |
""" |
| 1387 |
Set class to be used for inclusion of string literals into a parser. |
| 1388 |
|
| 1389 |
Example:: |
| 1390 |
|
| 1391 |
# default literal class used is Literal |
| 1392 |
integer = Word(nums) |
| 1393 |
date_str = integer("year") + '/' + integer("month") + '/' + integer("day") |
| 1394 |
|
| 1395 |
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] |
| 1396 |
|
| 1397 |
|
| 1398 |
# change to Suppress |
| 1399 |
ParserElement.inlineLiteralsUsing(Suppress) |
| 1400 |
date_str = integer("year") + '/' + integer("month") + '/' + integer("day") |
| 1401 |
|
| 1402 |
date_str.parseString("1999/12/31") # -> ['1999', '12', '31'] |
| 1403 |
""" |
| 1404 |
ParserElement._literalStringClass = cls |
| 1405 |
|
| 1406 |
@classmethod |
| 1407 |
def _trim_traceback(cls, tb): |
| 1408 |
while tb.tb_next: |
| 1409 |
tb = tb.tb_next |
| 1410 |
return tb |
| 1411 |
|
| 1412 |
def __init__(self, savelist=False): |
| 1413 |
self.parseAction = list() |
| 1414 |
self.failAction = None |
| 1415 |
# ~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall |
| 1416 |
self.strRepr = None |
| 1417 |
self.resultsName = None |
| 1418 |
self.saveAsList = savelist |
| 1419 |
self.skipWhitespace = True |
| 1420 |
self.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS) |
| 1421 |
self.copyDefaultWhiteChars = True |
| 1422 |
self.mayReturnEmpty = False # used when checking for left-recursion |
| 1423 |
self.keepTabs = False |
| 1424 |
self.ignoreExprs = list() |
| 1425 |
self.debug = False |
| 1426 |
self.streamlined = False |
| 1427 |
self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index |
| 1428 |
self.errmsg = "" |
| 1429 |
self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all) |
| 1430 |
self.debugActions = (None, None, None) # custom debug actions |
| 1431 |
self.re = None |
| 1432 |
self.callPreparse = True # used to avoid redundant calls to preParse |
| 1433 |
self.callDuringTry = False |
| 1434 |
|
| 1435 |
def copy(self): |
| 1436 |
""" |
| 1437 |
Make a copy of this :class:`ParserElement`. Useful for defining |
| 1438 |
different parse actions for the same parsing pattern, using copies of |
| 1439 |
the original parse element. |
| 1440 |
|
| 1441 |
Example:: |
| 1442 |
|
| 1443 |
integer = Word(nums).setParseAction(lambda toks: int(toks[0])) |
| 1444 |
integerK = integer.copy().addParseAction(lambda toks: toks[0] * 1024) + Suppress("K") |
| 1445 |
integerM = integer.copy().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M") |
| 1446 |
|
| 1447 |
print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M")) |
| 1448 |
|
| 1449 |
prints:: |
| 1450 |
|
| 1451 |
[5120, 100, 655360, 268435456] |
| 1452 |
|
| 1453 |
Equivalent form of ``expr.copy()`` is just ``expr()``:: |
| 1454 |
|
| 1455 |
integerM = integer().addParseAction(lambda toks: toks[0] * 1024 * 1024) + Suppress("M") |
| 1456 |
""" |
| 1457 |
cpy = copy.copy(self) |
| 1458 |
cpy.parseAction = self.parseAction[:] |
| 1459 |
cpy.ignoreExprs = self.ignoreExprs[:] |
| 1460 |
if self.copyDefaultWhiteChars: |
| 1461 |
cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS |
| 1462 |
return cpy |
| 1463 |
|
| 1464 |
def setName(self, name): |
| 1465 |
""" |
| 1466 |
Define name for this expression, makes debugging and exception messages clearer. |
| 1467 |
|
| 1468 |
Example:: |
| 1469 |
|
| 1470 |
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) |
| 1471 |
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) |
| 1472 |
""" |
| 1473 |
self.name = name |
| 1474 |
self.errmsg = "Expected " + self.name |
| 1475 |
if __diag__.enable_debug_on_named_expressions: |
| 1476 |
self.setDebug() |
| 1477 |
return self |
| 1478 |
|
| 1479 |
def setResultsName(self, name, listAllMatches=False): |
| 1480 |
""" |
| 1481 |
Define name for referencing matching tokens as a nested attribute |
| 1482 |
of the returned parse results. |
| 1483 |
NOTE: this returns a *copy* of the original :class:`ParserElement` object; |
| 1484 |
this is so that the client can define a basic element, such as an |
| 1485 |
integer, and reference it in multiple places with different names. |
| 1486 |
|
| 1487 |
You can also set results names using the abbreviated syntax, |
| 1488 |
``expr("name")`` in place of ``expr.setResultsName("name")`` |
| 1489 |
- see :class:`__call__`. |
| 1490 |
|
| 1491 |
Example:: |
| 1492 |
|
| 1493 |
date_str = (integer.setResultsName("year") + '/' |
| 1494 |
+ integer.setResultsName("month") + '/' |
| 1495 |
+ integer.setResultsName("day")) |
| 1496 |
|
| 1497 |
# equivalent form: |
| 1498 |
date_str = integer("year") + '/' + integer("month") + '/' + integer("day") |
| 1499 |
""" |
| 1500 |
return self._setResultsName(name, listAllMatches) |
| 1501 |
|
| 1502 |
def _setResultsName(self, name, listAllMatches=False): |
| 1503 |
newself = self.copy() |
| 1504 |
if name.endswith("*"): |
| 1505 |
name = name[:-1] |
| 1506 |
listAllMatches = True |
| 1507 |
newself.resultsName = name |
| 1508 |
newself.modalResults = not listAllMatches |
| 1509 |
return newself |
| 1510 |
|
| 1511 |
def setBreak(self, breakFlag=True): |
| 1512 |
"""Method to invoke the Python pdb debugger when this element is |
| 1513 |
about to be parsed. Set ``breakFlag`` to True to enable, False to |
| 1514 |
disable. |
| 1515 |
""" |
| 1516 |
if breakFlag: |
| 1517 |
_parseMethod = self._parse |
| 1518 |
def breaker(instring, loc, doActions=True, callPreParse=True): |
| 1519 |
import pdb |
| 1520 |
# this call to pdb.set_trace() is intentional, not a checkin error |
| 1521 |
pdb.set_trace() |
| 1522 |
return _parseMethod(instring, loc, doActions, callPreParse) |
| 1523 |
breaker._originalParseMethod = _parseMethod |
| 1524 |
self._parse = breaker |
| 1525 |
else: |
| 1526 |
if hasattr(self._parse, "_originalParseMethod"): |
| 1527 |
self._parse = self._parse._originalParseMethod |
| 1528 |
return self |
| 1529 |
|
| 1530 |
def setParseAction(self, *fns, **kwargs): |
| 1531 |
""" |
| 1532 |
Define one or more actions to perform when successfully matching parse element definition. |
| 1533 |
Parse action fn is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` , |
| 1534 |
``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where: |
| 1535 |
|
| 1536 |
- s = the original string being parsed (see note below) |
| 1537 |
- loc = the location of the matching substring |
| 1538 |
- toks = a list of the matched tokens, packaged as a :class:`ParseResults` object |
| 1539 |
|
| 1540 |
If the functions in fns modify the tokens, they can return them as the return |
| 1541 |
value from fn, and the modified list of tokens will replace the original. |
| 1542 |
Otherwise, fn does not need to return any value. |
| 1543 |
|
| 1544 |
If None is passed as the parse action, all previously added parse actions for this |
| 1545 |
expression are cleared. |
| 1546 |
|
| 1547 |
Optional keyword arguments: |
| 1548 |
- callDuringTry = (default= ``False``) indicate if parse action should be run during lookaheads and alternate testing |
| 1549 |
|
| 1550 |
Note: the default parsing behavior is to expand tabs in the input string |
| 1551 |
before starting the parsing process. See :class:`parseString for more |
| 1552 |
information on parsing strings containing ``<TAB>`` s, and suggested |
| 1553 |
methods to maintain a consistent view of the parsed string, the parse |
| 1554 |
location, and line and column positions within the parsed string. |
| 1555 |
|
| 1556 |
Example:: |
| 1557 |
|
| 1558 |
integer = Word(nums) |
| 1559 |
date_str = integer + '/' + integer + '/' + integer |
| 1560 |
|
| 1561 |
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] |
| 1562 |
|
| 1563 |
# use parse action to convert to ints at parse time |
| 1564 |
integer = Word(nums).setParseAction(lambda toks: int(toks[0])) |
| 1565 |
date_str = integer + '/' + integer + '/' + integer |
| 1566 |
|
| 1567 |
# note that integer fields are now ints, not strings |
| 1568 |
date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] |
| 1569 |
""" |
| 1570 |
if list(fns) == [None,]: |
| 1571 |
self.parseAction = [] |
| 1572 |
else: |
| 1573 |
if not all(callable(fn) for fn in fns): |
| 1574 |
raise TypeError("parse actions must be callable") |
| 1575 |
self.parseAction = list(map(_trim_arity, list(fns))) |
| 1576 |
self.callDuringTry = kwargs.get("callDuringTry", False) |
| 1577 |
return self |
| 1578 |
|
| 1579 |
def addParseAction(self, *fns, **kwargs): |
| 1580 |
""" |
| 1581 |
Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`. |
| 1582 |
|
| 1583 |
See examples in :class:`copy`. |
| 1584 |
""" |
| 1585 |
self.parseAction += list(map(_trim_arity, list(fns))) |
| 1586 |
self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) |
| 1587 |
return self |
| 1588 |
|
| 1589 |
def addCondition(self, *fns, **kwargs): |
| 1590 |
"""Add a boolean predicate function to expression's list of parse actions. See |
| 1591 |
:class:`setParseAction` for function call signatures. Unlike ``setParseAction``, |
| 1592 |
functions passed to ``addCondition`` need to return boolean success/fail of the condition. |
| 1593 |
|
| 1594 |
Optional keyword arguments: |
| 1595 |
- message = define a custom message to be used in the raised exception |
| 1596 |
- fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException |
| 1597 |
|
| 1598 |
Example:: |
| 1599 |
|
| 1600 |
integer = Word(nums).setParseAction(lambda toks: int(toks[0])) |
| 1601 |
year_int = integer.copy() |
| 1602 |
year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") |
| 1603 |
date_str = year_int + '/' + integer + '/' + integer |
| 1604 |
|
| 1605 |
result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) |
| 1606 |
""" |
| 1607 |
for fn in fns: |
| 1608 |
self.parseAction.append(conditionAsParseAction(fn, message=kwargs.get('message'), |
| 1609 |
fatal=kwargs.get('fatal', False))) |
| 1610 |
|
| 1611 |
self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) |
| 1612 |
return self |
| 1613 |
|
| 1614 |
def setFailAction(self, fn): |
| 1615 |
"""Define action to perform if parsing fails at this expression. |
| 1616 |
Fail acton fn is a callable function that takes the arguments |
| 1617 |
``fn(s, loc, expr, err)`` where: |
| 1618 |
- s = string being parsed |
| 1619 |
- loc = location where expression match was attempted and failed |
| 1620 |
- expr = the parse expression that failed |
| 1621 |
- err = the exception thrown |
| 1622 |
The function returns no value. It may throw :class:`ParseFatalException` |
| 1623 |
if it is desired to stop parsing immediately.""" |
| 1624 |
self.failAction = fn |
| 1625 |
return self |
| 1626 |
|
| 1627 |
def _skipIgnorables(self, instring, loc): |
| 1628 |
exprsFound = True |
| 1629 |
while exprsFound: |
| 1630 |
exprsFound = False |
| 1631 |
for e in self.ignoreExprs: |
| 1632 |
try: |
| 1633 |
while 1: |
| 1634 |
loc, dummy = e._parse(instring, loc) |
| 1635 |
exprsFound = True |
| 1636 |
except ParseException: |
| 1637 |
pass |
| 1638 |
return loc |
| 1639 |
|
| 1640 |
def preParse(self, instring, loc): |
| 1641 |
if self.ignoreExprs: |
| 1642 |
loc = self._skipIgnorables(instring, loc) |
| 1643 |
|
| 1644 |
if self.skipWhitespace: |
| 1645 |
wt = self.whiteChars |
| 1646 |
instrlen = len(instring) |
| 1647 |
while loc < instrlen and instring[loc] in wt: |
| 1648 |
loc += 1 |
| 1649 |
|
| 1650 |
return loc |
| 1651 |
|
| 1652 |
def parseImpl(self, instring, loc, doActions=True): |
| 1653 |
return loc, [] |
| 1654 |
|
| 1655 |
def postParse(self, instring, loc, tokenlist): |
| 1656 |
return tokenlist |
| 1657 |
|
| 1658 |
# ~ @profile |
| 1659 |
def _parseNoCache(self, instring, loc, doActions=True, callPreParse=True): |
| 1660 |
TRY, MATCH, FAIL = 0, 1, 2 |
| 1661 |
debugging = (self.debug) # and doActions) |
| 1662 |
|
| 1663 |
if debugging or self.failAction: |
| 1664 |
# ~ print ("Match", self, "at loc", loc, "(%d, %d)" % (lineno(loc, instring), col(loc, instring))) |
| 1665 |
if self.debugActions[TRY]: |
| 1666 |
self.debugActions[TRY](instring, loc, self) |
| 1667 |
try: |
| 1668 |
if callPreParse and self.callPreparse: |
| 1669 |
preloc = self.preParse(instring, loc) |
| 1670 |
else: |
| 1671 |
preloc = loc |
| 1672 |
tokensStart = preloc |
| 1673 |
if self.mayIndexError or preloc >= len(instring): |
| 1674 |
try: |
| 1675 |
loc, tokens = self.parseImpl(instring, preloc, doActions) |
| 1676 |
except IndexError: |
| 1677 |
raise ParseException(instring, len(instring), self.errmsg, self) |
| 1678 |
else: |
| 1679 |
loc, tokens = self.parseImpl(instring, preloc, doActions) |
| 1680 |
except Exception as err: |
| 1681 |
# ~ print ("Exception raised:", err) |
| 1682 |
if self.debugActions[FAIL]: |
| 1683 |
self.debugActions[FAIL](instring, tokensStart, self, err) |
| 1684 |
if self.failAction: |
| 1685 |
self.failAction(instring, tokensStart, self, err) |
| 1686 |
raise |
| 1687 |
else: |
| 1688 |
if callPreParse and self.callPreparse: |
| 1689 |
preloc = self.preParse(instring, loc) |
| 1690 |
else: |
| 1691 |
preloc = loc |
| 1692 |
tokensStart = preloc |
| 1693 |
if self.mayIndexError or preloc >= len(instring): |
| 1694 |
try: |
| 1695 |
loc, tokens = self.parseImpl(instring, preloc, doActions) |
| 1696 |
except IndexError: |
| 1697 |
raise ParseException(instring, len(instring), self.errmsg, self) |
| 1698 |
else: |
| 1699 |
loc, tokens = self.parseImpl(instring, preloc, doActions) |
| 1700 |
|
| 1701 |
tokens = self.postParse(instring, loc, tokens) |
| 1702 |
|
| 1703 |
retTokens = ParseResults(tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults) |
| 1704 |
if self.parseAction and (doActions or self.callDuringTry): |
| 1705 |
if debugging: |
| 1706 |
try: |
| 1707 |
for fn in self.parseAction: |
| 1708 |
try: |
| 1709 |
tokens = fn(instring, tokensStart, retTokens) |
| 1710 |
except IndexError as parse_action_exc: |
| 1711 |
exc = ParseException("exception raised in parse action") |
| 1712 |
exc.__cause__ = parse_action_exc |
| 1713 |
raise exc |
| 1714 |
|
| 1715 |
if tokens is not None and tokens is not retTokens: |
| 1716 |
retTokens = ParseResults(tokens, |
| 1717 |
self.resultsName, |
| 1718 |
asList=self.saveAsList and isinstance(tokens, (ParseResults, list)), |
| 1719 |
modal=self.modalResults) |
| 1720 |
except Exception as err: |
| 1721 |
# ~ print "Exception raised in user parse action:", err |
| 1722 |
if self.debugActions[FAIL]: |
| 1723 |
self.debugActions[FAIL](instring, tokensStart, self, err) |
| 1724 |
raise |
| 1725 |
else: |
| 1726 |
for fn in self.parseAction: |
| 1727 |
try: |
| 1728 |
tokens = fn(instring, tokensStart, retTokens) |
| 1729 |
except IndexError as parse_action_exc: |
| 1730 |
exc = ParseException("exception raised in parse action") |
| 1731 |
exc.__cause__ = parse_action_exc |
| 1732 |
raise exc |
| 1733 |
|
| 1734 |
if tokens is not None and tokens is not retTokens: |
| 1735 |
retTokens = ParseResults(tokens, |
| 1736 |
self.resultsName, |
| 1737 |
asList=self.saveAsList and isinstance(tokens, (ParseResults, list)), |
| 1738 |
modal=self.modalResults) |
| 1739 |
if debugging: |
| 1740 |
# ~ print ("Matched", self, "->", retTokens.asList()) |
| 1741 |
if self.debugActions[MATCH]: |
| 1742 |
self.debugActions[MATCH](instring, tokensStart, loc, self, retTokens) |
| 1743 |
|
| 1744 |
return loc, retTokens |
| 1745 |
|
| 1746 |
def tryParse(self, instring, loc): |
| 1747 |
try: |
| 1748 |
return self._parse(instring, loc, doActions=False)[0] |
| 1749 |
except ParseFatalException: |
| 1750 |
raise ParseException(instring, loc, self.errmsg, self) |
| 1751 |
|
| 1752 |
def canParseNext(self, instring, loc): |
| 1753 |
try: |
| 1754 |
self.tryParse(instring, loc) |
| 1755 |
except (ParseException, IndexError): |
| 1756 |
return False |
| 1757 |
else: |
| 1758 |
return True |
| 1759 |
|
| 1760 |
class _UnboundedCache(object): |
| 1761 |
def __init__(self): |
| 1762 |
cache = {} |
| 1763 |
self.not_in_cache = not_in_cache = object() |
| 1764 |
|
| 1765 |
def get(self, key): |
| 1766 |
return cache.get(key, not_in_cache) |
| 1767 |
|
| 1768 |
def set(self, key, value): |
| 1769 |
cache[key] = value |
| 1770 |
|
| 1771 |
def clear(self): |
| 1772 |
cache.clear() |
| 1773 |
|
| 1774 |
def cache_len(self): |
| 1775 |
return len(cache) |
| 1776 |
|
| 1777 |
self.get = types.MethodType(get, self) |
| 1778 |
self.set = types.MethodType(set, self) |
| 1779 |
self.clear = types.MethodType(clear, self) |
| 1780 |
self.__len__ = types.MethodType(cache_len, self) |
| 1781 |
|
| 1782 |
if _OrderedDict is not None: |
| 1783 |
class _FifoCache(object): |
| 1784 |
def __init__(self, size): |
| 1785 |
self.not_in_cache = not_in_cache = object() |
| 1786 |
|
| 1787 |
cache = _OrderedDict() |
| 1788 |
|
| 1789 |
def get(self, key): |
| 1790 |
return cache.get(key, not_in_cache) |
| 1791 |
|
| 1792 |
def set(self, key, value): |
| 1793 |
cache[key] = value |
| 1794 |
while len(cache) > size: |
| 1795 |
try: |
| 1796 |
cache.popitem(False) |
| 1797 |
except KeyError: |
| 1798 |
pass |
| 1799 |
|
| 1800 |
def clear(self): |
| 1801 |
cache.clear() |
| 1802 |
|
| 1803 |
def cache_len(self): |
| 1804 |
return len(cache) |
| 1805 |
|
| 1806 |
self.get = types.MethodType(get, self) |
| 1807 |
self.set = types.MethodType(set, self) |
| 1808 |
self.clear = types.MethodType(clear, self) |
| 1809 |
self.__len__ = types.MethodType(cache_len, self) |
| 1810 |
|
| 1811 |
else: |
| 1812 |
class _FifoCache(object): |
| 1813 |
def __init__(self, size): |
| 1814 |
self.not_in_cache = not_in_cache = object() |
| 1815 |
|
| 1816 |
cache = {} |
| 1817 |
key_fifo = collections.deque([], size) |
| 1818 |
|
| 1819 |
def get(self, key): |
| 1820 |
return cache.get(key, not_in_cache) |
| 1821 |
|
| 1822 |
def set(self, key, value): |
| 1823 |
cache[key] = value |
| 1824 |
while len(key_fifo) > size: |
| 1825 |
cache.pop(key_fifo.popleft(), None) |
| 1826 |
key_fifo.append(key) |
| 1827 |
|
| 1828 |
def clear(self): |
| 1829 |
cache.clear() |
| 1830 |
key_fifo.clear() |
| 1831 |
|
| 1832 |
def cache_len(self): |
| 1833 |
return len(cache) |
| 1834 |
|
| 1835 |
self.get = types.MethodType(get, self) |
| 1836 |
self.set = types.MethodType(set, self) |
| 1837 |
self.clear = types.MethodType(clear, self) |
| 1838 |
self.__len__ = types.MethodType(cache_len, self) |
| 1839 |
|
| 1840 |
# argument cache for optimizing repeated calls when backtracking through recursive expressions |
| 1841 |
packrat_cache = {} # this is set later by enabledPackrat(); this is here so that resetCache() doesn't fail |
| 1842 |
packrat_cache_lock = RLock() |
| 1843 |
packrat_cache_stats = [0, 0] |
| 1844 |
|
| 1845 |
# this method gets repeatedly called during backtracking with the same arguments - |
| 1846 |
# we can cache these arguments and save ourselves the trouble of re-parsing the contained expression |
| 1847 |
def _parseCache(self, instring, loc, doActions=True, callPreParse=True): |
| 1848 |
HIT, MISS = 0, 1 |
| 1849 |
lookup = (self, instring, loc, callPreParse, doActions) |
| 1850 |
with ParserElement.packrat_cache_lock: |
| 1851 |
cache = ParserElement.packrat_cache |
| 1852 |
value = cache.get(lookup) |
| 1853 |
if value is cache.not_in_cache: |
| 1854 |
ParserElement.packrat_cache_stats[MISS] += 1 |
| 1855 |
try: |
| 1856 |
value = self._parseNoCache(instring, loc, doActions, callPreParse) |
| 1857 |
except ParseBaseException as pe: |
| 1858 |
# cache a copy of the exception, without the traceback |
| 1859 |
cache.set(lookup, pe.__class__(*pe.args)) |
| 1860 |
raise |
| 1861 |
else: |
| 1862 |
cache.set(lookup, (value[0], value[1].copy())) |
| 1863 |
return value |
| 1864 |
else: |
| 1865 |
ParserElement.packrat_cache_stats[HIT] += 1 |
| 1866 |
if isinstance(value, Exception): |
| 1867 |
raise value |
| 1868 |
return value[0], value[1].copy() |
| 1869 |
|
| 1870 |
_parse = _parseNoCache |
| 1871 |
|
| 1872 |
@staticmethod |
| 1873 |
def resetCache(): |
| 1874 |
ParserElement.packrat_cache.clear() |
| 1875 |
ParserElement.packrat_cache_stats[:] = [0] * len(ParserElement.packrat_cache_stats) |
| 1876 |
|
| 1877 |
_packratEnabled = False |
| 1878 |
@staticmethod |
| 1879 |
def enablePackrat(cache_size_limit=128): |
| 1880 |
"""Enables "packrat" parsing, which adds memoizing to the parsing logic. |
| 1881 |
Repeated parse attempts at the same string location (which happens |
| 1882 |
often in many complex grammars) can immediately return a cached value, |
| 1883 |
instead of re-executing parsing/validating code. Memoizing is done of |
| 1884 |
both valid results and parsing exceptions. |
| 1885 |
|
| 1886 |
Parameters: |
| 1887 |
|
| 1888 |
- cache_size_limit - (default= ``128``) - if an integer value is provided |
| 1889 |
will limit the size of the packrat cache; if None is passed, then |
| 1890 |
the cache size will be unbounded; if 0 is passed, the cache will |
| 1891 |
be effectively disabled. |
| 1892 |
|
| 1893 |
This speedup may break existing programs that use parse actions that |
| 1894 |
have side-effects. For this reason, packrat parsing is disabled when |
| 1895 |
you first import pyparsing. To activate the packrat feature, your |
| 1896 |
program must call the class method :class:`ParserElement.enablePackrat`. |
| 1897 |
For best results, call ``enablePackrat()`` immediately after |
| 1898 |
importing pyparsing. |
| 1899 |
|
| 1900 |
Example:: |
| 1901 |
|
| 1902 |
import pyparsing |
| 1903 |
pyparsing.ParserElement.enablePackrat() |
| 1904 |
""" |
| 1905 |
if not ParserElement._packratEnabled: |
| 1906 |
ParserElement._packratEnabled = True |
| 1907 |
if cache_size_limit is None: |
| 1908 |
ParserElement.packrat_cache = ParserElement._UnboundedCache() |
| 1909 |
else: |
| 1910 |
ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit) |
| 1911 |
ParserElement._parse = ParserElement._parseCache |
| 1912 |
|
| 1913 |
def parseString(self, instring, parseAll=False): |
| 1914 |
""" |
| 1915 |
Execute the parse expression with the given string. |
| 1916 |
This is the main interface to the client code, once the complete |
| 1917 |
expression has been built. |
| 1918 |
|
| 1919 |
Returns the parsed data as a :class:`ParseResults` object, which may be |
| 1920 |
accessed as a list, or as a dict or object with attributes if the given parser |
| 1921 |
includes results names. |
| 1922 |
|
| 1923 |
If you want the grammar to require that the entire input string be |
| 1924 |
successfully parsed, then set ``parseAll`` to True (equivalent to ending |
| 1925 |
the grammar with ``StringEnd()``). |
| 1926 |
|
| 1927 |
Note: ``parseString`` implicitly calls ``expandtabs()`` on the input string, |
| 1928 |
in order to report proper column numbers in parse actions. |
| 1929 |
If the input string contains tabs and |
| 1930 |
the grammar uses parse actions that use the ``loc`` argument to index into the |
| 1931 |
string being parsed, you can ensure you have a consistent view of the input |
| 1932 |
string by: |
| 1933 |
|
| 1934 |
- calling ``parseWithTabs`` on your grammar before calling ``parseString`` |
| 1935 |
(see :class:`parseWithTabs`) |
| 1936 |
- define your parse action using the full ``(s, loc, toks)`` signature, and |
| 1937 |
reference the input string using the parse action's ``s`` argument |
| 1938 |
- explicitly expand the tabs in your input string before calling |
| 1939 |
``parseString`` |
| 1940 |
|
| 1941 |
Example:: |
| 1942 |
|
| 1943 |
Word('a').parseString('aaaaabaaa') # -> ['aaaaa'] |
| 1944 |
Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text |
| 1945 |
""" |
| 1946 |
ParserElement.resetCache() |
| 1947 |
if not self.streamlined: |
| 1948 |
self.streamline() |
| 1949 |
# ~ self.saveAsList = True |
| 1950 |
for e in self.ignoreExprs: |
| 1951 |
e.streamline() |
| 1952 |
if not self.keepTabs: |
| 1953 |
instring = instring.expandtabs() |
| 1954 |
try: |
| 1955 |
loc, tokens = self._parse(instring, 0) |
| 1956 |
if parseAll: |
| 1957 |
loc = self.preParse(instring, loc) |
| 1958 |
se = Empty() + StringEnd() |
| 1959 |
se._parse(instring, loc) |
| 1960 |
except ParseBaseException as exc: |
| 1961 |
if ParserElement.verbose_stacktrace: |
| 1962 |
raise |
| 1963 |
else: |
| 1964 |
# catch and re-raise exception from here, clearing out pyparsing internal stack trace |
| 1965 |
if getattr(exc, '__traceback__', None) is not None: |
| 1966 |
exc.__traceback__ = self._trim_traceback(exc.__traceback__) |
| 1967 |
raise exc |
| 1968 |
else: |
| 1969 |
return tokens |
| 1970 |
|
| 1971 |
def scanString(self, instring, maxMatches=_MAX_INT, overlap=False): |
| 1972 |
""" |
| 1973 |
Scan the input string for expression matches. Each match will return the |
| 1974 |
matching tokens, start location, and end location. May be called with optional |
| 1975 |
``maxMatches`` argument, to clip scanning after 'n' matches are found. If |
| 1976 |
``overlap`` is specified, then overlapping matches will be reported. |
| 1977 |
|
| 1978 |
Note that the start and end locations are reported relative to the string |
| 1979 |
being parsed. See :class:`parseString` for more information on parsing |
| 1980 |
strings with embedded tabs. |
| 1981 |
|
| 1982 |
Example:: |
| 1983 |
|
| 1984 |
source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" |
| 1985 |
print(source) |
| 1986 |
for tokens, start, end in Word(alphas).scanString(source): |
| 1987 |
print(' '*start + '^'*(end-start)) |
| 1988 |
print(' '*start + tokens[0]) |
| 1989 |
|
| 1990 |
prints:: |
| 1991 |
|
| 1992 |
sldjf123lsdjjkf345sldkjf879lkjsfd987 |
| 1993 |
^^^^^ |
| 1994 |
sldjf |
| 1995 |
^^^^^^^ |
| 1996 |
lsdjjkf |
| 1997 |
^^^^^^ |
| 1998 |
sldkjf |
| 1999 |
^^^^^^ |
| 2000 |
lkjsfd |
| 2001 |
""" |
| 2002 |
if not self.streamlined: |
| 2003 |
self.streamline() |
| 2004 |
for e in self.ignoreExprs: |
| 2005 |
e.streamline() |
| 2006 |
|
| 2007 |
if not self.keepTabs: |
| 2008 |
instring = _ustr(instring).expandtabs() |
| 2009 |
instrlen = len(instring) |
| 2010 |
loc = 0 |
| 2011 |
preparseFn = self.preParse |
| 2012 |
parseFn = self._parse |
| 2013 |
ParserElement.resetCache() |
| 2014 |
matches = 0 |
| 2015 |
try: |
| 2016 |
while loc <= instrlen and matches < maxMatches: |
| 2017 |
try: |
| 2018 |
preloc = preparseFn(instring, loc) |
| 2019 |
nextLoc, tokens = parseFn(instring, preloc, callPreParse=False) |
| 2020 |
except ParseException: |
| 2021 |
loc = preloc + 1 |
| 2022 |
else: |
| 2023 |
if nextLoc > loc: |
| 2024 |
matches += 1 |
| 2025 |
yield tokens, preloc, nextLoc |
| 2026 |
if overlap: |
| 2027 |
nextloc = preparseFn(instring, loc) |
| 2028 |
if nextloc > loc: |
| 2029 |
loc = nextLoc |
| 2030 |
else: |
| 2031 |
loc += 1 |
| 2032 |
else: |
| 2033 |
loc = nextLoc |
| 2034 |
else: |
| 2035 |
loc = preloc + 1 |
| 2036 |
except ParseBaseException as exc: |
| 2037 |
if ParserElement.verbose_stacktrace: |
| 2038 |
raise |
| 2039 |
else: |
| 2040 |
# catch and re-raise exception from here, clearing out pyparsing internal stack trace |
| 2041 |
if getattr(exc, '__traceback__', None) is not None: |
| 2042 |
exc.__traceback__ = self._trim_traceback(exc.__traceback__) |
| 2043 |
raise exc |
| 2044 |
|
| 2045 |
def transformString(self, instring): |
| 2046 |
""" |
| 2047 |
Extension to :class:`scanString`, to modify matching text with modified tokens that may |
| 2048 |
be returned from a parse action. To use ``transformString``, define a grammar and |
| 2049 |
attach a parse action to it that modifies the returned token list. |
| 2050 |
Invoking ``transformString()`` on a target string will then scan for matches, |
| 2051 |
and replace the matched text patterns according to the logic in the parse |
| 2052 |
action. ``transformString()`` returns the resulting transformed string. |
| 2053 |
|
| 2054 |
Example:: |
| 2055 |
|
| 2056 |
wd = Word(alphas) |
| 2057 |
wd.setParseAction(lambda toks: toks[0].title()) |
| 2058 |
|
| 2059 |
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) |
| 2060 |
|
| 2061 |
prints:: |
| 2062 |
|
| 2063 |
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. |
| 2064 |
""" |
| 2065 |
out = [] |
| 2066 |
lastE = 0 |
| 2067 |
# force preservation of <TAB>s, to minimize unwanted transformation of string, and to |
| 2068 |
# keep string locs straight between transformString and scanString |
| 2069 |
self.keepTabs = True |
| 2070 |
try: |
| 2071 |
for t, s, e in self.scanString(instring): |
| 2072 |
out.append(instring[lastE:s]) |
| 2073 |
if t: |
| 2074 |
if isinstance(t, ParseResults): |
| 2075 |
out += t.asList() |
| 2076 |
elif isinstance(t, list): |
| 2077 |
out += t |
| 2078 |
else: |
| 2079 |
out.append(t) |
| 2080 |
lastE = e |
| 2081 |
out.append(instring[lastE:]) |
| 2082 |
out = [o for o in out if o] |
| 2083 |
return "".join(map(_ustr, _flatten(out))) |
| 2084 |
except ParseBaseException as exc: |
| 2085 |
if ParserElement.verbose_stacktrace: |
| 2086 |
raise |
| 2087 |
else: |
| 2088 |
# catch and re-raise exception from here, clearing out pyparsing internal stack trace |
| 2089 |
if getattr(exc, '__traceback__', None) is not None: |
| 2090 |
exc.__traceback__ = self._trim_traceback(exc.__traceback__) |
| 2091 |
raise exc |
| 2092 |
|
| 2093 |
def searchString(self, instring, maxMatches=_MAX_INT): |
| 2094 |
""" |
| 2095 |
Another extension to :class:`scanString`, simplifying the access to the tokens found |
| 2096 |
to match the given parse expression. May be called with optional |
| 2097 |
``maxMatches`` argument, to clip searching after 'n' matches are found. |
| 2098 |
|
| 2099 |
Example:: |
| 2100 |
|
| 2101 |
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters |
| 2102 |
cap_word = Word(alphas.upper(), alphas.lower()) |
| 2103 |
|
| 2104 |
print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")) |
| 2105 |
|
| 2106 |
# the sum() builtin can be used to merge results into a single ParseResults object |
| 2107 |
print(sum(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))) |
| 2108 |
|
| 2109 |
prints:: |
| 2110 |
|
| 2111 |
[['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']] |
| 2112 |
['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity'] |
| 2113 |
""" |
| 2114 |
try: |
| 2115 |
return ParseResults([t for t, s, e in self.scanString(instring, maxMatches)]) |
| 2116 |
except ParseBaseException as exc: |
| 2117 |
if ParserElement.verbose_stacktrace: |
| 2118 |
raise |
| 2119 |
else: |
| 2120 |
# catch and re-raise exception from here, clearing out pyparsing internal stack trace |
| 2121 |
if getattr(exc, '__traceback__', None) is not None: |
| 2122 |
exc.__traceback__ = self._trim_traceback(exc.__traceback__) |
| 2123 |
raise exc |
| 2124 |
|
| 2125 |
def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False): |
| 2126 |
""" |
| 2127 |
Generator method to split a string using the given expression as a separator. |
| 2128 |
May be called with optional ``maxsplit`` argument, to limit the number of splits; |
| 2129 |
and the optional ``includeSeparators`` argument (default= ``False``), if the separating |
| 2130 |
matching text should be included in the split results. |
| 2131 |
|
| 2132 |
Example:: |
| 2133 |
|
| 2134 |
punc = oneOf(list(".,;:/-!?")) |
| 2135 |
print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) |
| 2136 |
|
| 2137 |
prints:: |
| 2138 |
|
| 2139 |
['This', ' this', '', ' this sentence', ' is badly punctuated', ''] |
| 2140 |
""" |
| 2141 |
splits = 0 |
| 2142 |
last = 0 |
| 2143 |
for t, s, e in self.scanString(instring, maxMatches=maxsplit): |
| 2144 |
yield instring[last:s] |
| 2145 |
if includeSeparators: |
| 2146 |
yield t[0] |
| 2147 |
last = e |
| 2148 |
yield instring[last:] |
| 2149 |
|
| 2150 |
def __add__(self, other): |
| 2151 |
""" |
| 2152 |
Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement |
| 2153 |
converts them to :class:`Literal`s by default. |
| 2154 |
|
| 2155 |
Example:: |
| 2156 |
|
| 2157 |
greet = Word(alphas) + "," + Word(alphas) + "!" |
| 2158 |
hello = "Hello, World!" |
| 2159 |
print (hello, "->", greet.parseString(hello)) |
| 2160 |
|
| 2161 |
prints:: |
| 2162 |
|
| 2163 |
Hello, World! -> ['Hello', ',', 'World', '!'] |
| 2164 |
|
| 2165 |
``...`` may be used as a parse expression as a short form of :class:`SkipTo`. |
| 2166 |
|
| 2167 |
Literal('start') + ... + Literal('end') |
| 2168 |
|
| 2169 |
is equivalent to: |
| 2170 |
|
| 2171 |
Literal('start') + SkipTo('end')("_skipped*") + Literal('end') |
| 2172 |
|
| 2173 |
Note that the skipped text is returned with '_skipped' as a results name, |
| 2174 |
and to support having multiple skips in the same parser, the value returned is |
| 2175 |
a list of all skipped text. |
| 2176 |
""" |
| 2177 |
if other is Ellipsis: |
| 2178 |
return _PendingSkip(self) |
| 2179 |
|
| 2180 |
if isinstance(other, basestring): |
| 2181 |
other = self._literalStringClass(other) |
| 2182 |
if not isinstance(other, ParserElement): |
| 2183 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2184 |
SyntaxWarning, stacklevel=2) |
| 2185 |
return None |
| 2186 |
return And([self, other]) |
| 2187 |
|
| 2188 |
def __radd__(self, other): |
| 2189 |
""" |
| 2190 |
Implementation of + operator when left operand is not a :class:`ParserElement` |
| 2191 |
""" |
| 2192 |
if other is Ellipsis: |
| 2193 |
return SkipTo(self)("_skipped*") + self |
| 2194 |
|
| 2195 |
if isinstance(other, basestring): |
| 2196 |
other = self._literalStringClass(other) |
| 2197 |
if not isinstance(other, ParserElement): |
| 2198 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2199 |
SyntaxWarning, stacklevel=2) |
| 2200 |
return None |
| 2201 |
return other + self |
| 2202 |
|
| 2203 |
def __sub__(self, other): |
| 2204 |
""" |
| 2205 |
Implementation of - operator, returns :class:`And` with error stop |
| 2206 |
""" |
| 2207 |
if isinstance(other, basestring): |
| 2208 |
other = self._literalStringClass(other) |
| 2209 |
if not isinstance(other, ParserElement): |
| 2210 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2211 |
SyntaxWarning, stacklevel=2) |
| 2212 |
return None |
| 2213 |
return self + And._ErrorStop() + other |
| 2214 |
|
| 2215 |
def __rsub__(self, other): |
| 2216 |
""" |
| 2217 |
Implementation of - operator when left operand is not a :class:`ParserElement` |
| 2218 |
""" |
| 2219 |
if isinstance(other, basestring): |
| 2220 |
other = self._literalStringClass(other) |
| 2221 |
if not isinstance(other, ParserElement): |
| 2222 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2223 |
SyntaxWarning, stacklevel=2) |
| 2224 |
return None |
| 2225 |
return other - self |
| 2226 |
|
| 2227 |
def __mul__(self, other): |
| 2228 |
""" |
| 2229 |
Implementation of * operator, allows use of ``expr * 3`` in place of |
| 2230 |
``expr + expr + expr``. Expressions may also me multiplied by a 2-integer |
| 2231 |
tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples |
| 2232 |
may also include ``None`` as in: |
| 2233 |
- ``expr*(n, None)`` or ``expr*(n, )`` is equivalent |
| 2234 |
to ``expr*n + ZeroOrMore(expr)`` |
| 2235 |
(read as "at least n instances of ``expr``") |
| 2236 |
- ``expr*(None, n)`` is equivalent to ``expr*(0, n)`` |
| 2237 |
(read as "0 to n instances of ``expr``") |
| 2238 |
- ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)`` |
| 2239 |
- ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)`` |
| 2240 |
|
| 2241 |
Note that ``expr*(None, n)`` does not raise an exception if |
| 2242 |
more than n exprs exist in the input stream; that is, |
| 2243 |
``expr*(None, n)`` does not enforce a maximum number of expr |
| 2244 |
occurrences. If this behavior is desired, then write |
| 2245 |
``expr*(None, n) + ~expr`` |
| 2246 |
""" |
| 2247 |
if other is Ellipsis: |
| 2248 |
other = (0, None) |
| 2249 |
elif isinstance(other, tuple) and other[:1] == (Ellipsis,): |
| 2250 |
other = ((0, ) + other[1:] + (None,))[:2] |
| 2251 |
|
| 2252 |
if isinstance(other, int): |
| 2253 |
minElements, optElements = other, 0 |
| 2254 |
elif isinstance(other, tuple): |
| 2255 |
other = tuple(o if o is not Ellipsis else None for o in other) |
| 2256 |
other = (other + (None, None))[:2] |
| 2257 |
if other[0] is None: |
| 2258 |
other = (0, other[1]) |
| 2259 |
if isinstance(other[0], int) and other[1] is None: |
| 2260 |
if other[0] == 0: |
| 2261 |
return ZeroOrMore(self) |
| 2262 |
if other[0] == 1: |
| 2263 |
return OneOrMore(self) |
| 2264 |
else: |
| 2265 |
return self * other[0] + ZeroOrMore(self) |
| 2266 |
elif isinstance(other[0], int) and isinstance(other[1], int): |
| 2267 |
minElements, optElements = other |
| 2268 |
optElements -= minElements |
| 2269 |
else: |
| 2270 |
raise TypeError("cannot multiply 'ParserElement' and ('%s', '%s') objects", type(other[0]), type(other[1])) |
| 2271 |
else: |
| 2272 |
raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other)) |
| 2273 |
|
| 2274 |
if minElements < 0: |
| 2275 |
raise ValueError("cannot multiply ParserElement by negative value") |
| 2276 |
if optElements < 0: |
| 2277 |
raise ValueError("second tuple value must be greater or equal to first tuple value") |
| 2278 |
if minElements == optElements == 0: |
| 2279 |
raise ValueError("cannot multiply ParserElement by 0 or (0, 0)") |
| 2280 |
|
| 2281 |
if optElements: |
| 2282 |
def makeOptionalList(n): |
| 2283 |
if n > 1: |
| 2284 |
return Optional(self + makeOptionalList(n - 1)) |
| 2285 |
else: |
| 2286 |
return Optional(self) |
| 2287 |
if minElements: |
| 2288 |
if minElements == 1: |
| 2289 |
ret = self + makeOptionalList(optElements) |
| 2290 |
else: |
| 2291 |
ret = And([self] * minElements) + makeOptionalList(optElements) |
| 2292 |
else: |
| 2293 |
ret = makeOptionalList(optElements) |
| 2294 |
else: |
| 2295 |
if minElements == 1: |
| 2296 |
ret = self |
| 2297 |
else: |
| 2298 |
ret = And([self] * minElements) |
| 2299 |
return ret |
| 2300 |
|
| 2301 |
def __rmul__(self, other): |
| 2302 |
return self.__mul__(other) |
| 2303 |
|
| 2304 |
def __or__(self, other): |
| 2305 |
""" |
| 2306 |
Implementation of | operator - returns :class:`MatchFirst` |
| 2307 |
""" |
| 2308 |
if other is Ellipsis: |
| 2309 |
return _PendingSkip(self, must_skip=True) |
| 2310 |
|
| 2311 |
if isinstance(other, basestring): |
| 2312 |
other = self._literalStringClass(other) |
| 2313 |
if not isinstance(other, ParserElement): |
| 2314 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2315 |
SyntaxWarning, stacklevel=2) |
| 2316 |
return None |
| 2317 |
return MatchFirst([self, other]) |
| 2318 |
|
| 2319 |
def __ror__(self, other): |
| 2320 |
""" |
| 2321 |
Implementation of | operator when left operand is not a :class:`ParserElement` |
| 2322 |
""" |
| 2323 |
if isinstance(other, basestring): |
| 2324 |
other = self._literalStringClass(other) |
| 2325 |
if not isinstance(other, ParserElement): |
| 2326 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2327 |
SyntaxWarning, stacklevel=2) |
| 2328 |
return None |
| 2329 |
return other | self |
| 2330 |
|
| 2331 |
def __xor__(self, other): |
| 2332 |
""" |
| 2333 |
Implementation of ^ operator - returns :class:`Or` |
| 2334 |
""" |
| 2335 |
if isinstance(other, basestring): |
| 2336 |
other = self._literalStringClass(other) |
| 2337 |
if not isinstance(other, ParserElement): |
| 2338 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2339 |
SyntaxWarning, stacklevel=2) |
| 2340 |
return None |
| 2341 |
return Or([self, other]) |
| 2342 |
|
| 2343 |
def __rxor__(self, other): |
| 2344 |
""" |
| 2345 |
Implementation of ^ operator when left operand is not a :class:`ParserElement` |
| 2346 |
""" |
| 2347 |
if isinstance(other, basestring): |
| 2348 |
other = self._literalStringClass(other) |
| 2349 |
if not isinstance(other, ParserElement): |
| 2350 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2351 |
SyntaxWarning, stacklevel=2) |
| 2352 |
return None |
| 2353 |
return other ^ self |
| 2354 |
|
| 2355 |
def __and__(self, other): |
| 2356 |
""" |
| 2357 |
Implementation of & operator - returns :class:`Each` |
| 2358 |
""" |
| 2359 |
if isinstance(other, basestring): |
| 2360 |
other = self._literalStringClass(other) |
| 2361 |
if not isinstance(other, ParserElement): |
| 2362 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2363 |
SyntaxWarning, stacklevel=2) |
| 2364 |
return None |
| 2365 |
return Each([self, other]) |
| 2366 |
|
| 2367 |
def __rand__(self, other): |
| 2368 |
""" |
| 2369 |
Implementation of & operator when left operand is not a :class:`ParserElement` |
| 2370 |
""" |
| 2371 |
if isinstance(other, basestring): |
| 2372 |
other = self._literalStringClass(other) |
| 2373 |
if not isinstance(other, ParserElement): |
| 2374 |
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), |
| 2375 |
SyntaxWarning, stacklevel=2) |
| 2376 |
return None |
| 2377 |
return other & self |
| 2378 |
|
| 2379 |
def __invert__(self): |
| 2380 |
""" |
| 2381 |
Implementation of ~ operator - returns :class:`NotAny` |
| 2382 |
""" |
| 2383 |
return NotAny(self) |
| 2384 |
|
| 2385 |
def __iter__(self): |
| 2386 |
# must implement __iter__ to override legacy use of sequential access to __getitem__ to |
| 2387 |
# iterate over a sequence |
| 2388 |
raise TypeError('%r object is not iterable' % self.__class__.__name__) |
| 2389 |
|
| 2390 |
def __getitem__(self, key): |
| 2391 |
""" |
| 2392 |
use ``[]`` indexing notation as a short form for expression repetition: |
| 2393 |
- ``expr[n]`` is equivalent to ``expr*n`` |
| 2394 |
- ``expr[m, n]`` is equivalent to ``expr*(m, n)`` |
| 2395 |
- ``expr[n, ...]`` or ``expr[n,]`` is equivalent |
| 2396 |
to ``expr*n + ZeroOrMore(expr)`` |
| 2397 |
(read as "at least n instances of ``expr``") |
| 2398 |
- ``expr[..., n]`` is equivalent to ``expr*(0, n)`` |
| 2399 |
(read as "0 to n instances of ``expr``") |
| 2400 |
- ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)`` |
| 2401 |
- ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)`` |
| 2402 |
``None`` may be used in place of ``...``. |
| 2403 |
|
| 2404 |
Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception |
| 2405 |
if more than ``n`` ``expr``s exist in the input stream. If this behavior is |
| 2406 |
desired, then write ``expr[..., n] + ~expr``. |
| 2407 |
""" |
| 2408 |
|
| 2409 |
# convert single arg keys to tuples |
| 2410 |
try: |
| 2411 |
if isinstance(key, str): |
| 2412 |
key = (key,) |
| 2413 |
iter(key) |
| 2414 |
except TypeError: |
| 2415 |
key = (key, key) |
| 2416 |
|
| 2417 |
if len(key) > 2: |
| 2418 |
warnings.warn("only 1 or 2 index arguments supported ({0}{1})".format(key[:5], |
| 2419 |
'... [{0}]'.format(len(key)) |
| 2420 |
if len(key) > 5 else '')) |
| 2421 |
|
| 2422 |
# clip to 2 elements |
| 2423 |
ret = self * tuple(key[:2]) |
| 2424 |
return ret |
| 2425 |
|
| 2426 |
def __call__(self, name=None): |
| 2427 |
""" |
| 2428 |
Shortcut for :class:`setResultsName`, with ``listAllMatches=False``. |
| 2429 |
|
| 2430 |
If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be |
| 2431 |
passed as ``True``. |
| 2432 |
|
| 2433 |
If ``name` is omitted, same as calling :class:`copy`. |
| 2434 |
|
| 2435 |
Example:: |
| 2436 |
|
| 2437 |
# these are equivalent |
| 2438 |
userdata = Word(alphas).setResultsName("name") + Word(nums + "-").setResultsName("socsecno") |
| 2439 |
userdata = Word(alphas)("name") + Word(nums + "-")("socsecno") |
| 2440 |
""" |
| 2441 |
if name is not None: |
| 2442 |
return self._setResultsName(name) |
| 2443 |
else: |
| 2444 |
return self.copy() |
| 2445 |
|
| 2446 |
def suppress(self): |
| 2447 |
""" |
| 2448 |
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from |
| 2449 |
cluttering up returned output. |
| 2450 |
""" |
| 2451 |
return Suppress(self) |
| 2452 |
|
| 2453 |
def leaveWhitespace(self): |
| 2454 |
""" |
| 2455 |
Disables the skipping of whitespace before matching the characters in the |
| 2456 |
:class:`ParserElement`'s defined pattern. This is normally only used internally by |
| 2457 |
the pyparsing module, but may be needed in some whitespace-sensitive grammars. |
| 2458 |
""" |
| 2459 |
self.skipWhitespace = False |
| 2460 |
return self |
| 2461 |
|
| 2462 |
def setWhitespaceChars(self, chars): |
| 2463 |
""" |
| 2464 |
Overrides the default whitespace chars |
| 2465 |
""" |
| 2466 |
self.skipWhitespace = True |
| 2467 |
self.whiteChars = chars |
| 2468 |
self.copyDefaultWhiteChars = False |
| 2469 |
return self |
| 2470 |
|
| 2471 |
def parseWithTabs(self): |
| 2472 |
""" |
| 2473 |
Overrides default behavior to expand ``<TAB>``s to spaces before parsing the input string. |
| 2474 |
Must be called before ``parseString`` when the input grammar contains elements that |
| 2475 |
match ``<TAB>`` characters. |
| 2476 |
""" |
| 2477 |
self.keepTabs = True |
| 2478 |
return self |
| 2479 |
|
| 2480 |
def ignore(self, other): |
| 2481 |
""" |
| 2482 |
Define expression to be ignored (e.g., comments) while doing pattern |
| 2483 |
matching; may be called repeatedly, to define multiple comment or other |
| 2484 |
ignorable patterns. |
| 2485 |
|
| 2486 |
Example:: |
| 2487 |
|
| 2488 |
patt = OneOrMore(Word(alphas)) |
| 2489 |
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'] |
| 2490 |
|
| 2491 |
patt.ignore(cStyleComment) |
| 2492 |
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] |
| 2493 |
""" |
| 2494 |
if isinstance(other, basestring): |
| 2495 |
other = Suppress(other) |
| 2496 |
|
| 2497 |
if isinstance(other, Suppress): |
| 2498 |
if other not in self.ignoreExprs: |
| 2499 |
self.ignoreExprs.append(other) |
| 2500 |
else: |
| 2501 |
self.ignoreExprs.append(Suppress(other.copy())) |
| 2502 |
return self |
| 2503 |
|
| 2504 |
def setDebugActions(self, startAction, successAction, exceptionAction): |
| 2505 |
""" |
| 2506 |
Enable display of debugging messages while doing pattern matching. |
| 2507 |
""" |
| 2508 |
self.debugActions = (startAction or _defaultStartDebugAction, |
| 2509 |
successAction or _defaultSuccessDebugAction, |
| 2510 |
exceptionAction or _defaultExceptionDebugAction) |
| 2511 |
self.debug = True |
| 2512 |
return self |
| 2513 |
|
| 2514 |
def setDebug(self, flag=True): |
| 2515 |
""" |
| 2516 |
Enable display of debugging messages while doing pattern matching. |
| 2517 |
Set ``flag`` to True to enable, False to disable. |
| 2518 |
|
| 2519 |
Example:: |
| 2520 |
|
| 2521 |
wd = Word(alphas).setName("alphaword") |
| 2522 |
integer = Word(nums).setName("numword") |
| 2523 |
term = wd | integer |
| 2524 |
|
| 2525 |
# turn on debugging for wd |
| 2526 |
wd.setDebug() |
| 2527 |
|
| 2528 |
OneOrMore(term).parseString("abc 123 xyz 890") |
| 2529 |
|
| 2530 |
prints:: |
| 2531 |
|
| 2532 |
Match alphaword at loc 0(1,1) |
| 2533 |
Matched alphaword -> ['abc'] |
| 2534 |
Match alphaword at loc 3(1,4) |
| 2535 |
Exception raised:Expected alphaword (at char 4), (line:1, col:5) |
| 2536 |
Match alphaword at loc 7(1,8) |
| 2537 |
Matched alphaword -> ['xyz'] |
| 2538 |
Match alphaword at loc 11(1,12) |
| 2539 |
Exception raised:Expected alphaword (at char 12), (line:1, col:13) |
| 2540 |
Match alphaword at loc 15(1,16) |
| 2541 |
Exception raised:Expected alphaword (at char 15), (line:1, col:16) |
| 2542 |
|
| 2543 |
The output shown is that produced by the default debug actions - custom debug actions can be |
| 2544 |
specified using :class:`setDebugActions`. Prior to attempting |
| 2545 |
to match the ``wd`` expression, the debugging message ``"Match <exprname> at loc <n>(<line>,<col>)"`` |
| 2546 |
is shown. Then if the parse succeeds, a ``"Matched"`` message is shown, or an ``"Exception raised"`` |
| 2547 |
message is shown. Also note the use of :class:`setName` to assign a human-readable name to the expression, |
| 2548 |
which makes debugging and exception messages easier to understand - for instance, the default |
| 2549 |
name created for the :class:`Word` expression without calling ``setName`` is ``"W:(ABCD...)"``. |
| 2550 |
""" |
| 2551 |
if flag: |
| 2552 |
self.setDebugActions(_defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction) |
| 2553 |
else: |
| 2554 |
self.debug = False |
| 2555 |
return self |
| 2556 |
|
| 2557 |
def __str__(self): |
| 2558 |
return self.name |
| 2559 |
|
| 2560 |
def __repr__(self): |
| 2561 |
return _ustr(self) |
| 2562 |
|
| 2563 |
def streamline(self): |
| 2564 |
self.streamlined = True |
| 2565 |
self.strRepr = None |
| 2566 |
return self |
| 2567 |
|
| 2568 |
def checkRecursion(self, parseElementList): |
| 2569 |
pass |
| 2570 |
|
| 2571 |
def validate(self, validateTrace=None): |
| 2572 |
""" |
| 2573 |
Check defined expressions for valid structure, check for infinite recursive definitions. |
| 2574 |
""" |
| 2575 |
self.checkRecursion([]) |
| 2576 |
|
| 2577 |
def parseFile(self, file_or_filename, parseAll=False): |
| 2578 |
""" |
| 2579 |
Execute the parse expression on the given file or filename. |
| 2580 |
If a filename is specified (instead of a file object), |
| 2581 |
the entire file is opened, read, and closed before parsing. |
| 2582 |
""" |
| 2583 |
try: |
| 2584 |
file_contents = file_or_filename.read() |
| 2585 |
except AttributeError: |
| 2586 |
with open(file_or_filename, "r") as f: |
| 2587 |
file_contents = f.read() |
| 2588 |
try: |
| 2589 |
return self.parseString(file_contents, parseAll) |
| 2590 |
except ParseBaseException as exc: |
| 2591 |
if ParserElement.verbose_stacktrace: |
| 2592 |
raise |
| 2593 |
else: |
| 2594 |
# catch and re-raise exception from here, clearing out pyparsing internal stack trace |
| 2595 |
if getattr(exc, '__traceback__', None) is not None: |
| 2596 |
exc.__traceback__ = self._trim_traceback(exc.__traceback__) |
| 2597 |
raise exc |
| 2598 |
|
| 2599 |
def __eq__(self, other): |
| 2600 |
if self is other: |
| 2601 |
return True |
| 2602 |
elif isinstance(other, basestring): |
| 2603 |
return self.matches(other) |
| 2604 |
elif isinstance(other, ParserElement): |
| 2605 |
return vars(self) == vars(other) |
| 2606 |
return False |
| 2607 |
|
| 2608 |
def __ne__(self, other): |
| 2609 |
return not (self == other) |
| 2610 |
|
| 2611 |
def __hash__(self): |
| 2612 |
return id(self) |
| 2613 |
|
| 2614 |
def __req__(self, other): |
| 2615 |
return self == other |
| 2616 |
|
| 2617 |
def __rne__(self, other): |
| 2618 |
return not (self == other) |
| 2619 |
|
| 2620 |
def matches(self, testString, parseAll=True): |
| 2621 |
""" |
| 2622 |
Method for quick testing of a parser against a test string. Good for simple |
| 2623 |
inline microtests of sub expressions while building up larger parser. |
| 2624 |
|
| 2625 |
Parameters: |
| 2626 |
- testString - to test against this expression for a match |
| 2627 |
- parseAll - (default= ``True``) - flag to pass to :class:`parseString` when running tests |
| 2628 |
|
| 2629 |
Example:: |
| 2630 |
|
| 2631 |
expr = Word(nums) |
| 2632 |
assert expr.matches("100") |
| 2633 |
""" |
| 2634 |
try: |
| 2635 |
self.parseString(_ustr(testString), parseAll=parseAll) |
| 2636 |
return True |
| 2637 |
except ParseBaseException: |
| 2638 |
return False |
| 2639 |
|
| 2640 |
def runTests(self, tests, parseAll=True, comment='#', |
| 2641 |
fullDump=True, printResults=True, failureTests=False, postParse=None, |
| 2642 |
file=None): |
| 2643 |
""" |
| 2644 |
Execute the parse expression on a series of test strings, showing each |
| 2645 |
test, the parsed results or where the parse failed. Quick and easy way to |
| 2646 |
run a parse expression against a list of sample strings. |
| 2647 |
|
| 2648 |
Parameters: |
| 2649 |
- tests - a list of separate test strings, or a multiline string of test strings |
| 2650 |
- parseAll - (default= ``True``) - flag to pass to :class:`parseString` when running tests |
| 2651 |
- comment - (default= ``'#'``) - expression for indicating embedded comments in the test |
| 2652 |
string; pass None to disable comment filtering |
| 2653 |
- fullDump - (default= ``True``) - dump results as list followed by results names in nested outline; |
| 2654 |
if False, only dump nested list |
| 2655 |
- printResults - (default= ``True``) prints test output to stdout |
| 2656 |
- failureTests - (default= ``False``) indicates if these tests are expected to fail parsing |
| 2657 |
- postParse - (default= ``None``) optional callback for successful parse results; called as |
| 2658 |
`fn(test_string, parse_results)` and returns a string to be added to the test output |
| 2659 |
- file - (default=``None``) optional file-like object to which test output will be written; |
| 2660 |
if None, will default to ``sys.stdout`` |
| 2661 |
|
| 2662 |
Returns: a (success, results) tuple, where success indicates that all tests succeeded |
| 2663 |
(or failed if ``failureTests`` is True), and the results contain a list of lines of each |
| 2664 |
test's output |
| 2665 |
|
| 2666 |
Example:: |
| 2667 |
|
| 2668 |
number_expr = pyparsing_common.number.copy() |
| 2669 |
|
| 2670 |
result = number_expr.runTests(''' |
| 2671 |
# unsigned integer |
| 2672 |
100 |
| 2673 |
# negative integer |
| 2674 |
-100 |
| 2675 |
# float with scientific notation |
| 2676 |
6.02e23 |
| 2677 |
# integer with scientific notation |
| 2678 |
1e-12 |
| 2679 |
''') |
| 2680 |
print("Success" if result[0] else "Failed!") |
| 2681 |
|
| 2682 |
result = number_expr.runTests(''' |
| 2683 |
# stray character |
| 2684 |
100Z |
| 2685 |
# missing leading digit before '.' |
| 2686 |
-.100 |
| 2687 |
# too many '.' |
| 2688 |
3.14.159 |
| 2689 |
''', failureTests=True) |
| 2690 |
print("Success" if result[0] else "Failed!") |
| 2691 |
|
| 2692 |
prints:: |
| 2693 |
|
| 2694 |
# unsigned integer |
| 2695 |
100 |
| 2696 |
[100] |
| 2697 |
|
| 2698 |
# negative integer |
| 2699 |
-100 |
| 2700 |
[-100] |
| 2701 |
|
| 2702 |
# float with scientific notation |
| 2703 |
6.02e23 |
| 2704 |
[6.02e+23] |
| 2705 |
|
| 2706 |
# integer with scientific notation |
| 2707 |
1e-12 |
| 2708 |
[1e-12] |
| 2709 |
|
| 2710 |
Success |
| 2711 |
|
| 2712 |
# stray character |
| 2713 |
100Z |
| 2714 |
^ |
| 2715 |
FAIL: Expected end of text (at char 3), (line:1, col:4) |
| 2716 |
|
| 2717 |
# missing leading digit before '.' |
| 2718 |
-.100 |
| 2719 |
^ |
| 2720 |
FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) |
| 2721 |
|
| 2722 |
# too many '.' |
| 2723 |
3.14.159 |
| 2724 |
^ |
| 2725 |
FAIL: Expected end of text (at char 4), (line:1, col:5) |
| 2726 |
|
| 2727 |
Success |
| 2728 |
|
| 2729 |
Each test string must be on a single line. If you want to test a string that spans multiple |
| 2730 |
lines, create a test like this:: |
| 2731 |
|
| 2732 |
expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") |
| 2733 |
|
| 2734 |
(Note that this is a raw string literal, you must include the leading 'r'.) |
| 2735 |
""" |
| 2736 |
if isinstance(tests, basestring): |
| 2737 |
tests = list(map(str.strip, tests.rstrip().splitlines())) |
| 2738 |
if isinstance(comment, basestring): |
| 2739 |
comment = Literal(comment) |
| 2740 |
if file is None: |
| 2741 |
file = sys.stdout |
| 2742 |
print_ = file.write |
| 2743 |
|
| 2744 |
allResults = [] |
| 2745 |
comments = [] |
| 2746 |
success = True |
| 2747 |
NL = Literal(r'\n').addParseAction(replaceWith('\n')).ignore(quotedString) |
| 2748 |
BOM = u'\ufeff' |
| 2749 |
for t in tests: |
| 2750 |
if comment is not None and comment.matches(t, False) or comments and not t: |
| 2751 |
comments.append(t) |
| 2752 |
continue |
| 2753 |
if not t: |
| 2754 |
continue |
| 2755 |
out = ['\n' + '\n'.join(comments) if comments else '', t] |
| 2756 |
comments = [] |
| 2757 |
try: |
| 2758 |
# convert newline marks to actual newlines, and strip leading BOM if present |
| 2759 |
t = NL.transformString(t.lstrip(BOM)) |
| 2760 |
result = self.parseString(t, parseAll=parseAll) |
| 2761 |
except ParseBaseException as pe: |
| 2762 |
fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else "" |
| 2763 |
if '\n' in t: |
| 2764 |
out.append(line(pe.loc, t)) |
| 2765 |
out.append(' ' * (col(pe.loc, t) - 1) + '^' + fatal) |
| 2766 |
else: |
| 2767 |
out.append(' ' * pe.loc + '^' + fatal) |
| 2768 |
out.append("FAIL: " + str(pe)) |
| 2769 |
success = success and failureTests |
| 2770 |
result = pe |
| 2771 |
except Exception as exc: |
| 2772 |
out.append("FAIL-EXCEPTION: " + str(exc)) |
| 2773 |
success = success and failureTests |
| 2774 |
result = exc |
| 2775 |
else: |
| 2776 |
success = success and not failureTests |
| 2777 |
if postParse is not None: |
| 2778 |
try: |
| 2779 |
pp_value = postParse(t, result) |
| 2780 |
if pp_value is not None: |
| 2781 |
if isinstance(pp_value, ParseResults): |
| 2782 |
out.append(pp_value.dump()) |
| 2783 |
else: |
| 2784 |
out.append(str(pp_value)) |
| 2785 |
else: |
| 2786 |
out.append(result.dump()) |
| 2787 |
except Exception as e: |
| 2788 |
out.append(result.dump(full=fullDump)) |
| 2789 |
out.append("{0} failed: {1}: {2}".format(postParse.__name__, type(e).__name__, e)) |
| 2790 |
else: |
| 2791 |
out.append(result.dump(full=fullDump)) |
| 2792 |
|
| 2793 |
if printResults: |
| 2794 |
if fullDump: |
| 2795 |
out.append('') |
| 2796 |
print_('\n'.join(out)) |
| 2797 |
|
| 2798 |
allResults.append((t, result)) |
| 2799 |
|
| 2800 |
return success, allResults |
| 2801 |
|
| 2802 |
|
| 2803 |
class _PendingSkip(ParserElement): |
| 2804 |
# internal placeholder class to hold a place were '...' is added to a parser element, |
| 2805 |
# once another ParserElement is added, this placeholder will be replaced with a SkipTo |
| 2806 |
def __init__(self, expr, must_skip=False): |
| 2807 |
super(_PendingSkip, self).__init__() |
| 2808 |
self.strRepr = str(expr + Empty()).replace('Empty', '...') |
| 2809 |
self.name = self.strRepr |
| 2810 |
self.anchor = expr |
| 2811 |
self.must_skip = must_skip |
| 2812 |
|
| 2813 |
def __add__(self, other): |
| 2814 |
skipper = SkipTo(other).setName("...")("_skipped*") |
| 2815 |
if self.must_skip: |
| 2816 |
def must_skip(t): |
| 2817 |
if not t._skipped or t._skipped.asList() == ['']: |
| 2818 |
del t[0] |
| 2819 |
t.pop("_skipped", None) |
| 2820 |
def show_skip(t): |
| 2821 |
if t._skipped.asList()[-1:] == ['']: |
| 2822 |
skipped = t.pop('_skipped') |
| 2823 |
t['_skipped'] = 'missing <' + repr(self.anchor) + '>' |
| 2824 |
return (self.anchor + skipper().addParseAction(must_skip) |
| 2825 |
| skipper().addParseAction(show_skip)) + other |
| 2826 |
|
| 2827 |
return self.anchor + skipper + other |
| 2828 |
|
| 2829 |
def __repr__(self): |
| 2830 |
return self.strRepr |
| 2831 |
|
| 2832 |
def parseImpl(self, *args): |
| 2833 |
raise Exception("use of `...` expression without following SkipTo target expression") |
| 2834 |
|
| 2835 |
|
| 2836 |
class Token(ParserElement): |
| 2837 |
"""Abstract :class:`ParserElement` subclass, for defining atomic |
| 2838 |
matching patterns. |
| 2839 |
""" |
| 2840 |
def __init__(self): |
| 2841 |
super(Token, self).__init__(savelist=False) |
| 2842 |
|
| 2843 |
|
| 2844 |
class Empty(Token): |
| 2845 |
"""An empty token, will always match. |
| 2846 |
""" |
| 2847 |
def __init__(self): |
| 2848 |
super(Empty, self).__init__() |
| 2849 |
self.name = "Empty" |
| 2850 |
self.mayReturnEmpty = True |
| 2851 |
self.mayIndexError = False |
| 2852 |
|
| 2853 |
|
| 2854 |
class NoMatch(Token): |
| 2855 |
"""A token that will never match. |
| 2856 |
""" |
| 2857 |
def __init__(self): |
| 2858 |
super(NoMatch, self).__init__() |
| 2859 |
self.name = "NoMatch" |
| 2860 |
self.mayReturnEmpty = True |
| 2861 |
self.mayIndexError = False |
| 2862 |
self.errmsg = "Unmatchable token" |
| 2863 |
|
| 2864 |
def parseImpl(self, instring, loc, doActions=True): |
| 2865 |
raise ParseException(instring, loc, self.errmsg, self) |
| 2866 |
|
| 2867 |
|
| 2868 |
class Literal(Token): |
| 2869 |
"""Token to exactly match a specified string. |
| 2870 |
|
| 2871 |
Example:: |
| 2872 |
|
| 2873 |
Literal('blah').parseString('blah') # -> ['blah'] |
| 2874 |
Literal('blah').parseString('blahfooblah') # -> ['blah'] |
| 2875 |
Literal('blah').parseString('bla') # -> Exception: Expected "blah" |
| 2876 |
|
| 2877 |
For case-insensitive matching, use :class:`CaselessLiteral`. |
| 2878 |
|
| 2879 |
For keyword matching (force word break before and after the matched string), |
| 2880 |
use :class:`Keyword` or :class:`CaselessKeyword`. |
| 2881 |
""" |
| 2882 |
def __init__(self, matchString): |
| 2883 |
super(Literal, self).__init__() |
| 2884 |
self.match = matchString |
| 2885 |
self.matchLen = len(matchString) |
| 2886 |
try: |
| 2887 |
self.firstMatchChar = matchString[0] |
| 2888 |
except IndexError: |
| 2889 |
warnings.warn("null string passed to Literal; use Empty() instead", |
| 2890 |
SyntaxWarning, stacklevel=2) |
| 2891 |
self.__class__ = Empty |
| 2892 |
self.name = '"%s"' % _ustr(self.match) |
| 2893 |
self.errmsg = "Expected " + self.name |
| 2894 |
self.mayReturnEmpty = False |
| 2895 |
self.mayIndexError = False |
| 2896 |
|
| 2897 |
# Performance tuning: modify __class__ to select |
| 2898 |
# a parseImpl optimized for single-character check |
| 2899 |
if self.matchLen == 1 and type(self) is Literal: |
| 2900 |
self.__class__ = _SingleCharLiteral |
| 2901 |
|
| 2902 |
def parseImpl(self, instring, loc, doActions=True): |
| 2903 |
if instring[loc] == self.firstMatchChar and instring.startswith(self.match, loc): |
| 2904 |
return loc + self.matchLen, self.match |
| 2905 |
raise ParseException(instring, loc, self.errmsg, self) |
| 2906 |
|
| 2907 |
class _SingleCharLiteral(Literal): |
| 2908 |
def parseImpl(self, instring, loc, doActions=True): |
| 2909 |
if instring[loc] == self.firstMatchChar: |
| 2910 |
return loc + 1, self.match |
| 2911 |
raise ParseException(instring, loc, self.errmsg, self) |
| 2912 |
|
| 2913 |
_L = Literal |
| 2914 |
ParserElement._literalStringClass = Literal |
| 2915 |
|
| 2916 |
class Keyword(Token): |
| 2917 |
"""Token to exactly match a specified string as a keyword, that is, |
| 2918 |
it must be immediately followed by a non-keyword character. Compare |
| 2919 |
with :class:`Literal`: |
| 2920 |
|
| 2921 |
- ``Literal("if")`` will match the leading ``'if'`` in |
| 2922 |
``'ifAndOnlyIf'``. |
| 2923 |
- ``Keyword("if")`` will not; it will only match the leading |
| 2924 |
``'if'`` in ``'if x=1'``, or ``'if(y==2)'`` |
| 2925 |
|
| 2926 |
Accepts two optional constructor arguments in addition to the |
| 2927 |
keyword string: |
| 2928 |
|
| 2929 |
- ``identChars`` is a string of characters that would be valid |
| 2930 |
identifier characters, defaulting to all alphanumerics + "_" and |
| 2931 |
"$" |
| 2932 |
- ``caseless`` allows case-insensitive matching, default is ``False``. |
| 2933 |
|
| 2934 |
Example:: |
| 2935 |
|
| 2936 |
Keyword("start").parseString("start") # -> ['start'] |
| 2937 |
Keyword("start").parseString("starting") # -> Exception |
| 2938 |
|
| 2939 |
For case-insensitive matching, use :class:`CaselessKeyword`. |
| 2940 |
""" |
| 2941 |
DEFAULT_KEYWORD_CHARS = alphanums + "_$" |
| 2942 |
|
| 2943 |
def __init__(self, matchString, identChars=None, caseless=False): |
| 2944 |
super(Keyword, self).__init__() |
| 2945 |
if identChars is None: |
| 2946 |
identChars = Keyword.DEFAULT_KEYWORD_CHARS |
| 2947 |
self.match = matchString |
| 2948 |
self.matchLen = len(matchString) |
| 2949 |
try: |
| 2950 |
self.firstMatchChar = matchString[0] |
| 2951 |
except IndexError: |
| 2952 |
warnings.warn("null string passed to Keyword; use Empty() instead", |
| 2953 |
SyntaxWarning, stacklevel=2) |
| 2954 |
self.name = '"%s"' % self.match |
| 2955 |
self.errmsg = "Expected " + self.name |
| 2956 |
self.mayReturnEmpty = False |
| 2957 |
self.mayIndexError = False |
| 2958 |
self.caseless = caseless |
| 2959 |
if caseless: |
| 2960 |
self.caselessmatch = matchString.upper() |
| 2961 |
identChars = identChars.upper() |
| 2962 |
self.identChars = set(identChars) |
| 2963 |
|
| 2964 |
def parseImpl(self, instring, loc, doActions=True): |
| 2965 |
if self.caseless: |
| 2966 |
if ((instring[loc:loc + self.matchLen].upper() == self.caselessmatch) |
| 2967 |
and (loc >= len(instring) - self.matchLen |
| 2968 |
or instring[loc + self.matchLen].upper() not in self.identChars) |
| 2969 |
and (loc == 0 |
| 2970 |
or instring[loc - 1].upper() not in self.identChars)): |
| 2971 |
return loc + self.matchLen, self.match |
| 2972 |
|
| 2973 |
else: |
| 2974 |
if instring[loc] == self.firstMatchChar: |
| 2975 |
if ((self.matchLen == 1 or instring.startswith(self.match, loc)) |
| 2976 |
and (loc >= len(instring) - self.matchLen |
| 2977 |
or instring[loc + self.matchLen] not in self.identChars) |
| 2978 |
and (loc == 0 or instring[loc - 1] not in self.identChars)): |
| 2979 |
return loc + self.matchLen, self.match |
| 2980 |
|
| 2981 |
raise ParseException(instring, loc, self.errmsg, self) |
| 2982 |
|
| 2983 |
def copy(self): |
| 2984 |
c = super(Keyword, self).copy() |
| 2985 |
c.identChars = Keyword.DEFAULT_KEYWORD_CHARS |
| 2986 |
return c |
| 2987 |
|
| 2988 |
@staticmethod |
| 2989 |
def setDefaultKeywordChars(chars): |
| 2990 |
"""Overrides the default Keyword chars |
| 2991 |
""" |
| 2992 |
Keyword.DEFAULT_KEYWORD_CHARS = chars |
| 2993 |
|
| 2994 |
class CaselessLiteral(Literal): |
| 2995 |
"""Token to match a specified string, ignoring case of letters. |
| 2996 |
Note: the matched results will always be in the case of the given |
| 2997 |
match string, NOT the case of the input text. |
| 2998 |
|
| 2999 |
Example:: |
| 3000 |
|
| 3001 |
OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD'] |
| 3002 |
|
| 3003 |
(Contrast with example for :class:`CaselessKeyword`.) |
| 3004 |
""" |
| 3005 |
def __init__(self, matchString): |
| 3006 |
super(CaselessLiteral, self).__init__(matchString.upper()) |
| 3007 |
# Preserve the defining literal. |
| 3008 |
self.returnString = matchString |
| 3009 |
self.name = "'%s'" % self.returnString |
| 3010 |
self.errmsg = "Expected " + self.name |
| 3011 |
|
| 3012 |
def parseImpl(self, instring, loc, doActions=True): |
| 3013 |
if instring[loc:loc + self.matchLen].upper() == self.match: |
| 3014 |
return loc + self.matchLen, self.returnString |
| 3015 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3016 |
|
| 3017 |
class CaselessKeyword(Keyword): |
| 3018 |
""" |
| 3019 |
Caseless version of :class:`Keyword`. |
| 3020 |
|
| 3021 |
Example:: |
| 3022 |
|
| 3023 |
OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD'] |
| 3024 |
|
| 3025 |
(Contrast with example for :class:`CaselessLiteral`.) |
| 3026 |
""" |
| 3027 |
def __init__(self, matchString, identChars=None): |
| 3028 |
super(CaselessKeyword, self).__init__(matchString, identChars, caseless=True) |
| 3029 |
|
| 3030 |
class CloseMatch(Token): |
| 3031 |
"""A variation on :class:`Literal` which matches "close" matches, |
| 3032 |
that is, strings with at most 'n' mismatching characters. |
| 3033 |
:class:`CloseMatch` takes parameters: |
| 3034 |
|
| 3035 |
- ``match_string`` - string to be matched |
| 3036 |
- ``maxMismatches`` - (``default=1``) maximum number of |
| 3037 |
mismatches allowed to count as a match |
| 3038 |
|
| 3039 |
The results from a successful parse will contain the matched text |
| 3040 |
from the input string and the following named results: |
| 3041 |
|
| 3042 |
- ``mismatches`` - a list of the positions within the |
| 3043 |
match_string where mismatches were found |
| 3044 |
- ``original`` - the original match_string used to compare |
| 3045 |
against the input string |
| 3046 |
|
| 3047 |
If ``mismatches`` is an empty list, then the match was an exact |
| 3048 |
match. |
| 3049 |
|
| 3050 |
Example:: |
| 3051 |
|
| 3052 |
patt = CloseMatch("ATCATCGAATGGA") |
| 3053 |
patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']}) |
| 3054 |
patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1) |
| 3055 |
|
| 3056 |
# exact match |
| 3057 |
patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']}) |
| 3058 |
|
| 3059 |
# close match allowing up to 2 mismatches |
| 3060 |
patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2) |
| 3061 |
patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']}) |
| 3062 |
""" |
| 3063 |
def __init__(self, match_string, maxMismatches=1): |
| 3064 |
super(CloseMatch, self).__init__() |
| 3065 |
self.name = match_string |
| 3066 |
self.match_string = match_string |
| 3067 |
self.maxMismatches = maxMismatches |
| 3068 |
self.errmsg = "Expected %r (with up to %d mismatches)" % (self.match_string, self.maxMismatches) |
| 3069 |
self.mayIndexError = False |
| 3070 |
self.mayReturnEmpty = False |
| 3071 |
|
| 3072 |
def parseImpl(self, instring, loc, doActions=True): |
| 3073 |
start = loc |
| 3074 |
instrlen = len(instring) |
| 3075 |
maxloc = start + len(self.match_string) |
| 3076 |
|
| 3077 |
if maxloc <= instrlen: |
| 3078 |
match_string = self.match_string |
| 3079 |
match_stringloc = 0 |
| 3080 |
mismatches = [] |
| 3081 |
maxMismatches = self.maxMismatches |
| 3082 |
|
| 3083 |
for match_stringloc, s_m in enumerate(zip(instring[loc:maxloc], match_string)): |
| 3084 |
src, mat = s_m |
| 3085 |
if src != mat: |
| 3086 |
mismatches.append(match_stringloc) |
| 3087 |
if len(mismatches) > maxMismatches: |
| 3088 |
break |
| 3089 |
else: |
| 3090 |
loc = match_stringloc + 1 |
| 3091 |
results = ParseResults([instring[start:loc]]) |
| 3092 |
results['original'] = match_string |
| 3093 |
results['mismatches'] = mismatches |
| 3094 |
return loc, results |
| 3095 |
|
| 3096 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3097 |
|
| 3098 |
|
| 3099 |
class Word(Token): |
| 3100 |
"""Token for matching words composed of allowed character sets. |
| 3101 |
Defined with string containing all allowed initial characters, an |
| 3102 |
optional string containing allowed body characters (if omitted, |
| 3103 |
defaults to the initial character set), and an optional minimum, |
| 3104 |
maximum, and/or exact length. The default value for ``min`` is |
| 3105 |
1 (a minimum value < 1 is not valid); the default values for |
| 3106 |
``max`` and ``exact`` are 0, meaning no maximum or exact |
| 3107 |
length restriction. An optional ``excludeChars`` parameter can |
| 3108 |
list characters that might be found in the input ``bodyChars`` |
| 3109 |
string; useful to define a word of all printables except for one or |
| 3110 |
two characters, for instance. |
| 3111 |
|
| 3112 |
:class:`srange` is useful for defining custom character set strings |
| 3113 |
for defining ``Word`` expressions, using range notation from |
| 3114 |
regular expression character sets. |
| 3115 |
|
| 3116 |
A common mistake is to use :class:`Word` to match a specific literal |
| 3117 |
string, as in ``Word("Address")``. Remember that :class:`Word` |
| 3118 |
uses the string argument to define *sets* of matchable characters. |
| 3119 |
This expression would match "Add", "AAA", "dAred", or any other word |
| 3120 |
made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an |
| 3121 |
exact literal string, use :class:`Literal` or :class:`Keyword`. |
| 3122 |
|
| 3123 |
pyparsing includes helper strings for building Words: |
| 3124 |
|
| 3125 |
- :class:`alphas` |
| 3126 |
- :class:`nums` |
| 3127 |
- :class:`alphanums` |
| 3128 |
- :class:`hexnums` |
| 3129 |
- :class:`alphas8bit` (alphabetic characters in ASCII range 128-255 |
| 3130 |
- accented, tilded, umlauted, etc.) |
| 3131 |
- :class:`punc8bit` (non-alphabetic characters in ASCII range |
| 3132 |
128-255 - currency, symbols, superscripts, diacriticals, etc.) |
| 3133 |
- :class:`printables` (any non-whitespace character) |
| 3134 |
|
| 3135 |
Example:: |
| 3136 |
|
| 3137 |
# a word composed of digits |
| 3138 |
integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9")) |
| 3139 |
|
| 3140 |
# a word with a leading capital, and zero or more lowercase |
| 3141 |
capital_word = Word(alphas.upper(), alphas.lower()) |
| 3142 |
|
| 3143 |
# hostnames are alphanumeric, with leading alpha, and '-' |
| 3144 |
hostname = Word(alphas, alphanums + '-') |
| 3145 |
|
| 3146 |
# roman numeral (not a strict parser, accepts invalid mix of characters) |
| 3147 |
roman = Word("IVXLCDM") |
| 3148 |
|
| 3149 |
# any string of non-whitespace characters, except for ',' |
| 3150 |
csv_value = Word(printables, excludeChars=",") |
| 3151 |
""" |
| 3152 |
def __init__(self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None): |
| 3153 |
super(Word, self).__init__() |
| 3154 |
if excludeChars: |
| 3155 |
excludeChars = set(excludeChars) |
| 3156 |
initChars = ''.join(c for c in initChars if c not in excludeChars) |
| 3157 |
if bodyChars: |
| 3158 |
bodyChars = ''.join(c for c in bodyChars if c not in excludeChars) |
| 3159 |
self.initCharsOrig = initChars |
| 3160 |
self.initChars = set(initChars) |
| 3161 |
if bodyChars: |
| 3162 |
self.bodyCharsOrig = bodyChars |
| 3163 |
self.bodyChars = set(bodyChars) |
| 3164 |
else: |
| 3165 |
self.bodyCharsOrig = initChars |
| 3166 |
self.bodyChars = set(initChars) |
| 3167 |
|
| 3168 |
self.maxSpecified = max > 0 |
| 3169 |
|
| 3170 |
if min < 1: |
| 3171 |
raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted") |
| 3172 |
|
| 3173 |
self.minLen = min |
| 3174 |
|
| 3175 |
if max > 0: |
| 3176 |
self.maxLen = max |
| 3177 |
else: |
| 3178 |
self.maxLen = _MAX_INT |
| 3179 |
|
| 3180 |
if exact > 0: |
| 3181 |
self.maxLen = exact |
| 3182 |
self.minLen = exact |
| 3183 |
|
| 3184 |
self.name = _ustr(self) |
| 3185 |
self.errmsg = "Expected " + self.name |
| 3186 |
self.mayIndexError = False |
| 3187 |
self.asKeyword = asKeyword |
| 3188 |
|
| 3189 |
if ' ' not in self.initCharsOrig + self.bodyCharsOrig and (min == 1 and max == 0 and exact == 0): |
| 3190 |
if self.bodyCharsOrig == self.initCharsOrig: |
| 3191 |
self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig) |
| 3192 |
elif len(self.initCharsOrig) == 1: |
| 3193 |
self.reString = "%s[%s]*" % (re.escape(self.initCharsOrig), |
| 3194 |
_escapeRegexRangeChars(self.bodyCharsOrig),) |
| 3195 |
else: |
| 3196 |
self.reString = "[%s][%s]*" % (_escapeRegexRangeChars(self.initCharsOrig), |
| 3197 |
_escapeRegexRangeChars(self.bodyCharsOrig),) |
| 3198 |
if self.asKeyword: |
| 3199 |
self.reString = r"\b" + self.reString + r"\b" |
| 3200 |
|
| 3201 |
try: |
| 3202 |
self.re = re.compile(self.reString) |
| 3203 |
except Exception: |
| 3204 |
self.re = None |
| 3205 |
else: |
| 3206 |
self.re_match = self.re.match |
| 3207 |
self.__class__ = _WordRegex |
| 3208 |
|
| 3209 |
def parseImpl(self, instring, loc, doActions=True): |
| 3210 |
if instring[loc] not in self.initChars: |
| 3211 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3212 |
|
| 3213 |
start = loc |
| 3214 |
loc += 1 |
| 3215 |
instrlen = len(instring) |
| 3216 |
bodychars = self.bodyChars |
| 3217 |
maxloc = start + self.maxLen |
| 3218 |
maxloc = min(maxloc, instrlen) |
| 3219 |
while loc < maxloc and instring[loc] in bodychars: |
| 3220 |
loc += 1 |
| 3221 |
|
| 3222 |
throwException = False |
| 3223 |
if loc - start < self.minLen: |
| 3224 |
throwException = True |
| 3225 |
elif self.maxSpecified and loc < instrlen and instring[loc] in bodychars: |
| 3226 |
throwException = True |
| 3227 |
elif self.asKeyword: |
| 3228 |
if (start > 0 and instring[start - 1] in bodychars |
| 3229 |
or loc < instrlen and instring[loc] in bodychars): |
| 3230 |
throwException = True |
| 3231 |
|
| 3232 |
if throwException: |
| 3233 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3234 |
|
| 3235 |
return loc, instring[start:loc] |
| 3236 |
|
| 3237 |
def __str__(self): |
| 3238 |
try: |
| 3239 |
return super(Word, self).__str__() |
| 3240 |
except Exception: |
| 3241 |
pass |
| 3242 |
|
| 3243 |
if self.strRepr is None: |
| 3244 |
|
| 3245 |
def charsAsStr(s): |
| 3246 |
if len(s) > 4: |
| 3247 |
return s[:4] + "..." |
| 3248 |
else: |
| 3249 |
return s |
| 3250 |
|
| 3251 |
if self.initCharsOrig != self.bodyCharsOrig: |
| 3252 |
self.strRepr = "W:(%s, %s)" % (charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig)) |
| 3253 |
else: |
| 3254 |
self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig) |
| 3255 |
|
| 3256 |
return self.strRepr |
| 3257 |
|
| 3258 |
class _WordRegex(Word): |
| 3259 |
def parseImpl(self, instring, loc, doActions=True): |
| 3260 |
result = self.re_match(instring, loc) |
| 3261 |
if not result: |
| 3262 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3263 |
|
| 3264 |
loc = result.end() |
| 3265 |
return loc, result.group() |
| 3266 |
|
| 3267 |
|
| 3268 |
class Char(_WordRegex): |
| 3269 |
"""A short-cut class for defining ``Word(characters, exact=1)``, |
| 3270 |
when defining a match of any single character in a string of |
| 3271 |
characters. |
| 3272 |
""" |
| 3273 |
def __init__(self, charset, asKeyword=False, excludeChars=None): |
| 3274 |
super(Char, self).__init__(charset, exact=1, asKeyword=asKeyword, excludeChars=excludeChars) |
| 3275 |
self.reString = "[%s]" % _escapeRegexRangeChars(''.join(self.initChars)) |
| 3276 |
if asKeyword: |
| 3277 |
self.reString = r"\b%s\b" % self.reString |
| 3278 |
self.re = re.compile(self.reString) |
| 3279 |
self.re_match = self.re.match |
| 3280 |
|
| 3281 |
|
| 3282 |
class Regex(Token): |
| 3283 |
r"""Token for matching strings that match a given regular |
| 3284 |
expression. Defined with string specifying the regular expression in |
| 3285 |
a form recognized by the stdlib Python `re module <https://docs.python.org/3/library/re.html>`_. |
| 3286 |
If the given regex contains named groups (defined using ``(?P<name>...)``), |
| 3287 |
these will be preserved as named parse results. |
| 3288 |
|
| 3289 |
If instead of the Python stdlib re module you wish to use a different RE module |
| 3290 |
(such as the `regex` module), you can replace it by either building your |
| 3291 |
Regex object with a compiled RE that was compiled using regex: |
| 3292 |
|
| 3293 |
Example:: |
| 3294 |
|
| 3295 |
realnum = Regex(r"[+-]?\d+\.\d*") |
| 3296 |
date = Regex(r'(?P<year>\d{4})-(?P<month>\d\d?)-(?P<day>\d\d?)') |
| 3297 |
# ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression |
| 3298 |
roman = Regex(r"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") |
| 3299 |
|
| 3300 |
# use regex module instead of stdlib re module to construct a Regex using |
| 3301 |
# a compiled regular expression |
| 3302 |
import regex |
| 3303 |
parser = pp.Regex(regex.compile(r'[0-9]')) |
| 3304 |
|
| 3305 |
""" |
| 3306 |
def __init__(self, pattern, flags=0, asGroupList=False, asMatch=False): |
| 3307 |
"""The parameters ``pattern`` and ``flags`` are passed |
| 3308 |
to the ``re.compile()`` function as-is. See the Python |
| 3309 |
`re module <https://docs.python.org/3/library/re.html>`_ module for an |
| 3310 |
explanation of the acceptable patterns and flags. |
| 3311 |
""" |
| 3312 |
super(Regex, self).__init__() |
| 3313 |
|
| 3314 |
if isinstance(pattern, basestring): |
| 3315 |
if not pattern: |
| 3316 |
warnings.warn("null string passed to Regex; use Empty() instead", |
| 3317 |
SyntaxWarning, stacklevel=2) |
| 3318 |
|
| 3319 |
self.pattern = pattern |
| 3320 |
self.flags = flags |
| 3321 |
|
| 3322 |
try: |
| 3323 |
self.re = re.compile(self.pattern, self.flags) |
| 3324 |
self.reString = self.pattern |
| 3325 |
except sre_constants.error: |
| 3326 |
warnings.warn("invalid pattern (%s) passed to Regex" % pattern, |
| 3327 |
SyntaxWarning, stacklevel=2) |
| 3328 |
raise |
| 3329 |
|
| 3330 |
elif hasattr(pattern, 'pattern') and hasattr(pattern, 'match'): |
| 3331 |
self.re = pattern |
| 3332 |
self.pattern = self.reString = pattern.pattern |
| 3333 |
self.flags = flags |
| 3334 |
|
| 3335 |
else: |
| 3336 |
raise TypeError("Regex may only be constructed with a string or a compiled RE object") |
| 3337 |
|
| 3338 |
self.re_match = self.re.match |
| 3339 |
|
| 3340 |
self.name = _ustr(self) |
| 3341 |
self.errmsg = "Expected " + self.name |
| 3342 |
self.mayIndexError = False |
| 3343 |
self.mayReturnEmpty = self.re_match("") is not None |
| 3344 |
self.asGroupList = asGroupList |
| 3345 |
self.asMatch = asMatch |
| 3346 |
if self.asGroupList: |
| 3347 |
self.parseImpl = self.parseImplAsGroupList |
| 3348 |
if self.asMatch: |
| 3349 |
self.parseImpl = self.parseImplAsMatch |
| 3350 |
|
| 3351 |
def parseImpl(self, instring, loc, doActions=True): |
| 3352 |
result = self.re_match(instring, loc) |
| 3353 |
if not result: |
| 3354 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3355 |
|
| 3356 |
loc = result.end() |
| 3357 |
ret = ParseResults(result.group()) |
| 3358 |
d = result.groupdict() |
| 3359 |
if d: |
| 3360 |
for k, v in d.items(): |
| 3361 |
ret[k] = v |
| 3362 |
return loc, ret |
| 3363 |
|
| 3364 |
def parseImplAsGroupList(self, instring, loc, doActions=True): |
| 3365 |
result = self.re_match(instring, loc) |
| 3366 |
if not result: |
| 3367 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3368 |
|
| 3369 |
loc = result.end() |
| 3370 |
ret = result.groups() |
| 3371 |
return loc, ret |
| 3372 |
|
| 3373 |
def parseImplAsMatch(self, instring, loc, doActions=True): |
| 3374 |
result = self.re_match(instring, loc) |
| 3375 |
if not result: |
| 3376 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3377 |
|
| 3378 |
loc = result.end() |
| 3379 |
ret = result |
| 3380 |
return loc, ret |
| 3381 |
|
| 3382 |
def __str__(self): |
| 3383 |
try: |
| 3384 |
return super(Regex, self).__str__() |
| 3385 |
except Exception: |
| 3386 |
pass |
| 3387 |
|
| 3388 |
if self.strRepr is None: |
| 3389 |
self.strRepr = "Re:(%s)" % repr(self.pattern) |
| 3390 |
|
| 3391 |
return self.strRepr |
| 3392 |
|
| 3393 |
def sub(self, repl): |
| 3394 |
r""" |
| 3395 |
Return Regex with an attached parse action to transform the parsed |
| 3396 |
result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_. |
| 3397 |
|
| 3398 |
Example:: |
| 3399 |
|
| 3400 |
make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>") |
| 3401 |
print(make_html.transformString("h1:main title:")) |
| 3402 |
# prints "<h1>main title</h1>" |
| 3403 |
""" |
| 3404 |
if self.asGroupList: |
| 3405 |
warnings.warn("cannot use sub() with Regex(asGroupList=True)", |
| 3406 |
SyntaxWarning, stacklevel=2) |
| 3407 |
raise SyntaxError() |
| 3408 |
|
| 3409 |
if self.asMatch and callable(repl): |
| 3410 |
warnings.warn("cannot use sub() with a callable with Regex(asMatch=True)", |
| 3411 |
SyntaxWarning, stacklevel=2) |
| 3412 |
raise SyntaxError() |
| 3413 |
|
| 3414 |
if self.asMatch: |
| 3415 |
def pa(tokens): |
| 3416 |
return tokens[0].expand(repl) |
| 3417 |
else: |
| 3418 |
def pa(tokens): |
| 3419 |
return self.re.sub(repl, tokens[0]) |
| 3420 |
return self.addParseAction(pa) |
| 3421 |
|
| 3422 |
class QuotedString(Token): |
| 3423 |
r""" |
| 3424 |
Token for matching strings that are delimited by quoting characters. |
| 3425 |
|
| 3426 |
Defined with the following parameters: |
| 3427 |
|
| 3428 |
- quoteChar - string of one or more characters defining the |
| 3429 |
quote delimiting string |
| 3430 |
- escChar - character to escape quotes, typically backslash |
| 3431 |
(default= ``None``) |
| 3432 |
- escQuote - special quote sequence to escape an embedded quote |
| 3433 |
string (such as SQL's ``""`` to escape an embedded ``"``) |
| 3434 |
(default= ``None``) |
| 3435 |
- multiline - boolean indicating whether quotes can span |
| 3436 |
multiple lines (default= ``False``) |
| 3437 |
- unquoteResults - boolean indicating whether the matched text |
| 3438 |
should be unquoted (default= ``True``) |
| 3439 |
- endQuoteChar - string of one or more characters defining the |
| 3440 |
end of the quote delimited string (default= ``None`` => same as |
| 3441 |
quoteChar) |
| 3442 |
- convertWhitespaceEscapes - convert escaped whitespace |
| 3443 |
(``'\t'``, ``'\n'``, etc.) to actual whitespace |
| 3444 |
(default= ``True``) |
| 3445 |
|
| 3446 |
Example:: |
| 3447 |
|
| 3448 |
qs = QuotedString('"') |
| 3449 |
print(qs.searchString('lsjdf "This is the quote" sldjf')) |
| 3450 |
complex_qs = QuotedString('{{', endQuoteChar='}}') |
| 3451 |
print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf')) |
| 3452 |
sql_qs = QuotedString('"', escQuote='""') |
| 3453 |
print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf')) |
| 3454 |
|
| 3455 |
prints:: |
| 3456 |
|
| 3457 |
[['This is the quote']] |
| 3458 |
[['This is the "quote"']] |
| 3459 |
[['This is the quote with "embedded" quotes']] |
| 3460 |
""" |
| 3461 |
def __init__(self, quoteChar, escChar=None, escQuote=None, multiline=False, |
| 3462 |
unquoteResults=True, endQuoteChar=None, convertWhitespaceEscapes=True): |
| 3463 |
super(QuotedString, self).__init__() |
| 3464 |
|
| 3465 |
# remove white space from quote chars - won't work anyway |
| 3466 |
quoteChar = quoteChar.strip() |
| 3467 |
if not quoteChar: |
| 3468 |
warnings.warn("quoteChar cannot be the empty string", SyntaxWarning, stacklevel=2) |
| 3469 |
raise SyntaxError() |
| 3470 |
|
| 3471 |
if endQuoteChar is None: |
| 3472 |
endQuoteChar = quoteChar |
| 3473 |
else: |
| 3474 |
endQuoteChar = endQuoteChar.strip() |
| 3475 |
if not endQuoteChar: |
| 3476 |
warnings.warn("endQuoteChar cannot be the empty string", SyntaxWarning, stacklevel=2) |
| 3477 |
raise SyntaxError() |
| 3478 |
|
| 3479 |
self.quoteChar = quoteChar |
| 3480 |
self.quoteCharLen = len(quoteChar) |
| 3481 |
self.firstQuoteChar = quoteChar[0] |
| 3482 |
self.endQuoteChar = endQuoteChar |
| 3483 |
self.endQuoteCharLen = len(endQuoteChar) |
| 3484 |
self.escChar = escChar |
| 3485 |
self.escQuote = escQuote |
| 3486 |
self.unquoteResults = unquoteResults |
| 3487 |
self.convertWhitespaceEscapes = convertWhitespaceEscapes |
| 3488 |
|
| 3489 |
if multiline: |
| 3490 |
self.flags = re.MULTILINE | re.DOTALL |
| 3491 |
self.pattern = r'%s(?:[^%s%s]' % (re.escape(self.quoteChar), |
| 3492 |
_escapeRegexRangeChars(self.endQuoteChar[0]), |
| 3493 |
(escChar is not None and _escapeRegexRangeChars(escChar) or '')) |
| 3494 |
else: |
| 3495 |
self.flags = 0 |
| 3496 |
self.pattern = r'%s(?:[^%s\n\r%s]' % (re.escape(self.quoteChar), |
| 3497 |
_escapeRegexRangeChars(self.endQuoteChar[0]), |
| 3498 |
(escChar is not None and _escapeRegexRangeChars(escChar) or '')) |
| 3499 |
if len(self.endQuoteChar) > 1: |
| 3500 |
self.pattern += ( |
| 3501 |
'|(?:' + ')|(?:'.join("%s[^%s]" % (re.escape(self.endQuoteChar[:i]), |
| 3502 |
_escapeRegexRangeChars(self.endQuoteChar[i])) |
| 3503 |
for i in range(len(self.endQuoteChar) - 1, 0, -1)) + ')') |
| 3504 |
|
| 3505 |
if escQuote: |
| 3506 |
self.pattern += (r'|(?:%s)' % re.escape(escQuote)) |
| 3507 |
if escChar: |
| 3508 |
self.pattern += (r'|(?:%s.)' % re.escape(escChar)) |
| 3509 |
self.escCharReplacePattern = re.escape(self.escChar) + "(.)" |
| 3510 |
self.pattern += (r')*%s' % re.escape(self.endQuoteChar)) |
| 3511 |
|
| 3512 |
try: |
| 3513 |
self.re = re.compile(self.pattern, self.flags) |
| 3514 |
self.reString = self.pattern |
| 3515 |
self.re_match = self.re.match |
| 3516 |
except sre_constants.error: |
| 3517 |
warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern, |
| 3518 |
SyntaxWarning, stacklevel=2) |
| 3519 |
raise |
| 3520 |
|
| 3521 |
self.name = _ustr(self) |
| 3522 |
self.errmsg = "Expected " + self.name |
| 3523 |
self.mayIndexError = False |
| 3524 |
self.mayReturnEmpty = True |
| 3525 |
|
| 3526 |
def parseImpl(self, instring, loc, doActions=True): |
| 3527 |
result = instring[loc] == self.firstQuoteChar and self.re_match(instring, loc) or None |
| 3528 |
if not result: |
| 3529 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3530 |
|
| 3531 |
loc = result.end() |
| 3532 |
ret = result.group() |
| 3533 |
|
| 3534 |
if self.unquoteResults: |
| 3535 |
|
| 3536 |
# strip off quotes |
| 3537 |
ret = ret[self.quoteCharLen: -self.endQuoteCharLen] |
| 3538 |
|
| 3539 |
if isinstance(ret, basestring): |
| 3540 |
# replace escaped whitespace |
| 3541 |
if '\\' in ret and self.convertWhitespaceEscapes: |
| 3542 |
ws_map = { |
| 3543 |
r'\t': '\t', |
| 3544 |
r'\n': '\n', |
| 3545 |
r'\f': '\f', |
| 3546 |
r'\r': '\r', |
| 3547 |
} |
| 3548 |
for wslit, wschar in ws_map.items(): |
| 3549 |
ret = ret.replace(wslit, wschar) |
| 3550 |
|
| 3551 |
# replace escaped characters |
| 3552 |
if self.escChar: |
| 3553 |
ret = re.sub(self.escCharReplacePattern, r"\g<1>", ret) |
| 3554 |
|
| 3555 |
# replace escaped quotes |
| 3556 |
if self.escQuote: |
| 3557 |
ret = ret.replace(self.escQuote, self.endQuoteChar) |
| 3558 |
|
| 3559 |
return loc, ret |
| 3560 |
|
| 3561 |
def __str__(self): |
| 3562 |
try: |
| 3563 |
return super(QuotedString, self).__str__() |
| 3564 |
except Exception: |
| 3565 |
pass |
| 3566 |
|
| 3567 |
if self.strRepr is None: |
| 3568 |
self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar) |
| 3569 |
|
| 3570 |
return self.strRepr |
| 3571 |
|
| 3572 |
|
| 3573 |
class CharsNotIn(Token): |
| 3574 |
"""Token for matching words composed of characters *not* in a given |
| 3575 |
set (will include whitespace in matched characters if not listed in |
| 3576 |
the provided exclusion set - see example). Defined with string |
| 3577 |
containing all disallowed characters, and an optional minimum, |
| 3578 |
maximum, and/or exact length. The default value for ``min`` is |
| 3579 |
1 (a minimum value < 1 is not valid); the default values for |
| 3580 |
``max`` and ``exact`` are 0, meaning no maximum or exact |
| 3581 |
length restriction. |
| 3582 |
|
| 3583 |
Example:: |
| 3584 |
|
| 3585 |
# define a comma-separated-value as anything that is not a ',' |
| 3586 |
csv_value = CharsNotIn(',') |
| 3587 |
print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213")) |
| 3588 |
|
| 3589 |
prints:: |
| 3590 |
|
| 3591 |
['dkls', 'lsdkjf', 's12 34', '@!#', '213'] |
| 3592 |
""" |
| 3593 |
def __init__(self, notChars, min=1, max=0, exact=0): |
| 3594 |
super(CharsNotIn, self).__init__() |
| 3595 |
self.skipWhitespace = False |
| 3596 |
self.notChars = notChars |
| 3597 |
|
| 3598 |
if min < 1: |
| 3599 |
raise ValueError("cannot specify a minimum length < 1; use " |
| 3600 |
"Optional(CharsNotIn()) if zero-length char group is permitted") |
| 3601 |
|
| 3602 |
self.minLen = min |
| 3603 |
|
| 3604 |
if max > 0: |
| 3605 |
self.maxLen = max |
| 3606 |
else: |
| 3607 |
self.maxLen = _MAX_INT |
| 3608 |
|
| 3609 |
if exact > 0: |
| 3610 |
self.maxLen = exact |
| 3611 |
self.minLen = exact |
| 3612 |
|
| 3613 |
self.name = _ustr(self) |
| 3614 |
self.errmsg = "Expected " + self.name |
| 3615 |
self.mayReturnEmpty = (self.minLen == 0) |
| 3616 |
self.mayIndexError = False |
| 3617 |
|
| 3618 |
def parseImpl(self, instring, loc, doActions=True): |
| 3619 |
if instring[loc] in self.notChars: |
| 3620 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3621 |
|
| 3622 |
start = loc |
| 3623 |
loc += 1 |
| 3624 |
notchars = self.notChars |
| 3625 |
maxlen = min(start + self.maxLen, len(instring)) |
| 3626 |
while loc < maxlen and instring[loc] not in notchars: |
| 3627 |
loc += 1 |
| 3628 |
|
| 3629 |
if loc - start < self.minLen: |
| 3630 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3631 |
|
| 3632 |
return loc, instring[start:loc] |
| 3633 |
|
| 3634 |
def __str__(self): |
| 3635 |
try: |
| 3636 |
return super(CharsNotIn, self).__str__() |
| 3637 |
except Exception: |
| 3638 |
pass |
| 3639 |
|
| 3640 |
if self.strRepr is None: |
| 3641 |
if len(self.notChars) > 4: |
| 3642 |
self.strRepr = "!W:(%s...)" % self.notChars[:4] |
| 3643 |
else: |
| 3644 |
self.strRepr = "!W:(%s)" % self.notChars |
| 3645 |
|
| 3646 |
return self.strRepr |
| 3647 |
|
| 3648 |
class White(Token): |
| 3649 |
"""Special matching class for matching whitespace. Normally, |
| 3650 |
whitespace is ignored by pyparsing grammars. This class is included |
| 3651 |
when some whitespace structures are significant. Define with |
| 3652 |
a string containing the whitespace characters to be matched; default |
| 3653 |
is ``" \\t\\r\\n"``. Also takes optional ``min``, |
| 3654 |
``max``, and ``exact`` arguments, as defined for the |
| 3655 |
:class:`Word` class. |
| 3656 |
""" |
| 3657 |
whiteStrs = { |
| 3658 |
' ' : '<SP>', |
| 3659 |
'\t': '<TAB>', |
| 3660 |
'\n': '<LF>', |
| 3661 |
'\r': '<CR>', |
| 3662 |
'\f': '<FF>', |
| 3663 |
u'\u00A0': '<NBSP>', |
| 3664 |
u'\u1680': '<OGHAM_SPACE_MARK>', |
| 3665 |
u'\u180E': '<MONGOLIAN_VOWEL_SEPARATOR>', |
| 3666 |
u'\u2000': '<EN_QUAD>', |
| 3667 |
u'\u2001': '<EM_QUAD>', |
| 3668 |
u'\u2002': '<EN_SPACE>', |
| 3669 |
u'\u2003': '<EM_SPACE>', |
| 3670 |
u'\u2004': '<THREE-PER-EM_SPACE>', |
| 3671 |
u'\u2005': '<FOUR-PER-EM_SPACE>', |
| 3672 |
u'\u2006': '<SIX-PER-EM_SPACE>', |
| 3673 |
u'\u2007': '<FIGURE_SPACE>', |
| 3674 |
u'\u2008': '<PUNCTUATION_SPACE>', |
| 3675 |
u'\u2009': '<THIN_SPACE>', |
| 3676 |
u'\u200A': '<HAIR_SPACE>', |
| 3677 |
u'\u200B': '<ZERO_WIDTH_SPACE>', |
| 3678 |
u'\u202F': '<NNBSP>', |
| 3679 |
u'\u205F': '<MMSP>', |
| 3680 |
u'\u3000': '<IDEOGRAPHIC_SPACE>', |
| 3681 |
} |
| 3682 |
def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0): |
| 3683 |
super(White, self).__init__() |
| 3684 |
self.matchWhite = ws |
| 3685 |
self.setWhitespaceChars("".join(c for c in self.whiteChars if c not in self.matchWhite)) |
| 3686 |
# ~ self.leaveWhitespace() |
| 3687 |
self.name = ("".join(White.whiteStrs[c] for c in self.matchWhite)) |
| 3688 |
self.mayReturnEmpty = True |
| 3689 |
self.errmsg = "Expected " + self.name |
| 3690 |
|
| 3691 |
self.minLen = min |
| 3692 |
|
| 3693 |
if max > 0: |
| 3694 |
self.maxLen = max |
| 3695 |
else: |
| 3696 |
self.maxLen = _MAX_INT |
| 3697 |
|
| 3698 |
if exact > 0: |
| 3699 |
self.maxLen = exact |
| 3700 |
self.minLen = exact |
| 3701 |
|
| 3702 |
def parseImpl(self, instring, loc, doActions=True): |
| 3703 |
if instring[loc] not in self.matchWhite: |
| 3704 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3705 |
start = loc |
| 3706 |
loc += 1 |
| 3707 |
maxloc = start + self.maxLen |
| 3708 |
maxloc = min(maxloc, len(instring)) |
| 3709 |
while loc < maxloc and instring[loc] in self.matchWhite: |
| 3710 |
loc += 1 |
| 3711 |
|
| 3712 |
if loc - start < self.minLen: |
| 3713 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3714 |
|
| 3715 |
return loc, instring[start:loc] |
| 3716 |
|
| 3717 |
|
| 3718 |
class _PositionToken(Token): |
| 3719 |
def __init__(self): |
| 3720 |
super(_PositionToken, self).__init__() |
| 3721 |
self.name = self.__class__.__name__ |
| 3722 |
self.mayReturnEmpty = True |
| 3723 |
self.mayIndexError = False |
| 3724 |
|
| 3725 |
class GoToColumn(_PositionToken): |
| 3726 |
"""Token to advance to a specific column of input text; useful for |
| 3727 |
tabular report scraping. |
| 3728 |
""" |
| 3729 |
def __init__(self, colno): |
| 3730 |
super(GoToColumn, self).__init__() |
| 3731 |
self.col = colno |
| 3732 |
|
| 3733 |
def preParse(self, instring, loc): |
| 3734 |
if col(loc, instring) != self.col: |
| 3735 |
instrlen = len(instring) |
| 3736 |
if self.ignoreExprs: |
| 3737 |
loc = self._skipIgnorables(instring, loc) |
| 3738 |
while loc < instrlen and instring[loc].isspace() and col(loc, instring) != self.col: |
| 3739 |
loc += 1 |
| 3740 |
return loc |
| 3741 |
|
| 3742 |
def parseImpl(self, instring, loc, doActions=True): |
| 3743 |
thiscol = col(loc, instring) |
| 3744 |
if thiscol > self.col: |
| 3745 |
raise ParseException(instring, loc, "Text not in expected column", self) |
| 3746 |
newloc = loc + self.col - thiscol |
| 3747 |
ret = instring[loc: newloc] |
| 3748 |
return newloc, ret |
| 3749 |
|
| 3750 |
|
| 3751 |
class LineStart(_PositionToken): |
| 3752 |
r"""Matches if current position is at the beginning of a line within |
| 3753 |
the parse string |
| 3754 |
|
| 3755 |
Example:: |
| 3756 |
|
| 3757 |
test = '''\ |
| 3758 |
AAA this line |
| 3759 |
AAA and this line |
| 3760 |
AAA but not this one |
| 3761 |
B AAA and definitely not this one |
| 3762 |
''' |
| 3763 |
|
| 3764 |
for t in (LineStart() + 'AAA' + restOfLine).searchString(test): |
| 3765 |
print(t) |
| 3766 |
|
| 3767 |
prints:: |
| 3768 |
|
| 3769 |
['AAA', ' this line'] |
| 3770 |
['AAA', ' and this line'] |
| 3771 |
|
| 3772 |
""" |
| 3773 |
def __init__(self): |
| 3774 |
super(LineStart, self).__init__() |
| 3775 |
self.errmsg = "Expected start of line" |
| 3776 |
|
| 3777 |
def parseImpl(self, instring, loc, doActions=True): |
| 3778 |
if col(loc, instring) == 1: |
| 3779 |
return loc, [] |
| 3780 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3781 |
|
| 3782 |
class LineEnd(_PositionToken): |
| 3783 |
"""Matches if current position is at the end of a line within the |
| 3784 |
parse string |
| 3785 |
""" |
| 3786 |
def __init__(self): |
| 3787 |
super(LineEnd, self).__init__() |
| 3788 |
self.setWhitespaceChars(ParserElement.DEFAULT_WHITE_CHARS.replace("\n", "")) |
| 3789 |
self.errmsg = "Expected end of line" |
| 3790 |
|
| 3791 |
def parseImpl(self, instring, loc, doActions=True): |
| 3792 |
if loc < len(instring): |
| 3793 |
if instring[loc] == "\n": |
| 3794 |
return loc + 1, "\n" |
| 3795 |
else: |
| 3796 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3797 |
elif loc == len(instring): |
| 3798 |
return loc + 1, [] |
| 3799 |
else: |
| 3800 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3801 |
|
| 3802 |
class StringStart(_PositionToken): |
| 3803 |
"""Matches if current position is at the beginning of the parse |
| 3804 |
string |
| 3805 |
""" |
| 3806 |
def __init__(self): |
| 3807 |
super(StringStart, self).__init__() |
| 3808 |
self.errmsg = "Expected start of text" |
| 3809 |
|
| 3810 |
def parseImpl(self, instring, loc, doActions=True): |
| 3811 |
if loc != 0: |
| 3812 |
# see if entire string up to here is just whitespace and ignoreables |
| 3813 |
if loc != self.preParse(instring, 0): |
| 3814 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3815 |
return loc, [] |
| 3816 |
|
| 3817 |
class StringEnd(_PositionToken): |
| 3818 |
"""Matches if current position is at the end of the parse string |
| 3819 |
""" |
| 3820 |
def __init__(self): |
| 3821 |
super(StringEnd, self).__init__() |
| 3822 |
self.errmsg = "Expected end of text" |
| 3823 |
|
| 3824 |
def parseImpl(self, instring, loc, doActions=True): |
| 3825 |
if loc < len(instring): |
| 3826 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3827 |
elif loc == len(instring): |
| 3828 |
return loc + 1, [] |
| 3829 |
elif loc > len(instring): |
| 3830 |
return loc, [] |
| 3831 |
else: |
| 3832 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3833 |
|
| 3834 |
class WordStart(_PositionToken): |
| 3835 |
"""Matches if the current position is at the beginning of a Word, |
| 3836 |
and is not preceded by any character in a given set of |
| 3837 |
``wordChars`` (default= ``printables``). To emulate the |
| 3838 |
``\b`` behavior of regular expressions, use |
| 3839 |
``WordStart(alphanums)``. ``WordStart`` will also match at |
| 3840 |
the beginning of the string being parsed, or at the beginning of |
| 3841 |
a line. |
| 3842 |
""" |
| 3843 |
def __init__(self, wordChars=printables): |
| 3844 |
super(WordStart, self).__init__() |
| 3845 |
self.wordChars = set(wordChars) |
| 3846 |
self.errmsg = "Not at the start of a word" |
| 3847 |
|
| 3848 |
def parseImpl(self, instring, loc, doActions=True): |
| 3849 |
if loc != 0: |
| 3850 |
if (instring[loc - 1] in self.wordChars |
| 3851 |
or instring[loc] not in self.wordChars): |
| 3852 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3853 |
return loc, [] |
| 3854 |
|
| 3855 |
class WordEnd(_PositionToken): |
| 3856 |
"""Matches if the current position is at the end of a Word, and is |
| 3857 |
not followed by any character in a given set of ``wordChars`` |
| 3858 |
(default= ``printables``). To emulate the ``\b`` behavior of |
| 3859 |
regular expressions, use ``WordEnd(alphanums)``. ``WordEnd`` |
| 3860 |
will also match at the end of the string being parsed, or at the end |
| 3861 |
of a line. |
| 3862 |
""" |
| 3863 |
def __init__(self, wordChars=printables): |
| 3864 |
super(WordEnd, self).__init__() |
| 3865 |
self.wordChars = set(wordChars) |
| 3866 |
self.skipWhitespace = False |
| 3867 |
self.errmsg = "Not at the end of a word" |
| 3868 |
|
| 3869 |
def parseImpl(self, instring, loc, doActions=True): |
| 3870 |
instrlen = len(instring) |
| 3871 |
if instrlen > 0 and loc < instrlen: |
| 3872 |
if (instring[loc] in self.wordChars or |
| 3873 |
instring[loc - 1] not in self.wordChars): |
| 3874 |
raise ParseException(instring, loc, self.errmsg, self) |
| 3875 |
return loc, [] |
| 3876 |
|
| 3877 |
|
| 3878 |
class ParseExpression(ParserElement): |
| 3879 |
"""Abstract subclass of ParserElement, for combining and |
| 3880 |
post-processing parsed tokens. |
| 3881 |
""" |
| 3882 |
def __init__(self, exprs, savelist=False): |
| 3883 |
super(ParseExpression, self).__init__(savelist) |
| 3884 |
if isinstance(exprs, _generatorType): |
| 3885 |
exprs = list(exprs) |
| 3886 |
|
| 3887 |
if isinstance(exprs, basestring): |
| 3888 |
self.exprs = [self._literalStringClass(exprs)] |
| 3889 |
elif isinstance(exprs, ParserElement): |
| 3890 |
self.exprs = [exprs] |
| 3891 |
elif isinstance(exprs, Iterable): |
| 3892 |
exprs = list(exprs) |
| 3893 |
# if sequence of strings provided, wrap with Literal |
| 3894 |
if any(isinstance(expr, basestring) for expr in exprs): |
| 3895 |
exprs = (self._literalStringClass(e) if isinstance(e, basestring) else e for e in exprs) |
| 3896 |
self.exprs = list(exprs) |
| 3897 |
else: |
| 3898 |
try: |
| 3899 |
self.exprs = list(exprs) |
| 3900 |
except TypeError: |
| 3901 |
self.exprs = [exprs] |
| 3902 |
self.callPreparse = False |
| 3903 |
|
| 3904 |
def append(self, other): |
| 3905 |
self.exprs.append(other) |
| 3906 |
self.strRepr = None |
| 3907 |
return self |
| 3908 |
|
| 3909 |
def leaveWhitespace(self): |
| 3910 |
"""Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on |
| 3911 |
all contained expressions.""" |
| 3912 |
self.skipWhitespace = False |
| 3913 |
self.exprs = [e.copy() for e in self.exprs] |
| 3914 |
for e in self.exprs: |
| 3915 |
e.leaveWhitespace() |
| 3916 |
return self |
| 3917 |
|
| 3918 |
def ignore(self, other): |
| 3919 |
if isinstance(other, Suppress): |
| 3920 |
if other not in self.ignoreExprs: |
| 3921 |
super(ParseExpression, self).ignore(other) |
| 3922 |
for e in self.exprs: |
| 3923 |
e.ignore(self.ignoreExprs[-1]) |
| 3924 |
else: |
| 3925 |
super(ParseExpression, self).ignore(other) |
| 3926 |
for e in self.exprs: |
| 3927 |
e.ignore(self.ignoreExprs[-1]) |
| 3928 |
return self |
| 3929 |
|
| 3930 |
def __str__(self): |
| 3931 |
try: |
| 3932 |
return super(ParseExpression, self).__str__() |
| 3933 |
except Exception: |
| 3934 |
pass |
| 3935 |
|
| 3936 |
if self.strRepr is None: |
| 3937 |
self.strRepr = "%s:(%s)" % (self.__class__.__name__, _ustr(self.exprs)) |
| 3938 |
return self.strRepr |
| 3939 |
|
| 3940 |
def streamline(self): |
| 3941 |
super(ParseExpression, self).streamline() |
| 3942 |
|
| 3943 |
for e in self.exprs: |
| 3944 |
e.streamline() |
| 3945 |
|
| 3946 |
# collapse nested And's of the form And(And(And(a, b), c), d) to And(a, b, c, d) |
| 3947 |
# but only if there are no parse actions or resultsNames on the nested And's |
| 3948 |
# (likewise for Or's and MatchFirst's) |
| 3949 |
if len(self.exprs) == 2: |
| 3950 |
other = self.exprs[0] |
| 3951 |
if (isinstance(other, self.__class__) |
| 3952 |
and not other.parseAction |
| 3953 |
and other.resultsName is None |
| 3954 |
and not other.debug): |
| 3955 |
self.exprs = other.exprs[:] + [self.exprs[1]] |
| 3956 |
self.strRepr = None |
| 3957 |
self.mayReturnEmpty |= other.mayReturnEmpty |
| 3958 |
self.mayIndexError |= other.mayIndexError |
| 3959 |
|
| 3960 |
other = self.exprs[-1] |
| 3961 |
if (isinstance(other, self.__class__) |
| 3962 |
and not other.parseAction |
| 3963 |
and other.resultsName is None |
| 3964 |
and not other.debug): |
| 3965 |
self.exprs = self.exprs[:-1] + other.exprs[:] |
| 3966 |
self.strRepr = None |
| 3967 |
self.mayReturnEmpty |= other.mayReturnEmpty |
| 3968 |
self.mayIndexError |= other.mayIndexError |
| 3969 |
|
| 3970 |
self.errmsg = "Expected " + _ustr(self) |
| 3971 |
|
| 3972 |
return self |
| 3973 |
|
| 3974 |
def validate(self, validateTrace=None): |
| 3975 |
tmp = (validateTrace if validateTrace is not None else [])[:] + [self] |
| 3976 |
for e in self.exprs: |
| 3977 |
e.validate(tmp) |
| 3978 |
self.checkRecursion([]) |
| 3979 |
|
| 3980 |
def copy(self): |
| 3981 |
ret = super(ParseExpression, self).copy() |
| 3982 |
ret.exprs = [e.copy() for e in self.exprs] |
| 3983 |
return ret |
| 3984 |
|
| 3985 |
def _setResultsName(self, name, listAllMatches=False): |
| 3986 |
if __diag__.warn_ungrouped_named_tokens_in_collection: |
| 3987 |
for e in self.exprs: |
| 3988 |
if isinstance(e, ParserElement) and e.resultsName: |
| 3989 |
warnings.warn("{0}: setting results name {1!r} on {2} expression " |
| 3990 |
"collides with {3!r} on contained expression".format("warn_ungrouped_named_tokens_in_collection", |
| 3991 |
name, |
| 3992 |
type(self).__name__, |
| 3993 |
e.resultsName), |
| 3994 |
stacklevel=3) |
| 3995 |
|
| 3996 |
return super(ParseExpression, self)._setResultsName(name, listAllMatches) |
| 3997 |
|
| 3998 |
|
| 3999 |
class And(ParseExpression): |
| 4000 |
""" |
| 4001 |
Requires all given :class:`ParseExpression` s to be found in the given order. |
| 4002 |
Expressions may be separated by whitespace. |
| 4003 |
May be constructed using the ``'+'`` operator. |
| 4004 |
May also be constructed using the ``'-'`` operator, which will |
| 4005 |
suppress backtracking. |
| 4006 |
|
| 4007 |
Example:: |
| 4008 |
|
| 4009 |
integer = Word(nums) |
| 4010 |
name_expr = OneOrMore(Word(alphas)) |
| 4011 |
|
| 4012 |
expr = And([integer("id"), name_expr("name"), integer("age")]) |
| 4013 |
# more easily written as: |
| 4014 |
expr = integer("id") + name_expr("name") + integer("age") |
| 4015 |
""" |
| 4016 |
|
| 4017 |
class _ErrorStop(Empty): |
| 4018 |
def __init__(self, *args, **kwargs): |
| 4019 |
super(And._ErrorStop, self).__init__(*args, **kwargs) |
| 4020 |
self.name = '-' |
| 4021 |
self.leaveWhitespace() |
| 4022 |
|
| 4023 |
def __init__(self, exprs, savelist=True): |
| 4024 |
exprs = list(exprs) |
| 4025 |
if exprs and Ellipsis in exprs: |
| 4026 |
tmp = [] |
| 4027 |
for i, expr in enumerate(exprs): |
| 4028 |
if expr is Ellipsis: |
| 4029 |
if i < len(exprs) - 1: |
| 4030 |
skipto_arg = (Empty() + exprs[i + 1]).exprs[-1] |
| 4031 |
tmp.append(SkipTo(skipto_arg)("_skipped*")) |
| 4032 |
else: |
| 4033 |
raise Exception("cannot construct And with sequence ending in ...") |
| 4034 |
else: |
| 4035 |
tmp.append(expr) |
| 4036 |
exprs[:] = tmp |
| 4037 |
super(And, self).__init__(exprs, savelist) |
| 4038 |
self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs) |
| 4039 |
self.setWhitespaceChars(self.exprs[0].whiteChars) |
| 4040 |
self.skipWhitespace = self.exprs[0].skipWhitespace |
| 4041 |
self.callPreparse = True |
| 4042 |
|
| 4043 |
def streamline(self): |
| 4044 |
# collapse any _PendingSkip's |
| 4045 |
if self.exprs: |
| 4046 |
if any(isinstance(e, ParseExpression) and e.exprs and isinstance(e.exprs[-1], _PendingSkip) |
| 4047 |
for e in self.exprs[:-1]): |
| 4048 |
for i, e in enumerate(self.exprs[:-1]): |
| 4049 |
if e is None: |
| 4050 |
continue |
| 4051 |
if (isinstance(e, ParseExpression) |
| 4052 |
and e.exprs and isinstance(e.exprs[-1], _PendingSkip)): |
| 4053 |
e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1] |
| 4054 |
self.exprs[i + 1] = None |
| 4055 |
self.exprs = [e for e in self.exprs if e is not None] |
| 4056 |
|
| 4057 |
super(And, self).streamline() |
| 4058 |
self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs) |
| 4059 |
return self |
| 4060 |
|
| 4061 |
def parseImpl(self, instring, loc, doActions=True): |
| 4062 |
# pass False as last arg to _parse for first element, since we already |
| 4063 |
# pre-parsed the string as part of our And pre-parsing |
| 4064 |
loc, resultlist = self.exprs[0]._parse(instring, loc, doActions, callPreParse=False) |
| 4065 |
errorStop = False |
| 4066 |
for e in self.exprs[1:]: |
| 4067 |
if isinstance(e, And._ErrorStop): |
| 4068 |
errorStop = True |
| 4069 |
continue |
| 4070 |
if errorStop: |
| 4071 |
try: |
| 4072 |
loc, exprtokens = e._parse(instring, loc, doActions) |
| 4073 |
except ParseSyntaxException: |
| 4074 |
raise |
| 4075 |
except ParseBaseException as pe: |
| 4076 |
pe.__traceback__ = None |
| 4077 |
raise ParseSyntaxException._from_exception(pe) |
| 4078 |
except IndexError: |
| 4079 |
raise ParseSyntaxException(instring, len(instring), self.errmsg, self) |
| 4080 |
else: |
| 4081 |
loc, exprtokens = e._parse(instring, loc, doActions) |
| 4082 |
if exprtokens or exprtokens.haskeys(): |
| 4083 |
resultlist += exprtokens |
| 4084 |
return loc, resultlist |
| 4085 |
|
| 4086 |
def __iadd__(self, other): |
| 4087 |
if isinstance(other, basestring): |
| 4088 |
other = self._literalStringClass(other) |
| 4089 |
return self.append(other) # And([self, other]) |
| 4090 |
|
| 4091 |
def checkRecursion(self, parseElementList): |
| 4092 |
subRecCheckList = parseElementList[:] + [self] |
| 4093 |
for e in self.exprs: |
| 4094 |
e.checkRecursion(subRecCheckList) |
| 4095 |
if not e.mayReturnEmpty: |
| 4096 |
break |
| 4097 |
|
| 4098 |
def __str__(self): |
| 4099 |
if hasattr(self, "name"): |
| 4100 |
return self.name |
| 4101 |
|
| 4102 |
if self.strRepr is None: |
| 4103 |
self.strRepr = "{" + " ".join(_ustr(e) for e in self.exprs) + "}" |
| 4104 |
|
| 4105 |
return self.strRepr |
| 4106 |
|
| 4107 |
|
| 4108 |
class Or(ParseExpression): |
| 4109 |
"""Requires that at least one :class:`ParseExpression` is found. If |
| 4110 |
two expressions match, the expression that matches the longest |
| 4111 |
string will be used. May be constructed using the ``'^'`` |
| 4112 |
operator. |
| 4113 |
|
| 4114 |
Example:: |
| 4115 |
|
| 4116 |
# construct Or using '^' operator |
| 4117 |
|
| 4118 |
number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums)) |
| 4119 |
print(number.searchString("123 3.1416 789")) |
| 4120 |
|
| 4121 |
prints:: |
| 4122 |
|
| 4123 |
[['123'], ['3.1416'], ['789']] |
| 4124 |
""" |
| 4125 |
def __init__(self, exprs, savelist=False): |
| 4126 |
super(Or, self).__init__(exprs, savelist) |
| 4127 |
if self.exprs: |
| 4128 |
self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs) |
| 4129 |
else: |
| 4130 |
self.mayReturnEmpty = True |
| 4131 |
|
| 4132 |
def streamline(self): |
| 4133 |
super(Or, self).streamline() |
| 4134 |
if __compat__.collect_all_And_tokens: |
| 4135 |
self.saveAsList = any(e.saveAsList for e in self.exprs) |
| 4136 |
return self |
| 4137 |
|
| 4138 |
def parseImpl(self, instring, loc, doActions=True): |
| 4139 |
maxExcLoc = -1 |
| 4140 |
maxException = None |
| 4141 |
matches = [] |
| 4142 |
for e in self.exprs: |
| 4143 |
try: |
| 4144 |
loc2 = e.tryParse(instring, loc) |
| 4145 |
except ParseException as err: |
| 4146 |
err.__traceback__ = None |
| 4147 |
if err.loc > maxExcLoc: |
| 4148 |
maxException = err |
| 4149 |
maxExcLoc = err.loc |
| 4150 |
except IndexError: |
| 4151 |
if len(instring) > maxExcLoc: |
| 4152 |
maxException = ParseException(instring, len(instring), e.errmsg, self) |
| 4153 |
maxExcLoc = len(instring) |
| 4154 |
else: |
| 4155 |
# save match among all matches, to retry longest to shortest |
| 4156 |
matches.append((loc2, e)) |
| 4157 |
|
| 4158 |
if matches: |
| 4159 |
# re-evaluate all matches in descending order of length of match, in case attached actions |
| 4160 |
# might change whether or how much they match of the input. |
| 4161 |
matches.sort(key=itemgetter(0), reverse=True) |
| 4162 |
|
| 4163 |
if not doActions: |
| 4164 |
# no further conditions or parse actions to change the selection of |
| 4165 |
# alternative, so the first match will be the best match |
| 4166 |
best_expr = matches[0][1] |
| 4167 |
return best_expr._parse(instring, loc, doActions) |
| 4168 |
|
| 4169 |
longest = -1, None |
| 4170 |
for loc1, expr1 in matches: |
| 4171 |
if loc1 <= longest[0]: |
| 4172 |
# already have a longer match than this one will deliver, we are done |
| 4173 |
return longest |
| 4174 |
|
| 4175 |
try: |
| 4176 |
loc2, toks = expr1._parse(instring, loc, doActions) |
| 4177 |
except ParseException as err: |
| 4178 |
err.__traceback__ = None |
| 4179 |
if err.loc > maxExcLoc: |
| 4180 |
maxException = err |
| 4181 |
maxExcLoc = err.loc |
| 4182 |
else: |
| 4183 |
if loc2 >= loc1: |
| 4184 |
return loc2, toks |
| 4185 |
# didn't match as much as before |
| 4186 |
elif loc2 > longest[0]: |
| 4187 |
longest = loc2, toks |
| 4188 |
|
| 4189 |
if longest != (-1, None): |
| 4190 |
return longest |
| 4191 |
|
| 4192 |
if maxException is not None: |
| 4193 |
maxException.msg = self.errmsg |
| 4194 |
raise maxException |
| 4195 |
else: |
| 4196 |
raise ParseException(instring, loc, "no defined alternatives to match", self) |
| 4197 |
|
| 4198 |
|
| 4199 |
def __ixor__(self, other): |
| 4200 |
if isinstance(other, basestring): |
| 4201 |
other = self._literalStringClass(other) |
| 4202 |
return self.append(other) # Or([self, other]) |
| 4203 |
|
| 4204 |
def __str__(self): |
| 4205 |
if hasattr(self, "name"): |
| 4206 |
return self.name |
| 4207 |
|
| 4208 |
if self.strRepr is None: |
| 4209 |
self.strRepr = "{" + " ^ ".join(_ustr(e) for e in self.exprs) + "}" |
| 4210 |
|
| 4211 |
return self.strRepr |
| 4212 |
|
| 4213 |
def checkRecursion(self, parseElementList): |
| 4214 |
subRecCheckList = parseElementList[:] + [self] |
| 4215 |
for e in self.exprs: |
| 4216 |
e.checkRecursion(subRecCheckList) |
| 4217 |
|
| 4218 |
def _setResultsName(self, name, listAllMatches=False): |
| 4219 |
if (not __compat__.collect_all_And_tokens |
| 4220 |
and __diag__.warn_multiple_tokens_in_named_alternation): |
| 4221 |
if any(isinstance(e, And) for e in self.exprs): |
| 4222 |
warnings.warn("{0}: setting results name {1!r} on {2} expression " |
| 4223 |
"may only return a single token for an And alternative, " |
| 4224 |
"in future will return the full list of tokens".format( |
| 4225 |
"warn_multiple_tokens_in_named_alternation", name, type(self).__name__), |
| 4226 |
stacklevel=3) |
| 4227 |
|
| 4228 |
return super(Or, self)._setResultsName(name, listAllMatches) |
| 4229 |
|
| 4230 |
|
| 4231 |
class MatchFirst(ParseExpression): |
| 4232 |
"""Requires that at least one :class:`ParseExpression` is found. If |
| 4233 |
two expressions match, the first one listed is the one that will |
| 4234 |
match. May be constructed using the ``'|'`` operator. |
| 4235 |
|
| 4236 |
Example:: |
| 4237 |
|
| 4238 |
# construct MatchFirst using '|' operator |
| 4239 |
|
| 4240 |
# watch the order of expressions to match |
| 4241 |
number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) |
| 4242 |
print(number.searchString("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']] |
| 4243 |
|
| 4244 |
# put more selective expression first |
| 4245 |
number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) |
| 4246 |
print(number.searchString("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']] |
| 4247 |
""" |
| 4248 |
def __init__(self, exprs, savelist=False): |
| 4249 |
super(MatchFirst, self).__init__(exprs, savelist) |
| 4250 |
if self.exprs: |
| 4251 |
self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs) |
| 4252 |
else: |
| 4253 |
self.mayReturnEmpty = True |
| 4254 |
|
| 4255 |
def streamline(self): |
| 4256 |
super(MatchFirst, self).streamline() |
| 4257 |
if __compat__.collect_all_And_tokens: |
| 4258 |
self.saveAsList = any(e.saveAsList for e in self.exprs) |
| 4259 |
return self |
| 4260 |
|
| 4261 |
def parseImpl(self, instring, loc, doActions=True): |
| 4262 |
maxExcLoc = -1 |
| 4263 |
maxException = None |
| 4264 |
for e in self.exprs: |
| 4265 |
try: |
| 4266 |
ret = e._parse(instring, loc, doActions) |
| 4267 |
return ret |
| 4268 |
except ParseException as err: |
| 4269 |
if err.loc > maxExcLoc: |
| 4270 |
maxException = err |
| 4271 |
maxExcLoc = err.loc |
| 4272 |
except IndexError: |
| 4273 |
if len(instring) > maxExcLoc: |
| 4274 |
maxException = ParseException(instring, len(instring), e.errmsg, self) |
| 4275 |
maxExcLoc = len(instring) |
| 4276 |
|
| 4277 |
# only got here if no expression matched, raise exception for match that made it the furthest |
| 4278 |
else: |
| 4279 |
if maxException is not None: |
| 4280 |
maxException.msg = self.errmsg |
| 4281 |
raise maxException |
| 4282 |
else: |
| 4283 |
raise ParseException(instring, loc, "no defined alternatives to match", self) |
| 4284 |
|
| 4285 |
def __ior__(self, other): |
| 4286 |
if isinstance(other, basestring): |
| 4287 |
other = self._literalStringClass(other) |
| 4288 |
return self.append(other) # MatchFirst([self, other]) |
| 4289 |
|
| 4290 |
def __str__(self): |
| 4291 |
if hasattr(self, "name"): |
| 4292 |
return self.name |
| 4293 |
|
| 4294 |
if self.strRepr is None: |
| 4295 |
self.strRepr = "{" + " | ".join(_ustr(e) for e in self.exprs) + "}" |
| 4296 |
|
| 4297 |
return self.strRepr |
| 4298 |
|
| 4299 |
def checkRecursion(self, parseElementList): |
| 4300 |
subRecCheckList = parseElementList[:] + [self] |
| 4301 |
for e in self.exprs: |
| 4302 |
e.checkRecursion(subRecCheckList) |
| 4303 |
|
| 4304 |
def _setResultsName(self, name, listAllMatches=False): |
| 4305 |
if (not __compat__.collect_all_And_tokens |
| 4306 |
and __diag__.warn_multiple_tokens_in_named_alternation): |
| 4307 |
if any(isinstance(e, And) for e in self.exprs): |
| 4308 |
warnings.warn("{0}: setting results name {1!r} on {2} expression " |
| 4309 |
"may only return a single token for an And alternative, " |
| 4310 |
"in future will return the full list of tokens".format( |
| 4311 |
"warn_multiple_tokens_in_named_alternation", name, type(self).__name__), |
| 4312 |
stacklevel=3) |
| 4313 |
|
| 4314 |
return super(MatchFirst, self)._setResultsName(name, listAllMatches) |
| 4315 |
|
| 4316 |
|
| 4317 |
class Each(ParseExpression): |
| 4318 |
"""Requires all given :class:`ParseExpression` s to be found, but in |
| 4319 |
any order. Expressions may be separated by whitespace. |
| 4320 |
|
| 4321 |
May be constructed using the ``'&'`` operator. |
| 4322 |
|
| 4323 |
Example:: |
| 4324 |
|
| 4325 |
color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") |
| 4326 |
shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON") |
| 4327 |
integer = Word(nums) |
| 4328 |
shape_attr = "shape:" + shape_type("shape") |
| 4329 |
posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn") |
| 4330 |
color_attr = "color:" + color("color") |
| 4331 |
size_attr = "size:" + integer("size") |
| 4332 |
|
| 4333 |
# use Each (using operator '&') to accept attributes in any order |
| 4334 |
# (shape and posn are required, color and size are optional) |
| 4335 |
shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr) |
| 4336 |
|
| 4337 |
shape_spec.runTests(''' |
| 4338 |
shape: SQUARE color: BLACK posn: 100, 120 |
| 4339 |
shape: CIRCLE size: 50 color: BLUE posn: 50,80 |
| 4340 |
color:GREEN size:20 shape:TRIANGLE posn:20,40 |
| 4341 |
''' |
| 4342 |
) |
| 4343 |
|
| 4344 |
prints:: |
| 4345 |
|
| 4346 |
shape: SQUARE color: BLACK posn: 100, 120 |
| 4347 |
['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']] |
| 4348 |
- color: BLACK |
| 4349 |
- posn: ['100', ',', '120'] |
| 4350 |
- x: 100 |
| 4351 |
- y: 120 |
| 4352 |
- shape: SQUARE |
| 4353 |
|
| 4354 |
|
| 4355 |
shape: CIRCLE size: 50 color: BLUE posn: 50,80 |
| 4356 |
['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']] |
| 4357 |
- color: BLUE |
| 4358 |
- posn: ['50', ',', '80'] |
| 4359 |
- x: 50 |
| 4360 |
- y: 80 |
| 4361 |
- shape: CIRCLE |
| 4362 |
- size: 50 |
| 4363 |
|
| 4364 |
|
| 4365 |
color: GREEN size: 20 shape: TRIANGLE posn: 20,40 |
| 4366 |
['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']] |
| 4367 |
- color: GREEN |
| 4368 |
- posn: ['20', ',', '40'] |
| 4369 |
- x: 20 |
| 4370 |
- y: 40 |
| 4371 |
- shape: TRIANGLE |
| 4372 |
- size: 20 |
| 4373 |
""" |
| 4374 |
def __init__(self, exprs, savelist=True): |
| 4375 |
super(Each, self).__init__(exprs, savelist) |
| 4376 |
self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs) |
| 4377 |
self.skipWhitespace = True |
| 4378 |
self.initExprGroups = True |
| 4379 |
self.saveAsList = True |
| 4380 |
|
| 4381 |
def streamline(self): |
| 4382 |
super(Each, self).streamline() |
| 4383 |
self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs) |
| 4384 |
return self |
| 4385 |
|
| 4386 |
def parseImpl(self, instring, loc, doActions=True): |
| 4387 |
if self.initExprGroups: |
| 4388 |
self.opt1map = dict((id(e.expr), e) for e in self.exprs if isinstance(e, Optional)) |
| 4389 |
opt1 = [e.expr for e in self.exprs if isinstance(e, Optional)] |
| 4390 |
opt2 = [e for e in self.exprs if e.mayReturnEmpty and not isinstance(e, (Optional, Regex))] |
| 4391 |
self.optionals = opt1 + opt2 |
| 4392 |
self.multioptionals = [e.expr for e in self.exprs if isinstance(e, ZeroOrMore)] |
| 4393 |
self.multirequired = [e.expr for e in self.exprs if isinstance(e, OneOrMore)] |
| 4394 |
self.required = [e for e in self.exprs if not isinstance(e, (Optional, ZeroOrMore, OneOrMore))] |
| 4395 |
self.required += self.multirequired |
| 4396 |
self.initExprGroups = False |
| 4397 |
tmpLoc = loc |
| 4398 |
tmpReqd = self.required[:] |
| 4399 |
tmpOpt = self.optionals[:] |
| 4400 |
matchOrder = [] |
| 4401 |
|
| 4402 |
keepMatching = True |
| 4403 |
while keepMatching: |
| 4404 |
tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired |
| 4405 |
failed = [] |
| 4406 |
for e in tmpExprs: |
| 4407 |
try: |
| 4408 |
tmpLoc = e.tryParse(instring, tmpLoc) |
| 4409 |
except ParseException: |
| 4410 |
failed.append(e) |
| 4411 |
else: |
| 4412 |
matchOrder.append(self.opt1map.get(id(e), e)) |
| 4413 |
if e in tmpReqd: |
| 4414 |
tmpReqd.remove(e) |
| 4415 |
elif e in tmpOpt: |
| 4416 |
tmpOpt.remove(e) |
| 4417 |
if len(failed) == len(tmpExprs): |
| 4418 |
keepMatching = False |
| 4419 |
|
| 4420 |
if tmpReqd: |
| 4421 |
missing = ", ".join(_ustr(e) for e in tmpReqd) |
| 4422 |
raise ParseException(instring, loc, "Missing one or more required elements (%s)" % missing) |
| 4423 |
|
| 4424 |
# add any unmatched Optionals, in case they have default values defined |
| 4425 |
matchOrder += [e for e in self.exprs if isinstance(e, Optional) and e.expr in tmpOpt] |
| 4426 |
|
| 4427 |
resultlist = [] |
| 4428 |
for e in matchOrder: |
| 4429 |
loc, results = e._parse(instring, loc, doActions) |
| 4430 |
resultlist.append(results) |
| 4431 |
|
| 4432 |
finalResults = sum(resultlist, ParseResults([])) |
| 4433 |
return loc, finalResults |
| 4434 |
|
| 4435 |
def __str__(self): |
| 4436 |
if hasattr(self, "name"): |
| 4437 |
return self.name |
| 4438 |
|
| 4439 |
if self.strRepr is None: |
| 4440 |
self.strRepr = "{" + " & ".join(_ustr(e) for e in self.exprs) + "}" |
| 4441 |
|
| 4442 |
return self.strRepr |
| 4443 |
|
| 4444 |
def checkRecursion(self, parseElementList): |
| 4445 |
subRecCheckList = parseElementList[:] + [self] |
| 4446 |
for e in self.exprs: |
| 4447 |
e.checkRecursion(subRecCheckList) |
| 4448 |
|
| 4449 |
|
| 4450 |
class ParseElementEnhance(ParserElement): |
| 4451 |
"""Abstract subclass of :class:`ParserElement`, for combining and |
| 4452 |
post-processing parsed tokens. |
| 4453 |
""" |
| 4454 |
def __init__(self, expr, savelist=False): |
| 4455 |
super(ParseElementEnhance, self).__init__(savelist) |
| 4456 |
if isinstance(expr, basestring): |
| 4457 |
if issubclass(self._literalStringClass, Token): |
| 4458 |
expr = self._literalStringClass(expr) |
| 4459 |
else: |
| 4460 |
expr = self._literalStringClass(Literal(expr)) |
| 4461 |
self.expr = expr |
| 4462 |
self.strRepr = None |
| 4463 |
if expr is not None: |
| 4464 |
self.mayIndexError = expr.mayIndexError |
| 4465 |
self.mayReturnEmpty = expr.mayReturnEmpty |
| 4466 |
self.setWhitespaceChars(expr.whiteChars) |
| 4467 |
self.skipWhitespace = expr.skipWhitespace |
| 4468 |
self.saveAsList = expr.saveAsList |
| 4469 |
self.callPreparse = expr.callPreparse |
| 4470 |
self.ignoreExprs.extend(expr.ignoreExprs) |
| 4471 |
|
| 4472 |
def parseImpl(self, instring, loc, doActions=True): |
| 4473 |
if self.expr is not None: |
| 4474 |
return self.expr._parse(instring, loc, doActions, callPreParse=False) |
| 4475 |
else: |
| 4476 |
raise ParseException("", loc, self.errmsg, self) |
| 4477 |
|
| 4478 |
def leaveWhitespace(self): |
| 4479 |
self.skipWhitespace = False |
| 4480 |
self.expr = self.expr.copy() |
| 4481 |
if self.expr is not None: |
| 4482 |
self.expr.leaveWhitespace() |
| 4483 |
return self |
| 4484 |
|
| 4485 |
def ignore(self, other): |
| 4486 |
if isinstance(other, Suppress): |
| 4487 |
if other not in self.ignoreExprs: |
| 4488 |
super(ParseElementEnhance, self).ignore(other) |
| 4489 |
if self.expr is not None: |
| 4490 |
self.expr.ignore(self.ignoreExprs[-1]) |
| 4491 |
else: |
| 4492 |
super(ParseElementEnhance, self).ignore(other) |
| 4493 |
if self.expr is not None: |
| 4494 |
self.expr.ignore(self.ignoreExprs[-1]) |
| 4495 |
return self |
| 4496 |
|
| 4497 |
def streamline(self): |
| 4498 |
super(ParseElementEnhance, self).streamline() |
| 4499 |
if self.expr is not None: |
| 4500 |
self.expr.streamline() |
| 4501 |
return self |
| 4502 |
|
| 4503 |
def checkRecursion(self, parseElementList): |
| 4504 |
if self in parseElementList: |
| 4505 |
raise RecursiveGrammarException(parseElementList + [self]) |
| 4506 |
subRecCheckList = parseElementList[:] + [self] |
| 4507 |
if self.expr is not None: |
| 4508 |
self.expr.checkRecursion(subRecCheckList) |
| 4509 |
|
| 4510 |
def validate(self, validateTrace=None): |
| 4511 |
if validateTrace is None: |
| 4512 |
validateTrace = [] |
| 4513 |
tmp = validateTrace[:] + [self] |
| 4514 |
if self.expr is not None: |
| 4515 |
self.expr.validate(tmp) |
| 4516 |
self.checkRecursion([]) |
| 4517 |
|
| 4518 |
def __str__(self): |
| 4519 |
try: |
| 4520 |
return super(ParseElementEnhance, self).__str__() |
| 4521 |
except Exception: |
| 4522 |
pass |
| 4523 |
|
| 4524 |
if self.strRepr is None and self.expr is not None: |
| 4525 |
self.strRepr = "%s:(%s)" % (self.__class__.__name__, _ustr(self.expr)) |
| 4526 |
return self.strRepr |
| 4527 |
|
| 4528 |
|
| 4529 |
class FollowedBy(ParseElementEnhance): |
| 4530 |
"""Lookahead matching of the given parse expression. |
| 4531 |
``FollowedBy`` does *not* advance the parsing position within |
| 4532 |
the input string, it only verifies that the specified parse |
| 4533 |
expression matches at the current position. ``FollowedBy`` |
| 4534 |
always returns a null token list. If any results names are defined |
| 4535 |
in the lookahead expression, those *will* be returned for access by |
| 4536 |
name. |
| 4537 |
|
| 4538 |
Example:: |
| 4539 |
|
| 4540 |
# use FollowedBy to match a label only if it is followed by a ':' |
| 4541 |
data_word = Word(alphas) |
| 4542 |
label = data_word + FollowedBy(':') |
| 4543 |
attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) |
| 4544 |
|
| 4545 |
OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint() |
| 4546 |
|
| 4547 |
prints:: |
| 4548 |
|
| 4549 |
[['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] |
| 4550 |
""" |
| 4551 |
def __init__(self, expr): |
| 4552 |
super(FollowedBy, self).__init__(expr) |
| 4553 |
self.mayReturnEmpty = True |
| 4554 |
|
| 4555 |
def parseImpl(self, instring, loc, doActions=True): |
| 4556 |
# by using self._expr.parse and deleting the contents of the returned ParseResults list |
| 4557 |
# we keep any named results that were defined in the FollowedBy expression |
| 4558 |
_, ret = self.expr._parse(instring, loc, doActions=doActions) |
| 4559 |
del ret[:] |
| 4560 |
|
| 4561 |
return loc, ret |
| 4562 |
|
| 4563 |
|
| 4564 |
class PrecededBy(ParseElementEnhance): |
| 4565 |
"""Lookbehind matching of the given parse expression. |
| 4566 |
``PrecededBy`` does not advance the parsing position within the |
| 4567 |
input string, it only verifies that the specified parse expression |
| 4568 |
matches prior to the current position. ``PrecededBy`` always |
| 4569 |
returns a null token list, but if a results name is defined on the |
| 4570 |
given expression, it is returned. |
| 4571 |
|
| 4572 |
Parameters: |
| 4573 |
|
| 4574 |
- expr - expression that must match prior to the current parse |
| 4575 |
location |
| 4576 |
- retreat - (default= ``None``) - (int) maximum number of characters |
| 4577 |
to lookbehind prior to the current parse location |
| 4578 |
|
| 4579 |
If the lookbehind expression is a string, Literal, Keyword, or |
| 4580 |
a Word or CharsNotIn with a specified exact or maximum length, then |
| 4581 |
the retreat parameter is not required. Otherwise, retreat must be |
| 4582 |
specified to give a maximum number of characters to look back from |
| 4583 |
the current parse position for a lookbehind match. |
| 4584 |
|
| 4585 |
Example:: |
| 4586 |
|
| 4587 |
# VB-style variable names with type prefixes |
| 4588 |
int_var = PrecededBy("#") + pyparsing_common.identifier |
| 4589 |
str_var = PrecededBy("$") + pyparsing_common.identifier |
| 4590 |
|
| 4591 |
""" |
| 4592 |
def __init__(self, expr, retreat=None): |
| 4593 |
super(PrecededBy, self).__init__(expr) |
| 4594 |
self.expr = self.expr().leaveWhitespace() |
| 4595 |
self.mayReturnEmpty = True |
| 4596 |
self.mayIndexError = False |
| 4597 |
self.exact = False |
| 4598 |
if isinstance(expr, str): |
| 4599 |
retreat = len(expr) |
| 4600 |
self.exact = True |
| 4601 |
elif isinstance(expr, (Literal, Keyword)): |
| 4602 |
retreat = expr.matchLen |
| 4603 |
self.exact = True |
| 4604 |
elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT: |
| 4605 |
retreat = expr.maxLen |
| 4606 |
self.exact = True |
| 4607 |
elif isinstance(expr, _PositionToken): |
| 4608 |
retreat = 0 |
| 4609 |
self.exact = True |
| 4610 |
self.retreat = retreat |
| 4611 |
self.errmsg = "not preceded by " + str(expr) |
| 4612 |
self.skipWhitespace = False |
| 4613 |
self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None))) |
| 4614 |
|
| 4615 |
def parseImpl(self, instring, loc=0, doActions=True): |
| 4616 |
if self.exact: |
| 4617 |
if loc < self.retreat: |
| 4618 |
raise ParseException(instring, loc, self.errmsg) |
| 4619 |
start = loc - self.retreat |
| 4620 |
_, ret = self.expr._parse(instring, start) |
| 4621 |
else: |
| 4622 |
# retreat specified a maximum lookbehind window, iterate |
| 4623 |
test_expr = self.expr + StringEnd() |
| 4624 |
instring_slice = instring[max(0, loc - self.retreat):loc] |
| 4625 |
last_expr = ParseException(instring, loc, self.errmsg) |
| 4626 |
for offset in range(1, min(loc, self.retreat + 1)+1): |
| 4627 |
try: |
| 4628 |
# print('trying', offset, instring_slice, repr(instring_slice[loc - offset:])) |
| 4629 |
_, ret = test_expr._parse(instring_slice, len(instring_slice) - offset) |
| 4630 |
except ParseBaseException as pbe: |
| 4631 |
last_expr = pbe |
| 4632 |
else: |
| 4633 |
break |
| 4634 |
else: |
| 4635 |
raise last_expr |
| 4636 |
return loc, ret |
| 4637 |
|
| 4638 |
|
| 4639 |
class NotAny(ParseElementEnhance): |
| 4640 |
"""Lookahead to disallow matching with the given parse expression. |
| 4641 |
``NotAny`` does *not* advance the parsing position within the |
| 4642 |
input string, it only verifies that the specified parse expression |
| 4643 |
does *not* match at the current position. Also, ``NotAny`` does |
| 4644 |
*not* skip over leading whitespace. ``NotAny`` always returns |
| 4645 |
a null token list. May be constructed using the '~' operator. |
| 4646 |
|
| 4647 |
Example:: |
| 4648 |
|
| 4649 |
AND, OR, NOT = map(CaselessKeyword, "AND OR NOT".split()) |
| 4650 |
|
| 4651 |
# take care not to mistake keywords for identifiers |
| 4652 |
ident = ~(AND | OR | NOT) + Word(alphas) |
| 4653 |
boolean_term = Optional(NOT) + ident |
| 4654 |
|
| 4655 |
# very crude boolean expression - to support parenthesis groups and |
| 4656 |
# operation hierarchy, use infixNotation |
| 4657 |
boolean_expr = boolean_term + ZeroOrMore((AND | OR) + boolean_term) |
| 4658 |
|
| 4659 |
# integers that are followed by "." are actually floats |
| 4660 |
integer = Word(nums) + ~Char(".") |
| 4661 |
""" |
| 4662 |
def __init__(self, expr): |
| 4663 |
super(NotAny, self).__init__(expr) |
| 4664 |
# ~ self.leaveWhitespace() |
| 4665 |
self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs |
| 4666 |
self.mayReturnEmpty = True |
| 4667 |
self.errmsg = "Found unwanted token, " + _ustr(self.expr) |
| 4668 |
|
| 4669 |
def parseImpl(self, instring, loc, doActions=True): |
| 4670 |
if self.expr.canParseNext(instring, loc): |
| 4671 |
raise ParseException(instring, loc, self.errmsg, self) |
| 4672 |
return loc, [] |
| 4673 |
|
| 4674 |
def __str__(self): |
| 4675 |
if hasattr(self, "name"): |
| 4676 |
return self.name |
| 4677 |
|
| 4678 |
if self.strRepr is None: |
| 4679 |
self.strRepr = "~{" + _ustr(self.expr) + "}" |
| 4680 |
|
| 4681 |
return self.strRepr |
| 4682 |
|
| 4683 |
class _MultipleMatch(ParseElementEnhance): |
| 4684 |
def __init__(self, expr, stopOn=None): |
| 4685 |
super(_MultipleMatch, self).__init__(expr) |
| 4686 |
self.saveAsList = True |
| 4687 |
ender = stopOn |
| 4688 |
if isinstance(ender, basestring): |
| 4689 |
ender = self._literalStringClass(ender) |
| 4690 |
self.stopOn(ender) |
| 4691 |
|
| 4692 |
def stopOn(self, ender): |
| 4693 |
if isinstance(ender, basestring): |
| 4694 |
ender = self._literalStringClass(ender) |
| 4695 |
self.not_ender = ~ender if ender is not None else None |
| 4696 |
return self |
| 4697 |
|
| 4698 |
def parseImpl(self, instring, loc, doActions=True): |
| 4699 |
self_expr_parse = self.expr._parse |
| 4700 |
self_skip_ignorables = self._skipIgnorables |
| 4701 |
check_ender = self.not_ender is not None |
| 4702 |
if check_ender: |
| 4703 |
try_not_ender = self.not_ender.tryParse |
| 4704 |
|
| 4705 |
# must be at least one (but first see if we are the stopOn sentinel; |
| 4706 |
# if so, fail) |
| 4707 |
if check_ender: |
| 4708 |
try_not_ender(instring, loc) |
| 4709 |
loc, tokens = self_expr_parse(instring, loc, doActions, callPreParse=False) |
| 4710 |
try: |
| 4711 |
hasIgnoreExprs = (not not self.ignoreExprs) |
| 4712 |
while 1: |
| 4713 |
if check_ender: |
| 4714 |
try_not_ender(instring, loc) |
| 4715 |
if hasIgnoreExprs: |
| 4716 |
preloc = self_skip_ignorables(instring, loc) |
| 4717 |
else: |
| 4718 |
preloc = loc |
| 4719 |
loc, tmptokens = self_expr_parse(instring, preloc, doActions) |
| 4720 |
if tmptokens or tmptokens.haskeys(): |
| 4721 |
tokens += tmptokens |
| 4722 |
except (ParseException, IndexError): |
| 4723 |
pass |
| 4724 |
|
| 4725 |
return loc, tokens |
| 4726 |
|
| 4727 |
def _setResultsName(self, name, listAllMatches=False): |
| 4728 |
if __diag__.warn_ungrouped_named_tokens_in_collection: |
| 4729 |
for e in [self.expr] + getattr(self.expr, 'exprs', []): |
| 4730 |
if isinstance(e, ParserElement) and e.resultsName: |
| 4731 |
warnings.warn("{0}: setting results name {1!r} on {2} expression " |
| 4732 |
"collides with {3!r} on contained expression".format("warn_ungrouped_named_tokens_in_collection", |
| 4733 |
name, |
| 4734 |
type(self).__name__, |
| 4735 |
e.resultsName), |
| 4736 |
stacklevel=3) |
| 4737 |
|
| 4738 |
return super(_MultipleMatch, self)._setResultsName(name, listAllMatches) |
| 4739 |
|
| 4740 |
|
| 4741 |
class OneOrMore(_MultipleMatch): |
| 4742 |
"""Repetition of one or more of the given expression. |
| 4743 |
|
| 4744 |
Parameters: |
| 4745 |
- expr - expression that must match one or more times |
| 4746 |
- stopOn - (default= ``None``) - expression for a terminating sentinel |
| 4747 |
(only required if the sentinel would ordinarily match the repetition |
| 4748 |
expression) |
| 4749 |
|
| 4750 |
Example:: |
| 4751 |
|
| 4752 |
data_word = Word(alphas) |
| 4753 |
label = data_word + FollowedBy(':') |
| 4754 |
attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) |
| 4755 |
|
| 4756 |
text = "shape: SQUARE posn: upper left color: BLACK" |
| 4757 |
OneOrMore(attr_expr).parseString(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] |
| 4758 |
|
| 4759 |
# use stopOn attribute for OneOrMore to avoid reading label string as part of the data |
| 4760 |
attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) |
| 4761 |
OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] |
| 4762 |
|
| 4763 |
# could also be written as |
| 4764 |
(attr_expr * (1,)).parseString(text).pprint() |
| 4765 |
""" |
| 4766 |
|
| 4767 |
def __str__(self): |
| 4768 |
if hasattr(self, "name"): |
| 4769 |
return self.name |
| 4770 |
|
| 4771 |
if self.strRepr is None: |
| 4772 |
self.strRepr = "{" + _ustr(self.expr) + "}..." |
| 4773 |
|
| 4774 |
return self.strRepr |
| 4775 |
|
| 4776 |
class ZeroOrMore(_MultipleMatch): |
| 4777 |
"""Optional repetition of zero or more of the given expression. |
| 4778 |
|
| 4779 |
Parameters: |
| 4780 |
- expr - expression that must match zero or more times |
| 4781 |
- stopOn - (default= ``None``) - expression for a terminating sentinel |
| 4782 |
(only required if the sentinel would ordinarily match the repetition |
| 4783 |
expression) |
| 4784 |
|
| 4785 |
Example: similar to :class:`OneOrMore` |
| 4786 |
""" |
| 4787 |
def __init__(self, expr, stopOn=None): |
| 4788 |
super(ZeroOrMore, self).__init__(expr, stopOn=stopOn) |
| 4789 |
self.mayReturnEmpty = True |
| 4790 |
|
| 4791 |
def parseImpl(self, instring, loc, doActions=True): |
| 4792 |
try: |
| 4793 |
return super(ZeroOrMore, self).parseImpl(instring, loc, doActions) |
| 4794 |
except (ParseException, IndexError): |
| 4795 |
return loc, [] |
| 4796 |
|
| 4797 |
def __str__(self): |
| 4798 |
if hasattr(self, "name"): |
| 4799 |
return self.name |
| 4800 |
|
| 4801 |
if self.strRepr is None: |
| 4802 |
self.strRepr = "[" + _ustr(self.expr) + "]..." |
| 4803 |
|
| 4804 |
return self.strRepr |
| 4805 |
|
| 4806 |
|
| 4807 |
class _NullToken(object): |
| 4808 |
def __bool__(self): |
| 4809 |
return False |
| 4810 |
__nonzero__ = __bool__ |
| 4811 |
def __str__(self): |
| 4812 |
return "" |
| 4813 |
|
| 4814 |
class Optional(ParseElementEnhance): |
| 4815 |
"""Optional matching of the given expression. |
| 4816 |
|
| 4817 |
Parameters: |
| 4818 |
- expr - expression that must match zero or more times |
| 4819 |
- default (optional) - value to be returned if the optional expression is not found. |
| 4820 |
|
| 4821 |
Example:: |
| 4822 |
|
| 4823 |
# US postal code can be a 5-digit zip, plus optional 4-digit qualifier |
| 4824 |
zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4))) |
| 4825 |
zip.runTests(''' |
| 4826 |
# traditional ZIP code |
| 4827 |
12345 |
| 4828 |
|
| 4829 |
# ZIP+4 form |
| 4830 |
12101-0001 |
| 4831 |
|
| 4832 |
# invalid ZIP |
| 4833 |
98765- |
| 4834 |
''') |
| 4835 |
|
| 4836 |
prints:: |
| 4837 |
|
| 4838 |
# traditional ZIP code |
| 4839 |
12345 |
| 4840 |
['12345'] |
| 4841 |
|
| 4842 |
# ZIP+4 form |
| 4843 |
12101-0001 |
| 4844 |
['12101-0001'] |
| 4845 |
|
| 4846 |
# invalid ZIP |
| 4847 |
98765- |
| 4848 |
^ |
| 4849 |
FAIL: Expected end of text (at char 5), (line:1, col:6) |
| 4850 |
""" |
| 4851 |
__optionalNotMatched = _NullToken() |
| 4852 |
|
| 4853 |
def __init__(self, expr, default=__optionalNotMatched): |
| 4854 |
super(Optional, self).__init__(expr, savelist=False) |
| 4855 |
self.saveAsList = self.expr.saveAsList |
| 4856 |
self.defaultValue = default |
| 4857 |
self.mayReturnEmpty = True |
| 4858 |
|
| 4859 |
def parseImpl(self, instring, loc, doActions=True): |
| 4860 |
try: |
| 4861 |
loc, tokens = self.expr._parse(instring, loc, doActions, callPreParse=False) |
| 4862 |
except (ParseException, IndexError): |
| 4863 |
if self.defaultValue is not self.__optionalNotMatched: |
| 4864 |
if self.expr.resultsName: |
| 4865 |
tokens = ParseResults([self.defaultValue]) |
| 4866 |
tokens[self.expr.resultsName] = self.defaultValue |
| 4867 |
else: |
| 4868 |
tokens = [self.defaultValue] |
| 4869 |
else: |
| 4870 |
tokens = [] |
| 4871 |
return loc, tokens |
| 4872 |
|
| 4873 |
def __str__(self): |
| 4874 |
if hasattr(self, "name"): |
| 4875 |
return self.name |
| 4876 |
|
| 4877 |
if self.strRepr is None: |
| 4878 |
self.strRepr = "[" + _ustr(self.expr) + "]" |
| 4879 |
|
| 4880 |
return self.strRepr |
| 4881 |
|
| 4882 |
class SkipTo(ParseElementEnhance): |
| 4883 |
"""Token for skipping over all undefined text until the matched |
| 4884 |
expression is found. |
| 4885 |
|
| 4886 |
Parameters: |
| 4887 |
- expr - target expression marking the end of the data to be skipped |
| 4888 |
- include - (default= ``False``) if True, the target expression is also parsed |
| 4889 |
(the skipped text and target expression are returned as a 2-element list). |
| 4890 |
- ignore - (default= ``None``) used to define grammars (typically quoted strings and |
| 4891 |
comments) that might contain false matches to the target expression |
| 4892 |
- failOn - (default= ``None``) define expressions that are not allowed to be |
| 4893 |
included in the skipped test; if found before the target expression is found, |
| 4894 |
the SkipTo is not a match |
| 4895 |
|
| 4896 |
Example:: |
| 4897 |
|
| 4898 |
report = ''' |
| 4899 |
Outstanding Issues Report - 1 Jan 2000 |
| 4900 |
|
| 4901 |
# | Severity | Description | Days Open |
| 4902 |
-----+----------+-------------------------------------------+----------- |
| 4903 |
101 | Critical | Intermittent system crash | 6 |
| 4904 |
94 | Cosmetic | Spelling error on Login ('log|n') | 14 |
| 4905 |
79 | Minor | System slow when running too many reports | 47 |
| 4906 |
''' |
| 4907 |
integer = Word(nums) |
| 4908 |
SEP = Suppress('|') |
| 4909 |
# use SkipTo to simply match everything up until the next SEP |
| 4910 |
# - ignore quoted strings, so that a '|' character inside a quoted string does not match |
| 4911 |
# - parse action will call token.strip() for each matched token, i.e., the description body |
| 4912 |
string_data = SkipTo(SEP, ignore=quotedString) |
| 4913 |
string_data.setParseAction(tokenMap(str.strip)) |
| 4914 |
ticket_expr = (integer("issue_num") + SEP |
| 4915 |
+ string_data("sev") + SEP |
| 4916 |
+ string_data("desc") + SEP |
| 4917 |
+ integer("days_open")) |
| 4918 |
|
| 4919 |
for tkt in ticket_expr.searchString(report): |
| 4920 |
print tkt.dump() |
| 4921 |
|
| 4922 |
prints:: |
| 4923 |
|
| 4924 |
['101', 'Critical', 'Intermittent system crash', '6'] |
| 4925 |
- days_open: 6 |
| 4926 |
- desc: Intermittent system crash |
| 4927 |
- issue_num: 101 |
| 4928 |
- sev: Critical |
| 4929 |
['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14'] |
| 4930 |
- days_open: 14 |
| 4931 |
- desc: Spelling error on Login ('log|n') |
| 4932 |
- issue_num: 94 |
| 4933 |
- sev: Cosmetic |
| 4934 |
['79', 'Minor', 'System slow when running too many reports', '47'] |
| 4935 |
- days_open: 47 |
| 4936 |
- desc: System slow when running too many reports |
| 4937 |
- issue_num: 79 |
| 4938 |
- sev: Minor |
| 4939 |
""" |
| 4940 |
def __init__(self, other, include=False, ignore=None, failOn=None): |
| 4941 |
super(SkipTo, self).__init__(other) |
| 4942 |
self.ignoreExpr = ignore |
| 4943 |
self.mayReturnEmpty = True |
| 4944 |
self.mayIndexError = False |
| 4945 |
self.includeMatch = include |
| 4946 |
self.saveAsList = False |
| 4947 |
if isinstance(failOn, basestring): |
| 4948 |
self.failOn = self._literalStringClass(failOn) |
| 4949 |
else: |
| 4950 |
self.failOn = failOn |
| 4951 |
self.errmsg = "No match found for " + _ustr(self.expr) |
| 4952 |
|
| 4953 |
def parseImpl(self, instring, loc, doActions=True): |
| 4954 |
startloc = loc |
| 4955 |
instrlen = len(instring) |
| 4956 |
expr = self.expr |
| 4957 |
expr_parse = self.expr._parse |
| 4958 |
self_failOn_canParseNext = self.failOn.canParseNext if self.failOn is not None else None |
| 4959 |
self_ignoreExpr_tryParse = self.ignoreExpr.tryParse if self.ignoreExpr is not None else None |
| 4960 |
|
| 4961 |
tmploc = loc |
| 4962 |
while tmploc <= instrlen: |
| 4963 |
if self_failOn_canParseNext is not None: |
| 4964 |
# break if failOn expression matches |
| 4965 |
if self_failOn_canParseNext(instring, tmploc): |
| 4966 |
break |
| 4967 |
|
| 4968 |
if self_ignoreExpr_tryParse is not None: |
| 4969 |
# advance past ignore expressions |
| 4970 |
while 1: |
| 4971 |
try: |
| 4972 |
tmploc = self_ignoreExpr_tryParse(instring, tmploc) |
| 4973 |
except ParseBaseException: |
| 4974 |
break |
| 4975 |
|
| 4976 |
try: |
| 4977 |
expr_parse(instring, tmploc, doActions=False, callPreParse=False) |
| 4978 |
except (ParseException, IndexError): |
| 4979 |
# no match, advance loc in string |
| 4980 |
tmploc += 1 |
| 4981 |
else: |
| 4982 |
# matched skipto expr, done |
| 4983 |
break |
| 4984 |
|
| 4985 |
else: |
| 4986 |
# ran off the end of the input string without matching skipto expr, fail |
| 4987 |
raise ParseException(instring, loc, self.errmsg, self) |
| 4988 |
|
| 4989 |
# build up return values |
| 4990 |
loc = tmploc |
| 4991 |
skiptext = instring[startloc:loc] |
| 4992 |
skipresult = ParseResults(skiptext) |
| 4993 |
|
| 4994 |
if self.includeMatch: |
| 4995 |
loc, mat = expr_parse(instring, loc, doActions, callPreParse=False) |
| 4996 |
skipresult += mat |
| 4997 |
|
| 4998 |
return loc, skipresult |
| 4999 |
|
| 5000 |
class Forward(ParseElementEnhance): |
| 5001 |
"""Forward declaration of an expression to be defined later - |
| 5002 |
used for recursive grammars, such as algebraic infix notation. |
| 5003 |
When the expression is known, it is assigned to the ``Forward`` |
| 5004 |
variable using the '<<' operator. |
| 5005 |
|
| 5006 |
Note: take care when assigning to ``Forward`` not to overlook |
| 5007 |
precedence of operators. |
| 5008 |
|
| 5009 |
Specifically, '|' has a lower precedence than '<<', so that:: |
| 5010 |
|
| 5011 |
fwdExpr << a | b | c |
| 5012 |
|
| 5013 |
will actually be evaluated as:: |
| 5014 |
|
| 5015 |
(fwdExpr << a) | b | c |
| 5016 |
|
| 5017 |
thereby leaving b and c out as parseable alternatives. It is recommended that you |
| 5018 |
explicitly group the values inserted into the ``Forward``:: |
| 5019 |
|
| 5020 |
fwdExpr << (a | b | c) |
| 5021 |
|
| 5022 |
Converting to use the '<<=' operator instead will avoid this problem. |
| 5023 |
|
| 5024 |
See :class:`ParseResults.pprint` for an example of a recursive |
| 5025 |
parser created using ``Forward``. |
| 5026 |
""" |
| 5027 |
def __init__(self, other=None): |
| 5028 |
super(Forward, self).__init__(other, savelist=False) |
| 5029 |
|
| 5030 |
def __lshift__(self, other): |
| 5031 |
if isinstance(other, basestring): |
| 5032 |
other = self._literalStringClass(other) |
| 5033 |
self.expr = other |
| 5034 |
self.strRepr = None |
| 5035 |
self.mayIndexError = self.expr.mayIndexError |
| 5036 |
self.mayReturnEmpty = self.expr.mayReturnEmpty |
| 5037 |
self.setWhitespaceChars(self.expr.whiteChars) |
| 5038 |
self.skipWhitespace = self.expr.skipWhitespace |
| 5039 |
self.saveAsList = self.expr.saveAsList |
| 5040 |
self.ignoreExprs.extend(self.expr.ignoreExprs) |
| 5041 |
return self |
| 5042 |
|
| 5043 |
def __ilshift__(self, other): |
| 5044 |
return self << other |
| 5045 |
|
| 5046 |
def leaveWhitespace(self): |
| 5047 |
self.skipWhitespace = False |
| 5048 |
return self |
| 5049 |
|
| 5050 |
def streamline(self): |
| 5051 |
if not self.streamlined: |
| 5052 |
self.streamlined = True |
| 5053 |
if self.expr is not None: |
| 5054 |
self.expr.streamline() |
| 5055 |
return self |
| 5056 |
|
| 5057 |
def validate(self, validateTrace=None): |
| 5058 |
if validateTrace is None: |
| 5059 |
validateTrace = [] |
| 5060 |
|
| 5061 |
if self not in validateTrace: |
| 5062 |
tmp = validateTrace[:] + [self] |
| 5063 |
if self.expr is not None: |
| 5064 |
self.expr.validate(tmp) |
| 5065 |
self.checkRecursion([]) |
| 5066 |
|
| 5067 |
def __str__(self): |
| 5068 |
if hasattr(self, "name"): |
| 5069 |
return self.name |
| 5070 |
if self.strRepr is not None: |
| 5071 |
return self.strRepr |
| 5072 |
|
| 5073 |
# Avoid infinite recursion by setting a temporary strRepr |
| 5074 |
self.strRepr = ": ..." |
| 5075 |
|
| 5076 |
# Use the string representation of main expression. |
| 5077 |
retString = '...' |
| 5078 |
try: |
| 5079 |
if self.expr is not None: |
| 5080 |
retString = _ustr(self.expr)[:1000] |
| 5081 |
else: |
| 5082 |
retString = "None" |
| 5083 |
finally: |
| 5084 |
self.strRepr = self.__class__.__name__ + ": " + retString |
| 5085 |
return self.strRepr |
| 5086 |
|
| 5087 |
def copy(self): |
| 5088 |
if self.expr is not None: |
| 5089 |
return super(Forward, self).copy() |
| 5090 |
else: |
| 5091 |
ret = Forward() |
| 5092 |
ret <<= self |
| 5093 |
return ret |
| 5094 |
|
| 5095 |
def _setResultsName(self, name, listAllMatches=False): |
| 5096 |
if __diag__.warn_name_set_on_empty_Forward: |
| 5097 |
if self.expr is None: |
| 5098 |
warnings.warn("{0}: setting results name {0!r} on {1} expression " |
| 5099 |
"that has no contained expression".format("warn_name_set_on_empty_Forward", |
| 5100 |
name, |
| 5101 |
type(self).__name__), |
| 5102 |
stacklevel=3) |
| 5103 |
|
| 5104 |
return super(Forward, self)._setResultsName(name, listAllMatches) |
| 5105 |
|
| 5106 |
class TokenConverter(ParseElementEnhance): |
| 5107 |
""" |
| 5108 |
Abstract subclass of :class:`ParseExpression`, for converting parsed results. |
| 5109 |
""" |
| 5110 |
def __init__(self, expr, savelist=False): |
| 5111 |
super(TokenConverter, self).__init__(expr) # , savelist) |
| 5112 |
self.saveAsList = False |
| 5113 |
|
| 5114 |
class Combine(TokenConverter): |
| 5115 |
"""Converter to concatenate all matching tokens to a single string. |
| 5116 |
By default, the matching patterns must also be contiguous in the |
| 5117 |
input string; this can be disabled by specifying |
| 5118 |
``'adjacent=False'`` in the constructor. |
| 5119 |
|
| 5120 |
Example:: |
| 5121 |
|
| 5122 |
real = Word(nums) + '.' + Word(nums) |
| 5123 |
print(real.parseString('3.1416')) # -> ['3', '.', '1416'] |
| 5124 |
# will also erroneously match the following |
| 5125 |
print(real.parseString('3. 1416')) # -> ['3', '.', '1416'] |
| 5126 |
|
| 5127 |
real = Combine(Word(nums) + '.' + Word(nums)) |
| 5128 |
print(real.parseString('3.1416')) # -> ['3.1416'] |
| 5129 |
# no match when there are internal spaces |
| 5130 |
print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...) |
| 5131 |
""" |
| 5132 |
def __init__(self, expr, joinString="", adjacent=True): |
| 5133 |
super(Combine, self).__init__(expr) |
| 5134 |
# suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself |
| 5135 |
if adjacent: |
| 5136 |
self.leaveWhitespace() |
| 5137 |
self.adjacent = adjacent |
| 5138 |
self.skipWhitespace = True |
| 5139 |
self.joinString = joinString |
| 5140 |
self.callPreparse = True |
| 5141 |
|
| 5142 |
def ignore(self, other): |
| 5143 |
if self.adjacent: |
| 5144 |
ParserElement.ignore(self, other) |
| 5145 |
else: |
| 5146 |
super(Combine, self).ignore(other) |
| 5147 |
return self |
| 5148 |
|
| 5149 |
def postParse(self, instring, loc, tokenlist): |
| 5150 |
retToks = tokenlist.copy() |
| 5151 |
del retToks[:] |
| 5152 |
retToks += ParseResults(["".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults) |
| 5153 |
|
| 5154 |
if self.resultsName and retToks.haskeys(): |
| 5155 |
return [retToks] |
| 5156 |
else: |
| 5157 |
return retToks |
| 5158 |
|
| 5159 |
class Group(TokenConverter): |
| 5160 |
"""Converter to return the matched tokens as a list - useful for |
| 5161 |
returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions. |
| 5162 |
|
| 5163 |
Example:: |
| 5164 |
|
| 5165 |
ident = Word(alphas) |
| 5166 |
num = Word(nums) |
| 5167 |
term = ident | num |
| 5168 |
func = ident + Optional(delimitedList(term)) |
| 5169 |
print(func.parseString("fn a, b, 100")) # -> ['fn', 'a', 'b', '100'] |
| 5170 |
|
| 5171 |
func = ident + Group(Optional(delimitedList(term))) |
| 5172 |
print(func.parseString("fn a, b, 100")) # -> ['fn', ['a', 'b', '100']] |
| 5173 |
""" |
| 5174 |
def __init__(self, expr): |
| 5175 |
super(Group, self).__init__(expr) |
| 5176 |
self.saveAsList = True |
| 5177 |
|
| 5178 |
def postParse(self, instring, loc, tokenlist): |
| 5179 |
return [tokenlist] |
| 5180 |
|
| 5181 |
class Dict(TokenConverter): |
| 5182 |
"""Converter to return a repetitive expression as a list, but also |
| 5183 |
as a dictionary. Each element can also be referenced using the first |
| 5184 |
token in the expression as its key. Useful for tabular report |
| 5185 |
scraping when the first column can be used as a item key. |
| 5186 |
|
| 5187 |
Example:: |
| 5188 |
|
| 5189 |
data_word = Word(alphas) |
| 5190 |
label = data_word + FollowedBy(':') |
| 5191 |
attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) |
| 5192 |
|
| 5193 |
text = "shape: SQUARE posn: upper left color: light blue texture: burlap" |
| 5194 |
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) |
| 5195 |
|
| 5196 |
# print attributes as plain groups |
| 5197 |
print(OneOrMore(attr_expr).parseString(text).dump()) |
| 5198 |
|
| 5199 |
# instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names |
| 5200 |
result = Dict(OneOrMore(Group(attr_expr))).parseString(text) |
| 5201 |
print(result.dump()) |
| 5202 |
|
| 5203 |
# access named fields as dict entries, or output as dict |
| 5204 |
print(result['shape']) |
| 5205 |
print(result.asDict()) |
| 5206 |
|
| 5207 |
prints:: |
| 5208 |
|
| 5209 |
['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] |
| 5210 |
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] |
| 5211 |
- color: light blue |
| 5212 |
- posn: upper left |
| 5213 |
- shape: SQUARE |
| 5214 |
- texture: burlap |
| 5215 |
SQUARE |
| 5216 |
{'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'} |
| 5217 |
|
| 5218 |
See more examples at :class:`ParseResults` of accessing fields by results name. |
| 5219 |
""" |
| 5220 |
def __init__(self, expr): |
| 5221 |
super(Dict, self).__init__(expr) |
| 5222 |
self.saveAsList = True |
| 5223 |
|
| 5224 |
def postParse(self, instring, loc, tokenlist): |
| 5225 |
for i, tok in enumerate(tokenlist): |
| 5226 |
if len(tok) == 0: |
| 5227 |
continue |
| 5228 |
ikey = tok[0] |
| 5229 |
if isinstance(ikey, int): |
| 5230 |
ikey = _ustr(tok[0]).strip() |
| 5231 |
if len(tok) == 1: |
| 5232 |
tokenlist[ikey] = _ParseResultsWithOffset("", i) |
| 5233 |
elif len(tok) == 2 and not isinstance(tok[1], ParseResults): |
| 5234 |
tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i) |
| 5235 |
else: |
| 5236 |
dictvalue = tok.copy() # ParseResults(i) |
| 5237 |
del dictvalue[0] |
| 5238 |
if len(dictvalue) != 1 or (isinstance(dictvalue, ParseResults) and dictvalue.haskeys()): |
| 5239 |
tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i) |
| 5240 |
else: |
| 5241 |
tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i) |
| 5242 |
|
| 5243 |
if self.resultsName: |
| 5244 |
return [tokenlist] |
| 5245 |
else: |
| 5246 |
return tokenlist |
| 5247 |
|
| 5248 |
|
| 5249 |
class Suppress(TokenConverter): |
| 5250 |
"""Converter for ignoring the results of a parsed expression. |
| 5251 |
|
| 5252 |
Example:: |
| 5253 |
|
| 5254 |
source = "a, b, c,d" |
| 5255 |
wd = Word(alphas) |
| 5256 |
wd_list1 = wd + ZeroOrMore(',' + wd) |
| 5257 |
print(wd_list1.parseString(source)) |
| 5258 |
|
| 5259 |
# often, delimiters that are useful during parsing are just in the |
| 5260 |
# way afterward - use Suppress to keep them out of the parsed output |
| 5261 |
wd_list2 = wd + ZeroOrMore(Suppress(',') + wd) |
| 5262 |
print(wd_list2.parseString(source)) |
| 5263 |
|
| 5264 |
prints:: |
| 5265 |
|
| 5266 |
['a', ',', 'b', ',', 'c', ',', 'd'] |
| 5267 |
['a', 'b', 'c', 'd'] |
| 5268 |
|
| 5269 |
(See also :class:`delimitedList`.) |
| 5270 |
""" |
| 5271 |
def postParse(self, instring, loc, tokenlist): |
| 5272 |
return [] |
| 5273 |
|
| 5274 |
def suppress(self): |
| 5275 |
return self |
| 5276 |
|
| 5277 |
|
| 5278 |
class OnlyOnce(object): |
| 5279 |
"""Wrapper for parse actions, to ensure they are only called once. |
| 5280 |
""" |
| 5281 |
def __init__(self, methodCall): |
| 5282 |
self.callable = _trim_arity(methodCall) |
| 5283 |
self.called = False |
| 5284 |
def __call__(self, s, l, t): |
| 5285 |
if not self.called: |
| 5286 |
results = self.callable(s, l, t) |
| 5287 |
self.called = True |
| 5288 |
return results |
| 5289 |
raise ParseException(s, l, "") |
| 5290 |
def reset(self): |
| 5291 |
self.called = False |
| 5292 |
|
| 5293 |
def traceParseAction(f): |
| 5294 |
"""Decorator for debugging parse actions. |
| 5295 |
|
| 5296 |
When the parse action is called, this decorator will print |
| 5297 |
``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``. |
| 5298 |
When the parse action completes, the decorator will print |
| 5299 |
``"<<"`` followed by the returned value, or any exception that the parse action raised. |
| 5300 |
|
| 5301 |
Example:: |
| 5302 |
|
| 5303 |
wd = Word(alphas) |
| 5304 |
|
| 5305 |
@traceParseAction |
| 5306 |
def remove_duplicate_chars(tokens): |
| 5307 |
return ''.join(sorted(set(''.join(tokens)))) |
| 5308 |
|
| 5309 |
wds = OneOrMore(wd).setParseAction(remove_duplicate_chars) |
| 5310 |
print(wds.parseString("slkdjs sld sldd sdlf sdljf")) |
| 5311 |
|
| 5312 |
prints:: |
| 5313 |
|
| 5314 |
>>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) |
| 5315 |
<<leaving remove_duplicate_chars (ret: 'dfjkls') |
| 5316 |
['dfjkls'] |
| 5317 |
""" |
| 5318 |
f = _trim_arity(f) |
| 5319 |
def z(*paArgs): |
| 5320 |
thisFunc = f.__name__ |
| 5321 |
s, l, t = paArgs[-3:] |
| 5322 |
if len(paArgs) > 3: |
| 5323 |
thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc |
| 5324 |
sys.stderr.write(">>entering %s(line: '%s', %d, %r)\n" % (thisFunc, line(l, s), l, t)) |
| 5325 |
try: |
| 5326 |
ret = f(*paArgs) |
| 5327 |
except Exception as exc: |
| 5328 |
sys.stderr.write("<<leaving %s (exception: %s)\n" % (thisFunc, exc)) |
| 5329 |
raise |
| 5330 |
sys.stderr.write("<<leaving %s (ret: %r)\n" % (thisFunc, ret)) |
| 5331 |
return ret |
| 5332 |
try: |
| 5333 |
z.__name__ = f.__name__ |
| 5334 |
except AttributeError: |
| 5335 |
pass |
| 5336 |
return z |
| 5337 |
|
| 5338 |
# |
| 5339 |
# global helpers |
| 5340 |
# |
| 5341 |
def delimitedList(expr, delim=",", combine=False): |
| 5342 |
"""Helper to define a delimited list of expressions - the delimiter |
| 5343 |
defaults to ','. By default, the list elements and delimiters can |
| 5344 |
have intervening whitespace, and comments, but this can be |
| 5345 |
overridden by passing ``combine=True`` in the constructor. If |
| 5346 |
``combine`` is set to ``True``, the matching tokens are |
| 5347 |
returned as a single token string, with the delimiters included; |
| 5348 |
otherwise, the matching tokens are returned as a list of tokens, |
| 5349 |
with the delimiters suppressed. |
| 5350 |
|
| 5351 |
Example:: |
| 5352 |
|
| 5353 |
delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc'] |
| 5354 |
delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE'] |
| 5355 |
""" |
| 5356 |
dlName = _ustr(expr) + " [" + _ustr(delim) + " " + _ustr(expr) + "]..." |
| 5357 |
if combine: |
| 5358 |
return Combine(expr + ZeroOrMore(delim + expr)).setName(dlName) |
| 5359 |
else: |
| 5360 |
return (expr + ZeroOrMore(Suppress(delim) + expr)).setName(dlName) |
| 5361 |
|
| 5362 |
def countedArray(expr, intExpr=None): |
| 5363 |
"""Helper to define a counted list of expressions. |
| 5364 |
|
| 5365 |
This helper defines a pattern of the form:: |
| 5366 |
|
| 5367 |
integer expr expr expr... |
| 5368 |
|
| 5369 |
where the leading integer tells how many expr expressions follow. |
| 5370 |
The matched tokens returns the array of expr tokens as a list - the |
| 5371 |
leading count token is suppressed. |
| 5372 |
|
| 5373 |
If ``intExpr`` is specified, it should be a pyparsing expression |
| 5374 |
that produces an integer value. |
| 5375 |
|
| 5376 |
Example:: |
| 5377 |
|
| 5378 |
countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd'] |
| 5379 |
|
| 5380 |
# in this parser, the leading integer value is given in binary, |
| 5381 |
# '10' indicating that 2 values are in the array |
| 5382 |
binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2)) |
| 5383 |
countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd'] |
| 5384 |
""" |
| 5385 |
arrayExpr = Forward() |
| 5386 |
def countFieldParseAction(s, l, t): |
| 5387 |
n = t[0] |
| 5388 |
arrayExpr << (n and Group(And([expr] * n)) or Group(empty)) |
| 5389 |
return [] |
| 5390 |
if intExpr is None: |
| 5391 |
intExpr = Word(nums).setParseAction(lambda t: int(t[0])) |
| 5392 |
else: |
| 5393 |
intExpr = intExpr.copy() |
| 5394 |
intExpr.setName("arrayLen") |
| 5395 |
intExpr.addParseAction(countFieldParseAction, callDuringTry=True) |
| 5396 |
return (intExpr + arrayExpr).setName('(len) ' + _ustr(expr) + '...') |
| 5397 |
|
| 5398 |
def _flatten(L): |
| 5399 |
ret = [] |
| 5400 |
for i in L: |
| 5401 |
if isinstance(i, list): |
| 5402 |
ret.extend(_flatten(i)) |
| 5403 |
else: |
| 5404 |
ret.append(i) |
| 5405 |
return ret |
| 5406 |
|
| 5407 |
def matchPreviousLiteral(expr): |
| 5408 |
"""Helper to define an expression that is indirectly defined from |
| 5409 |
the tokens matched in a previous expression, that is, it looks for |
| 5410 |
a 'repeat' of a previous expression. For example:: |
| 5411 |
|
| 5412 |
first = Word(nums) |
| 5413 |
second = matchPreviousLiteral(first) |
| 5414 |
matchExpr = first + ":" + second |
| 5415 |
|
| 5416 |
will match ``"1:1"``, but not ``"1:2"``. Because this |
| 5417 |
matches a previous literal, will also match the leading |
| 5418 |
``"1:1"`` in ``"1:10"``. If this is not desired, use |
| 5419 |
:class:`matchPreviousExpr`. Do *not* use with packrat parsing |
| 5420 |
enabled. |
| 5421 |
""" |
| 5422 |
rep = Forward() |
| 5423 |
def copyTokenToRepeater(s, l, t): |
| 5424 |
if t: |
| 5425 |
if len(t) == 1: |
| 5426 |
rep << t[0] |
| 5427 |
else: |
| 5428 |
# flatten t tokens |
| 5429 |
tflat = _flatten(t.asList()) |
| 5430 |
rep << And(Literal(tt) for tt in tflat) |
| 5431 |
else: |
| 5432 |
rep << Empty() |
| 5433 |
expr.addParseAction(copyTokenToRepeater, callDuringTry=True) |
| 5434 |
rep.setName('(prev) ' + _ustr(expr)) |
| 5435 |
return rep |
| 5436 |
|
| 5437 |
def matchPreviousExpr(expr): |
| 5438 |
"""Helper to define an expression that is indirectly defined from |
| 5439 |
the tokens matched in a previous expression, that is, it looks for |
| 5440 |
a 'repeat' of a previous expression. For example:: |
| 5441 |
|
| 5442 |
first = Word(nums) |
| 5443 |
second = matchPreviousExpr(first) |
| 5444 |
matchExpr = first + ":" + second |
| 5445 |
|
| 5446 |
will match ``"1:1"``, but not ``"1:2"``. Because this |
| 5447 |
matches by expressions, will *not* match the leading ``"1:1"`` |
| 5448 |
in ``"1:10"``; the expressions are evaluated first, and then |
| 5449 |
compared, so ``"1"`` is compared with ``"10"``. Do *not* use |
| 5450 |
with packrat parsing enabled. |
| 5451 |
""" |
| 5452 |
rep = Forward() |
| 5453 |
e2 = expr.copy() |
| 5454 |
rep <<= e2 |
| 5455 |
def copyTokenToRepeater(s, l, t): |
| 5456 |
matchTokens = _flatten(t.asList()) |
| 5457 |
def mustMatchTheseTokens(s, l, t): |
| 5458 |
theseTokens = _flatten(t.asList()) |
| 5459 |
if theseTokens != matchTokens: |
| 5460 |
raise ParseException('', 0, '') |
| 5461 |
rep.setParseAction(mustMatchTheseTokens, callDuringTry=True) |
| 5462 |
expr.addParseAction(copyTokenToRepeater, callDuringTry=True) |
| 5463 |
rep.setName('(prev) ' + _ustr(expr)) |
| 5464 |
return rep |
| 5465 |
|
| 5466 |
def _escapeRegexRangeChars(s): |
| 5467 |
# ~ escape these chars: ^-[] |
| 5468 |
for c in r"\^-[]": |
| 5469 |
s = s.replace(c, _bslash + c) |
| 5470 |
s = s.replace("\n", r"\n") |
| 5471 |
s = s.replace("\t", r"\t") |
| 5472 |
return _ustr(s) |
| 5473 |
|
| 5474 |
def oneOf(strs, caseless=False, useRegex=True, asKeyword=False): |
| 5475 |
"""Helper to quickly define a set of alternative Literals, and makes |
| 5476 |
sure to do longest-first testing when there is a conflict, |
| 5477 |
regardless of the input order, but returns |
| 5478 |
a :class:`MatchFirst` for best performance. |
| 5479 |
|
| 5480 |
Parameters: |
| 5481 |
|
| 5482 |
- strs - a string of space-delimited literals, or a collection of |
| 5483 |
string literals |
| 5484 |
- caseless - (default= ``False``) - treat all literals as |
| 5485 |
caseless |
| 5486 |
- useRegex - (default= ``True``) - as an optimization, will |
| 5487 |
generate a Regex object; otherwise, will generate |
| 5488 |
a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if |
| 5489 |
creating a :class:`Regex` raises an exception) |
| 5490 |
- asKeyword - (default=``False``) - enforce Keyword-style matching on the |
| 5491 |
generated expressions |
| 5492 |
|
| 5493 |
Example:: |
| 5494 |
|
| 5495 |
comp_oper = oneOf("< = > <= >= !=") |
| 5496 |
var = Word(alphas) |
| 5497 |
number = Word(nums) |
| 5498 |
term = var | number |
| 5499 |
comparison_expr = term + comp_oper + term |
| 5500 |
print(comparison_expr.searchString("B = 12 AA=23 B<=AA AA>12")) |
| 5501 |
|
| 5502 |
prints:: |
| 5503 |
|
| 5504 |
[['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] |
| 5505 |
""" |
| 5506 |
if isinstance(caseless, basestring): |
| 5507 |
warnings.warn("More than one string argument passed to oneOf, pass " |
| 5508 |
"choices as a list or space-delimited string", stacklevel=2) |
| 5509 |
|
| 5510 |
if caseless: |
| 5511 |
isequal = (lambda a, b: a.upper() == b.upper()) |
| 5512 |
masks = (lambda a, b: b.upper().startswith(a.upper())) |
| 5513 |
parseElementClass = CaselessKeyword if asKeyword else CaselessLiteral |
| 5514 |
else: |
| 5515 |
isequal = (lambda a, b: a == b) |
| 5516 |
masks = (lambda a, b: b.startswith(a)) |
| 5517 |
parseElementClass = Keyword if asKeyword else Literal |
| 5518 |
|
| 5519 |
symbols = [] |
| 5520 |
if isinstance(strs, basestring): |
| 5521 |
symbols = strs.split() |
| 5522 |
elif isinstance(strs, Iterable): |
| 5523 |
symbols = list(strs) |
| 5524 |
else: |
| 5525 |
warnings.warn("Invalid argument to oneOf, expected string or iterable", |
| 5526 |
SyntaxWarning, stacklevel=2) |
| 5527 |
if not symbols: |
| 5528 |
return NoMatch() |
| 5529 |
|
| 5530 |
if not asKeyword: |
| 5531 |
# if not producing keywords, need to reorder to take care to avoid masking |
| 5532 |
# longer choices with shorter ones |
| 5533 |
i = 0 |
| 5534 |
while i < len(symbols) - 1: |
| 5535 |
cur = symbols[i] |
| 5536 |
for j, other in enumerate(symbols[i + 1:]): |
| 5537 |
if isequal(other, cur): |
| 5538 |
del symbols[i + j + 1] |
| 5539 |
break |
| 5540 |
elif masks(cur, other): |
| 5541 |
del symbols[i + j + 1] |
| 5542 |
symbols.insert(i, other) |
| 5543 |
break |
| 5544 |
else: |
| 5545 |
i += 1 |
| 5546 |
|
| 5547 |
if not (caseless or asKeyword) and useRegex: |
| 5548 |
# ~ print (strs, "->", "|".join([_escapeRegexChars(sym) for sym in symbols])) |
| 5549 |
try: |
| 5550 |
if len(symbols) == len("".join(symbols)): |
| 5551 |
return Regex("[%s]" % "".join(_escapeRegexRangeChars(sym) for sym in symbols)).setName(' | '.join(symbols)) |
| 5552 |
else: |
| 5553 |
return Regex("|".join(re.escape(sym) for sym in symbols)).setName(' | '.join(symbols)) |
| 5554 |
except Exception: |
| 5555 |
warnings.warn("Exception creating Regex for oneOf, building MatchFirst", |
| 5556 |
SyntaxWarning, stacklevel=2) |
| 5557 |
|
| 5558 |
# last resort, just use MatchFirst |
| 5559 |
return MatchFirst(parseElementClass(sym) for sym in symbols).setName(' | '.join(symbols)) |
| 5560 |
|
| 5561 |
def dictOf(key, value): |
| 5562 |
"""Helper to easily and clearly define a dictionary by specifying |
| 5563 |
the respective patterns for the key and value. Takes care of |
| 5564 |
defining the :class:`Dict`, :class:`ZeroOrMore`, and |
| 5565 |
:class:`Group` tokens in the proper order. The key pattern |
| 5566 |
can include delimiting markers or punctuation, as long as they are |
| 5567 |
suppressed, thereby leaving the significant key text. The value |
| 5568 |
pattern can include named results, so that the :class:`Dict` results |
| 5569 |
can include named token fields. |
| 5570 |
|
| 5571 |
Example:: |
| 5572 |
|
| 5573 |
text = "shape: SQUARE posn: upper left color: light blue texture: burlap" |
| 5574 |
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) |
| 5575 |
print(OneOrMore(attr_expr).parseString(text).dump()) |
| 5576 |
|
| 5577 |
attr_label = label |
| 5578 |
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) |
| 5579 |
|
| 5580 |
# similar to Dict, but simpler call format |
| 5581 |
result = dictOf(attr_label, attr_value).parseString(text) |
| 5582 |
print(result.dump()) |
| 5583 |
print(result['shape']) |
| 5584 |
print(result.shape) # object attribute access works too |
| 5585 |
print(result.asDict()) |
| 5586 |
|
| 5587 |
prints:: |
| 5588 |
|
| 5589 |
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] |
| 5590 |
- color: light blue |
| 5591 |
- posn: upper left |
| 5592 |
- shape: SQUARE |
| 5593 |
- texture: burlap |
| 5594 |
SQUARE |
| 5595 |
SQUARE |
| 5596 |
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} |
| 5597 |
""" |
| 5598 |
return Dict(OneOrMore(Group(key + value))) |
| 5599 |
|
| 5600 |
def originalTextFor(expr, asString=True): |
| 5601 |
"""Helper to return the original, untokenized text for a given |
| 5602 |
expression. Useful to restore the parsed fields of an HTML start |
| 5603 |
tag into the raw tag text itself, or to revert separate tokens with |
| 5604 |
intervening whitespace back to the original matching input text. By |
| 5605 |
default, returns astring containing the original parsed text. |
| 5606 |
|
| 5607 |
If the optional ``asString`` argument is passed as |
| 5608 |
``False``, then the return value is |
| 5609 |
a :class:`ParseResults` containing any results names that |
| 5610 |
were originally matched, and a single token containing the original |
| 5611 |
matched text from the input string. So if the expression passed to |
| 5612 |
:class:`originalTextFor` contains expressions with defined |
| 5613 |
results names, you must set ``asString`` to ``False`` if you |
| 5614 |
want to preserve those results name values. |
| 5615 |
|
| 5616 |
Example:: |
| 5617 |
|
| 5618 |
src = "this is test <b> bold <i>text</i> </b> normal text " |
| 5619 |
for tag in ("b", "i"): |
| 5620 |
opener, closer = makeHTMLTags(tag) |
| 5621 |
patt = originalTextFor(opener + SkipTo(closer) + closer) |
| 5622 |
print(patt.searchString(src)[0]) |
| 5623 |
|
| 5624 |
prints:: |
| 5625 |
|
| 5626 |
['<b> bold <i>text</i> </b>'] |
| 5627 |
['<i>text</i>'] |
| 5628 |
""" |
| 5629 |
locMarker = Empty().setParseAction(lambda s, loc, t: loc) |
| 5630 |
endlocMarker = locMarker.copy() |
| 5631 |
endlocMarker.callPreparse = False |
| 5632 |
matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end") |
| 5633 |
if asString: |
| 5634 |
extractText = lambda s, l, t: s[t._original_start: t._original_end] |
| 5635 |
else: |
| 5636 |
def extractText(s, l, t): |
| 5637 |
t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]] |
| 5638 |
matchExpr.setParseAction(extractText) |
| 5639 |
matchExpr.ignoreExprs = expr.ignoreExprs |
| 5640 |
return matchExpr |
| 5641 |
|
| 5642 |
def ungroup(expr): |
| 5643 |
"""Helper to undo pyparsing's default grouping of And expressions, |
| 5644 |
even if all but one are non-empty. |
| 5645 |
""" |
| 5646 |
return TokenConverter(expr).addParseAction(lambda t: t[0]) |
| 5647 |
|
| 5648 |
def locatedExpr(expr): |
| 5649 |
"""Helper to decorate a returned token with its starting and ending |
| 5650 |
locations in the input string. |
| 5651 |
|
| 5652 |
This helper adds the following results names: |
| 5653 |
|
| 5654 |
- locn_start = location where matched expression begins |
| 5655 |
- locn_end = location where matched expression ends |
| 5656 |
- value = the actual parsed results |
| 5657 |
|
| 5658 |
Be careful if the input text contains ``<TAB>`` characters, you |
| 5659 |
may want to call :class:`ParserElement.parseWithTabs` |
| 5660 |
|
| 5661 |
Example:: |
| 5662 |
|
| 5663 |
wd = Word(alphas) |
| 5664 |
for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"): |
| 5665 |
print(match) |
| 5666 |
|
| 5667 |
prints:: |
| 5668 |
|
| 5669 |
[[0, 'ljsdf', 5]] |
| 5670 |
[[8, 'lksdjjf', 15]] |
| 5671 |
[[18, 'lkkjj', 23]] |
| 5672 |
""" |
| 5673 |
locator = Empty().setParseAction(lambda s, l, t: l) |
| 5674 |
return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end")) |
| 5675 |
|
| 5676 |
|
| 5677 |
# convenience constants for positional expressions |
| 5678 |
empty = Empty().setName("empty") |
| 5679 |
lineStart = LineStart().setName("lineStart") |
| 5680 |
lineEnd = LineEnd().setName("lineEnd") |
| 5681 |
stringStart = StringStart().setName("stringStart") |
| 5682 |
stringEnd = StringEnd().setName("stringEnd") |
| 5683 |
|
| 5684 |
_escapedPunc = Word(_bslash, r"\[]-*.$+^?()~ ", exact=2).setParseAction(lambda s, l, t: t[0][1]) |
| 5685 |
_escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").setParseAction(lambda s, l, t: unichr(int(t[0].lstrip(r'\0x'), 16))) |
| 5686 |
_escapedOctChar = Regex(r"\\0[0-7]+").setParseAction(lambda s, l, t: unichr(int(t[0][1:], 8))) |
| 5687 |
_singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | CharsNotIn(r'\]', exact=1) |
| 5688 |
_charRange = Group(_singleChar + Suppress("-") + _singleChar) |
| 5689 |
_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group(OneOrMore(_charRange | _singleChar)).setResultsName("body") + "]" |
| 5690 |
|
| 5691 |
def srange(s): |
| 5692 |
r"""Helper to easily define string ranges for use in Word |
| 5693 |
construction. Borrows syntax from regexp '[]' string range |
| 5694 |
definitions:: |
| 5695 |
|
| 5696 |
srange("[0-9]") -> "0123456789" |
| 5697 |
srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" |
| 5698 |
srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" |
| 5699 |
|
| 5700 |
The input string must be enclosed in []'s, and the returned string |
| 5701 |
is the expanded character set joined into a single string. The |
| 5702 |
values enclosed in the []'s may be: |
| 5703 |
|
| 5704 |
- a single character |
| 5705 |
- an escaped character with a leading backslash (such as ``\-`` |
| 5706 |
or ``\]``) |
| 5707 |
- an escaped hex character with a leading ``'\x'`` |
| 5708 |
(``\x21``, which is a ``'!'`` character) (``\0x##`` |
| 5709 |
is also supported for backwards compatibility) |
| 5710 |
- an escaped octal character with a leading ``'\0'`` |
| 5711 |
(``\041``, which is a ``'!'`` character) |
| 5712 |
- a range of any of the above, separated by a dash (``'a-z'``, |
| 5713 |
etc.) |
| 5714 |
- any combination of the above (``'aeiouy'``, |
| 5715 |
``'a-zA-Z0-9_$'``, etc.) |
| 5716 |
""" |
| 5717 |
_expanded = lambda p: p if not isinstance(p, ParseResults) else ''.join(unichr(c) for c in range(ord(p[0]), ord(p[1]) + 1)) |
| 5718 |
try: |
| 5719 |
return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body) |
| 5720 |
except Exception: |
| 5721 |
return "" |
| 5722 |
|
| 5723 |
def matchOnlyAtCol(n): |
| 5724 |
"""Helper method for defining parse actions that require matching at |
| 5725 |
a specific column in the input text. |
| 5726 |
""" |
| 5727 |
def verifyCol(strg, locn, toks): |
| 5728 |
if col(locn, strg) != n: |
| 5729 |
raise ParseException(strg, locn, "matched token not at column %d" % n) |
| 5730 |
return verifyCol |
| 5731 |
|
| 5732 |
def replaceWith(replStr): |
| 5733 |
"""Helper method for common parse actions that simply return |
| 5734 |
a literal value. Especially useful when used with |
| 5735 |
:class:`transformString<ParserElement.transformString>` (). |
| 5736 |
|
| 5737 |
Example:: |
| 5738 |
|
| 5739 |
num = Word(nums).setParseAction(lambda toks: int(toks[0])) |
| 5740 |
na = oneOf("N/A NA").setParseAction(replaceWith(math.nan)) |
| 5741 |
term = na | num |
| 5742 |
|
| 5743 |
OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234] |
| 5744 |
""" |
| 5745 |
return lambda s, l, t: [replStr] |
| 5746 |
|
| 5747 |
def removeQuotes(s, l, t): |
| 5748 |
"""Helper parse action for removing quotation marks from parsed |
| 5749 |
quoted strings. |
| 5750 |
|
| 5751 |
Example:: |
| 5752 |
|
| 5753 |
# by default, quotation marks are included in parsed results |
| 5754 |
quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] |
| 5755 |
|
| 5756 |
# use removeQuotes to strip quotation marks from parsed results |
| 5757 |
quotedString.setParseAction(removeQuotes) |
| 5758 |
quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] |
| 5759 |
""" |
| 5760 |
return t[0][1:-1] |
| 5761 |
|
| 5762 |
def tokenMap(func, *args): |
| 5763 |
"""Helper to define a parse action by mapping a function to all |
| 5764 |
elements of a ParseResults list. If any additional args are passed, |
| 5765 |
they are forwarded to the given function as additional arguments |
| 5766 |
after the token, as in |
| 5767 |
``hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))``, |
| 5768 |
which will convert the parsed data to an integer using base 16. |
| 5769 |
|
| 5770 |
Example (compare the last to example in :class:`ParserElement.transformString`:: |
| 5771 |
|
| 5772 |
hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16)) |
| 5773 |
hex_ints.runTests(''' |
| 5774 |
00 11 22 aa FF 0a 0d 1a |
| 5775 |
''') |
| 5776 |
|
| 5777 |
upperword = Word(alphas).setParseAction(tokenMap(str.upper)) |
| 5778 |
OneOrMore(upperword).runTests(''' |
| 5779 |
my kingdom for a horse |
| 5780 |
''') |
| 5781 |
|
| 5782 |
wd = Word(alphas).setParseAction(tokenMap(str.title)) |
| 5783 |
OneOrMore(wd).setParseAction(' '.join).runTests(''' |
| 5784 |
now is the winter of our discontent made glorious summer by this sun of york |
| 5785 |
''') |
| 5786 |
|
| 5787 |
prints:: |
| 5788 |
|
| 5789 |
00 11 22 aa FF 0a 0d 1a |
| 5790 |
[0, 17, 34, 170, 255, 10, 13, 26] |
| 5791 |
|
| 5792 |
my kingdom for a horse |
| 5793 |
['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] |
| 5794 |
|
| 5795 |
now is the winter of our discontent made glorious summer by this sun of york |
| 5796 |
['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] |
| 5797 |
""" |
| 5798 |
def pa(s, l, t): |
| 5799 |
return [func(tokn, *args) for tokn in t] |
| 5800 |
|
| 5801 |
try: |
| 5802 |
func_name = getattr(func, '__name__', |
| 5803 |
getattr(func, '__class__').__name__) |
| 5804 |
except Exception: |
| 5805 |
func_name = str(func) |
| 5806 |
pa.__name__ = func_name |
| 5807 |
|
| 5808 |
return pa |
| 5809 |
|
| 5810 |
upcaseTokens = tokenMap(lambda t: _ustr(t).upper()) |
| 5811 |
"""(Deprecated) Helper parse action to convert tokens to upper case. |
| 5812 |
Deprecated in favor of :class:`pyparsing_common.upcaseTokens`""" |
| 5813 |
|
| 5814 |
downcaseTokens = tokenMap(lambda t: _ustr(t).lower()) |
| 5815 |
"""(Deprecated) Helper parse action to convert tokens to lower case. |
| 5816 |
Deprecated in favor of :class:`pyparsing_common.downcaseTokens`""" |
| 5817 |
|
| 5818 |
def _makeTags(tagStr, xml, |
| 5819 |
suppress_LT=Suppress("<"), |
| 5820 |
suppress_GT=Suppress(">")): |
| 5821 |
"""Internal helper to construct opening and closing tag expressions, given a tag name""" |
| 5822 |
if isinstance(tagStr, basestring): |
| 5823 |
resname = tagStr |
| 5824 |
tagStr = Keyword(tagStr, caseless=not xml) |
| 5825 |
else: |
| 5826 |
resname = tagStr.name |
| 5827 |
|
| 5828 |
tagAttrName = Word(alphas, alphanums + "_-:") |
| 5829 |
if xml: |
| 5830 |
tagAttrValue = dblQuotedString.copy().setParseAction(removeQuotes) |
| 5831 |
openTag = (suppress_LT |
| 5832 |
+ tagStr("tag") |
| 5833 |
+ Dict(ZeroOrMore(Group(tagAttrName + Suppress("=") + tagAttrValue))) |
| 5834 |
+ Optional("/", default=[False])("empty").setParseAction(lambda s, l, t: t[0] == '/') |
| 5835 |
+ suppress_GT) |
| 5836 |
else: |
| 5837 |
tagAttrValue = quotedString.copy().setParseAction(removeQuotes) | Word(printables, excludeChars=">") |
| 5838 |
openTag = (suppress_LT |
| 5839 |
+ tagStr("tag") |
| 5840 |
+ Dict(ZeroOrMore(Group(tagAttrName.setParseAction(downcaseTokens) |
| 5841 |
+ Optional(Suppress("=") + tagAttrValue)))) |
| 5842 |
+ Optional("/", default=[False])("empty").setParseAction(lambda s, l, t: t[0] == '/') |
| 5843 |
+ suppress_GT) |
| 5844 |
closeTag = Combine(_L("</") + tagStr + ">", adjacent=False) |
| 5845 |
|
| 5846 |
openTag.setName("<%s>" % resname) |
| 5847 |
# add start<tagname> results name in parse action now that ungrouped names are not reported at two levels |
| 5848 |
openTag.addParseAction(lambda t: t.__setitem__("start" + "".join(resname.replace(":", " ").title().split()), t.copy())) |
| 5849 |
closeTag = closeTag("end" + "".join(resname.replace(":", " ").title().split())).setName("</%s>" % resname) |
| 5850 |
openTag.tag = resname |
| 5851 |
closeTag.tag = resname |
| 5852 |
openTag.tag_body = SkipTo(closeTag()) |
| 5853 |
return openTag, closeTag |
| 5854 |
|
| 5855 |
def makeHTMLTags(tagStr): |
| 5856 |
"""Helper to construct opening and closing tag expressions for HTML, |
| 5857 |
given a tag name. Matches tags in either upper or lower case, |
| 5858 |
attributes with namespaces and with quoted or unquoted values. |
| 5859 |
|
| 5860 |
Example:: |
| 5861 |
|
| 5862 |
text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>' |
| 5863 |
# makeHTMLTags returns pyparsing expressions for the opening and |
| 5864 |
# closing tags as a 2-tuple |
| 5865 |
a, a_end = makeHTMLTags("A") |
| 5866 |
link_expr = a + SkipTo(a_end)("link_text") + a_end |
| 5867 |
|
| 5868 |
for link in link_expr.searchString(text): |
| 5869 |
# attributes in the <A> tag (like "href" shown here) are |
| 5870 |
# also accessible as named results |
| 5871 |
print(link.link_text, '->', link.href) |
| 5872 |
|
| 5873 |
prints:: |
| 5874 |
|
| 5875 |
pyparsing -> https://github.com/pyparsing/pyparsing/wiki |
| 5876 |
""" |
| 5877 |
return _makeTags(tagStr, False) |
| 5878 |
|
| 5879 |
def makeXMLTags(tagStr): |
| 5880 |
"""Helper to construct opening and closing tag expressions for XML, |
| 5881 |
given a tag name. Matches tags only in the given upper/lower case. |
| 5882 |
|
| 5883 |
Example: similar to :class:`makeHTMLTags` |
| 5884 |
""" |
| 5885 |
return _makeTags(tagStr, True) |
| 5886 |
|
| 5887 |
def withAttribute(*args, **attrDict): |
| 5888 |
"""Helper to create a validating parse action to be used with start |
| 5889 |
tags created with :class:`makeXMLTags` or |
| 5890 |
:class:`makeHTMLTags`. Use ``withAttribute`` to qualify |
| 5891 |
a starting tag with a required attribute value, to avoid false |
| 5892 |
matches on common tags such as ``<TD>`` or ``<DIV>``. |
| 5893 |
|
| 5894 |
Call ``withAttribute`` with a series of attribute names and |
| 5895 |
values. Specify the list of filter attributes names and values as: |
| 5896 |
|
| 5897 |
- keyword arguments, as in ``(align="right")``, or |
| 5898 |
- as an explicit dict with ``**`` operator, when an attribute |
| 5899 |
name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}`` |
| 5900 |
- a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))`` |
| 5901 |
|
| 5902 |
For attribute names with a namespace prefix, you must use the second |
| 5903 |
form. Attribute names are matched insensitive to upper/lower case. |
| 5904 |
|
| 5905 |
If just testing for ``class`` (with or without a namespace), use |
| 5906 |
:class:`withClass`. |
| 5907 |
|
| 5908 |
To verify that the attribute exists, but without specifying a value, |
| 5909 |
pass ``withAttribute.ANY_VALUE`` as the value. |
| 5910 |
|
| 5911 |
Example:: |
| 5912 |
|
| 5913 |
html = ''' |
| 5914 |
<div> |
| 5915 |
Some text |
| 5916 |
<div type="grid">1 4 0 1 0</div> |
| 5917 |
<div type="graph">1,3 2,3 1,1</div> |
| 5918 |
<div>this has no type</div> |
| 5919 |
</div> |
| 5920 |
|
| 5921 |
''' |
| 5922 |
div,div_end = makeHTMLTags("div") |
| 5923 |
|
| 5924 |
# only match div tag having a type attribute with value "grid" |
| 5925 |
div_grid = div().setParseAction(withAttribute(type="grid")) |
| 5926 |
grid_expr = div_grid + SkipTo(div | div_end)("body") |
| 5927 |
for grid_header in grid_expr.searchString(html): |
| 5928 |
print(grid_header.body) |
| 5929 |
|
| 5930 |
# construct a match with any div tag having a type attribute, regardless of the value |
| 5931 |
div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE)) |
| 5932 |
div_expr = div_any_type + SkipTo(div | div_end)("body") |
| 5933 |
for div_header in div_expr.searchString(html): |
| 5934 |
print(div_header.body) |
| 5935 |
|
| 5936 |
prints:: |
| 5937 |
|
| 5938 |
1 4 0 1 0 |
| 5939 |
|
| 5940 |
1 4 0 1 0 |
| 5941 |
1,3 2,3 1,1 |
| 5942 |
""" |
| 5943 |
if args: |
| 5944 |
attrs = args[:] |
| 5945 |
else: |
| 5946 |
attrs = attrDict.items() |
| 5947 |
attrs = [(k, v) for k, v in attrs] |
| 5948 |
def pa(s, l, tokens): |
| 5949 |
for attrName, attrValue in attrs: |
| 5950 |
if attrName not in tokens: |
| 5951 |
raise ParseException(s, l, "no matching attribute " + attrName) |
| 5952 |
if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue: |
| 5953 |
raise ParseException(s, l, "attribute '%s' has value '%s', must be '%s'" % |
| 5954 |
(attrName, tokens[attrName], attrValue)) |
| 5955 |
return pa |
| 5956 |
withAttribute.ANY_VALUE = object() |
| 5957 |
|
| 5958 |
def withClass(classname, namespace=''): |
| 5959 |
"""Simplified version of :class:`withAttribute` when |
| 5960 |
matching on a div class - made difficult because ``class`` is |
| 5961 |
a reserved word in Python. |
| 5962 |
|
| 5963 |
Example:: |
| 5964 |
|
| 5965 |
html = ''' |
| 5966 |
<div> |
| 5967 |
Some text |
| 5968 |
<div class="grid">1 4 0 1 0</div> |
| 5969 |
<div class="graph">1,3 2,3 1,1</div> |
| 5970 |
<div>this <div> has no class</div> |
| 5971 |
</div> |
| 5972 |
|
| 5973 |
''' |
| 5974 |
div,div_end = makeHTMLTags("div") |
| 5975 |
div_grid = div().setParseAction(withClass("grid")) |
| 5976 |
|
| 5977 |
grid_expr = div_grid + SkipTo(div | div_end)("body") |
| 5978 |
for grid_header in grid_expr.searchString(html): |
| 5979 |
print(grid_header.body) |
| 5980 |
|
| 5981 |
div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE)) |
| 5982 |
div_expr = div_any_type + SkipTo(div | div_end)("body") |
| 5983 |
for div_header in div_expr.searchString(html): |
| 5984 |
print(div_header.body) |
| 5985 |
|
| 5986 |
prints:: |
| 5987 |
|
| 5988 |
1 4 0 1 0 |
| 5989 |
|
| 5990 |
1 4 0 1 0 |
| 5991 |
1,3 2,3 1,1 |
| 5992 |
""" |
| 5993 |
classattr = "%s:class" % namespace if namespace else "class" |
| 5994 |
return withAttribute(**{classattr: classname}) |
| 5995 |
|
| 5996 |
opAssoc = SimpleNamespace() |
| 5997 |
opAssoc.LEFT = object() |
| 5998 |
opAssoc.RIGHT = object() |
| 5999 |
|
| 6000 |
def infixNotation(baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')')): |
| 6001 |
"""Helper method for constructing grammars of expressions made up of |
| 6002 |
operators working in a precedence hierarchy. Operators may be unary |
| 6003 |
or binary, left- or right-associative. Parse actions can also be |
| 6004 |
attached to operator expressions. The generated parser will also |
| 6005 |
recognize the use of parentheses to override operator precedences |
| 6006 |
(see example below). |
| 6007 |
|
| 6008 |
Note: if you define a deep operator list, you may see performance |
| 6009 |
issues when using infixNotation. See |
| 6010 |
:class:`ParserElement.enablePackrat` for a mechanism to potentially |
| 6011 |
improve your parser performance. |
| 6012 |
|
| 6013 |
Parameters: |
| 6014 |
- baseExpr - expression representing the most basic element for the |
| 6015 |
nested |
| 6016 |
- opList - list of tuples, one for each operator precedence level |
| 6017 |
in the expression grammar; each tuple is of the form ``(opExpr, |
| 6018 |
numTerms, rightLeftAssoc, parseAction)``, where: |
| 6019 |
|
| 6020 |
- opExpr is the pyparsing expression for the operator; may also |
| 6021 |
be a string, which will be converted to a Literal; if numTerms |
| 6022 |
is 3, opExpr is a tuple of two expressions, for the two |
| 6023 |
operators separating the 3 terms |
| 6024 |
- numTerms is the number of terms for this operator (must be 1, |
| 6025 |
2, or 3) |
| 6026 |
- rightLeftAssoc is the indicator whether the operator is right |
| 6027 |
or left associative, using the pyparsing-defined constants |
| 6028 |
``opAssoc.RIGHT`` and ``opAssoc.LEFT``. |
| 6029 |
- parseAction is the parse action to be associated with |
| 6030 |
expressions matching this operator expression (the parse action |
| 6031 |
tuple member may be omitted); if the parse action is passed |
| 6032 |
a tuple or list of functions, this is equivalent to calling |
| 6033 |
``setParseAction(*fn)`` |
| 6034 |
(:class:`ParserElement.setParseAction`) |
| 6035 |
- lpar - expression for matching left-parentheses |
| 6036 |
(default= ``Suppress('(')``) |
| 6037 |
- rpar - expression for matching right-parentheses |
| 6038 |
(default= ``Suppress(')')``) |
| 6039 |
|
| 6040 |
Example:: |
| 6041 |
|
| 6042 |
# simple example of four-function arithmetic with ints and |
| 6043 |
# variable names |
| 6044 |
integer = pyparsing_common.signed_integer |
| 6045 |
varname = pyparsing_common.identifier |
| 6046 |
|
| 6047 |
arith_expr = infixNotation(integer | varname, |
| 6048 |
[ |
| 6049 |
('-', 1, opAssoc.RIGHT), |
| 6050 |
(oneOf('* /'), 2, opAssoc.LEFT), |
| 6051 |
(oneOf('+ -'), 2, opAssoc.LEFT), |
| 6052 |
]) |
| 6053 |
|
| 6054 |
arith_expr.runTests(''' |
| 6055 |
5+3*6 |
| 6056 |
(5+3)*6 |
| 6057 |
-2--11 |
| 6058 |
''', fullDump=False) |
| 6059 |
|
| 6060 |
prints:: |
| 6061 |
|
| 6062 |
5+3*6 |
| 6063 |
[[5, '+', [3, '*', 6]]] |
| 6064 |
|
| 6065 |
(5+3)*6 |
| 6066 |
[[[5, '+', 3], '*', 6]] |
| 6067 |
|
| 6068 |
-2--11 |
| 6069 |
[[['-', 2], '-', ['-', 11]]] |
| 6070 |
""" |
| 6071 |
# captive version of FollowedBy that does not do parse actions or capture results names |
| 6072 |
class _FB(FollowedBy): |
| 6073 |
def parseImpl(self, instring, loc, doActions=True): |
| 6074 |
self.expr.tryParse(instring, loc) |
| 6075 |
return loc, [] |
| 6076 |
|
| 6077 |
ret = Forward() |
| 6078 |
lastExpr = baseExpr | (lpar + ret + rpar) |
| 6079 |
for i, operDef in enumerate(opList): |
| 6080 |
opExpr, arity, rightLeftAssoc, pa = (operDef + (None, ))[:4] |
| 6081 |
termName = "%s term" % opExpr if arity < 3 else "%s%s term" % opExpr |
| 6082 |
if arity == 3: |
| 6083 |
if opExpr is None or len(opExpr) != 2: |
| 6084 |
raise ValueError( |
| 6085 |
"if numterms=3, opExpr must be a tuple or list of two expressions") |
| 6086 |
opExpr1, opExpr2 = opExpr |
| 6087 |
thisExpr = Forward().setName(termName) |
| 6088 |
if rightLeftAssoc == opAssoc.LEFT: |
| 6089 |
if arity == 1: |
| 6090 |
matchExpr = _FB(lastExpr + opExpr) + Group(lastExpr + OneOrMore(opExpr)) |
| 6091 |
elif arity == 2: |
| 6092 |
if opExpr is not None: |
| 6093 |
matchExpr = _FB(lastExpr + opExpr + lastExpr) + Group(lastExpr + OneOrMore(opExpr + lastExpr)) |
| 6094 |
else: |
| 6095 |
matchExpr = _FB(lastExpr + lastExpr) + Group(lastExpr + OneOrMore(lastExpr)) |
| 6096 |
elif arity == 3: |
| 6097 |
matchExpr = (_FB(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) |
| 6098 |
+ Group(lastExpr + OneOrMore(opExpr1 + lastExpr + opExpr2 + lastExpr))) |
| 6099 |
else: |
| 6100 |
raise ValueError("operator must be unary (1), binary (2), or ternary (3)") |
| 6101 |
elif rightLeftAssoc == opAssoc.RIGHT: |
| 6102 |
if arity == 1: |
| 6103 |
# try to avoid LR with this extra test |
| 6104 |
if not isinstance(opExpr, Optional): |
| 6105 |
opExpr = Optional(opExpr) |
| 6106 |
matchExpr = _FB(opExpr.expr + thisExpr) + Group(opExpr + thisExpr) |
| 6107 |
elif arity == 2: |
| 6108 |
if opExpr is not None: |
| 6109 |
matchExpr = _FB(lastExpr + opExpr + thisExpr) + Group(lastExpr + OneOrMore(opExpr + thisExpr)) |
| 6110 |
else: |
| 6111 |
matchExpr = _FB(lastExpr + thisExpr) + Group(lastExpr + OneOrMore(thisExpr)) |
| 6112 |
elif arity == 3: |
| 6113 |
matchExpr = (_FB(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) |
| 6114 |
+ Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr)) |
| 6115 |
else: |
| 6116 |
raise ValueError("operator must be unary (1), binary (2), or ternary (3)") |
| 6117 |
else: |
| 6118 |
raise ValueError("operator must indicate right or left associativity") |
| 6119 |
if pa: |
| 6120 |
if isinstance(pa, (tuple, list)): |
| 6121 |
matchExpr.setParseAction(*pa) |
| 6122 |
else: |
| 6123 |
matchExpr.setParseAction(pa) |
| 6124 |
thisExpr <<= (matchExpr.setName(termName) | lastExpr) |
| 6125 |
lastExpr = thisExpr |
| 6126 |
ret <<= lastExpr |
| 6127 |
return ret |
| 6128 |
|
| 6129 |
operatorPrecedence = infixNotation |
| 6130 |
"""(Deprecated) Former name of :class:`infixNotation`, will be |
| 6131 |
dropped in a future release.""" |
| 6132 |
|
| 6133 |
dblQuotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"').setName("string enclosed in double quotes") |
| 6134 |
sglQuotedString = Combine(Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").setName("string enclosed in single quotes") |
| 6135 |
quotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*') + '"' |
| 6136 |
| Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*") + "'").setName("quotedString using single or double quotes") |
| 6137 |
unicodeString = Combine(_L('u') + quotedString.copy()).setName("unicode string literal") |
| 6138 |
|
| 6139 |
def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()): |
| 6140 |
"""Helper method for defining nested lists enclosed in opening and |
| 6141 |
closing delimiters ("(" and ")" are the default). |
| 6142 |
|
| 6143 |
Parameters: |
| 6144 |
- opener - opening character for a nested list |
| 6145 |
(default= ``"("``); can also be a pyparsing expression |
| 6146 |
- closer - closing character for a nested list |
| 6147 |
(default= ``")"``); can also be a pyparsing expression |
| 6148 |
- content - expression for items within the nested lists |
| 6149 |
(default= ``None``) |
| 6150 |
- ignoreExpr - expression for ignoring opening and closing |
| 6151 |
delimiters (default= :class:`quotedString`) |
| 6152 |
|
| 6153 |
If an expression is not provided for the content argument, the |
| 6154 |
nested expression will capture all whitespace-delimited content |
| 6155 |
between delimiters as a list of separate values. |
| 6156 |
|
| 6157 |
Use the ``ignoreExpr`` argument to define expressions that may |
| 6158 |
contain opening or closing characters that should not be treated as |
| 6159 |
opening or closing characters for nesting, such as quotedString or |
| 6160 |
a comment expression. Specify multiple expressions using an |
| 6161 |
:class:`Or` or :class:`MatchFirst`. The default is |
| 6162 |
:class:`quotedString`, but if no expressions are to be ignored, then |
| 6163 |
pass ``None`` for this argument. |
| 6164 |
|
| 6165 |
Example:: |
| 6166 |
|
| 6167 |
data_type = oneOf("void int short long char float double") |
| 6168 |
decl_data_type = Combine(data_type + Optional(Word('*'))) |
| 6169 |
ident = Word(alphas+'_', alphanums+'_') |
| 6170 |
number = pyparsing_common.number |
| 6171 |
arg = Group(decl_data_type + ident) |
| 6172 |
LPAR, RPAR = map(Suppress, "()") |
| 6173 |
|
| 6174 |
code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment)) |
| 6175 |
|
| 6176 |
c_function = (decl_data_type("type") |
| 6177 |
+ ident("name") |
| 6178 |
+ LPAR + Optional(delimitedList(arg), [])("args") + RPAR |
| 6179 |
+ code_body("body")) |
| 6180 |
c_function.ignore(cStyleComment) |
| 6181 |
|
| 6182 |
source_code = ''' |
| 6183 |
int is_odd(int x) { |
| 6184 |
return (x%2); |
| 6185 |
} |
| 6186 |
|
| 6187 |
int dec_to_hex(char hchar) { |
| 6188 |
if (hchar >= '0' && hchar <= '9') { |
| 6189 |
return (ord(hchar)-ord('0')); |
| 6190 |
} else { |
| 6191 |
return (10+ord(hchar)-ord('A')); |
| 6192 |
} |
| 6193 |
} |
| 6194 |
''' |
| 6195 |
for func in c_function.searchString(source_code): |
| 6196 |
print("%(name)s (%(type)s) args: %(args)s" % func) |
| 6197 |
|
| 6198 |
|
| 6199 |
prints:: |
| 6200 |
|
| 6201 |
is_odd (int) args: [['int', 'x']] |
| 6202 |
dec_to_hex (int) args: [['char', 'hchar']] |
| 6203 |
""" |
| 6204 |
if opener == closer: |
| 6205 |
raise ValueError("opening and closing strings cannot be the same") |
| 6206 |
if content is None: |
| 6207 |
if isinstance(opener, basestring) and isinstance(closer, basestring): |
| 6208 |
if len(opener) == 1 and len(closer) == 1: |
| 6209 |
if ignoreExpr is not None: |
| 6210 |
content = (Combine(OneOrMore(~ignoreExpr |
| 6211 |
+ CharsNotIn(opener |
| 6212 |
+ closer |
| 6213 |
+ ParserElement.DEFAULT_WHITE_CHARS, exact=1) |
| 6214 |
) |
| 6215 |
).setParseAction(lambda t: t[0].strip())) |
| 6216 |
else: |
| 6217 |
content = (empty.copy() + CharsNotIn(opener |
| 6218 |
+ closer |
| 6219 |
+ ParserElement.DEFAULT_WHITE_CHARS |
| 6220 |
).setParseAction(lambda t: t[0].strip())) |
| 6221 |
else: |
| 6222 |
if ignoreExpr is not None: |
| 6223 |
content = (Combine(OneOrMore(~ignoreExpr |
| 6224 |
+ ~Literal(opener) |
| 6225 |
+ ~Literal(closer) |
| 6226 |
+ CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)) |
| 6227 |
).setParseAction(lambda t: t[0].strip())) |
| 6228 |
else: |
| 6229 |
content = (Combine(OneOrMore(~Literal(opener) |
| 6230 |
+ ~Literal(closer) |
| 6231 |
+ CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)) |
| 6232 |
).setParseAction(lambda t: t[0].strip())) |
| 6233 |
else: |
| 6234 |
raise ValueError("opening and closing arguments must be strings if no content expression is given") |
| 6235 |
ret = Forward() |
| 6236 |
if ignoreExpr is not None: |
| 6237 |
ret <<= Group(Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer)) |
| 6238 |
else: |
| 6239 |
ret <<= Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer)) |
| 6240 |
ret.setName('nested %s%s expression' % (opener, closer)) |
| 6241 |
return ret |
| 6242 |
|
| 6243 |
def indentedBlock(blockStatementExpr, indentStack, indent=True): |
| 6244 |
"""Helper method for defining space-delimited indentation blocks, |
| 6245 |
such as those used to define block statements in Python source code. |
| 6246 |
|
| 6247 |
Parameters: |
| 6248 |
|
| 6249 |
- blockStatementExpr - expression defining syntax of statement that |
| 6250 |
is repeated within the indented block |
| 6251 |
- indentStack - list created by caller to manage indentation stack |
| 6252 |
(multiple statementWithIndentedBlock expressions within a single |
| 6253 |
grammar should share a common indentStack) |
| 6254 |
- indent - boolean indicating whether block must be indented beyond |
| 6255 |
the current level; set to False for block of left-most |
| 6256 |
statements (default= ``True``) |
| 6257 |
|
| 6258 |
A valid block must contain at least one ``blockStatement``. |
| 6259 |
|
| 6260 |
Example:: |
| 6261 |
|
| 6262 |
data = ''' |
| 6263 |
def A(z): |
| 6264 |
A1 |
| 6265 |
B = 100 |
| 6266 |
G = A2 |
| 6267 |
A2 |
| 6268 |
A3 |
| 6269 |
B |
| 6270 |
def BB(a,b,c): |
| 6271 |
BB1 |
| 6272 |
def BBA(): |
| 6273 |
bba1 |
| 6274 |
bba2 |
| 6275 |
bba3 |
| 6276 |
C |
| 6277 |
D |
| 6278 |
def spam(x,y): |
| 6279 |
def eggs(z): |
| 6280 |
pass |
| 6281 |
''' |
| 6282 |
|
| 6283 |
|
| 6284 |
indentStack = [1] |
| 6285 |
stmt = Forward() |
| 6286 |
|
| 6287 |
identifier = Word(alphas, alphanums) |
| 6288 |
funcDecl = ("def" + identifier + Group("(" + Optional(delimitedList(identifier)) + ")") + ":") |
| 6289 |
func_body = indentedBlock(stmt, indentStack) |
| 6290 |
funcDef = Group(funcDecl + func_body) |
| 6291 |
|
| 6292 |
rvalue = Forward() |
| 6293 |
funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") |
| 6294 |
rvalue << (funcCall | identifier | Word(nums)) |
| 6295 |
assignment = Group(identifier + "=" + rvalue) |
| 6296 |
stmt << (funcDef | assignment | identifier) |
| 6297 |
|
| 6298 |
module_body = OneOrMore(stmt) |
| 6299 |
|
| 6300 |
parseTree = module_body.parseString(data) |
| 6301 |
parseTree.pprint() |
| 6302 |
|
| 6303 |
prints:: |
| 6304 |
|
| 6305 |
[['def', |
| 6306 |
'A', |
| 6307 |
['(', 'z', ')'], |
| 6308 |
':', |
| 6309 |
[['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], |
| 6310 |
'B', |
| 6311 |
['def', |
| 6312 |
'BB', |
| 6313 |
['(', 'a', 'b', 'c', ')'], |
| 6314 |
':', |
| 6315 |
[['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], |
| 6316 |
'C', |
| 6317 |
'D', |
| 6318 |
['def', |
| 6319 |
'spam', |
| 6320 |
['(', 'x', 'y', ')'], |
| 6321 |
':', |
| 6322 |
[[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] |
| 6323 |
""" |
| 6324 |
backup_stack = indentStack[:] |
| 6325 |
|
| 6326 |
def reset_stack(): |
| 6327 |
indentStack[:] = backup_stack |
| 6328 |
|
| 6329 |
def checkPeerIndent(s, l, t): |
| 6330 |
if l >= len(s): return |
| 6331 |
curCol = col(l, s) |
| 6332 |
if curCol != indentStack[-1]: |
| 6333 |
if curCol > indentStack[-1]: |
| 6334 |
raise ParseException(s, l, "illegal nesting") |
| 6335 |
raise ParseException(s, l, "not a peer entry") |
| 6336 |
|
| 6337 |
def checkSubIndent(s, l, t): |
| 6338 |
curCol = col(l, s) |
| 6339 |
if curCol > indentStack[-1]: |
| 6340 |
indentStack.append(curCol) |
| 6341 |
else: |
| 6342 |
raise ParseException(s, l, "not a subentry") |
| 6343 |
|
| 6344 |
def checkUnindent(s, l, t): |
| 6345 |
if l >= len(s): return |
| 6346 |
curCol = col(l, s) |
| 6347 |
if not(indentStack and curCol in indentStack): |
| 6348 |
raise ParseException(s, l, "not an unindent") |
| 6349 |
if curCol < indentStack[-1]: |
| 6350 |
indentStack.pop() |
| 6351 |
|
| 6352 |
NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress(), stopOn=StringEnd()) |
| 6353 |
INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT') |
| 6354 |
PEER = Empty().setParseAction(checkPeerIndent).setName('') |
| 6355 |
UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT') |
| 6356 |
if indent: |
| 6357 |
smExpr = Group(Optional(NL) |
| 6358 |
+ INDENT |
| 6359 |
+ OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL), stopOn=StringEnd()) |
| 6360 |
+ UNDENT) |
| 6361 |
else: |
| 6362 |
smExpr = Group(Optional(NL) |
| 6363 |
+ OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL), stopOn=StringEnd()) |
| 6364 |
+ UNDENT) |
| 6365 |
smExpr.setFailAction(lambda a, b, c, d: reset_stack()) |
| 6366 |
blockStatementExpr.ignore(_bslash + LineEnd()) |
| 6367 |
return smExpr.setName('indented block') |
| 6368 |
|
| 6369 |
alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]") |
| 6370 |
punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]") |
| 6371 |
|
| 6372 |
anyOpenTag, anyCloseTag = makeHTMLTags(Word(alphas, alphanums + "_:").setName('any tag')) |
| 6373 |
_htmlEntityMap = dict(zip("gt lt amp nbsp quot apos".split(), '><& "\'')) |
| 6374 |
commonHTMLEntity = Regex('&(?P<entity>' + '|'.join(_htmlEntityMap.keys()) +");").setName("common HTML entity") |
| 6375 |
def replaceHTMLEntity(t): |
| 6376 |
"""Helper parser action to replace common HTML entities with their special characters""" |
| 6377 |
return _htmlEntityMap.get(t.entity) |
| 6378 |
|
| 6379 |
# it's easy to get these comment structures wrong - they're very common, so may as well make them available |
| 6380 |
cStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/').setName("C style comment") |
| 6381 |
"Comment of the form ``/* ... */``" |
| 6382 |
|
| 6383 |
htmlComment = Regex(r"<!--[\s\S]*?-->").setName("HTML comment") |
| 6384 |
"Comment of the form ``<!-- ... -->``" |
| 6385 |
|
| 6386 |
restOfLine = Regex(r".*").leaveWhitespace().setName("rest of line") |
| 6387 |
dblSlashComment = Regex(r"//(?:\\\n|[^\n])*").setName("// comment") |
| 6388 |
"Comment of the form ``// ... (to end of line)``" |
| 6389 |
|
| 6390 |
cppStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/' | dblSlashComment).setName("C++ style comment") |
| 6391 |
"Comment of either form :class:`cStyleComment` or :class:`dblSlashComment`" |
| 6392 |
|
| 6393 |
javaStyleComment = cppStyleComment |
| 6394 |
"Same as :class:`cppStyleComment`" |
| 6395 |
|
| 6396 |
pythonStyleComment = Regex(r"#.*").setName("Python style comment") |
| 6397 |
"Comment of the form ``# ... (to end of line)``" |
| 6398 |
|
| 6399 |
_commasepitem = Combine(OneOrMore(Word(printables, excludeChars=',') |
| 6400 |
+ Optional(Word(" \t") |
| 6401 |
+ ~Literal(",") + ~LineEnd()))).streamline().setName("commaItem") |
| 6402 |
commaSeparatedList = delimitedList(Optional(quotedString.copy() | _commasepitem, default="")).setName("commaSeparatedList") |
| 6403 |
"""(Deprecated) Predefined expression of 1 or more printable words or |
| 6404 |
quoted strings, separated by commas. |
| 6405 |
|
| 6406 |
This expression is deprecated in favor of :class:`pyparsing_common.comma_separated_list`. |
| 6407 |
""" |
| 6408 |
|
| 6409 |
# some other useful expressions - using lower-case class name since we are really using this as a namespace |
| 6410 |
class pyparsing_common: |
| 6411 |
"""Here are some common low-level expressions that may be useful in |
| 6412 |
jump-starting parser development: |
| 6413 |
|
| 6414 |
- numeric forms (:class:`integers<integer>`, :class:`reals<real>`, |
| 6415 |
:class:`scientific notation<sci_real>`) |
| 6416 |
- common :class:`programming identifiers<identifier>` |
| 6417 |
- network addresses (:class:`MAC<mac_address>`, |
| 6418 |
:class:`IPv4<ipv4_address>`, :class:`IPv6<ipv6_address>`) |
| 6419 |
- ISO8601 :class:`dates<iso8601_date>` and |
| 6420 |
:class:`datetime<iso8601_datetime>` |
| 6421 |
- :class:`UUID<uuid>` |
| 6422 |
- :class:`comma-separated list<comma_separated_list>` |
| 6423 |
|
| 6424 |
Parse actions: |
| 6425 |
|
| 6426 |
- :class:`convertToInteger` |
| 6427 |
- :class:`convertToFloat` |
| 6428 |
- :class:`convertToDate` |
| 6429 |
- :class:`convertToDatetime` |
| 6430 |
- :class:`stripHTMLTags` |
| 6431 |
- :class:`upcaseTokens` |
| 6432 |
- :class:`downcaseTokens` |
| 6433 |
|
| 6434 |
Example:: |
| 6435 |
|
| 6436 |
pyparsing_common.number.runTests(''' |
| 6437 |
# any int or real number, returned as the appropriate type |
| 6438 |
100 |
| 6439 |
-100 |
| 6440 |
+100 |
| 6441 |
3.14159 |
| 6442 |
6.02e23 |
| 6443 |
1e-12 |
| 6444 |
''') |
| 6445 |
|
| 6446 |
pyparsing_common.fnumber.runTests(''' |
| 6447 |
# any int or real number, returned as float |
| 6448 |
100 |
| 6449 |
-100 |
| 6450 |
+100 |
| 6451 |
3.14159 |
| 6452 |
6.02e23 |
| 6453 |
1e-12 |
| 6454 |
''') |
| 6455 |
|
| 6456 |
pyparsing_common.hex_integer.runTests(''' |
| 6457 |
# hex numbers |
| 6458 |
100 |
| 6459 |
FF |
| 6460 |
''') |
| 6461 |
|
| 6462 |
pyparsing_common.fraction.runTests(''' |
| 6463 |
# fractions |
| 6464 |
1/2 |
| 6465 |
-3/4 |
| 6466 |
''') |
| 6467 |
|
| 6468 |
pyparsing_common.mixed_integer.runTests(''' |
| 6469 |
# mixed fractions |
| 6470 |
1 |
| 6471 |
1/2 |
| 6472 |
-3/4 |
| 6473 |
1-3/4 |
| 6474 |
''') |
| 6475 |
|
| 6476 |
import uuid |
| 6477 |
pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID)) |
| 6478 |
pyparsing_common.uuid.runTests(''' |
| 6479 |
# uuid |
| 6480 |
12345678-1234-5678-1234-567812345678 |
| 6481 |
''') |
| 6482 |
|
| 6483 |
prints:: |
| 6484 |
|
| 6485 |
# any int or real number, returned as the appropriate type |
| 6486 |
100 |
| 6487 |
[100] |
| 6488 |
|
| 6489 |
-100 |
| 6490 |
[-100] |
| 6491 |
|
| 6492 |
+100 |
| 6493 |
[100] |
| 6494 |
|
| 6495 |
3.14159 |
| 6496 |
[3.14159] |
| 6497 |
|
| 6498 |
6.02e23 |
| 6499 |
[6.02e+23] |
| 6500 |
|
| 6501 |
1e-12 |
| 6502 |
[1e-12] |
| 6503 |
|
| 6504 |
# any int or real number, returned as float |
| 6505 |
100 |
| 6506 |
[100.0] |
| 6507 |
|
| 6508 |
-100 |
| 6509 |
[-100.0] |
| 6510 |
|
| 6511 |
+100 |
| 6512 |
[100.0] |
| 6513 |
|
| 6514 |
3.14159 |
| 6515 |
[3.14159] |
| 6516 |
|
| 6517 |
6.02e23 |
| 6518 |
[6.02e+23] |
| 6519 |
|
| 6520 |
1e-12 |
| 6521 |
[1e-12] |
| 6522 |
|
| 6523 |
# hex numbers |
| 6524 |
100 |
| 6525 |
[256] |
| 6526 |
|
| 6527 |
FF |
| 6528 |
[255] |
| 6529 |
|
| 6530 |
# fractions |
| 6531 |
1/2 |
| 6532 |
[0.5] |
| 6533 |
|
| 6534 |
-3/4 |
| 6535 |
[-0.75] |
| 6536 |
|
| 6537 |
# mixed fractions |
| 6538 |
1 |
| 6539 |
[1] |
| 6540 |
|
| 6541 |
1/2 |
| 6542 |
[0.5] |
| 6543 |
|
| 6544 |
-3/4 |
| 6545 |
[-0.75] |
| 6546 |
|
| 6547 |
1-3/4 |
| 6548 |
[1.75] |
| 6549 |
|
| 6550 |
# uuid |
| 6551 |
12345678-1234-5678-1234-567812345678 |
| 6552 |
[UUID('12345678-1234-5678-1234-567812345678')] |
| 6553 |
""" |
| 6554 |
|
| 6555 |
convertToInteger = tokenMap(int) |
| 6556 |
""" |
| 6557 |
Parse action for converting parsed integers to Python int |
| 6558 |
""" |
| 6559 |
|
| 6560 |
convertToFloat = tokenMap(float) |
| 6561 |
""" |
| 6562 |
Parse action for converting parsed numbers to Python float |
| 6563 |
""" |
| 6564 |
|
| 6565 |
integer = Word(nums).setName("integer").setParseAction(convertToInteger) |
| 6566 |
"""expression that parses an unsigned integer, returns an int""" |
| 6567 |
|
| 6568 |
hex_integer = Word(hexnums).setName("hex integer").setParseAction(tokenMap(int, 16)) |
| 6569 |
"""expression that parses a hexadecimal integer, returns an int""" |
| 6570 |
|
| 6571 |
signed_integer = Regex(r'[+-]?\d+').setName("signed integer").setParseAction(convertToInteger) |
| 6572 |
"""expression that parses an integer with optional leading sign, returns an int""" |
| 6573 |
|
| 6574 |
fraction = (signed_integer().setParseAction(convertToFloat) + '/' + signed_integer().setParseAction(convertToFloat)).setName("fraction") |
| 6575 |
"""fractional expression of an integer divided by an integer, returns a float""" |
| 6576 |
fraction.addParseAction(lambda t: t[0]/t[-1]) |
| 6577 |
|
| 6578 |
mixed_integer = (fraction | signed_integer + Optional(Optional('-').suppress() + fraction)).setName("fraction or mixed integer-fraction") |
| 6579 |
"""mixed integer of the form 'integer - fraction', with optional leading integer, returns float""" |
| 6580 |
mixed_integer.addParseAction(sum) |
| 6581 |
|
| 6582 |
real = Regex(r'[+-]?(?:\d+\.\d*|\.\d+)').setName("real number").setParseAction(convertToFloat) |
| 6583 |
"""expression that parses a floating point number and returns a float""" |
| 6584 |
|
| 6585 |
sci_real = Regex(r'[+-]?(?:\d+(?:[eE][+-]?\d+)|(?:\d+\.\d*|\.\d+)(?:[eE][+-]?\d+)?)').setName("real number with scientific notation").setParseAction(convertToFloat) |
| 6586 |
"""expression that parses a floating point number with optional |
| 6587 |
scientific notation and returns a float""" |
| 6588 |
|
| 6589 |
# streamlining this expression makes the docs nicer-looking |
| 6590 |
number = (sci_real | real | signed_integer).streamline() |
| 6591 |
"""any numeric expression, returns the corresponding Python type""" |
| 6592 |
|
| 6593 |
fnumber = Regex(r'[+-]?\d+\.?\d*([eE][+-]?\d+)?').setName("fnumber").setParseAction(convertToFloat) |
| 6594 |
"""any int or real number, returned as float""" |
| 6595 |
|
| 6596 |
identifier = Word(alphas + '_', alphanums + '_').setName("identifier") |
| 6597 |
"""typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')""" |
| 6598 |
|
| 6599 |
ipv4_address = Regex(r'(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}').setName("IPv4 address") |
| 6600 |
"IPv4 address (``0.0.0.0 - 255.255.255.255``)" |
| 6601 |
|
| 6602 |
_ipv6_part = Regex(r'[0-9a-fA-F]{1,4}').setName("hex_integer") |
| 6603 |
_full_ipv6_address = (_ipv6_part + (':' + _ipv6_part) * 7).setName("full IPv6 address") |
| 6604 |
_short_ipv6_address = (Optional(_ipv6_part + (':' + _ipv6_part) * (0, 6)) |
| 6605 |
+ "::" |
| 6606 |
+ Optional(_ipv6_part + (':' + _ipv6_part) * (0, 6)) |
| 6607 |
).setName("short IPv6 address") |
| 6608 |
_short_ipv6_address.addCondition(lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8) |
| 6609 |
_mixed_ipv6_address = ("::ffff:" + ipv4_address).setName("mixed IPv6 address") |
| 6610 |
ipv6_address = Combine((_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).setName("IPv6 address")).setName("IPv6 address") |
| 6611 |
"IPv6 address (long, short, or mixed form)" |
| 6612 |
|
| 6613 |
mac_address = Regex(r'[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}').setName("MAC address") |
| 6614 |
"MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)" |
| 6615 |
|
| 6616 |
@staticmethod |
| 6617 |
def convertToDate(fmt="%Y-%m-%d"): |
| 6618 |
""" |
| 6619 |
Helper to create a parse action for converting parsed date string to Python datetime.date |
| 6620 |
|
| 6621 |
Params - |
| 6622 |
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``) |
| 6623 |
|
| 6624 |
Example:: |
| 6625 |
|
| 6626 |
date_expr = pyparsing_common.iso8601_date.copy() |
| 6627 |
date_expr.setParseAction(pyparsing_common.convertToDate()) |
| 6628 |
print(date_expr.parseString("1999-12-31")) |
| 6629 |
|
| 6630 |
prints:: |
| 6631 |
|
| 6632 |
[datetime.date(1999, 12, 31)] |
| 6633 |
""" |
| 6634 |
def cvt_fn(s, l, t): |
| 6635 |
try: |
| 6636 |
return datetime.strptime(t[0], fmt).date() |
| 6637 |
except ValueError as ve: |
| 6638 |
raise ParseException(s, l, str(ve)) |
| 6639 |
return cvt_fn |
| 6640 |
|
| 6641 |
@staticmethod |
| 6642 |
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"): |
| 6643 |
"""Helper to create a parse action for converting parsed |
| 6644 |
datetime string to Python datetime.datetime |
| 6645 |
|
| 6646 |
Params - |
| 6647 |
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``) |
| 6648 |
|
| 6649 |
Example:: |
| 6650 |
|
| 6651 |
dt_expr = pyparsing_common.iso8601_datetime.copy() |
| 6652 |
dt_expr.setParseAction(pyparsing_common.convertToDatetime()) |
| 6653 |
print(dt_expr.parseString("1999-12-31T23:59:59.999")) |
| 6654 |
|
| 6655 |
prints:: |
| 6656 |
|
| 6657 |
[datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] |
| 6658 |
""" |
| 6659 |
def cvt_fn(s, l, t): |
| 6660 |
try: |
| 6661 |
return datetime.strptime(t[0], fmt) |
| 6662 |
except ValueError as ve: |
| 6663 |
raise ParseException(s, l, str(ve)) |
| 6664 |
return cvt_fn |
| 6665 |
|
| 6666 |
iso8601_date = Regex(r'(?P<year>\d{4})(?:-(?P<month>\d\d)(?:-(?P<day>\d\d))?)?').setName("ISO8601 date") |
| 6667 |
"ISO8601 date (``yyyy-mm-dd``)" |
| 6668 |
|
| 6669 |
iso8601_datetime = Regex(r'(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d)[T ](?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d(\.\d*)?)?)?(?P<tz>Z|[+-]\d\d:?\d\d)?').setName("ISO8601 datetime") |
| 6670 |
"ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``" |
| 6671 |
|
| 6672 |
uuid = Regex(r'[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}').setName("UUID") |
| 6673 |
"UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)" |
| 6674 |
|
| 6675 |
_html_stripper = anyOpenTag.suppress() | anyCloseTag.suppress() |
| 6676 |
@staticmethod |
| 6677 |
def stripHTMLTags(s, l, tokens): |
| 6678 |
"""Parse action to remove HTML tags from web page HTML source |
| 6679 |
|
| 6680 |
Example:: |
| 6681 |
|
| 6682 |
# strip HTML links from normal text |
| 6683 |
text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>' |
| 6684 |
td, td_end = makeHTMLTags("TD") |
| 6685 |
table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end |
| 6686 |
print(table_text.parseString(text).body) |
| 6687 |
|
| 6688 |
Prints:: |
| 6689 |
|
| 6690 |
More info at the pyparsing wiki page |
| 6691 |
""" |
| 6692 |
return pyparsing_common._html_stripper.transformString(tokens[0]) |
| 6693 |
|
| 6694 |
_commasepitem = Combine(OneOrMore(~Literal(",") |
| 6695 |
+ ~LineEnd() |
| 6696 |
+ Word(printables, excludeChars=',') |
| 6697 |
+ Optional(White(" \t")))).streamline().setName("commaItem") |
| 6698 |
comma_separated_list = delimitedList(Optional(quotedString.copy() |
| 6699 |
| _commasepitem, default='') |
| 6700 |
).setName("comma separated list") |
| 6701 |
"""Predefined expression of 1 or more printable words or quoted strings, separated by commas.""" |
| 6702 |
|
| 6703 |
upcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).upper())) |
| 6704 |
"""Parse action to convert tokens to upper case.""" |
| 6705 |
|
| 6706 |
downcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).lower())) |
| 6707 |
"""Parse action to convert tokens to lower case.""" |
| 6708 |
|
| 6709 |
|
| 6710 |
class _lazyclassproperty(object): |
| 6711 |
def __init__(self, fn): |
| 6712 |
self.fn = fn |
| 6713 |
self.__doc__ = fn.__doc__ |
| 6714 |
self.__name__ = fn.__name__ |
| 6715 |
|
| 6716 |
def __get__(self, obj, cls): |
| 6717 |
if cls is None: |
| 6718 |
cls = type(obj) |
| 6719 |
if not hasattr(cls, '_intern') or any(cls._intern is getattr(superclass, '_intern', []) |
| 6720 |
for superclass in cls.__mro__[1:]): |
| 6721 |
cls._intern = {} |
| 6722 |
attrname = self.fn.__name__ |
| 6723 |
if attrname not in cls._intern: |
| 6724 |
cls._intern[attrname] = self.fn(cls) |
| 6725 |
return cls._intern[attrname] |
| 6726 |
|
| 6727 |
|
| 6728 |
class unicode_set(object): |
| 6729 |
""" |
| 6730 |
A set of Unicode characters, for language-specific strings for |
| 6731 |
``alphas``, ``nums``, ``alphanums``, and ``printables``. |
| 6732 |
A unicode_set is defined by a list of ranges in the Unicode character |
| 6733 |
set, in a class attribute ``_ranges``, such as:: |
| 6734 |
|
| 6735 |
_ranges = [(0x0020, 0x007e), (0x00a0, 0x00ff),] |
| 6736 |
|
| 6737 |
A unicode set can also be defined using multiple inheritance of other unicode sets:: |
| 6738 |
|
| 6739 |
class CJK(Chinese, Japanese, Korean): |
| 6740 |
pass |
| 6741 |
""" |
| 6742 |
_ranges = [] |
| 6743 |
|
| 6744 |
@classmethod |
| 6745 |
def _get_chars_for_ranges(cls): |
| 6746 |
ret = [] |
| 6747 |
for cc in cls.__mro__: |
| 6748 |
if cc is unicode_set: |
| 6749 |
break |
| 6750 |
for rr in cc._ranges: |
| 6751 |
ret.extend(range(rr[0], rr[-1] + 1)) |
| 6752 |
return [unichr(c) for c in sorted(set(ret))] |
| 6753 |
|
| 6754 |
@_lazyclassproperty |
| 6755 |
def printables(cls): |
| 6756 |
"all non-whitespace characters in this range" |
| 6757 |
return u''.join(filterfalse(unicode.isspace, cls._get_chars_for_ranges())) |
| 6758 |
|
| 6759 |
@_lazyclassproperty |
| 6760 |
def alphas(cls): |
| 6761 |
"all alphabetic characters in this range" |
| 6762 |
return u''.join(filter(unicode.isalpha, cls._get_chars_for_ranges())) |
| 6763 |
|
| 6764 |
@_lazyclassproperty |
| 6765 |
def nums(cls): |
| 6766 |
"all numeric digit characters in this range" |
| 6767 |
return u''.join(filter(unicode.isdigit, cls._get_chars_for_ranges())) |
| 6768 |
|
| 6769 |
@_lazyclassproperty |
| 6770 |
def alphanums(cls): |
| 6771 |
"all alphanumeric characters in this range" |
| 6772 |
return cls.alphas + cls.nums |
| 6773 |
|
| 6774 |
|
| 6775 |
class pyparsing_unicode(unicode_set): |
| 6776 |
""" |
| 6777 |
A namespace class for defining common language unicode_sets. |
| 6778 |
""" |
| 6779 |
_ranges = [(32, sys.maxunicode)] |
| 6780 |
|
| 6781 |
class Latin1(unicode_set): |
| 6782 |
"Unicode set for Latin-1 Unicode Character Range" |
| 6783 |
_ranges = [(0x0020, 0x007e), (0x00a0, 0x00ff),] |
| 6784 |
|
| 6785 |
class LatinA(unicode_set): |
| 6786 |
"Unicode set for Latin-A Unicode Character Range" |
| 6787 |
_ranges = [(0x0100, 0x017f),] |
| 6788 |
|
| 6789 |
class LatinB(unicode_set): |
| 6790 |
"Unicode set for Latin-B Unicode Character Range" |
| 6791 |
_ranges = [(0x0180, 0x024f),] |
| 6792 |
|
| 6793 |
class Greek(unicode_set): |
| 6794 |
"Unicode set for Greek Unicode Character Ranges" |
| 6795 |
_ranges = [ |
| 6796 |
(0x0370, 0x03ff), (0x1f00, 0x1f15), (0x1f18, 0x1f1d), (0x1f20, 0x1f45), (0x1f48, 0x1f4d), |
| 6797 |
(0x1f50, 0x1f57), (0x1f59,), (0x1f5b,), (0x1f5d,), (0x1f5f, 0x1f7d), (0x1f80, 0x1fb4), (0x1fb6, 0x1fc4), |
| 6798 |
(0x1fc6, 0x1fd3), (0x1fd6, 0x1fdb), (0x1fdd, 0x1fef), (0x1ff2, 0x1ff4), (0x1ff6, 0x1ffe), |
| 6799 |
] |
| 6800 |
|
| 6801 |
class Cyrillic(unicode_set): |
| 6802 |
"Unicode set for Cyrillic Unicode Character Range" |
| 6803 |
_ranges = [(0x0400, 0x04ff)] |
| 6804 |
|
| 6805 |
class Chinese(unicode_set): |
| 6806 |
"Unicode set for Chinese Unicode Character Range" |
| 6807 |
_ranges = [(0x4e00, 0x9fff), (0x3000, 0x303f),] |
| 6808 |
|
| 6809 |
class Japanese(unicode_set): |
| 6810 |
"Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges" |
| 6811 |
_ranges = [] |
| 6812 |
|
| 6813 |
class Kanji(unicode_set): |
| 6814 |
"Unicode set for Kanji Unicode Character Range" |
| 6815 |
_ranges = [(0x4E00, 0x9Fbf), (0x3000, 0x303f),] |
| 6816 |
|
| 6817 |
class Hiragana(unicode_set): |
| 6818 |
"Unicode set for Hiragana Unicode Character Range" |
| 6819 |
_ranges = [(0x3040, 0x309f),] |
| 6820 |
|
| 6821 |
class Katakana(unicode_set): |
| 6822 |
"Unicode set for Katakana Unicode Character Range" |
| 6823 |
_ranges = [(0x30a0, 0x30ff),] |
| 6824 |
|
| 6825 |
class Korean(unicode_set): |
| 6826 |
"Unicode set for Korean Unicode Character Range" |
| 6827 |
_ranges = [(0xac00, 0xd7af), (0x1100, 0x11ff), (0x3130, 0x318f), (0xa960, 0xa97f), (0xd7b0, 0xd7ff), (0x3000, 0x303f),] |
| 6828 |
|
| 6829 |
class CJK(Chinese, Japanese, Korean): |
| 6830 |
"Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range" |
| 6831 |
pass |
| 6832 |
|
| 6833 |
class Thai(unicode_set): |
| 6834 |
"Unicode set for Thai Unicode Character Range" |
| 6835 |
_ranges = [(0x0e01, 0x0e3a), (0x0e3f, 0x0e5b),] |
| 6836 |
|
| 6837 |
class Arabic(unicode_set): |
| 6838 |
"Unicode set for Arabic Unicode Character Range" |
| 6839 |
_ranges = [(0x0600, 0x061b), (0x061e, 0x06ff), (0x0700, 0x077f),] |
| 6840 |
|
| 6841 |
class Hebrew(unicode_set): |
| 6842 |
"Unicode set for Hebrew Unicode Character Range" |
| 6843 |
_ranges = [(0x0590, 0x05ff),] |
| 6844 |
|
| 6845 |
class Devanagari(unicode_set): |
| 6846 |
"Unicode set for Devanagari Unicode Character Range" |
| 6847 |
_ranges = [(0x0900, 0x097f), (0xa8e0, 0xa8ff)] |
| 6848 |
|
| 6849 |
pyparsing_unicode.Japanese._ranges = (pyparsing_unicode.Japanese.Kanji._ranges |
| 6850 |
+ pyparsing_unicode.Japanese.Hiragana._ranges |
| 6851 |
+ pyparsing_unicode.Japanese.Katakana._ranges) |
| 6852 |
|
| 6853 |
# define ranges in language character sets |
| 6854 |
if PY_3: |
| 6855 |
setattr(pyparsing_unicode, u"العربية", pyparsing_unicode.Arabic) |
| 6856 |
setattr(pyparsing_unicode, u"中文", pyparsing_unicode.Chinese) |
| 6857 |
setattr(pyparsing_unicode, u"кириллица", pyparsing_unicode.Cyrillic) |
| 6858 |
setattr(pyparsing_unicode, u"Ελληνικά", pyparsing_unicode.Greek) |
| 6859 |
setattr(pyparsing_unicode, u"עִברִית", pyparsing_unicode.Hebrew) |
| 6860 |
setattr(pyparsing_unicode, u"日本語", pyparsing_unicode.Japanese) |
| 6861 |
setattr(pyparsing_unicode.Japanese, u"漢字", pyparsing_unicode.Japanese.Kanji) |
| 6862 |
setattr(pyparsing_unicode.Japanese, u"カタカナ", pyparsing_unicode.Japanese.Katakana) |
| 6863 |
setattr(pyparsing_unicode.Japanese, u"ひらがな", pyparsing_unicode.Japanese.Hiragana) |
| 6864 |
setattr(pyparsing_unicode, u"한국어", pyparsing_unicode.Korean) |
| 6865 |
setattr(pyparsing_unicode, u"ไทย", pyparsing_unicode.Thai) |
| 6866 |
setattr(pyparsing_unicode, u"देवनागरी", pyparsing_unicode.Devanagari) |
| 6867 |
|
| 6868 |
|
| 6869 |
class pyparsing_test: |
| 6870 |
""" |
| 6871 |
namespace class for classes useful in writing unit tests |
| 6872 |
""" |
| 6873 |
|
| 6874 |
class reset_pyparsing_context: |
| 6875 |
""" |
| 6876 |
Context manager to be used when writing unit tests that modify pyparsing config values: |
| 6877 |
- packrat parsing |
| 6878 |
- default whitespace characters. |
| 6879 |
- default keyword characters |
| 6880 |
- literal string auto-conversion class |
| 6881 |
- __diag__ settings |
| 6882 |
|
| 6883 |
Example: |
| 6884 |
with reset_pyparsing_context(): |
| 6885 |
# test that literals used to construct a grammar are automatically suppressed |
| 6886 |
ParserElement.inlineLiteralsUsing(Suppress) |
| 6887 |
|
| 6888 |
term = Word(alphas) | Word(nums) |
| 6889 |
group = Group('(' + term[...] + ')') |
| 6890 |
|
| 6891 |
# assert that the '()' characters are not included in the parsed tokens |
| 6892 |
self.assertParseAndCheckLisst(group, "(abc 123 def)", ['abc', '123', 'def']) |
| 6893 |
|
| 6894 |
# after exiting context manager, literals are converted to Literal expressions again |
| 6895 |
""" |
| 6896 |
|
| 6897 |
def __init__(self): |
| 6898 |
self._save_context = {} |
| 6899 |
|
| 6900 |
def save(self): |
| 6901 |
self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS |
| 6902 |
self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS |
| 6903 |
self._save_context[ |
| 6904 |
"literal_string_class" |
| 6905 |
] = ParserElement._literalStringClass |
| 6906 |
self._save_context["packrat_enabled"] = ParserElement._packratEnabled |
| 6907 |
self._save_context["packrat_parse"] = ParserElement._parse |
| 6908 |
self._save_context["__diag__"] = { |
| 6909 |
name: getattr(__diag__, name) for name in __diag__._all_names |
| 6910 |
} |
| 6911 |
self._save_context["__compat__"] = { |
| 6912 |
"collect_all_And_tokens": __compat__.collect_all_And_tokens |
| 6913 |
} |
| 6914 |
return self |
| 6915 |
|
| 6916 |
def restore(self): |
| 6917 |
# reset pyparsing global state |
| 6918 |
if ( |
| 6919 |
ParserElement.DEFAULT_WHITE_CHARS |
| 6920 |
!= self._save_context["default_whitespace"] |
| 6921 |
): |
| 6922 |
ParserElement.setDefaultWhitespaceChars( |
| 6923 |
self._save_context["default_whitespace"] |
| 6924 |
) |
| 6925 |
Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"] |
| 6926 |
ParserElement.inlineLiteralsUsing( |
| 6927 |
self._save_context["literal_string_class"] |
| 6928 |
) |
| 6929 |
for name, value in self._save_context["__diag__"].items(): |
| 6930 |
setattr(__diag__, name, value) |
| 6931 |
ParserElement._packratEnabled = self._save_context["packrat_enabled"] |
| 6932 |
ParserElement._parse = self._save_context["packrat_parse"] |
| 6933 |
__compat__.collect_all_And_tokens = self._save_context["__compat__"] |
| 6934 |
|
| 6935 |
def __enter__(self): |
| 6936 |
return self.save() |
| 6937 |
|
| 6938 |
def __exit__(self, *args): |
| 6939 |
return self.restore() |
| 6940 |
|
| 6941 |
class TestParseResultsAsserts: |
| 6942 |
""" |
| 6943 |
A mixin class to add parse results assertion methods to normal unittest.TestCase classes. |
| 6944 |
""" |
| 6945 |
def assertParseResultsEquals( |
| 6946 |
self, result, expected_list=None, expected_dict=None, msg=None |
| 6947 |
): |
| 6948 |
""" |
| 6949 |
Unit test assertion to compare a ParseResults object with an optional expected_list, |
| 6950 |
and compare any defined results names with an optional expected_dict. |
| 6951 |
""" |
| 6952 |
if expected_list is not None: |
| 6953 |
self.assertEqual(expected_list, result.asList(), msg=msg) |
| 6954 |
if expected_dict is not None: |
| 6955 |
self.assertEqual(expected_dict, result.asDict(), msg=msg) |
| 6956 |
|
| 6957 |
def assertParseAndCheckList( |
| 6958 |
self, expr, test_string, expected_list, msg=None, verbose=True |
| 6959 |
): |
| 6960 |
""" |
| 6961 |
Convenience wrapper assert to test a parser element and input string, and assert that |
| 6962 |
the resulting ParseResults.asList() is equal to the expected_list. |
| 6963 |
""" |
| 6964 |
result = expr.parseString(test_string, parseAll=True) |
| 6965 |
if verbose: |
| 6966 |
print(result.dump()) |
| 6967 |
self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg) |
| 6968 |
|
| 6969 |
def assertParseAndCheckDict( |
| 6970 |
self, expr, test_string, expected_dict, msg=None, verbose=True |
| 6971 |
): |
| 6972 |
""" |
| 6973 |
Convenience wrapper assert to test a parser element and input string, and assert that |
| 6974 |
the resulting ParseResults.asDict() is equal to the expected_dict. |
| 6975 |
""" |
| 6976 |
result = expr.parseString(test_string, parseAll=True) |
| 6977 |
if verbose: |
| 6978 |
print(result.dump()) |
| 6979 |
self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg) |
| 6980 |
|
| 6981 |
def assertRunTestResults( |
| 6982 |
self, run_tests_report, expected_parse_results=None, msg=None |
| 6983 |
): |
| 6984 |
""" |
| 6985 |
Unit test assertion to evaluate output of ParserElement.runTests(). If a list of |
| 6986 |
list-dict tuples is given as the expected_parse_results argument, then these are zipped |
| 6987 |
with the report tuples returned by runTests and evaluated using assertParseResultsEquals. |
| 6988 |
Finally, asserts that the overall runTests() success value is True. |
| 6989 |
|
| 6990 |
:param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests |
| 6991 |
:param expected_parse_results (optional): [tuple(str, list, dict, Exception)] |
| 6992 |
""" |
| 6993 |
run_test_success, run_test_results = run_tests_report |
| 6994 |
|
| 6995 |
if expected_parse_results is not None: |
| 6996 |
merged = [ |
| 6997 |
(rpt[0], rpt[1], expected) |
| 6998 |
for rpt, expected in zip(run_test_results, expected_parse_results) |
| 6999 |
] |
| 7000 |
for test_string, result, expected in merged: |
| 7001 |
# expected should be a tuple containing a list and/or a dict or an exception, |
| 7002 |
# and optional failure message string |
| 7003 |
# an empty tuple will skip any result validation |
| 7004 |
fail_msg = next( |
| 7005 |
(exp for exp in expected if isinstance(exp, str)), None |
| 7006 |
) |
| 7007 |
expected_exception = next( |
| 7008 |
( |
| 7009 |
exp |
| 7010 |
for exp in expected |
| 7011 |
if isinstance(exp, type) and issubclass(exp, Exception) |
| 7012 |
), |
| 7013 |
None, |
| 7014 |
) |
| 7015 |
if expected_exception is not None: |
| 7016 |
with self.assertRaises( |
| 7017 |
expected_exception=expected_exception, msg=fail_msg or msg |
| 7018 |
): |
| 7019 |
if isinstance(result, Exception): |
| 7020 |
raise result |
| 7021 |
else: |
| 7022 |
expected_list = next( |
| 7023 |
(exp for exp in expected if isinstance(exp, list)), None |
| 7024 |
) |
| 7025 |
expected_dict = next( |
| 7026 |
(exp for exp in expected if isinstance(exp, dict)), None |
| 7027 |
) |
| 7028 |
if (expected_list, expected_dict) != (None, None): |
| 7029 |
self.assertParseResultsEquals( |
| 7030 |
result, |
| 7031 |
expected_list=expected_list, |
| 7032 |
expected_dict=expected_dict, |
| 7033 |
msg=fail_msg or msg, |
| 7034 |
) |
| 7035 |
else: |
| 7036 |
# warning here maybe? |
| 7037 |
print("no validation for {!r}".format(test_string)) |
| 7038 |
|
| 7039 |
# do this last, in case some specific test results can be reported instead |
| 7040 |
self.assertTrue( |
| 7041 |
run_test_success, msg=msg if msg is not None else "failed runTests" |
| 7042 |
) |
| 7043 |
|
| 7044 |
@contextmanager |
| 7045 |
def assertRaisesParseException(self, exc_type=ParseException, msg=None): |
| 7046 |
with self.assertRaises(exc_type, msg=msg): |
| 7047 |
yield |
| 7048 |
|
| 7049 |
|
| 7050 |
if __name__ == "__main__": |
| 7051 |
|
| 7052 |
selectToken = CaselessLiteral("select") |
| 7053 |
fromToken = CaselessLiteral("from") |
| 7054 |
|
| 7055 |
ident = Word(alphas, alphanums + "_$") |
| 7056 |
|
| 7057 |
columnName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens) |
| 7058 |
columnNameList = Group(delimitedList(columnName)).setName("columns") |
| 7059 |
columnSpec = ('*' | columnNameList) |
| 7060 |
|
| 7061 |
tableName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens) |
| 7062 |
tableNameList = Group(delimitedList(tableName)).setName("tables") |
| 7063 |
|
| 7064 |
simpleSQL = selectToken("command") + columnSpec("columns") + fromToken + tableNameList("tables") |
| 7065 |
|
| 7066 |
# demo runTests method, including embedded comments in test string |
| 7067 |
simpleSQL.runTests(""" |
| 7068 |
# '*' as column list and dotted table name |
| 7069 |
select * from SYS.XYZZY |
| 7070 |
|
| 7071 |
# caseless match on "SELECT", and casts back to "select" |
| 7072 |
SELECT * from XYZZY, ABC |
| 7073 |
|
| 7074 |
# list of column names, and mixed case SELECT keyword |
| 7075 |
Select AA,BB,CC from Sys.dual |
| 7076 |
|
| 7077 |
# multiple tables |
| 7078 |
Select A, B, C from Sys.dual, Table2 |
| 7079 |
|
| 7080 |
# invalid SELECT keyword - should fail |
| 7081 |
Xelect A, B, C from Sys.dual |
| 7082 |
|
| 7083 |
# incomplete command - should fail |
| 7084 |
Select |
| 7085 |
|
| 7086 |
# invalid column name - should fail |
| 7087 |
Select ^^^ frox Sys.dual |
| 7088 |
|
| 7089 |
""") |
| 7090 |
|
| 7091 |
pyparsing_common.number.runTests(""" |
| 7092 |
100 |
| 7093 |
-100 |
| 7094 |
+100 |
| 7095 |
3.14159 |
| 7096 |
6.02e23 |
| 7097 |
1e-12 |
| 7098 |
""") |
| 7099 |
|
| 7100 |
# any int or real number, returned as float |
| 7101 |
pyparsing_common.fnumber.runTests(""" |
| 7102 |
100 |
| 7103 |
-100 |
| 7104 |
+100 |
| 7105 |
3.14159 |
| 7106 |
6.02e23 |
| 7107 |
1e-12 |
| 7108 |
""") |
| 7109 |
|
| 7110 |
pyparsing_common.hex_integer.runTests(""" |
| 7111 |
100 |
| 7112 |
FF |
| 7113 |
""") |
| 7114 |
|
| 7115 |
import uuid |
| 7116 |
pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID)) |
| 7117 |
pyparsing_common.uuid.runTests(""" |
| 7118 |
12345678-1234-5678-1234-567812345678 |
| 7119 |
""") |