# # Copyright (c) 2003-2022 Paul T. McGuire # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #
if sys.version_info >= (3, 8): from functools import cached_property else:
class cached_property: def __init__(self, func):
self._func = func
def __get__(self, instance, owner=None):
ret = instance.__dict__[self._func.__name__] = self._func(instance) return ret
class __compat__(__config_flags): """
A cross-version compatibility configuration for pyparsing features that will be
released in a future version. By setting values in this configuration to True,
those features can be enabled in prior versions for compatibility development and testing.
- ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping
of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`;
maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1
behavior """
_type_desc = "compatibility"
collect_all_And_tokens = True
_all_names = [__ for __ in locals() ifnot __.startswith("_")]
_fixed_names = """
collect_all_And_tokens """.split()
class __diag__(__config_flags):
_type_desc = "diagnostic"
_all_names = [__ for __ in locals() ifnot __.startswith("_")]
_warning_names = [name for name in _all_names if name.startswith("warn")]
_debug_names = [name for name in _all_names if name.startswith("enable_debug")]
@classmethod def enable_all_warnings(cls) -> None: for name in cls._warning_names:
cls.enable(name)
class Diagnostics(Enum): """
Diagnostic configuration (all default to disabled)
- ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results
name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions
- ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results
name is defined on a containing expression with ungrouped subexpressions that also
have results names
- ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined with a results name, but has no contents defined
- ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is
defined in a grammar but has never had an expression attached to it
- ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined
but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'``
- ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is
incorrectly called with multiple str arguments
- ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent
calls to :class:`ParserElement.set_name`
Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`.
All warnings can be enabled by calling :class:`enable_all_warnings`. """
def enable_diag(diag_enum: Diagnostics) -> None: """
Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`). """
__diag__.enable(diag_enum.name)
def disable_diag(diag_enum: Diagnostics) -> None: """
Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`). """
__diag__.disable(diag_enum.name)
def enable_all_warnings() -> None: """
Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`). """
__diag__.enable_all_warnings()
# hide abstract class del __config_flags
def _should_enable_warnings(
cmd_line_warn_options: typing.Iterable[str], warn_env_var: typing.Optional[str]
) -> bool:
enable = bool(warn_env_var) for warn_opt in cmd_line_warn_options:
w_action, w_message, w_category, w_module, w_line = (warn_opt + "::::").split( ":"
)[:5] ifnot w_action.lower().startswith("i") and ( not (w_message or w_category or w_module) or w_module == "pyparsing"
):
enable = True elif w_action.lower().startswith("i") and w_module in ("pyparsing", ""):
enable = False return enable
if _should_enable_warnings(
sys.warnoptions, os.environ.get("PYPARSINGENABLEALLWARNINGS")
):
enable_all_warnings()
# build list of single arg builtins, that can be used as parse actions
_single_arg_builtins = {
sum,
len,
sorted,
reversed,
list,
tuple,
set,
any,
all,
min,
max,
}
def _trim_arity(func, max_limit=3): """decorator to trim function calls to match the arity of the target""" global _trim_arity_call_line
if func in _single_arg_builtins: returnlambda s, l, t: func(t)
limit = 0
found_arity = False
# synthesize what would be returned by traceback.extract_stack at the call to # user's parse action 'func', so that we don't incur call penalty at parse time
# fmt: off
LINE_DIFF = 7 # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!
_trim_arity_call_line = (_trim_arity_call_line or traceback.extract_stack(limit=2)[-1])
pa_call_line_synth = (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF)
def wrapper(*args): nonlocal found_arity, limit while 1: try:
ret = func(*args[limit:])
found_arity = True return ret except TypeError as te: # re-raise TypeErrors if they did not come from our arity testing if found_arity: raise else:
tb = te.__traceback__
frames = traceback.extract_tb(tb, limit=2)
frame_summary = frames[-1]
trim_arity_type_error = (
[frame_summary[:2]][-1][:2] == pa_call_line_synth
) del tb
if trim_arity_type_error: if limit < max_limit:
limit += 1 continue
raise # fmt: on
# copy func name to wrapper for sensible debug output # (can't use functools.wraps, since that messes with function signature)
func_name = getattr(func, "__name__", getattr(func, "__class__").__name__)
wrapper.__name__ = func_name
wrapper.__doc__ = func.__doc__
return wrapper
def condition_as_parse_action(
fn: ParseCondition, message: typing.Optional[str] = None, fatal: bool = False
) -> ParseAction: """
Function to convert a simple predicate function that returns ``True`` or ``False``
into a parse action. Can be used in places when a parse action is required and :class:`ParserElement.add_condition` cannot be used (such as when adding a condition
to an operator level in :class:`infix_notation`).
Optional keyword arguments:
- ``message`` - define a custom message to be used in the raised exception
- ``fatal`` - ifTrue, will raise :class:`ParseFatalException` to stop parsing immediately;
otherwise will raise :class:`ParseException`
"""
msg = message if message isnotNoneelse"failed user-defined condition"
exc_type = ParseFatalException if fatal else ParseException
fn = _trim_arity(fn)
# default whitespace chars are space, <TAB> and newline
Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.set_default_whitespace_chars(" \t")
Word(alphas)[1, ...].parse_string("abc def\nghi jkl") # -> ['abc', 'def'] """
ParserElement.DEFAULT_WHITE_CHARS = chars
# update whitespace all parse expressions defined in this module for expr in _builtin_exprs: if expr.copyDefaultWhiteChars:
expr.whiteChars = set(chars)
@staticmethod def inline_literals_using(cls: type) -> None: """
Set class to be used for inclusion of string literals into a parser.
Example::
# default literal class used is Literal
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
def suppress_warning(self, warning_type: Diagnostics) -> "ParserElement": """
Suppress warnings emitted for a particular diagnostic on this expression.
Example::
base = pp.Forward()
base.suppress_warning(Diagnostics.warn_on_parse_using_empty_Forward)
# statement would normally raise a warning, but is now suppressed
print(base.parse_string("x"))
def visit_all(self): """General-purpose method to yield all expressions and sub-expressions in a grammar. Typically just for internal use. """
to_visit = deque([self])
seen = set() while to_visit:
cur = to_visit.popleft()
# guard against looping forever through recursive grammars if cur in seen: continue
seen.add(cur)
to_visit.extend(cur.recurse()) yield cur
def copy(self) -> "ParserElement": """
Make a copy of this :class:`ParserElement`. Useful for defining
different parse actions for the same parsing pattern, using copies of
the original parse element.
def set_results_name(
self, name: str, list_all_matches: bool = False, *, listAllMatches: bool = False
) -> "ParserElement": """
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
Normally, results names are assigned as you would assign keys in a dict:
any existing value is overwritten by later values. If it is necessary to
keep all values captured for a particular results name, call ``set_results_name`` with ``list_all_matches`` = True.
NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
``expr("name")`` in place of ``expr.set_results_name("name")``
- see :class:`__call__`. If ``list_all_matches`` is required, use
``expr("name*")``.
def _setResultsName(self, name, listAllMatches=False): if name isNone: return self
newself = self.copy() if name.endswith("*"):
name = name[:-1]
listAllMatches = True
newself.resultsName = name
newself.modalResults = not listAllMatches return newself
def set_break(self, break_flag: bool = True) -> "ParserElement": """
Method to invoke the Python pdb debugger when this element is
about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to
disable. """ if break_flag:
_parseMethod = self._parse
def set_parse_action(self, *fns: ParseAction, **kwargs) -> "ParserElement": """
Define one or more actions to perform when successfully matching parse element definition.
Parse actions can be called to perform data conversions, do extra validation,
update external data structures, or enhance or replace the parsed tokens.
Each parse action ``fn`` is a callable method with 0-3 arguments, called as
``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:
- ``s`` = the original string being parsed (see note below)
- ``loc`` = the location of the matching substring
- ``toks`` = a list of the matched tokens, packaged as a :class:`ParseResults` object
The parsed tokens are passed to the parse action as ParseResults. They can be
modified in place using list-style append, extend, and pop operations to update
the parsed list elements; andwith dictionary-style item set anddel operations
to add, update, or remove any named results. If the tokens are modified in place,
it isnot necessary to return them with a return statement.
Parse actions can also completely replace the given tokens, with another ``ParseResults``
object, orwith some entirely different object (common for parse actions that perform data
conversions). A convenient way to build a new parse result is to define the values
using a dict, and then create the return value using :class:`ParseResults.from_dict`.
IfNoneis passed as the ``fn`` parse action, all previously added parse actions for this
expression are cleared.
Optional keyword arguments:
- ``call_during_try`` = (default= ``False``) indicate if parse action should be run during
lookaheads and alternate testing. For parse actions that have side effects, it is
important to only call the parse action once it is determined that it is being
called as part of a successful parse. For parse actions that perform additional
validation, then call_during_try should be passed asTrue, so that the validation
code is included in the preliminary "try" parses.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See :class:`parse_string` for more
information on parsing strings containing ``<TAB>`` s, and suggested
methods to maintain a consistent view of the parsed string, the parse
location, and line and column positions within the parsed string.
Example::
# parse dates in the form YYYY/MM/DD
# use parse action to convert toks from str to int at parse time def convert_to_int(toks): return int(toks[0])
# use a parse action to verify that the date is a valid date def is_valid_date(instring, loc, toks): from datetime import date
year, month, day = toks[::2] try:
date(year, month, day) except ValueError: raise ParseException(instring, loc, "invalid date given")
# note that integer fields are now ints, not strings
date_str.run_tests(''' # successful parse - note that integer fields were converted to ints
1999/12/31
# fail - invalid date
1999/13/31 ''') """ if list(fns) == [None]:
self.parseAction = [] else: ifnot all(callable(fn) for fn in fns): raise TypeError("parse actions must be callable")
self.parseAction = [_trim_arity(fn) for fn in fns]
self.callDuringTry = kwargs.get( "call_during_try", kwargs.get("callDuringTry", False)
) return self
def add_parse_action(self, *fns: ParseAction, **kwargs) -> "ParserElement": """
Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`.
See examples in :class:`copy`. """
self.parseAction += [_trim_arity(fn) for fn in fns]
self.callDuringTry = self.callDuringTry or kwargs.get( "call_during_try", kwargs.get("callDuringTry", False)
) return self
def add_condition(self, *fns: ParseCondition, **kwargs) -> "ParserElement": """Add a boolean predicate function to expression's list of parse actions. See
:class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``,
functions passed to ``add_condition`` need to return boolean success/fail of the condition.
Optional keyword arguments:
- ``message`` = define a custom message to be used in the raised exception
- ``fatal`` = ifTrue, will raise ParseFatalException to stop parsing immediately; otherwise will raise
ParseException
- ``call_during_try`` = boolean to indicate if this method should be called during internal tryParse calls,
default=False
Example::
integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.add_condition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parse_string("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0),
(line:1, col:1) """ for fn in fns:
self.parseAction.append(
condition_as_parse_action(
fn,
message=str(kwargs.get("message")),
fatal=bool(kwargs.get("fatal", False)),
)
)
def set_fail_action(self, fn: ParseFailAction) -> "ParserElement": """
Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
``fn(s, loc, expr, err)`` where:
- ``s`` = string being parsed
- ``loc`` = location where expression match was attempted and failed
- ``expr`` = the parse expression that failed
- ``err`` = the exception thrown
The function returns no value. It may throw :class:`ParseFatalException` if it is desired to stop parsing immediately."""
self.failAction = fn return self
def _skipIgnorables(self, instring: str, loc: int) -> int: ifnot self.ignoreExprs: return loc
exprsFound = True
ignore_expr_fns = [e._parse for e in self.ignoreExprs] while exprsFound:
exprsFound = False for ignore_fn in ignore_expr_fns: try: while 1:
loc, dummy = ignore_fn(instring, loc)
exprsFound = True except ParseException: pass return loc
def preParse(self, instring: str, loc: int) -> int: if self.ignoreExprs:
loc = self._skipIgnorables(instring, loc)
if self.skipWhitespace:
instrlen = len(instring)
white_chars = self.whiteChars while loc < instrlen and instring[loc] in white_chars:
loc += 1
class _CacheType(dict): """ class to help type checking """
not_in_cache: bool
def get(self, *args):
...
def set(self, *args):
...
# argument cache for optimizing repeated calls when backtracking through recursive expressions
packrat_cache = (
_CacheType()
) # set later by enable_packrat(); this is here so that reset_cache() doesn't fail
packrat_cache_lock = RLock()
packrat_cache_stats = [0, 0]
# this method gets repeatedly called during backtracking with the same arguments - # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression def _parseCache(
self, instring, loc, doActions=True, callPreParse=True
) -> Tuple[int, ParseResults]:
HIT, MISS = 0, 1 TRY, MATCH, FAIL = 0, 1, 2
lookup = (self, instring, loc, callPreParse, doActions) with ParserElement.packrat_cache_lock:
cache = ParserElement.packrat_cache
value = cache.get(lookup) if value is cache.not_in_cache:
ParserElement.packrat_cache_stats[MISS] += 1 try:
value = self._parseNoCache(instring, loc, doActions, callPreParse) except ParseBaseException as pe: # cache a copy of the exception, without the traceback
cache.set(lookup, pe.__class__(*pe.args)) raise else:
cache.set(lookup, (value[0], value[1].copy(), loc)) return value else:
ParserElement.packrat_cache_stats[HIT] += 1 if self.debug and self.debugActions.debug_try: try:
self.debugActions.debug_try(instring, loc, self, cache_hit=True) # type: ignore [call-arg] except TypeError: pass if isinstance(value, Exception): if self.debug and self.debugActions.debug_fail: try:
self.debugActions.debug_fail(
instring, loc, self, value, cache_hit=True# type: ignore [call-arg]
) except TypeError: pass raise value
@staticmethod def disable_memoization() -> None: """
Disables active Packrat or Left Recursion parsing and their memoization
This method also works if neither Packrat nor Left Recursion are enabled.
This makes it safe to call before activating Packrat nor Left Recursion
to clear any previous settings. """
ParserElement.reset_cache()
ParserElement._left_recursion_enabled = False
ParserElement._packratEnabled = False
ParserElement._parse = ParserElement._parseNoCache
@staticmethod def enable_left_recursion(
cache_size_limit: typing.Optional[int] = None, *, force=False
) -> None: """
Enables "bounded recursion" parsing, which allows for both direct and indirect
left-recursion. During parsing, left-recursive :class:`Forward` elements are
repeatedly matched with a fixed recursion depth that is gradually increased
until finding the longest match.
Example::
from pip._vendor import pyparsing as pp
pp.ParserElement.enable_left_recursion()
E = pp.Forward("E")
num = pp.Word(pp.nums) # match `num`, or `num '+' num`, or `num '+' num '+' num`, ...
E <<= E + '+' - num | num
print(E.parse_string("1+2+3"))
Recursion search naturally memoizes matches of ``Forward`` elements and may
thus skip reevaluation of parse actions during backtracking. This may break
programs with parse actions which rely on strict ordering of side-effects.
Parameters:
- ``cache_size_limit`` - (default=``None``) - memoize at most this many
``Forward`` elements during matching; if ``None`` (the default),
memoize all ``Forward`` elements.
Bounded Recursion parsing works similar but not identical to Packrat parsing,
thus the two cannot be used together. Use ``force=True`` to disable any
previous, conflicting settings. """ if force:
ParserElement.disable_memoization() elif ParserElement._packratEnabled: raise RuntimeError("Packrat and Bounded Recursion are not compatible") if cache_size_limit isNone:
ParserElement.recursion_memos = _UnboundedMemo() # type: ignore[assignment] elif cache_size_limit > 0:
ParserElement.recursion_memos = _LRUMemo(capacity=cache_size_limit) # type: ignore[assignment] else: raise NotImplementedError("Memo size of %s" % cache_size_limit)
ParserElement._left_recursion_enabled = True
@staticmethod def enable_packrat(cache_size_limit: int = 128, *, force: bool = False) -> None: """
Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
Parameters:
- ``cache_size_limit`` - (default= ``128``) - if an integer value is provided
will limit the size of the packrat cache; ifNoneis passed, then
the cache size will be unbounded; if 0 is passed, the cache will
be effectively disabled.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method :class:`ParserElement.enable_packrat`. For best results, call ``enable_packrat()`` immediately after
importing pyparsing.
Example::
from pip._vendor import pyparsing
pyparsing.ParserElement.enable_packrat()
Packrat parsing works similar but not identical to Bounded Recursion parsing,
thus the two cannot be used together. Use ``force=True`` to disable any
previous, conflicting settings. """ if force:
ParserElement.disable_memoization() elif ParserElement._left_recursion_enabled: raise RuntimeError("Packrat and Bounded Recursion are not compatible") ifnot ParserElement._packratEnabled:
ParserElement._packratEnabled = True if cache_size_limit isNone:
ParserElement.packrat_cache = _UnboundedCache() else:
ParserElement.packrat_cache = _FifoCache(cache_size_limit) # type: ignore[assignment]
ParserElement._parse = ParserElement._parseCache
def parse_string(
self, instring: str, parse_all: bool = False, *, parseAll: bool = False
) -> ParseResults: """
Parse a string with respect to the parser definition. This function is intended as the primary interface to the
client code.
:param instring: The input string to be parsed.
:param parse_all: If set, the entire input string must match the grammar.
:param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release.
:raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar.
:returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or
an object with attributes if the given parser includes results names.
If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This is also equivalent to ending the grammar with :class:`StringEnd`\\ ().
To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are
converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string
contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string
being parsed, one can ensure a consistent view of the input string by doing one of the following:
- calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`),
- define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the
parse action's ``s`` argument, or
- explicitly expand the tabs in your input string before calling ``parse_string``.
Examples:
By default, partial matches are OK.
>>> res = Word('a').parse_string('aaaaabaaa')
>>> print(res)
['aaaaa']
The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children
directly to see more examples.
It raises an exception if parse_all flag is set and instring does not match the whole grammar.
>>> res = Word('a').parse_string('aaaaabaaa', parse_all=True)
Traceback (most recent call last):
...
pyparsing.ParseException: Expected end of text, found 'b' (at char 5), (line:1, col:6) """
parseAll = parse_all or parseAll
ParserElement.reset_cache() ifnot self.streamlined:
self.streamline() for e in self.ignoreExprs:
e.streamline() ifnot self.keepTabs:
instring = instring.expandtabs() try:
loc, tokens = self._parse(instring, 0) if parseAll:
loc = self.preParse(instring, loc)
se = Empty() + StringEnd()
se._parse(instring, loc) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clearing out pyparsing internal stack trace raise exc.with_traceback(None) else: return tokens
def scan_string(
self,
instring: str,
max_matches: int = _MAX_INT,
overlap: bool = False,
*,
debug: bool = False,
maxMatches: int = _MAX_INT,
) -> Generator[Tuple[ParseResults, int, int], None, None]: """
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
``max_matches`` argument, to clip scanning after 'n' matches are found. If
``overlap`` is specified, then overlapping matches will be reported.
Note that the start and end locations are reported relative to the string
being parsed. See :class:`parse_string` for more information on parsing
strings with embedded tabs.
Example::
source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
print(source) for tokens, start, end in Word(alphas).scan_string(source):
print(' '*start + '^'*(end-start))
print(' '*start + tokens[0])
prints::
sldjf123lsdjjkf345sldkjf879lkjsfd987
^^^^^
sldjf
^^^^^^^
lsdjjkf
^^^^^^
sldkjf
^^^^^^
lkjsfd """
maxMatches = min(maxMatches, max_matches) ifnot self.streamlined:
self.streamline() for e in self.ignoreExprs:
e.streamline()
ifnot self.keepTabs:
instring = str(instring).expandtabs()
instrlen = len(instring)
loc = 0
preparseFn = self.preParse
parseFn = self._parse
ParserElement.resetCache()
matches = 0 try: while loc <= instrlen and matches < maxMatches: try:
preloc: int = preparseFn(instring, loc)
nextLoc: int
tokens: ParseResults
nextLoc, tokens = parseFn(instring, preloc, callPreParse=False) except ParseException:
loc = preloc + 1 else: if nextLoc > loc:
matches += 1 if debug:
print(
{ "tokens": tokens.asList(), "start": preloc, "end": nextLoc,
}
) yield tokens, preloc, nextLoc if overlap:
nextloc = preparseFn(instring, loc) if nextloc > loc:
loc = nextLoc else:
loc += 1 else:
loc = nextLoc else:
loc = preloc + 1 except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc.with_traceback(None)
def transform_string(self, instring: str, *, debug: bool = False) -> str: """
Extension to :class:`scan_string`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transform_string``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transform_string()`` on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse
action. ``transform_string()`` returns the resulting transformed string.
print(wd.transform_string("now is the winter of our discontent made glorious summer by this sun of york."))
prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. """
out: List[str] = []
lastE = 0 # force preservation of <TAB>s, to minimize unwanted transformation of string, and to # keep string locs straight between transform_string and scan_string
self.keepTabs = True try: for t, s, e in self.scan_string(instring, debug=debug):
out.append(instring[lastE:s]) if t: if isinstance(t, ParseResults):
out += t.as_list() elif isinstance(t, Iterable) andnot isinstance(t, str_type):
out.extend(t) else:
out.append(t)
lastE = e
out.append(instring[lastE:])
out = [o for o in out if o] return"".join([str(s) for s in _flatten(out)]) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc.with_traceback(None)
def search_string(
self,
instring: str,
max_matches: int = _MAX_INT,
*,
debug: bool = False,
maxMatches: int = _MAX_INT,
) -> ParseResults: """
Another extension to :class:`scan_string`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``max_matches`` argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
cap_word = Word(alphas.upper(), alphas.lower())
print(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity"))
# the sum() builtin can be used to merge results into a single ParseResults object
print(sum(cap_word.search_string("More than Iron, more than Lead, more than Gold I need Electricity")))
prints::
[['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]
['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity'] """
maxMatches = min(maxMatches, max_matches) try: return ParseResults(
[t for t, s, e in self.scan_string(instring, maxMatches, debug=debug)]
) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc.with_traceback(None)
def split(
self,
instring: str,
maxsplit: int = _MAX_INT,
include_separators: bool = False,
*,
includeSeparators=False,
) -> Generator[str, None, None]: """
Generator method to split a string using the given expression as a separator.
May be called with optional ``maxsplit`` argument, to limit the number of splits; and the optional ``include_separators`` argument (default= ``False``), if the separating
matching text should be included in the split results.
Example::
punc = one_of(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', ''] """
includeSeparators = includeSeparators or include_separators
last = 0 for t, s, e in self.scan_string(instring, max_matches=maxsplit): yield instring[last:s] if includeSeparators: yield t[0]
last = e yield instring[last:]
def __add__(self, other) -> "ParserElement": """
Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement`
converts them to :class:`Literal`\\ s by default.
Note that the skipped text is returned with'_skipped'as a results name, and to support having multiple skips in the same parser, the value returned is
a list of all skipped text. """ if other is Ellipsis: return _PendingSkip(self)
if isinstance(other, str_type):
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented returnAnd([self, other])
def __radd__(self, other) -> "ParserElement": """
Implementation of ``+`` operator when left operand isnot a :class:`ParserElement` """ if other is Ellipsis: return SkipTo(self)("_skipped*") + self
if isinstance(other, str_type):
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented return other + self
def __sub__(self, other) -> "ParserElement": """
Implementation of ``-`` operator, returns :class:`And` with error stop """ if isinstance(other, str_type):
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented return self + And._ErrorStop() + other
def __rsub__(self, other) -> "ParserElement": """
Implementation of ``-`` operator when left operand isnot a :class:`ParserElement` """ if isinstance(other, str_type):
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented return other - self
def __mul__(self, other) -> "ParserElement": """
Implementation of ``*`` operator, allows use of ``expr * 3`` in place of
``expr + expr + expr``. Expressions may also be multiplied by a 2-integer
tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
may also include ``None`` asin:
- ``expr*(n, None)`` or ``expr*(n, )`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as"at least n instances of ``expr``")
- ``expr*(None, n)`` is equivalent to ``expr*(0, n)``
(read as"0 to n instances of ``expr``")
- ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``
- ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``
Note that ``expr*(None, n)`` does notraise an exception if
more than n exprs exist in the input stream; that is,
``expr*(None, n)`` does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
``expr*(None, n) + ~expr`` """ if other is Ellipsis:
other = (0, None) elif isinstance(other, tuple) and other[:1] == (Ellipsis,):
other = ((0,) + other[1:] + (None,))[:2]
if isinstance(other, int):
minElements, optElements = other, 0 elif isinstance(other, tuple):
other = tuple(o if o isnot Ellipsis elseNonefor o in other)
other = (other + (None, None))[:2] if other[0] isNone:
other = (0, other[1]) if isinstance(other[0], int) and other[1] isNone: if other[0] == 0: return ZeroOrMore(self) if other[0] == 1: return OneOrMore(self) else: return self * other[0] + ZeroOrMore(self) elif isinstance(other[0], int) and isinstance(other[1], int):
minElements, optElements = other
optElements -= minElements else: return NotImplemented else: return NotImplemented
if minElements < 0: raise ValueError("cannot multiply ParserElement by negative value") if optElements < 0: raise ValueError( "second tuple value must be greater or equal to first tuple value"
) if minElements == optElements == 0: returnAnd([])
if optElements:
def makeOptionalList(n): if n > 1: return Opt(self + makeOptionalList(n - 1)) else: return Opt(self)
if minElements: if minElements == 1:
ret = self + makeOptionalList(optElements) else:
ret = And([self] * minElements) + makeOptionalList(optElements) else:
ret = makeOptionalList(optElements) else: if minElements == 1:
ret = self else:
ret = And([self] * minElements) return ret
def __or__(self, other) -> "ParserElement": """
Implementation of ``|`` operator - returns :class:`MatchFirst` """ if other is Ellipsis: return _PendingSkip(self, must_skip=True)
if isinstance(other, str_type): # `expr | ""` is equivalent to `Opt(expr)` if other == "": return Opt(self)
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented return MatchFirst([self, other])
def __ror__(self, other) -> "ParserElement": """
Implementation of ``|`` operator when left operand isnot a :class:`ParserElement` """ if isinstance(other, str_type):
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented return other | self
def __xor__(self, other) -> "ParserElement": """
Implementation of ``^`` operator - returns :class:`Or` """ if isinstance(other, str_type):
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented returnOr([self, other])
def __rxor__(self, other) -> "ParserElement": """
Implementation of ``^`` operator when left operand isnot a :class:`ParserElement` """ if isinstance(other, str_type):
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented return other ^ self
def __and__(self, other) -> "ParserElement": """
Implementation of ``&`` operator - returns :class:`Each` """ if isinstance(other, str_type):
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented return Each([self, other])
def __rand__(self, other) -> "ParserElement": """
Implementation of ``&`` operator when left operand isnot a :class:`ParserElement` """ if isinstance(other, str_type):
other = self._literalStringClass(other) ifnot isinstance(other, ParserElement): return NotImplemented return other & self
# disable __iter__ to override legacy use of sequential access to __getitem__ to # iterate over a sequence
__iter__ = None
def __getitem__(self, key): """
use ``[]`` indexing notation as a short form for expression repetition:
- ``expr[n]`` is equivalent to ``expr*n``
- ``expr[m, n]`` is equivalent to ``expr*(m, n)``
- ``expr[n, ...]`` or ``expr[n,]`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as"at least n instances of ``expr``")
- ``expr[..., n]`` is equivalent to ``expr*(0, n)``
(read as"0 to n instances of ``expr``")
- ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``
- ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``
``None`` may be used in place of ``...``.
Note that ``expr[..., n]`` and ``expr[m, n]`` do notraise an exception if more than ``n`` ``expr``\\ s exist in the input stream. If this behavior is
desired, then write ``expr[..., n] + ~expr``.
For repetition with a stop_on expression, use slice notation:
- ``expr[...: end_expr]`` and ``expr[0, ...: end_expr]`` are equivalent to ``ZeroOrMore(expr, stop_on=end_expr)``
- ``expr[1, ...: end_expr]`` is equivalent to ``OneOrMore(expr, stop_on=end_expr)``
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.