Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/__pycache__/distro.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/__pycache__/six.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/__pycache__/typing_extensions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__init__.py +3 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__main__.py +12 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/__main__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/core.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/cacert.pem +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/core.py +76 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/cli/__init__.py +1 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/cli/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/cli/__pycache__/chardetect.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/metadata/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/metadata/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/metadata/__pycache__/languages.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/metadata/languages.py +310 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__init__.py +6 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/ansi.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/ansitowin32.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/initialise.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/win32.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/winterm.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/ansi.py +102 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/ansitowin32.py +258 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/initialise.py +80 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/win32.py +152 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/winterm.py +169 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__init__.py +328 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/actions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/helpers.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/testing.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/unicode.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/util.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/actions.py +207 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/common.py +424 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/core.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/diagram/__init__.py +593 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/diagram/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/exceptions.py +267 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/helpers.py +1069 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/results.py +760 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/testing.py +331 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/unicode.py +332 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/util.py +235 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/tenacity/__init__.py +517 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/tenacity/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pip/_vendor/tenacity/__pycache__/_asyncio.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/pip/_vendor/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (2.92 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/__pycache__/distro.cpython-310.pyc
ADDED
Binary file (38.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/__pycache__/six.cpython-310.pyc
ADDED
Binary file (27.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/__pycache__/typing_extensions.cpython-310.pyc
ADDED
Binary file (66.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__init__.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
from .core import contents, where
|
2 |
+
|
3 |
+
__version__ = "2021.10.08"
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__main__.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
|
3 |
+
from pip._vendor.certifi import contents, where
|
4 |
+
|
5 |
+
parser = argparse.ArgumentParser()
|
6 |
+
parser.add_argument("-c", "--contents", action="store_true")
|
7 |
+
args = parser.parse_args()
|
8 |
+
|
9 |
+
if args.contents:
|
10 |
+
print(contents())
|
11 |
+
else:
|
12 |
+
print(where())
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (276 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/__main__.cpython-310.pyc
ADDED
Binary file (455 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/core.cpython-310.pyc
ADDED
Binary file (1.51 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/cacert.pem
ADDED
The diff for this file is too large to render.
See raw diff
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/certifi/core.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
|
3 |
+
"""
|
4 |
+
certifi.py
|
5 |
+
~~~~~~~~~~
|
6 |
+
|
7 |
+
This module returns the installation location of cacert.pem or its contents.
|
8 |
+
"""
|
9 |
+
import os
|
10 |
+
|
11 |
+
|
12 |
+
class _PipPatchedCertificate(Exception):
|
13 |
+
pass
|
14 |
+
|
15 |
+
|
16 |
+
DEBIAN_CA_CERTS_PATH = '/etc/ssl/certs/ca-certificates.crt'
|
17 |
+
|
18 |
+
try:
|
19 |
+
# Return a certificate file on disk for a standalone pip zipapp running in
|
20 |
+
# an isolated build environment to use. Passing --cert to the standalone
|
21 |
+
# pip does not work since requests calls where() unconditionally on import.
|
22 |
+
_PIP_STANDALONE_CERT = os.environ.get("_PIP_STANDALONE_CERT")
|
23 |
+
if _PIP_STANDALONE_CERT:
|
24 |
+
def where():
|
25 |
+
return _PIP_STANDALONE_CERT
|
26 |
+
raise _PipPatchedCertificate()
|
27 |
+
|
28 |
+
from importlib.resources import path as get_path, read_text
|
29 |
+
|
30 |
+
_CACERT_CTX = None
|
31 |
+
_CACERT_PATH = None
|
32 |
+
|
33 |
+
def where():
|
34 |
+
# This is slightly terrible, but we want to delay extracting the file
|
35 |
+
# in cases where we're inside of a zipimport situation until someone
|
36 |
+
# actually calls where(), but we don't want to re-extract the file
|
37 |
+
# on every call of where(), so we'll do it once then store it in a
|
38 |
+
# global variable.
|
39 |
+
global _CACERT_CTX
|
40 |
+
global _CACERT_PATH
|
41 |
+
if _CACERT_PATH is None:
|
42 |
+
# This is slightly janky, the importlib.resources API wants you to
|
43 |
+
# manage the cleanup of this file, so it doesn't actually return a
|
44 |
+
# path, it returns a context manager that will give you the path
|
45 |
+
# when you enter it and will do any cleanup when you leave it. In
|
46 |
+
# the common case of not needing a temporary file, it will just
|
47 |
+
# return the file system location and the __exit__() is a no-op.
|
48 |
+
#
|
49 |
+
# We also have to hold onto the actual context manager, because
|
50 |
+
# it will do the cleanup whenever it gets garbage collected, so
|
51 |
+
# we will also store that at the global level as well.
|
52 |
+
_CACERT_PATH = DEBIAN_CA_CERTS_PATH
|
53 |
+
|
54 |
+
return _CACERT_PATH
|
55 |
+
|
56 |
+
except _PipPatchedCertificate:
|
57 |
+
pass
|
58 |
+
|
59 |
+
except ImportError:
|
60 |
+
# This fallback will work for Python versions prior to 3.7 that lack the
|
61 |
+
# importlib.resources module but relies on the existing `where` function
|
62 |
+
# so won't address issues with environments like PyOxidizer that don't set
|
63 |
+
# __file__ on modules.
|
64 |
+
def read_text(_module, _path, encoding="ascii"):
|
65 |
+
with open(where(), "r", encoding=encoding) as data:
|
66 |
+
return data.read()
|
67 |
+
|
68 |
+
# If we don't have importlib.resources, then we will just do the old logic
|
69 |
+
# of assuming we're on the filesystem and munge the path directly.
|
70 |
+
def where():
|
71 |
+
return DEBIAN_CA_CERTS_PATH
|
72 |
+
|
73 |
+
|
74 |
+
def contents():
|
75 |
+
with open(where(), "r", encoding="ascii") as data:
|
76 |
+
return data.read()
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/cli/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/cli/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (196 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/cli/__pycache__/chardetect.cpython-310.pyc
ADDED
Binary file (2.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/metadata/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/metadata/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (201 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/metadata/__pycache__/languages.cpython-310.pyc
ADDED
Binary file (7.96 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/chardet/metadata/languages.py
ADDED
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# -*- coding: utf-8 -*-
|
3 |
+
"""
|
4 |
+
Metadata about languages used by our model training code for our
|
5 |
+
SingleByteCharSetProbers. Could be used for other things in the future.
|
6 |
+
|
7 |
+
This code is based on the language metadata from the uchardet project.
|
8 |
+
"""
|
9 |
+
from __future__ import absolute_import, print_function
|
10 |
+
|
11 |
+
from string import ascii_letters
|
12 |
+
|
13 |
+
|
14 |
+
# TODO: Add Ukranian (KOI8-U)
|
15 |
+
|
16 |
+
class Language(object):
|
17 |
+
"""Metadata about a language useful for training models
|
18 |
+
|
19 |
+
:ivar name: The human name for the language, in English.
|
20 |
+
:type name: str
|
21 |
+
:ivar iso_code: 2-letter ISO 639-1 if possible, 3-letter ISO code otherwise,
|
22 |
+
or use another catalog as a last resort.
|
23 |
+
:type iso_code: str
|
24 |
+
:ivar use_ascii: Whether or not ASCII letters should be included in trained
|
25 |
+
models.
|
26 |
+
:type use_ascii: bool
|
27 |
+
:ivar charsets: The charsets we want to support and create data for.
|
28 |
+
:type charsets: list of str
|
29 |
+
:ivar alphabet: The characters in the language's alphabet. If `use_ascii` is
|
30 |
+
`True`, you only need to add those not in the ASCII set.
|
31 |
+
:type alphabet: str
|
32 |
+
:ivar wiki_start_pages: The Wikipedia pages to start from if we're crawling
|
33 |
+
Wikipedia for training data.
|
34 |
+
:type wiki_start_pages: list of str
|
35 |
+
"""
|
36 |
+
def __init__(self, name=None, iso_code=None, use_ascii=True, charsets=None,
|
37 |
+
alphabet=None, wiki_start_pages=None):
|
38 |
+
super(Language, self).__init__()
|
39 |
+
self.name = name
|
40 |
+
self.iso_code = iso_code
|
41 |
+
self.use_ascii = use_ascii
|
42 |
+
self.charsets = charsets
|
43 |
+
if self.use_ascii:
|
44 |
+
if alphabet:
|
45 |
+
alphabet += ascii_letters
|
46 |
+
else:
|
47 |
+
alphabet = ascii_letters
|
48 |
+
elif not alphabet:
|
49 |
+
raise ValueError('Must supply alphabet if use_ascii is False')
|
50 |
+
self.alphabet = ''.join(sorted(set(alphabet))) if alphabet else None
|
51 |
+
self.wiki_start_pages = wiki_start_pages
|
52 |
+
|
53 |
+
def __repr__(self):
|
54 |
+
return '{}({})'.format(self.__class__.__name__,
|
55 |
+
', '.join('{}={!r}'.format(k, v)
|
56 |
+
for k, v in self.__dict__.items()
|
57 |
+
if not k.startswith('_')))
|
58 |
+
|
59 |
+
|
60 |
+
LANGUAGES = {'Arabic': Language(name='Arabic',
|
61 |
+
iso_code='ar',
|
62 |
+
use_ascii=False,
|
63 |
+
# We only support encodings that use isolated
|
64 |
+
# forms, because the current recommendation is
|
65 |
+
# that the rendering system handles presentation
|
66 |
+
# forms. This means we purposefully skip IBM864.
|
67 |
+
charsets=['ISO-8859-6', 'WINDOWS-1256',
|
68 |
+
'CP720', 'CP864'],
|
69 |
+
alphabet=u'ءآأؤإئابةتثجحخدذرزسشصضطظعغػؼؽؾؿـفقكلمنهوىيًٌٍَُِّ',
|
70 |
+
wiki_start_pages=[u'الصفحة_الرئيسية']),
|
71 |
+
'Belarusian': Language(name='Belarusian',
|
72 |
+
iso_code='be',
|
73 |
+
use_ascii=False,
|
74 |
+
charsets=['ISO-8859-5', 'WINDOWS-1251',
|
75 |
+
'IBM866', 'MacCyrillic'],
|
76 |
+
alphabet=(u'АБВГДЕЁЖЗІЙКЛМНОПРСТУЎФХЦЧШЫЬЭЮЯ'
|
77 |
+
u'абвгдеёжзійклмнопрстуўфхцчшыьэюяʼ'),
|
78 |
+
wiki_start_pages=[u'Галоўная_старонка']),
|
79 |
+
'Bulgarian': Language(name='Bulgarian',
|
80 |
+
iso_code='bg',
|
81 |
+
use_ascii=False,
|
82 |
+
charsets=['ISO-8859-5', 'WINDOWS-1251',
|
83 |
+
'IBM855'],
|
84 |
+
alphabet=(u'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯ'
|
85 |
+
u'абвгдежзийклмнопрстуфхцчшщъьюя'),
|
86 |
+
wiki_start_pages=[u'Начална_страница']),
|
87 |
+
'Czech': Language(name='Czech',
|
88 |
+
iso_code='cz',
|
89 |
+
use_ascii=True,
|
90 |
+
charsets=['ISO-8859-2', 'WINDOWS-1250'],
|
91 |
+
alphabet=u'áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ',
|
92 |
+
wiki_start_pages=[u'Hlavní_strana']),
|
93 |
+
'Danish': Language(name='Danish',
|
94 |
+
iso_code='da',
|
95 |
+
use_ascii=True,
|
96 |
+
charsets=['ISO-8859-1', 'ISO-8859-15',
|
97 |
+
'WINDOWS-1252'],
|
98 |
+
alphabet=u'æøåÆØÅ',
|
99 |
+
wiki_start_pages=[u'Forside']),
|
100 |
+
'German': Language(name='German',
|
101 |
+
iso_code='de',
|
102 |
+
use_ascii=True,
|
103 |
+
charsets=['ISO-8859-1', 'WINDOWS-1252'],
|
104 |
+
alphabet=u'äöüßÄÖÜ',
|
105 |
+
wiki_start_pages=[u'Wikipedia:Hauptseite']),
|
106 |
+
'Greek': Language(name='Greek',
|
107 |
+
iso_code='el',
|
108 |
+
use_ascii=False,
|
109 |
+
charsets=['ISO-8859-7', 'WINDOWS-1253'],
|
110 |
+
alphabet=(u'αβγδεζηθικλμνξοπρσςτυφχψωάέήίόύώ'
|
111 |
+
u'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΣΤΥΦΧΨΩΆΈΉΊΌΎΏ'),
|
112 |
+
wiki_start_pages=[u'Πύλη:Κύρια']),
|
113 |
+
'English': Language(name='English',
|
114 |
+
iso_code='en',
|
115 |
+
use_ascii=True,
|
116 |
+
charsets=['ISO-8859-1', 'WINDOWS-1252'],
|
117 |
+
wiki_start_pages=[u'Main_Page']),
|
118 |
+
'Esperanto': Language(name='Esperanto',
|
119 |
+
iso_code='eo',
|
120 |
+
# Q, W, X, and Y not used at all
|
121 |
+
use_ascii=False,
|
122 |
+
charsets=['ISO-8859-3'],
|
123 |
+
alphabet=(u'abcĉdefgĝhĥijĵklmnoprsŝtuŭvz'
|
124 |
+
u'ABCĈDEFGĜHĤIJĴKLMNOPRSŜTUŬVZ'),
|
125 |
+
wiki_start_pages=[u'Vikipedio:Ĉefpaĝo']),
|
126 |
+
'Spanish': Language(name='Spanish',
|
127 |
+
iso_code='es',
|
128 |
+
use_ascii=True,
|
129 |
+
charsets=['ISO-8859-1', 'ISO-8859-15',
|
130 |
+
'WINDOWS-1252'],
|
131 |
+
alphabet=u'ñáéíóúüÑÁÉÍÓÚÜ',
|
132 |
+
wiki_start_pages=[u'Wikipedia:Portada']),
|
133 |
+
'Estonian': Language(name='Estonian',
|
134 |
+
iso_code='et',
|
135 |
+
use_ascii=False,
|
136 |
+
charsets=['ISO-8859-4', 'ISO-8859-13',
|
137 |
+
'WINDOWS-1257'],
|
138 |
+
# C, F, Š, Q, W, X, Y, Z, Ž are only for
|
139 |
+
# loanwords
|
140 |
+
alphabet=(u'ABDEGHIJKLMNOPRSTUVÕÄÖÜ'
|
141 |
+
u'abdeghijklmnoprstuvõäöü'),
|
142 |
+
wiki_start_pages=[u'Esileht']),
|
143 |
+
'Finnish': Language(name='Finnish',
|
144 |
+
iso_code='fi',
|
145 |
+
use_ascii=True,
|
146 |
+
charsets=['ISO-8859-1', 'ISO-8859-15',
|
147 |
+
'WINDOWS-1252'],
|
148 |
+
alphabet=u'ÅÄÖŠŽåäöšž',
|
149 |
+
wiki_start_pages=[u'Wikipedia:Etusivu']),
|
150 |
+
'French': Language(name='French',
|
151 |
+
iso_code='fr',
|
152 |
+
use_ascii=True,
|
153 |
+
charsets=['ISO-8859-1', 'ISO-8859-15',
|
154 |
+
'WINDOWS-1252'],
|
155 |
+
alphabet=u'œàâçèéîïùûêŒÀÂÇÈÉÎÏÙÛÊ',
|
156 |
+
wiki_start_pages=[u'Wikipédia:Accueil_principal',
|
157 |
+
u'Bœuf (animal)']),
|
158 |
+
'Hebrew': Language(name='Hebrew',
|
159 |
+
iso_code='he',
|
160 |
+
use_ascii=False,
|
161 |
+
charsets=['ISO-8859-8', 'WINDOWS-1255'],
|
162 |
+
alphabet=u'אבגדהוזחטיךכלםמןנסעףפץצקרשתװױײ',
|
163 |
+
wiki_start_pages=[u'עמוד_ראשי']),
|
164 |
+
'Croatian': Language(name='Croatian',
|
165 |
+
iso_code='hr',
|
166 |
+
# Q, W, X, Y are only used for foreign words.
|
167 |
+
use_ascii=False,
|
168 |
+
charsets=['ISO-8859-2', 'WINDOWS-1250'],
|
169 |
+
alphabet=(u'abcčćdđefghijklmnoprsštuvzž'
|
170 |
+
u'ABCČĆDĐEFGHIJKLMNOPRSŠTUVZŽ'),
|
171 |
+
wiki_start_pages=[u'Glavna_stranica']),
|
172 |
+
'Hungarian': Language(name='Hungarian',
|
173 |
+
iso_code='hu',
|
174 |
+
# Q, W, X, Y are only used for foreign words.
|
175 |
+
use_ascii=False,
|
176 |
+
charsets=['ISO-8859-2', 'WINDOWS-1250'],
|
177 |
+
alphabet=(u'abcdefghijklmnoprstuvzáéíóöőúüű'
|
178 |
+
u'ABCDEFGHIJKLMNOPRSTUVZÁÉÍÓÖŐÚÜŰ'),
|
179 |
+
wiki_start_pages=[u'Kezdőlap']),
|
180 |
+
'Italian': Language(name='Italian',
|
181 |
+
iso_code='it',
|
182 |
+
use_ascii=True,
|
183 |
+
charsets=['ISO-8859-1', 'ISO-8859-15',
|
184 |
+
'WINDOWS-1252'],
|
185 |
+
alphabet=u'ÀÈÉÌÒÓÙàèéìòóù',
|
186 |
+
wiki_start_pages=[u'Pagina_principale']),
|
187 |
+
'Lithuanian': Language(name='Lithuanian',
|
188 |
+
iso_code='lt',
|
189 |
+
use_ascii=False,
|
190 |
+
charsets=['ISO-8859-13', 'WINDOWS-1257',
|
191 |
+
'ISO-8859-4'],
|
192 |
+
# Q, W, and X not used at all
|
193 |
+
alphabet=(u'AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽ'
|
194 |
+
u'aąbcčdeęėfghiįyjklmnoprsštuųūvzž'),
|
195 |
+
wiki_start_pages=[u'Pagrindinis_puslapis']),
|
196 |
+
'Latvian': Language(name='Latvian',
|
197 |
+
iso_code='lv',
|
198 |
+
use_ascii=False,
|
199 |
+
charsets=['ISO-8859-13', 'WINDOWS-1257',
|
200 |
+
'ISO-8859-4'],
|
201 |
+
# Q, W, X, Y are only for loanwords
|
202 |
+
alphabet=(u'AĀBCČDEĒFGĢHIĪJKĶLĻMNŅOPRSŠTUŪVZŽ'
|
203 |
+
u'aābcčdeēfgģhiījkķlļmnņoprsštuūvzž'),
|
204 |
+
wiki_start_pages=[u'Sākumlapa']),
|
205 |
+
'Macedonian': Language(name='Macedonian',
|
206 |
+
iso_code='mk',
|
207 |
+
use_ascii=False,
|
208 |
+
charsets=['ISO-8859-5', 'WINDOWS-1251',
|
209 |
+
'MacCyrillic', 'IBM855'],
|
210 |
+
alphabet=(u'АБВГДЃЕЖЗЅИЈКЛЉМНЊОПРСТЌУФХЦЧЏШ'
|
211 |
+
u'абвгдѓежзѕијклљмнњопрстќуфхцчџш'),
|
212 |
+
wiki_start_pages=[u'Главна_страница']),
|
213 |
+
'Dutch': Language(name='Dutch',
|
214 |
+
iso_code='nl',
|
215 |
+
use_ascii=True,
|
216 |
+
charsets=['ISO-8859-1', 'WINDOWS-1252'],
|
217 |
+
wiki_start_pages=[u'Hoofdpagina']),
|
218 |
+
'Polish': Language(name='Polish',
|
219 |
+
iso_code='pl',
|
220 |
+
# Q and X are only used for foreign words.
|
221 |
+
use_ascii=False,
|
222 |
+
charsets=['ISO-8859-2', 'WINDOWS-1250'],
|
223 |
+
alphabet=(u'AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUWYZŹŻ'
|
224 |
+
u'aąbcćdeęfghijklłmnńoóprsśtuwyzźż'),
|
225 |
+
wiki_start_pages=[u'Wikipedia:Strona_główna']),
|
226 |
+
'Portuguese': Language(name='Portuguese',
|
227 |
+
iso_code='pt',
|
228 |
+
use_ascii=True,
|
229 |
+
charsets=['ISO-8859-1', 'ISO-8859-15',
|
230 |
+
'WINDOWS-1252'],
|
231 |
+
alphabet=u'ÁÂÃÀÇÉÊÍÓÔÕÚáâãàçéêíóôõú',
|
232 |
+
wiki_start_pages=[u'Wikipédia:Página_principal']),
|
233 |
+
'Romanian': Language(name='Romanian',
|
234 |
+
iso_code='ro',
|
235 |
+
use_ascii=True,
|
236 |
+
charsets=['ISO-8859-2', 'WINDOWS-1250'],
|
237 |
+
alphabet=u'ăâîșțĂÂÎȘȚ',
|
238 |
+
wiki_start_pages=[u'Pagina_principală']),
|
239 |
+
'Russian': Language(name='Russian',
|
240 |
+
iso_code='ru',
|
241 |
+
use_ascii=False,
|
242 |
+
charsets=['ISO-8859-5', 'WINDOWS-1251',
|
243 |
+
'KOI8-R', 'MacCyrillic', 'IBM866',
|
244 |
+
'IBM855'],
|
245 |
+
alphabet=(u'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
|
246 |
+
u'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'),
|
247 |
+
wiki_start_pages=[u'Заглавная_страница']),
|
248 |
+
'Slovak': Language(name='Slovak',
|
249 |
+
iso_code='sk',
|
250 |
+
use_ascii=True,
|
251 |
+
charsets=['ISO-8859-2', 'WINDOWS-1250'],
|
252 |
+
alphabet=u'áäčďéíĺľňóôŕšťúýžÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ',
|
253 |
+
wiki_start_pages=[u'Hlavná_stránka']),
|
254 |
+
'Slovene': Language(name='Slovene',
|
255 |
+
iso_code='sl',
|
256 |
+
# Q, W, X, Y are only used for foreign words.
|
257 |
+
use_ascii=False,
|
258 |
+
charsets=['ISO-8859-2', 'WINDOWS-1250'],
|
259 |
+
alphabet=(u'abcčdefghijklmnoprsštuvzž'
|
260 |
+
u'ABCČDEFGHIJKLMNOPRSŠTUVZŽ'),
|
261 |
+
wiki_start_pages=[u'Glavna_stran']),
|
262 |
+
# Serbian can be written in both Latin and Cyrillic, but there's no
|
263 |
+
# simple way to get the Latin alphabet pages from Wikipedia through
|
264 |
+
# the API, so for now we just support Cyrillic.
|
265 |
+
'Serbian': Language(name='Serbian',
|
266 |
+
iso_code='sr',
|
267 |
+
alphabet=(u'АБВГДЂЕЖЗИЈКЛЉМНЊОПРСТЋУФХЦЧЏШ'
|
268 |
+
u'абвгдђежзијклљмнњопрстћуфхцчџш'),
|
269 |
+
charsets=['ISO-8859-5', 'WINDOWS-1251',
|
270 |
+
'MacCyrillic', 'IBM855'],
|
271 |
+
wiki_start_pages=[u'Главна_страна']),
|
272 |
+
'Thai': Language(name='Thai',
|
273 |
+
iso_code='th',
|
274 |
+
use_ascii=False,
|
275 |
+
charsets=['ISO-8859-11', 'TIS-620', 'CP874'],
|
276 |
+
alphabet=u'กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛',
|
277 |
+
wiki_start_pages=[u'หน้าหลัก']),
|
278 |
+
'Turkish': Language(name='Turkish',
|
279 |
+
iso_code='tr',
|
280 |
+
# Q, W, and X are not used by Turkish
|
281 |
+
use_ascii=False,
|
282 |
+
charsets=['ISO-8859-3', 'ISO-8859-9',
|
283 |
+
'WINDOWS-1254'],
|
284 |
+
alphabet=(u'abcçdefgğhıijklmnoöprsştuüvyzâîû'
|
285 |
+
u'ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛ'),
|
286 |
+
wiki_start_pages=[u'Ana_Sayfa']),
|
287 |
+
'Vietnamese': Language(name='Vietnamese',
|
288 |
+
iso_code='vi',
|
289 |
+
use_ascii=False,
|
290 |
+
# Windows-1258 is the only common 8-bit
|
291 |
+
# Vietnamese encoding supported by Python.
|
292 |
+
# From Wikipedia:
|
293 |
+
# For systems that lack support for Unicode,
|
294 |
+
# dozens of 8-bit Vietnamese code pages are
|
295 |
+
# available.[1] The most common are VISCII
|
296 |
+
# (TCVN 5712:1993), VPS, and Windows-1258.[3]
|
297 |
+
# Where ASCII is required, such as when
|
298 |
+
# ensuring readability in plain text e-mail,
|
299 |
+
# Vietnamese letters are often encoded
|
300 |
+
# according to Vietnamese Quoted-Readable
|
301 |
+
# (VIQR) or VSCII Mnemonic (VSCII-MNEM),[4]
|
302 |
+
# though usage of either variable-width
|
303 |
+
# scheme has declined dramatically following
|
304 |
+
# the adoption of Unicode on the World Wide
|
305 |
+
# Web.
|
306 |
+
charsets=['WINDOWS-1258'],
|
307 |
+
alphabet=(u'aăâbcdđeêghiklmnoôơpqrstuưvxy'
|
308 |
+
u'AĂÂBCDĐEÊGHIKLMNOÔƠPQRSTUƯVXY'),
|
309 |
+
wiki_start_pages=[u'Chữ_Quốc_ngữ']),
|
310 |
+
}
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__init__.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
from .initialise import init, deinit, reinit, colorama_text
|
3 |
+
from .ansi import Fore, Back, Style, Cursor
|
4 |
+
from .ansitowin32 import AnsiToWin32
|
5 |
+
|
6 |
+
__version__ = '0.4.4'
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (444 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/ansi.cpython-310.pyc
ADDED
Binary file (3.01 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/ansitowin32.cpython-310.pyc
ADDED
Binary file (7.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/initialise.cpython-310.pyc
ADDED
Binary file (1.69 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/win32.cpython-310.pyc
ADDED
Binary file (3.95 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/__pycache__/winterm.cpython-310.pyc
ADDED
Binary file (4.57 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/ansi.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
'''
|
3 |
+
This module generates ANSI character codes to printing colors to terminals.
|
4 |
+
See: http://en.wikipedia.org/wiki/ANSI_escape_code
|
5 |
+
'''
|
6 |
+
|
7 |
+
CSI = '\033['
|
8 |
+
OSC = '\033]'
|
9 |
+
BEL = '\a'
|
10 |
+
|
11 |
+
|
12 |
+
def code_to_chars(code):
|
13 |
+
return CSI + str(code) + 'm'
|
14 |
+
|
15 |
+
def set_title(title):
|
16 |
+
return OSC + '2;' + title + BEL
|
17 |
+
|
18 |
+
def clear_screen(mode=2):
|
19 |
+
return CSI + str(mode) + 'J'
|
20 |
+
|
21 |
+
def clear_line(mode=2):
|
22 |
+
return CSI + str(mode) + 'K'
|
23 |
+
|
24 |
+
|
25 |
+
class AnsiCodes(object):
|
26 |
+
def __init__(self):
|
27 |
+
# the subclasses declare class attributes which are numbers.
|
28 |
+
# Upon instantiation we define instance attributes, which are the same
|
29 |
+
# as the class attributes but wrapped with the ANSI escape sequence
|
30 |
+
for name in dir(self):
|
31 |
+
if not name.startswith('_'):
|
32 |
+
value = getattr(self, name)
|
33 |
+
setattr(self, name, code_to_chars(value))
|
34 |
+
|
35 |
+
|
36 |
+
class AnsiCursor(object):
|
37 |
+
def UP(self, n=1):
|
38 |
+
return CSI + str(n) + 'A'
|
39 |
+
def DOWN(self, n=1):
|
40 |
+
return CSI + str(n) + 'B'
|
41 |
+
def FORWARD(self, n=1):
|
42 |
+
return CSI + str(n) + 'C'
|
43 |
+
def BACK(self, n=1):
|
44 |
+
return CSI + str(n) + 'D'
|
45 |
+
def POS(self, x=1, y=1):
|
46 |
+
return CSI + str(y) + ';' + str(x) + 'H'
|
47 |
+
|
48 |
+
|
49 |
+
class AnsiFore(AnsiCodes):
|
50 |
+
BLACK = 30
|
51 |
+
RED = 31
|
52 |
+
GREEN = 32
|
53 |
+
YELLOW = 33
|
54 |
+
BLUE = 34
|
55 |
+
MAGENTA = 35
|
56 |
+
CYAN = 36
|
57 |
+
WHITE = 37
|
58 |
+
RESET = 39
|
59 |
+
|
60 |
+
# These are fairly well supported, but not part of the standard.
|
61 |
+
LIGHTBLACK_EX = 90
|
62 |
+
LIGHTRED_EX = 91
|
63 |
+
LIGHTGREEN_EX = 92
|
64 |
+
LIGHTYELLOW_EX = 93
|
65 |
+
LIGHTBLUE_EX = 94
|
66 |
+
LIGHTMAGENTA_EX = 95
|
67 |
+
LIGHTCYAN_EX = 96
|
68 |
+
LIGHTWHITE_EX = 97
|
69 |
+
|
70 |
+
|
71 |
+
class AnsiBack(AnsiCodes):
|
72 |
+
BLACK = 40
|
73 |
+
RED = 41
|
74 |
+
GREEN = 42
|
75 |
+
YELLOW = 43
|
76 |
+
BLUE = 44
|
77 |
+
MAGENTA = 45
|
78 |
+
CYAN = 46
|
79 |
+
WHITE = 47
|
80 |
+
RESET = 49
|
81 |
+
|
82 |
+
# These are fairly well supported, but not part of the standard.
|
83 |
+
LIGHTBLACK_EX = 100
|
84 |
+
LIGHTRED_EX = 101
|
85 |
+
LIGHTGREEN_EX = 102
|
86 |
+
LIGHTYELLOW_EX = 103
|
87 |
+
LIGHTBLUE_EX = 104
|
88 |
+
LIGHTMAGENTA_EX = 105
|
89 |
+
LIGHTCYAN_EX = 106
|
90 |
+
LIGHTWHITE_EX = 107
|
91 |
+
|
92 |
+
|
93 |
+
class AnsiStyle(AnsiCodes):
|
94 |
+
BRIGHT = 1
|
95 |
+
DIM = 2
|
96 |
+
NORMAL = 22
|
97 |
+
RESET_ALL = 0
|
98 |
+
|
99 |
+
Fore = AnsiFore()
|
100 |
+
Back = AnsiBack()
|
101 |
+
Style = AnsiStyle()
|
102 |
+
Cursor = AnsiCursor()
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/ansitowin32.py
ADDED
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import re
|
3 |
+
import sys
|
4 |
+
import os
|
5 |
+
|
6 |
+
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
|
7 |
+
from .winterm import WinTerm, WinColor, WinStyle
|
8 |
+
from .win32 import windll, winapi_test
|
9 |
+
|
10 |
+
|
11 |
+
winterm = None
|
12 |
+
if windll is not None:
|
13 |
+
winterm = WinTerm()
|
14 |
+
|
15 |
+
|
16 |
+
class StreamWrapper(object):
|
17 |
+
'''
|
18 |
+
Wraps a stream (such as stdout), acting as a transparent proxy for all
|
19 |
+
attribute access apart from method 'write()', which is delegated to our
|
20 |
+
Converter instance.
|
21 |
+
'''
|
22 |
+
def __init__(self, wrapped, converter):
|
23 |
+
# double-underscore everything to prevent clashes with names of
|
24 |
+
# attributes on the wrapped stream object.
|
25 |
+
self.__wrapped = wrapped
|
26 |
+
self.__convertor = converter
|
27 |
+
|
28 |
+
def __getattr__(self, name):
|
29 |
+
return getattr(self.__wrapped, name)
|
30 |
+
|
31 |
+
def __enter__(self, *args, **kwargs):
|
32 |
+
# special method lookup bypasses __getattr__/__getattribute__, see
|
33 |
+
# https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit
|
34 |
+
# thus, contextlib magic methods are not proxied via __getattr__
|
35 |
+
return self.__wrapped.__enter__(*args, **kwargs)
|
36 |
+
|
37 |
+
def __exit__(self, *args, **kwargs):
|
38 |
+
return self.__wrapped.__exit__(*args, **kwargs)
|
39 |
+
|
40 |
+
def write(self, text):
|
41 |
+
self.__convertor.write(text)
|
42 |
+
|
43 |
+
def isatty(self):
|
44 |
+
stream = self.__wrapped
|
45 |
+
if 'PYCHARM_HOSTED' in os.environ:
|
46 |
+
if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
|
47 |
+
return True
|
48 |
+
try:
|
49 |
+
stream_isatty = stream.isatty
|
50 |
+
except AttributeError:
|
51 |
+
return False
|
52 |
+
else:
|
53 |
+
return stream_isatty()
|
54 |
+
|
55 |
+
@property
|
56 |
+
def closed(self):
|
57 |
+
stream = self.__wrapped
|
58 |
+
try:
|
59 |
+
return stream.closed
|
60 |
+
except AttributeError:
|
61 |
+
return True
|
62 |
+
|
63 |
+
|
64 |
+
class AnsiToWin32(object):
|
65 |
+
'''
|
66 |
+
Implements a 'write()' method which, on Windows, will strip ANSI character
|
67 |
+
sequences from the text, and if outputting to a tty, will convert them into
|
68 |
+
win32 function calls.
|
69 |
+
'''
|
70 |
+
ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer
|
71 |
+
ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command
|
72 |
+
|
73 |
+
def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
|
74 |
+
# The wrapped stream (normally sys.stdout or sys.stderr)
|
75 |
+
self.wrapped = wrapped
|
76 |
+
|
77 |
+
# should we reset colors to defaults after every .write()
|
78 |
+
self.autoreset = autoreset
|
79 |
+
|
80 |
+
# create the proxy wrapping our output stream
|
81 |
+
self.stream = StreamWrapper(wrapped, self)
|
82 |
+
|
83 |
+
on_windows = os.name == 'nt'
|
84 |
+
# We test if the WinAPI works, because even if we are on Windows
|
85 |
+
# we may be using a terminal that doesn't support the WinAPI
|
86 |
+
# (e.g. Cygwin Terminal). In this case it's up to the terminal
|
87 |
+
# to support the ANSI codes.
|
88 |
+
conversion_supported = on_windows and winapi_test()
|
89 |
+
|
90 |
+
# should we strip ANSI sequences from our output?
|
91 |
+
if strip is None:
|
92 |
+
strip = conversion_supported or (not self.stream.closed and not self.stream.isatty())
|
93 |
+
self.strip = strip
|
94 |
+
|
95 |
+
# should we should convert ANSI sequences into win32 calls?
|
96 |
+
if convert is None:
|
97 |
+
convert = conversion_supported and not self.stream.closed and self.stream.isatty()
|
98 |
+
self.convert = convert
|
99 |
+
|
100 |
+
# dict of ansi codes to win32 functions and parameters
|
101 |
+
self.win32_calls = self.get_win32_calls()
|
102 |
+
|
103 |
+
# are we wrapping stderr?
|
104 |
+
self.on_stderr = self.wrapped is sys.stderr
|
105 |
+
|
106 |
+
def should_wrap(self):
|
107 |
+
'''
|
108 |
+
True if this class is actually needed. If false, then the output
|
109 |
+
stream will not be affected, nor will win32 calls be issued, so
|
110 |
+
wrapping stdout is not actually required. This will generally be
|
111 |
+
False on non-Windows platforms, unless optional functionality like
|
112 |
+
autoreset has been requested using kwargs to init()
|
113 |
+
'''
|
114 |
+
return self.convert or self.strip or self.autoreset
|
115 |
+
|
116 |
+
def get_win32_calls(self):
|
117 |
+
if self.convert and winterm:
|
118 |
+
return {
|
119 |
+
AnsiStyle.RESET_ALL: (winterm.reset_all, ),
|
120 |
+
AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),
|
121 |
+
AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),
|
122 |
+
AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),
|
123 |
+
AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),
|
124 |
+
AnsiFore.RED: (winterm.fore, WinColor.RED),
|
125 |
+
AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),
|
126 |
+
AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),
|
127 |
+
AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),
|
128 |
+
AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),
|
129 |
+
AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),
|
130 |
+
AnsiFore.WHITE: (winterm.fore, WinColor.GREY),
|
131 |
+
AnsiFore.RESET: (winterm.fore, ),
|
132 |
+
AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),
|
133 |
+
AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),
|
134 |
+
AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),
|
135 |
+
AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),
|
136 |
+
AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),
|
137 |
+
AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),
|
138 |
+
AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),
|
139 |
+
AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),
|
140 |
+
AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
|
141 |
+
AnsiBack.RED: (winterm.back, WinColor.RED),
|
142 |
+
AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
|
143 |
+
AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
|
144 |
+
AnsiBack.BLUE: (winterm.back, WinColor.BLUE),
|
145 |
+
AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
|
146 |
+
AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
|
147 |
+
AnsiBack.WHITE: (winterm.back, WinColor.GREY),
|
148 |
+
AnsiBack.RESET: (winterm.back, ),
|
149 |
+
AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),
|
150 |
+
AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),
|
151 |
+
AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),
|
152 |
+
AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),
|
153 |
+
AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),
|
154 |
+
AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),
|
155 |
+
AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),
|
156 |
+
AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),
|
157 |
+
}
|
158 |
+
return dict()
|
159 |
+
|
160 |
+
def write(self, text):
|
161 |
+
if self.strip or self.convert:
|
162 |
+
self.write_and_convert(text)
|
163 |
+
else:
|
164 |
+
self.wrapped.write(text)
|
165 |
+
self.wrapped.flush()
|
166 |
+
if self.autoreset:
|
167 |
+
self.reset_all()
|
168 |
+
|
169 |
+
|
170 |
+
def reset_all(self):
|
171 |
+
if self.convert:
|
172 |
+
self.call_win32('m', (0,))
|
173 |
+
elif not self.strip and not self.stream.closed:
|
174 |
+
self.wrapped.write(Style.RESET_ALL)
|
175 |
+
|
176 |
+
|
177 |
+
def write_and_convert(self, text):
|
178 |
+
'''
|
179 |
+
Write the given text to our wrapped stream, stripping any ANSI
|
180 |
+
sequences from the text, and optionally converting them into win32
|
181 |
+
calls.
|
182 |
+
'''
|
183 |
+
cursor = 0
|
184 |
+
text = self.convert_osc(text)
|
185 |
+
for match in self.ANSI_CSI_RE.finditer(text):
|
186 |
+
start, end = match.span()
|
187 |
+
self.write_plain_text(text, cursor, start)
|
188 |
+
self.convert_ansi(*match.groups())
|
189 |
+
cursor = end
|
190 |
+
self.write_plain_text(text, cursor, len(text))
|
191 |
+
|
192 |
+
|
193 |
+
def write_plain_text(self, text, start, end):
|
194 |
+
if start < end:
|
195 |
+
self.wrapped.write(text[start:end])
|
196 |
+
self.wrapped.flush()
|
197 |
+
|
198 |
+
|
199 |
+
def convert_ansi(self, paramstring, command):
|
200 |
+
if self.convert:
|
201 |
+
params = self.extract_params(command, paramstring)
|
202 |
+
self.call_win32(command, params)
|
203 |
+
|
204 |
+
|
205 |
+
def extract_params(self, command, paramstring):
|
206 |
+
if command in 'Hf':
|
207 |
+
params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';'))
|
208 |
+
while len(params) < 2:
|
209 |
+
# defaults:
|
210 |
+
params = params + (1,)
|
211 |
+
else:
|
212 |
+
params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)
|
213 |
+
if len(params) == 0:
|
214 |
+
# defaults:
|
215 |
+
if command in 'JKm':
|
216 |
+
params = (0,)
|
217 |
+
elif command in 'ABCD':
|
218 |
+
params = (1,)
|
219 |
+
|
220 |
+
return params
|
221 |
+
|
222 |
+
|
223 |
+
def call_win32(self, command, params):
|
224 |
+
if command == 'm':
|
225 |
+
for param in params:
|
226 |
+
if param in self.win32_calls:
|
227 |
+
func_args = self.win32_calls[param]
|
228 |
+
func = func_args[0]
|
229 |
+
args = func_args[1:]
|
230 |
+
kwargs = dict(on_stderr=self.on_stderr)
|
231 |
+
func(*args, **kwargs)
|
232 |
+
elif command in 'J':
|
233 |
+
winterm.erase_screen(params[0], on_stderr=self.on_stderr)
|
234 |
+
elif command in 'K':
|
235 |
+
winterm.erase_line(params[0], on_stderr=self.on_stderr)
|
236 |
+
elif command in 'Hf': # cursor position - absolute
|
237 |
+
winterm.set_cursor_position(params, on_stderr=self.on_stderr)
|
238 |
+
elif command in 'ABCD': # cursor position - relative
|
239 |
+
n = params[0]
|
240 |
+
# A - up, B - down, C - forward, D - back
|
241 |
+
x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command]
|
242 |
+
winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)
|
243 |
+
|
244 |
+
|
245 |
+
def convert_osc(self, text):
|
246 |
+
for match in self.ANSI_OSC_RE.finditer(text):
|
247 |
+
start, end = match.span()
|
248 |
+
text = text[:start] + text[end:]
|
249 |
+
paramstring, command = match.groups()
|
250 |
+
if command == BEL:
|
251 |
+
if paramstring.count(";") == 1:
|
252 |
+
params = paramstring.split(";")
|
253 |
+
# 0 - change title and icon (we will only change title)
|
254 |
+
# 1 - change icon (we don't support this)
|
255 |
+
# 2 - change title
|
256 |
+
if params[0] in '02':
|
257 |
+
winterm.set_title(params[1])
|
258 |
+
return text
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/initialise.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
import atexit
|
3 |
+
import contextlib
|
4 |
+
import sys
|
5 |
+
|
6 |
+
from .ansitowin32 import AnsiToWin32
|
7 |
+
|
8 |
+
|
9 |
+
orig_stdout = None
|
10 |
+
orig_stderr = None
|
11 |
+
|
12 |
+
wrapped_stdout = None
|
13 |
+
wrapped_stderr = None
|
14 |
+
|
15 |
+
atexit_done = False
|
16 |
+
|
17 |
+
|
18 |
+
def reset_all():
|
19 |
+
if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
|
20 |
+
AnsiToWin32(orig_stdout).reset_all()
|
21 |
+
|
22 |
+
|
23 |
+
def init(autoreset=False, convert=None, strip=None, wrap=True):
|
24 |
+
|
25 |
+
if not wrap and any([autoreset, convert, strip]):
|
26 |
+
raise ValueError('wrap=False conflicts with any other arg=True')
|
27 |
+
|
28 |
+
global wrapped_stdout, wrapped_stderr
|
29 |
+
global orig_stdout, orig_stderr
|
30 |
+
|
31 |
+
orig_stdout = sys.stdout
|
32 |
+
orig_stderr = sys.stderr
|
33 |
+
|
34 |
+
if sys.stdout is None:
|
35 |
+
wrapped_stdout = None
|
36 |
+
else:
|
37 |
+
sys.stdout = wrapped_stdout = \
|
38 |
+
wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
|
39 |
+
if sys.stderr is None:
|
40 |
+
wrapped_stderr = None
|
41 |
+
else:
|
42 |
+
sys.stderr = wrapped_stderr = \
|
43 |
+
wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
|
44 |
+
|
45 |
+
global atexit_done
|
46 |
+
if not atexit_done:
|
47 |
+
atexit.register(reset_all)
|
48 |
+
atexit_done = True
|
49 |
+
|
50 |
+
|
51 |
+
def deinit():
|
52 |
+
if orig_stdout is not None:
|
53 |
+
sys.stdout = orig_stdout
|
54 |
+
if orig_stderr is not None:
|
55 |
+
sys.stderr = orig_stderr
|
56 |
+
|
57 |
+
|
58 |
+
@contextlib.contextmanager
|
59 |
+
def colorama_text(*args, **kwargs):
|
60 |
+
init(*args, **kwargs)
|
61 |
+
try:
|
62 |
+
yield
|
63 |
+
finally:
|
64 |
+
deinit()
|
65 |
+
|
66 |
+
|
67 |
+
def reinit():
|
68 |
+
if wrapped_stdout is not None:
|
69 |
+
sys.stdout = wrapped_stdout
|
70 |
+
if wrapped_stderr is not None:
|
71 |
+
sys.stderr = wrapped_stderr
|
72 |
+
|
73 |
+
|
74 |
+
def wrap_stream(stream, convert, strip, autoreset, wrap):
|
75 |
+
if wrap:
|
76 |
+
wrapper = AnsiToWin32(stream,
|
77 |
+
convert=convert, strip=strip, autoreset=autoreset)
|
78 |
+
if wrapper.should_wrap():
|
79 |
+
stream = wrapper.stream
|
80 |
+
return stream
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/win32.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
|
3 |
+
# from winbase.h
|
4 |
+
STDOUT = -11
|
5 |
+
STDERR = -12
|
6 |
+
|
7 |
+
try:
|
8 |
+
import ctypes
|
9 |
+
from ctypes import LibraryLoader
|
10 |
+
windll = LibraryLoader(ctypes.WinDLL)
|
11 |
+
from ctypes import wintypes
|
12 |
+
except (AttributeError, ImportError):
|
13 |
+
windll = None
|
14 |
+
SetConsoleTextAttribute = lambda *_: None
|
15 |
+
winapi_test = lambda *_: None
|
16 |
+
else:
|
17 |
+
from ctypes import byref, Structure, c_char, POINTER
|
18 |
+
|
19 |
+
COORD = wintypes._COORD
|
20 |
+
|
21 |
+
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
|
22 |
+
"""struct in wincon.h."""
|
23 |
+
_fields_ = [
|
24 |
+
("dwSize", COORD),
|
25 |
+
("dwCursorPosition", COORD),
|
26 |
+
("wAttributes", wintypes.WORD),
|
27 |
+
("srWindow", wintypes.SMALL_RECT),
|
28 |
+
("dwMaximumWindowSize", COORD),
|
29 |
+
]
|
30 |
+
def __str__(self):
|
31 |
+
return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (
|
32 |
+
self.dwSize.Y, self.dwSize.X
|
33 |
+
, self.dwCursorPosition.Y, self.dwCursorPosition.X
|
34 |
+
, self.wAttributes
|
35 |
+
, self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right
|
36 |
+
, self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X
|
37 |
+
)
|
38 |
+
|
39 |
+
_GetStdHandle = windll.kernel32.GetStdHandle
|
40 |
+
_GetStdHandle.argtypes = [
|
41 |
+
wintypes.DWORD,
|
42 |
+
]
|
43 |
+
_GetStdHandle.restype = wintypes.HANDLE
|
44 |
+
|
45 |
+
_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
|
46 |
+
_GetConsoleScreenBufferInfo.argtypes = [
|
47 |
+
wintypes.HANDLE,
|
48 |
+
POINTER(CONSOLE_SCREEN_BUFFER_INFO),
|
49 |
+
]
|
50 |
+
_GetConsoleScreenBufferInfo.restype = wintypes.BOOL
|
51 |
+
|
52 |
+
_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
|
53 |
+
_SetConsoleTextAttribute.argtypes = [
|
54 |
+
wintypes.HANDLE,
|
55 |
+
wintypes.WORD,
|
56 |
+
]
|
57 |
+
_SetConsoleTextAttribute.restype = wintypes.BOOL
|
58 |
+
|
59 |
+
_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition
|
60 |
+
_SetConsoleCursorPosition.argtypes = [
|
61 |
+
wintypes.HANDLE,
|
62 |
+
COORD,
|
63 |
+
]
|
64 |
+
_SetConsoleCursorPosition.restype = wintypes.BOOL
|
65 |
+
|
66 |
+
_FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA
|
67 |
+
_FillConsoleOutputCharacterA.argtypes = [
|
68 |
+
wintypes.HANDLE,
|
69 |
+
c_char,
|
70 |
+
wintypes.DWORD,
|
71 |
+
COORD,
|
72 |
+
POINTER(wintypes.DWORD),
|
73 |
+
]
|
74 |
+
_FillConsoleOutputCharacterA.restype = wintypes.BOOL
|
75 |
+
|
76 |
+
_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
|
77 |
+
_FillConsoleOutputAttribute.argtypes = [
|
78 |
+
wintypes.HANDLE,
|
79 |
+
wintypes.WORD,
|
80 |
+
wintypes.DWORD,
|
81 |
+
COORD,
|
82 |
+
POINTER(wintypes.DWORD),
|
83 |
+
]
|
84 |
+
_FillConsoleOutputAttribute.restype = wintypes.BOOL
|
85 |
+
|
86 |
+
_SetConsoleTitleW = windll.kernel32.SetConsoleTitleW
|
87 |
+
_SetConsoleTitleW.argtypes = [
|
88 |
+
wintypes.LPCWSTR
|
89 |
+
]
|
90 |
+
_SetConsoleTitleW.restype = wintypes.BOOL
|
91 |
+
|
92 |
+
def _winapi_test(handle):
|
93 |
+
csbi = CONSOLE_SCREEN_BUFFER_INFO()
|
94 |
+
success = _GetConsoleScreenBufferInfo(
|
95 |
+
handle, byref(csbi))
|
96 |
+
return bool(success)
|
97 |
+
|
98 |
+
def winapi_test():
|
99 |
+
return any(_winapi_test(h) for h in
|
100 |
+
(_GetStdHandle(STDOUT), _GetStdHandle(STDERR)))
|
101 |
+
|
102 |
+
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
|
103 |
+
handle = _GetStdHandle(stream_id)
|
104 |
+
csbi = CONSOLE_SCREEN_BUFFER_INFO()
|
105 |
+
success = _GetConsoleScreenBufferInfo(
|
106 |
+
handle, byref(csbi))
|
107 |
+
return csbi
|
108 |
+
|
109 |
+
def SetConsoleTextAttribute(stream_id, attrs):
|
110 |
+
handle = _GetStdHandle(stream_id)
|
111 |
+
return _SetConsoleTextAttribute(handle, attrs)
|
112 |
+
|
113 |
+
def SetConsoleCursorPosition(stream_id, position, adjust=True):
|
114 |
+
position = COORD(*position)
|
115 |
+
# If the position is out of range, do nothing.
|
116 |
+
if position.Y <= 0 or position.X <= 0:
|
117 |
+
return
|
118 |
+
# Adjust for Windows' SetConsoleCursorPosition:
|
119 |
+
# 1. being 0-based, while ANSI is 1-based.
|
120 |
+
# 2. expecting (x,y), while ANSI uses (y,x).
|
121 |
+
adjusted_position = COORD(position.Y - 1, position.X - 1)
|
122 |
+
if adjust:
|
123 |
+
# Adjust for viewport's scroll position
|
124 |
+
sr = GetConsoleScreenBufferInfo(STDOUT).srWindow
|
125 |
+
adjusted_position.Y += sr.Top
|
126 |
+
adjusted_position.X += sr.Left
|
127 |
+
# Resume normal processing
|
128 |
+
handle = _GetStdHandle(stream_id)
|
129 |
+
return _SetConsoleCursorPosition(handle, adjusted_position)
|
130 |
+
|
131 |
+
def FillConsoleOutputCharacter(stream_id, char, length, start):
|
132 |
+
handle = _GetStdHandle(stream_id)
|
133 |
+
char = c_char(char.encode())
|
134 |
+
length = wintypes.DWORD(length)
|
135 |
+
num_written = wintypes.DWORD(0)
|
136 |
+
# Note that this is hard-coded for ANSI (vs wide) bytes.
|
137 |
+
success = _FillConsoleOutputCharacterA(
|
138 |
+
handle, char, length, start, byref(num_written))
|
139 |
+
return num_written.value
|
140 |
+
|
141 |
+
def FillConsoleOutputAttribute(stream_id, attr, length, start):
|
142 |
+
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
|
143 |
+
handle = _GetStdHandle(stream_id)
|
144 |
+
attribute = wintypes.WORD(attr)
|
145 |
+
length = wintypes.DWORD(length)
|
146 |
+
num_written = wintypes.DWORD(0)
|
147 |
+
# Note that this is hard-coded for ANSI (vs wide) bytes.
|
148 |
+
return _FillConsoleOutputAttribute(
|
149 |
+
handle, attribute, length, start, byref(num_written))
|
150 |
+
|
151 |
+
def SetConsoleTitle(title):
|
152 |
+
return _SetConsoleTitleW(title)
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/colorama/winterm.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
|
2 |
+
from . import win32
|
3 |
+
|
4 |
+
|
5 |
+
# from wincon.h
|
6 |
+
class WinColor(object):
|
7 |
+
BLACK = 0
|
8 |
+
BLUE = 1
|
9 |
+
GREEN = 2
|
10 |
+
CYAN = 3
|
11 |
+
RED = 4
|
12 |
+
MAGENTA = 5
|
13 |
+
YELLOW = 6
|
14 |
+
GREY = 7
|
15 |
+
|
16 |
+
# from wincon.h
|
17 |
+
class WinStyle(object):
|
18 |
+
NORMAL = 0x00 # dim text, dim background
|
19 |
+
BRIGHT = 0x08 # bright text, dim background
|
20 |
+
BRIGHT_BACKGROUND = 0x80 # dim text, bright background
|
21 |
+
|
22 |
+
class WinTerm(object):
|
23 |
+
|
24 |
+
def __init__(self):
|
25 |
+
self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
|
26 |
+
self.set_attrs(self._default)
|
27 |
+
self._default_fore = self._fore
|
28 |
+
self._default_back = self._back
|
29 |
+
self._default_style = self._style
|
30 |
+
# In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style.
|
31 |
+
# So that LIGHT_EX colors and BRIGHT style do not clobber each other,
|
32 |
+
# we track them separately, since LIGHT_EX is overwritten by Fore/Back
|
33 |
+
# and BRIGHT is overwritten by Style codes.
|
34 |
+
self._light = 0
|
35 |
+
|
36 |
+
def get_attrs(self):
|
37 |
+
return self._fore + self._back * 16 + (self._style | self._light)
|
38 |
+
|
39 |
+
def set_attrs(self, value):
|
40 |
+
self._fore = value & 7
|
41 |
+
self._back = (value >> 4) & 7
|
42 |
+
self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND)
|
43 |
+
|
44 |
+
def reset_all(self, on_stderr=None):
|
45 |
+
self.set_attrs(self._default)
|
46 |
+
self.set_console(attrs=self._default)
|
47 |
+
self._light = 0
|
48 |
+
|
49 |
+
def fore(self, fore=None, light=False, on_stderr=False):
|
50 |
+
if fore is None:
|
51 |
+
fore = self._default_fore
|
52 |
+
self._fore = fore
|
53 |
+
# Emulate LIGHT_EX with BRIGHT Style
|
54 |
+
if light:
|
55 |
+
self._light |= WinStyle.BRIGHT
|
56 |
+
else:
|
57 |
+
self._light &= ~WinStyle.BRIGHT
|
58 |
+
self.set_console(on_stderr=on_stderr)
|
59 |
+
|
60 |
+
def back(self, back=None, light=False, on_stderr=False):
|
61 |
+
if back is None:
|
62 |
+
back = self._default_back
|
63 |
+
self._back = back
|
64 |
+
# Emulate LIGHT_EX with BRIGHT_BACKGROUND Style
|
65 |
+
if light:
|
66 |
+
self._light |= WinStyle.BRIGHT_BACKGROUND
|
67 |
+
else:
|
68 |
+
self._light &= ~WinStyle.BRIGHT_BACKGROUND
|
69 |
+
self.set_console(on_stderr=on_stderr)
|
70 |
+
|
71 |
+
def style(self, style=None, on_stderr=False):
|
72 |
+
if style is None:
|
73 |
+
style = self._default_style
|
74 |
+
self._style = style
|
75 |
+
self.set_console(on_stderr=on_stderr)
|
76 |
+
|
77 |
+
def set_console(self, attrs=None, on_stderr=False):
|
78 |
+
if attrs is None:
|
79 |
+
attrs = self.get_attrs()
|
80 |
+
handle = win32.STDOUT
|
81 |
+
if on_stderr:
|
82 |
+
handle = win32.STDERR
|
83 |
+
win32.SetConsoleTextAttribute(handle, attrs)
|
84 |
+
|
85 |
+
def get_position(self, handle):
|
86 |
+
position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition
|
87 |
+
# Because Windows coordinates are 0-based,
|
88 |
+
# and win32.SetConsoleCursorPosition expects 1-based.
|
89 |
+
position.X += 1
|
90 |
+
position.Y += 1
|
91 |
+
return position
|
92 |
+
|
93 |
+
def set_cursor_position(self, position=None, on_stderr=False):
|
94 |
+
if position is None:
|
95 |
+
# I'm not currently tracking the position, so there is no default.
|
96 |
+
# position = self.get_position()
|
97 |
+
return
|
98 |
+
handle = win32.STDOUT
|
99 |
+
if on_stderr:
|
100 |
+
handle = win32.STDERR
|
101 |
+
win32.SetConsoleCursorPosition(handle, position)
|
102 |
+
|
103 |
+
def cursor_adjust(self, x, y, on_stderr=False):
|
104 |
+
handle = win32.STDOUT
|
105 |
+
if on_stderr:
|
106 |
+
handle = win32.STDERR
|
107 |
+
position = self.get_position(handle)
|
108 |
+
adjusted_position = (position.Y + y, position.X + x)
|
109 |
+
win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False)
|
110 |
+
|
111 |
+
def erase_screen(self, mode=0, on_stderr=False):
|
112 |
+
# 0 should clear from the cursor to the end of the screen.
|
113 |
+
# 1 should clear from the cursor to the beginning of the screen.
|
114 |
+
# 2 should clear the entire screen, and move cursor to (1,1)
|
115 |
+
handle = win32.STDOUT
|
116 |
+
if on_stderr:
|
117 |
+
handle = win32.STDERR
|
118 |
+
csbi = win32.GetConsoleScreenBufferInfo(handle)
|
119 |
+
# get the number of character cells in the current buffer
|
120 |
+
cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y
|
121 |
+
# get number of character cells before current cursor position
|
122 |
+
cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X
|
123 |
+
if mode == 0:
|
124 |
+
from_coord = csbi.dwCursorPosition
|
125 |
+
cells_to_erase = cells_in_screen - cells_before_cursor
|
126 |
+
elif mode == 1:
|
127 |
+
from_coord = win32.COORD(0, 0)
|
128 |
+
cells_to_erase = cells_before_cursor
|
129 |
+
elif mode == 2:
|
130 |
+
from_coord = win32.COORD(0, 0)
|
131 |
+
cells_to_erase = cells_in_screen
|
132 |
+
else:
|
133 |
+
# invalid mode
|
134 |
+
return
|
135 |
+
# fill the entire screen with blanks
|
136 |
+
win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
|
137 |
+
# now set the buffer's attributes accordingly
|
138 |
+
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
|
139 |
+
if mode == 2:
|
140 |
+
# put the cursor where needed
|
141 |
+
win32.SetConsoleCursorPosition(handle, (1, 1))
|
142 |
+
|
143 |
+
def erase_line(self, mode=0, on_stderr=False):
|
144 |
+
# 0 should clear from the cursor to the end of the line.
|
145 |
+
# 1 should clear from the cursor to the beginning of the line.
|
146 |
+
# 2 should clear the entire line.
|
147 |
+
handle = win32.STDOUT
|
148 |
+
if on_stderr:
|
149 |
+
handle = win32.STDERR
|
150 |
+
csbi = win32.GetConsoleScreenBufferInfo(handle)
|
151 |
+
if mode == 0:
|
152 |
+
from_coord = csbi.dwCursorPosition
|
153 |
+
cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X
|
154 |
+
elif mode == 1:
|
155 |
+
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
|
156 |
+
cells_to_erase = csbi.dwCursorPosition.X
|
157 |
+
elif mode == 2:
|
158 |
+
from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)
|
159 |
+
cells_to_erase = csbi.dwSize.X
|
160 |
+
else:
|
161 |
+
# invalid mode
|
162 |
+
return
|
163 |
+
# fill the entire screen with blanks
|
164 |
+
win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)
|
165 |
+
# now set the buffer's attributes accordingly
|
166 |
+
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)
|
167 |
+
|
168 |
+
def set_title(self, title):
|
169 |
+
win32.SetConsoleTitle(title)
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__init__.py
ADDED
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# module pyparsing.py
|
2 |
+
#
|
3 |
+
# Copyright (c) 2003-2021 Paul T. McGuire
|
4 |
+
#
|
5 |
+
# Permission is hereby granted, free of charge, to any person obtaining
|
6 |
+
# a copy of this software and associated documentation files (the
|
7 |
+
# "Software"), to deal in the Software without restriction, including
|
8 |
+
# without limitation the rights to use, copy, modify, merge, publish,
|
9 |
+
# distribute, sublicense, and/or sell copies of the Software, and to
|
10 |
+
# permit persons to whom the Software is furnished to do so, subject to
|
11 |
+
# the following conditions:
|
12 |
+
#
|
13 |
+
# The above copyright notice and this permission notice shall be
|
14 |
+
# included in all copies or substantial portions of the Software.
|
15 |
+
#
|
16 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
17 |
+
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
18 |
+
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
19 |
+
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
20 |
+
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
21 |
+
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
22 |
+
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
23 |
+
#
|
24 |
+
|
25 |
+
__doc__ = """
|
26 |
+
pyparsing module - Classes and methods to define and execute parsing grammars
|
27 |
+
=============================================================================
|
28 |
+
|
29 |
+
The pyparsing module is an alternative approach to creating and
|
30 |
+
executing simple grammars, vs. the traditional lex/yacc approach, or the
|
31 |
+
use of regular expressions. With pyparsing, you don't need to learn
|
32 |
+
a new syntax for defining grammars or matching expressions - the parsing
|
33 |
+
module provides a library of classes that you use to construct the
|
34 |
+
grammar directly in Python.
|
35 |
+
|
36 |
+
Here is a program to parse "Hello, World!" (or any greeting of the form
|
37 |
+
``"<salutation>, <addressee>!"``), built up using :class:`Word`,
|
38 |
+
:class:`Literal`, and :class:`And` elements
|
39 |
+
(the :meth:`'+'<ParserElement.__add__>` operators create :class:`And` expressions,
|
40 |
+
and the strings are auto-converted to :class:`Literal` expressions)::
|
41 |
+
|
42 |
+
from pip._vendor.pyparsing import Word, alphas
|
43 |
+
|
44 |
+
# define grammar of a greeting
|
45 |
+
greet = Word(alphas) + "," + Word(alphas) + "!"
|
46 |
+
|
47 |
+
hello = "Hello, World!"
|
48 |
+
print(hello, "->", greet.parse_string(hello))
|
49 |
+
|
50 |
+
The program outputs the following::
|
51 |
+
|
52 |
+
Hello, World! -> ['Hello', ',', 'World', '!']
|
53 |
+
|
54 |
+
The Python representation of the grammar is quite readable, owing to the
|
55 |
+
self-explanatory class names, and the use of :class:`'+'<And>`,
|
56 |
+
:class:`'|'<MatchFirst>`, :class:`'^'<Or>` and :class:`'&'<Each>` operators.
|
57 |
+
|
58 |
+
The :class:`ParseResults` object returned from
|
59 |
+
:class:`ParserElement.parseString` can be
|
60 |
+
accessed as a nested list, a dictionary, or an object with named
|
61 |
+
attributes.
|
62 |
+
|
63 |
+
The pyparsing module handles some of the problems that are typically
|
64 |
+
vexing when writing text parsers:
|
65 |
+
|
66 |
+
- extra or missing whitespace (the above program will also handle
|
67 |
+
"Hello,World!", "Hello , World !", etc.)
|
68 |
+
- quoted strings
|
69 |
+
- embedded comments
|
70 |
+
|
71 |
+
|
72 |
+
Getting Started -
|
73 |
+
-----------------
|
74 |
+
Visit the classes :class:`ParserElement` and :class:`ParseResults` to
|
75 |
+
see the base classes that most other pyparsing
|
76 |
+
classes inherit from. Use the docstrings for examples of how to:
|
77 |
+
|
78 |
+
- construct literal match expressions from :class:`Literal` and
|
79 |
+
:class:`CaselessLiteral` classes
|
80 |
+
- construct character word-group expressions using the :class:`Word`
|
81 |
+
class
|
82 |
+
- see how to create repetitive expressions using :class:`ZeroOrMore`
|
83 |
+
and :class:`OneOrMore` classes
|
84 |
+
- use :class:`'+'<And>`, :class:`'|'<MatchFirst>`, :class:`'^'<Or>`,
|
85 |
+
and :class:`'&'<Each>` operators to combine simple expressions into
|
86 |
+
more complex ones
|
87 |
+
- associate names with your parsed results using
|
88 |
+
:class:`ParserElement.setResultsName`
|
89 |
+
- access the parsed data, which is returned as a :class:`ParseResults`
|
90 |
+
object
|
91 |
+
- find some helpful expression short-cuts like :class:`delimitedList`
|
92 |
+
and :class:`oneOf`
|
93 |
+
- find more useful common expressions in the :class:`pyparsing_common`
|
94 |
+
namespace class
|
95 |
+
"""
|
96 |
+
from typing import NamedTuple
|
97 |
+
|
98 |
+
|
99 |
+
class version_info(NamedTuple):
|
100 |
+
major: int
|
101 |
+
minor: int
|
102 |
+
micro: int
|
103 |
+
releaselevel: str
|
104 |
+
serial: int
|
105 |
+
|
106 |
+
@property
|
107 |
+
def __version__(self):
|
108 |
+
return "{}.{}.{}".format(self.major, self.minor, self.micro) + (
|
109 |
+
"{}{}{}".format(
|
110 |
+
"r" if self.releaselevel[0] == "c" else "",
|
111 |
+
self.releaselevel[0],
|
112 |
+
self.serial,
|
113 |
+
),
|
114 |
+
"",
|
115 |
+
)[self.releaselevel == "final"]
|
116 |
+
|
117 |
+
def __str__(self):
|
118 |
+
return "{} {} / {}".format(__name__, self.__version__, __version_time__)
|
119 |
+
|
120 |
+
def __repr__(self):
|
121 |
+
return "{}.{}({})".format(
|
122 |
+
__name__,
|
123 |
+
type(self).__name__,
|
124 |
+
", ".join("{}={!r}".format(*nv) for nv in zip(self._fields, self)),
|
125 |
+
)
|
126 |
+
|
127 |
+
|
128 |
+
__version_info__ = version_info(3, 0, 7, "final", 0)
|
129 |
+
__version_time__ = "15 Jan 2022 04:10 UTC"
|
130 |
+
__version__ = __version_info__.__version__
|
131 |
+
__versionTime__ = __version_time__
|
132 |
+
__author__ = "Paul McGuire <[email protected]>"
|
133 |
+
|
134 |
+
from .util import *
|
135 |
+
from .exceptions import *
|
136 |
+
from .actions import *
|
137 |
+
from .core import __diag__, __compat__
|
138 |
+
from .results import *
|
139 |
+
from .core import *
|
140 |
+
from .core import _builtin_exprs as core_builtin_exprs
|
141 |
+
from .helpers import *
|
142 |
+
from .helpers import _builtin_exprs as helper_builtin_exprs
|
143 |
+
|
144 |
+
from .unicode import unicode_set, UnicodeRangeList, pyparsing_unicode as unicode
|
145 |
+
from .testing import pyparsing_test as testing
|
146 |
+
from .common import (
|
147 |
+
pyparsing_common as common,
|
148 |
+
_builtin_exprs as common_builtin_exprs,
|
149 |
+
)
|
150 |
+
|
151 |
+
# define backward compat synonyms
|
152 |
+
if "pyparsing_unicode" not in globals():
|
153 |
+
pyparsing_unicode = unicode
|
154 |
+
if "pyparsing_common" not in globals():
|
155 |
+
pyparsing_common = common
|
156 |
+
if "pyparsing_test" not in globals():
|
157 |
+
pyparsing_test = testing
|
158 |
+
|
159 |
+
core_builtin_exprs += common_builtin_exprs + helper_builtin_exprs
|
160 |
+
|
161 |
+
|
162 |
+
__all__ = [
|
163 |
+
"__version__",
|
164 |
+
"__version_time__",
|
165 |
+
"__author__",
|
166 |
+
"__compat__",
|
167 |
+
"__diag__",
|
168 |
+
"And",
|
169 |
+
"AtLineStart",
|
170 |
+
"AtStringStart",
|
171 |
+
"CaselessKeyword",
|
172 |
+
"CaselessLiteral",
|
173 |
+
"CharsNotIn",
|
174 |
+
"Combine",
|
175 |
+
"Dict",
|
176 |
+
"Each",
|
177 |
+
"Empty",
|
178 |
+
"FollowedBy",
|
179 |
+
"Forward",
|
180 |
+
"GoToColumn",
|
181 |
+
"Group",
|
182 |
+
"IndentedBlock",
|
183 |
+
"Keyword",
|
184 |
+
"LineEnd",
|
185 |
+
"LineStart",
|
186 |
+
"Literal",
|
187 |
+
"Located",
|
188 |
+
"PrecededBy",
|
189 |
+
"MatchFirst",
|
190 |
+
"NoMatch",
|
191 |
+
"NotAny",
|
192 |
+
"OneOrMore",
|
193 |
+
"OnlyOnce",
|
194 |
+
"OpAssoc",
|
195 |
+
"Opt",
|
196 |
+
"Optional",
|
197 |
+
"Or",
|
198 |
+
"ParseBaseException",
|
199 |
+
"ParseElementEnhance",
|
200 |
+
"ParseException",
|
201 |
+
"ParseExpression",
|
202 |
+
"ParseFatalException",
|
203 |
+
"ParseResults",
|
204 |
+
"ParseSyntaxException",
|
205 |
+
"ParserElement",
|
206 |
+
"PositionToken",
|
207 |
+
"QuotedString",
|
208 |
+
"RecursiveGrammarException",
|
209 |
+
"Regex",
|
210 |
+
"SkipTo",
|
211 |
+
"StringEnd",
|
212 |
+
"StringStart",
|
213 |
+
"Suppress",
|
214 |
+
"Token",
|
215 |
+
"TokenConverter",
|
216 |
+
"White",
|
217 |
+
"Word",
|
218 |
+
"WordEnd",
|
219 |
+
"WordStart",
|
220 |
+
"ZeroOrMore",
|
221 |
+
"Char",
|
222 |
+
"alphanums",
|
223 |
+
"alphas",
|
224 |
+
"alphas8bit",
|
225 |
+
"any_close_tag",
|
226 |
+
"any_open_tag",
|
227 |
+
"c_style_comment",
|
228 |
+
"col",
|
229 |
+
"common_html_entity",
|
230 |
+
"counted_array",
|
231 |
+
"cpp_style_comment",
|
232 |
+
"dbl_quoted_string",
|
233 |
+
"dbl_slash_comment",
|
234 |
+
"delimited_list",
|
235 |
+
"dict_of",
|
236 |
+
"empty",
|
237 |
+
"hexnums",
|
238 |
+
"html_comment",
|
239 |
+
"identchars",
|
240 |
+
"identbodychars",
|
241 |
+
"java_style_comment",
|
242 |
+
"line",
|
243 |
+
"line_end",
|
244 |
+
"line_start",
|
245 |
+
"lineno",
|
246 |
+
"make_html_tags",
|
247 |
+
"make_xml_tags",
|
248 |
+
"match_only_at_col",
|
249 |
+
"match_previous_expr",
|
250 |
+
"match_previous_literal",
|
251 |
+
"nested_expr",
|
252 |
+
"null_debug_action",
|
253 |
+
"nums",
|
254 |
+
"one_of",
|
255 |
+
"printables",
|
256 |
+
"punc8bit",
|
257 |
+
"python_style_comment",
|
258 |
+
"quoted_string",
|
259 |
+
"remove_quotes",
|
260 |
+
"replace_with",
|
261 |
+
"replace_html_entity",
|
262 |
+
"rest_of_line",
|
263 |
+
"sgl_quoted_string",
|
264 |
+
"srange",
|
265 |
+
"string_end",
|
266 |
+
"string_start",
|
267 |
+
"trace_parse_action",
|
268 |
+
"unicode_string",
|
269 |
+
"with_attribute",
|
270 |
+
"indentedBlock",
|
271 |
+
"original_text_for",
|
272 |
+
"ungroup",
|
273 |
+
"infix_notation",
|
274 |
+
"locatedExpr",
|
275 |
+
"with_class",
|
276 |
+
"CloseMatch",
|
277 |
+
"token_map",
|
278 |
+
"pyparsing_common",
|
279 |
+
"pyparsing_unicode",
|
280 |
+
"unicode_set",
|
281 |
+
"condition_as_parse_action",
|
282 |
+
"pyparsing_test",
|
283 |
+
# pre-PEP8 compatibility names
|
284 |
+
"__versionTime__",
|
285 |
+
"anyCloseTag",
|
286 |
+
"anyOpenTag",
|
287 |
+
"cStyleComment",
|
288 |
+
"commonHTMLEntity",
|
289 |
+
"countedArray",
|
290 |
+
"cppStyleComment",
|
291 |
+
"dblQuotedString",
|
292 |
+
"dblSlashComment",
|
293 |
+
"delimitedList",
|
294 |
+
"dictOf",
|
295 |
+
"htmlComment",
|
296 |
+
"javaStyleComment",
|
297 |
+
"lineEnd",
|
298 |
+
"lineStart",
|
299 |
+
"makeHTMLTags",
|
300 |
+
"makeXMLTags",
|
301 |
+
"matchOnlyAtCol",
|
302 |
+
"matchPreviousExpr",
|
303 |
+
"matchPreviousLiteral",
|
304 |
+
"nestedExpr",
|
305 |
+
"nullDebugAction",
|
306 |
+
"oneOf",
|
307 |
+
"opAssoc",
|
308 |
+
"pythonStyleComment",
|
309 |
+
"quotedString",
|
310 |
+
"removeQuotes",
|
311 |
+
"replaceHTMLEntity",
|
312 |
+
"replaceWith",
|
313 |
+
"restOfLine",
|
314 |
+
"sglQuotedString",
|
315 |
+
"stringEnd",
|
316 |
+
"stringStart",
|
317 |
+
"traceParseAction",
|
318 |
+
"unicodeString",
|
319 |
+
"withAttribute",
|
320 |
+
"indentedBlock",
|
321 |
+
"originalTextFor",
|
322 |
+
"infixNotation",
|
323 |
+
"locatedExpr",
|
324 |
+
"withClass",
|
325 |
+
"tokenMap",
|
326 |
+
"conditionAsParseAction",
|
327 |
+
"autoname_elements",
|
328 |
+
]
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/actions.cpython-310.pyc
ADDED
Binary file (7.18 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/helpers.cpython-310.pyc
ADDED
Binary file (34.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/testing.cpython-310.pyc
ADDED
Binary file (12.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/unicode.cpython-310.pyc
ADDED
Binary file (9.82 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/__pycache__/util.cpython-310.pyc
ADDED
Binary file (8.61 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/actions.py
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# actions.py
|
2 |
+
|
3 |
+
from .exceptions import ParseException
|
4 |
+
from .util import col
|
5 |
+
|
6 |
+
|
7 |
+
class OnlyOnce:
|
8 |
+
"""
|
9 |
+
Wrapper for parse actions, to ensure they are only called once.
|
10 |
+
"""
|
11 |
+
|
12 |
+
def __init__(self, method_call):
|
13 |
+
from .core import _trim_arity
|
14 |
+
|
15 |
+
self.callable = _trim_arity(method_call)
|
16 |
+
self.called = False
|
17 |
+
|
18 |
+
def __call__(self, s, l, t):
|
19 |
+
if not self.called:
|
20 |
+
results = self.callable(s, l, t)
|
21 |
+
self.called = True
|
22 |
+
return results
|
23 |
+
raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset")
|
24 |
+
|
25 |
+
def reset(self):
|
26 |
+
"""
|
27 |
+
Allow the associated parse action to be called once more.
|
28 |
+
"""
|
29 |
+
|
30 |
+
self.called = False
|
31 |
+
|
32 |
+
|
33 |
+
def match_only_at_col(n):
|
34 |
+
"""
|
35 |
+
Helper method for defining parse actions that require matching at
|
36 |
+
a specific column in the input text.
|
37 |
+
"""
|
38 |
+
|
39 |
+
def verify_col(strg, locn, toks):
|
40 |
+
if col(locn, strg) != n:
|
41 |
+
raise ParseException(strg, locn, "matched token not at column {}".format(n))
|
42 |
+
|
43 |
+
return verify_col
|
44 |
+
|
45 |
+
|
46 |
+
def replace_with(repl_str):
|
47 |
+
"""
|
48 |
+
Helper method for common parse actions that simply return
|
49 |
+
a literal value. Especially useful when used with
|
50 |
+
:class:`transform_string<ParserElement.transform_string>` ().
|
51 |
+
|
52 |
+
Example::
|
53 |
+
|
54 |
+
num = Word(nums).set_parse_action(lambda toks: int(toks[0]))
|
55 |
+
na = one_of("N/A NA").set_parse_action(replace_with(math.nan))
|
56 |
+
term = na | num
|
57 |
+
|
58 |
+
OneOrMore(term).parse_string("324 234 N/A 234") # -> [324, 234, nan, 234]
|
59 |
+
"""
|
60 |
+
return lambda s, l, t: [repl_str]
|
61 |
+
|
62 |
+
|
63 |
+
def remove_quotes(s, l, t):
|
64 |
+
"""
|
65 |
+
Helper parse action for removing quotation marks from parsed
|
66 |
+
quoted strings.
|
67 |
+
|
68 |
+
Example::
|
69 |
+
|
70 |
+
# by default, quotation marks are included in parsed results
|
71 |
+
quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
|
72 |
+
|
73 |
+
# use remove_quotes to strip quotation marks from parsed results
|
74 |
+
quoted_string.set_parse_action(remove_quotes)
|
75 |
+
quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
|
76 |
+
"""
|
77 |
+
return t[0][1:-1]
|
78 |
+
|
79 |
+
|
80 |
+
def with_attribute(*args, **attr_dict):
|
81 |
+
"""
|
82 |
+
Helper to create a validating parse action to be used with start
|
83 |
+
tags created with :class:`make_xml_tags` or
|
84 |
+
:class:`make_html_tags`. Use ``with_attribute`` to qualify
|
85 |
+
a starting tag with a required attribute value, to avoid false
|
86 |
+
matches on common tags such as ``<TD>`` or ``<DIV>``.
|
87 |
+
|
88 |
+
Call ``with_attribute`` with a series of attribute names and
|
89 |
+
values. Specify the list of filter attributes names and values as:
|
90 |
+
|
91 |
+
- keyword arguments, as in ``(align="right")``, or
|
92 |
+
- as an explicit dict with ``**`` operator, when an attribute
|
93 |
+
name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}``
|
94 |
+
- a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))``
|
95 |
+
|
96 |
+
For attribute names with a namespace prefix, you must use the second
|
97 |
+
form. Attribute names are matched insensitive to upper/lower case.
|
98 |
+
|
99 |
+
If just testing for ``class`` (with or without a namespace), use
|
100 |
+
:class:`with_class`.
|
101 |
+
|
102 |
+
To verify that the attribute exists, but without specifying a value,
|
103 |
+
pass ``with_attribute.ANY_VALUE`` as the value.
|
104 |
+
|
105 |
+
Example::
|
106 |
+
|
107 |
+
html = '''
|
108 |
+
<div>
|
109 |
+
Some text
|
110 |
+
<div type="grid">1 4 0 1 0</div>
|
111 |
+
<div type="graph">1,3 2,3 1,1</div>
|
112 |
+
<div>this has no type</div>
|
113 |
+
</div>
|
114 |
+
|
115 |
+
'''
|
116 |
+
div,div_end = make_html_tags("div")
|
117 |
+
|
118 |
+
# only match div tag having a type attribute with value "grid"
|
119 |
+
div_grid = div().set_parse_action(with_attribute(type="grid"))
|
120 |
+
grid_expr = div_grid + SkipTo(div | div_end)("body")
|
121 |
+
for grid_header in grid_expr.search_string(html):
|
122 |
+
print(grid_header.body)
|
123 |
+
|
124 |
+
# construct a match with any div tag having a type attribute, regardless of the value
|
125 |
+
div_any_type = div().set_parse_action(with_attribute(type=with_attribute.ANY_VALUE))
|
126 |
+
div_expr = div_any_type + SkipTo(div | div_end)("body")
|
127 |
+
for div_header in div_expr.search_string(html):
|
128 |
+
print(div_header.body)
|
129 |
+
|
130 |
+
prints::
|
131 |
+
|
132 |
+
1 4 0 1 0
|
133 |
+
|
134 |
+
1 4 0 1 0
|
135 |
+
1,3 2,3 1,1
|
136 |
+
"""
|
137 |
+
if args:
|
138 |
+
attrs = args[:]
|
139 |
+
else:
|
140 |
+
attrs = attr_dict.items()
|
141 |
+
attrs = [(k, v) for k, v in attrs]
|
142 |
+
|
143 |
+
def pa(s, l, tokens):
|
144 |
+
for attrName, attrValue in attrs:
|
145 |
+
if attrName not in tokens:
|
146 |
+
raise ParseException(s, l, "no matching attribute " + attrName)
|
147 |
+
if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue:
|
148 |
+
raise ParseException(
|
149 |
+
s,
|
150 |
+
l,
|
151 |
+
"attribute {!r} has value {!r}, must be {!r}".format(
|
152 |
+
attrName, tokens[attrName], attrValue
|
153 |
+
),
|
154 |
+
)
|
155 |
+
|
156 |
+
return pa
|
157 |
+
|
158 |
+
|
159 |
+
with_attribute.ANY_VALUE = object()
|
160 |
+
|
161 |
+
|
162 |
+
def with_class(classname, namespace=""):
|
163 |
+
"""
|
164 |
+
Simplified version of :class:`with_attribute` when
|
165 |
+
matching on a div class - made difficult because ``class`` is
|
166 |
+
a reserved word in Python.
|
167 |
+
|
168 |
+
Example::
|
169 |
+
|
170 |
+
html = '''
|
171 |
+
<div>
|
172 |
+
Some text
|
173 |
+
<div class="grid">1 4 0 1 0</div>
|
174 |
+
<div class="graph">1,3 2,3 1,1</div>
|
175 |
+
<div>this <div> has no class</div>
|
176 |
+
</div>
|
177 |
+
|
178 |
+
'''
|
179 |
+
div,div_end = make_html_tags("div")
|
180 |
+
div_grid = div().set_parse_action(with_class("grid"))
|
181 |
+
|
182 |
+
grid_expr = div_grid + SkipTo(div | div_end)("body")
|
183 |
+
for grid_header in grid_expr.search_string(html):
|
184 |
+
print(grid_header.body)
|
185 |
+
|
186 |
+
div_any_type = div().set_parse_action(with_class(withAttribute.ANY_VALUE))
|
187 |
+
div_expr = div_any_type + SkipTo(div | div_end)("body")
|
188 |
+
for div_header in div_expr.search_string(html):
|
189 |
+
print(div_header.body)
|
190 |
+
|
191 |
+
prints::
|
192 |
+
|
193 |
+
1 4 0 1 0
|
194 |
+
|
195 |
+
1 4 0 1 0
|
196 |
+
1,3 2,3 1,1
|
197 |
+
"""
|
198 |
+
classattr = "{}:class".format(namespace) if namespace else "class"
|
199 |
+
return with_attribute(**{classattr: classname})
|
200 |
+
|
201 |
+
|
202 |
+
# pre-PEP8 compatibility symbols
|
203 |
+
replaceWith = replace_with
|
204 |
+
removeQuotes = remove_quotes
|
205 |
+
withAttribute = with_attribute
|
206 |
+
withClass = with_class
|
207 |
+
matchOnlyAtCol = match_only_at_col
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/common.py
ADDED
@@ -0,0 +1,424 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# common.py
|
2 |
+
from .core import *
|
3 |
+
from .helpers import delimited_list, any_open_tag, any_close_tag
|
4 |
+
from datetime import datetime
|
5 |
+
|
6 |
+
|
7 |
+
# some other useful expressions - using lower-case class name since we are really using this as a namespace
|
8 |
+
class pyparsing_common:
|
9 |
+
"""Here are some common low-level expressions that may be useful in
|
10 |
+
jump-starting parser development:
|
11 |
+
|
12 |
+
- numeric forms (:class:`integers<integer>`, :class:`reals<real>`,
|
13 |
+
:class:`scientific notation<sci_real>`)
|
14 |
+
- common :class:`programming identifiers<identifier>`
|
15 |
+
- network addresses (:class:`MAC<mac_address>`,
|
16 |
+
:class:`IPv4<ipv4_address>`, :class:`IPv6<ipv6_address>`)
|
17 |
+
- ISO8601 :class:`dates<iso8601_date>` and
|
18 |
+
:class:`datetime<iso8601_datetime>`
|
19 |
+
- :class:`UUID<uuid>`
|
20 |
+
- :class:`comma-separated list<comma_separated_list>`
|
21 |
+
- :class:`url`
|
22 |
+
|
23 |
+
Parse actions:
|
24 |
+
|
25 |
+
- :class:`convertToInteger`
|
26 |
+
- :class:`convertToFloat`
|
27 |
+
- :class:`convertToDate`
|
28 |
+
- :class:`convertToDatetime`
|
29 |
+
- :class:`stripHTMLTags`
|
30 |
+
- :class:`upcaseTokens`
|
31 |
+
- :class:`downcaseTokens`
|
32 |
+
|
33 |
+
Example::
|
34 |
+
|
35 |
+
pyparsing_common.number.runTests('''
|
36 |
+
# any int or real number, returned as the appropriate type
|
37 |
+
100
|
38 |
+
-100
|
39 |
+
+100
|
40 |
+
3.14159
|
41 |
+
6.02e23
|
42 |
+
1e-12
|
43 |
+
''')
|
44 |
+
|
45 |
+
pyparsing_common.fnumber.runTests('''
|
46 |
+
# any int or real number, returned as float
|
47 |
+
100
|
48 |
+
-100
|
49 |
+
+100
|
50 |
+
3.14159
|
51 |
+
6.02e23
|
52 |
+
1e-12
|
53 |
+
''')
|
54 |
+
|
55 |
+
pyparsing_common.hex_integer.runTests('''
|
56 |
+
# hex numbers
|
57 |
+
100
|
58 |
+
FF
|
59 |
+
''')
|
60 |
+
|
61 |
+
pyparsing_common.fraction.runTests('''
|
62 |
+
# fractions
|
63 |
+
1/2
|
64 |
+
-3/4
|
65 |
+
''')
|
66 |
+
|
67 |
+
pyparsing_common.mixed_integer.runTests('''
|
68 |
+
# mixed fractions
|
69 |
+
1
|
70 |
+
1/2
|
71 |
+
-3/4
|
72 |
+
1-3/4
|
73 |
+
''')
|
74 |
+
|
75 |
+
import uuid
|
76 |
+
pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))
|
77 |
+
pyparsing_common.uuid.runTests('''
|
78 |
+
# uuid
|
79 |
+
12345678-1234-5678-1234-567812345678
|
80 |
+
''')
|
81 |
+
|
82 |
+
prints::
|
83 |
+
|
84 |
+
# any int or real number, returned as the appropriate type
|
85 |
+
100
|
86 |
+
[100]
|
87 |
+
|
88 |
+
-100
|
89 |
+
[-100]
|
90 |
+
|
91 |
+
+100
|
92 |
+
[100]
|
93 |
+
|
94 |
+
3.14159
|
95 |
+
[3.14159]
|
96 |
+
|
97 |
+
6.02e23
|
98 |
+
[6.02e+23]
|
99 |
+
|
100 |
+
1e-12
|
101 |
+
[1e-12]
|
102 |
+
|
103 |
+
# any int or real number, returned as float
|
104 |
+
100
|
105 |
+
[100.0]
|
106 |
+
|
107 |
+
-100
|
108 |
+
[-100.0]
|
109 |
+
|
110 |
+
+100
|
111 |
+
[100.0]
|
112 |
+
|
113 |
+
3.14159
|
114 |
+
[3.14159]
|
115 |
+
|
116 |
+
6.02e23
|
117 |
+
[6.02e+23]
|
118 |
+
|
119 |
+
1e-12
|
120 |
+
[1e-12]
|
121 |
+
|
122 |
+
# hex numbers
|
123 |
+
100
|
124 |
+
[256]
|
125 |
+
|
126 |
+
FF
|
127 |
+
[255]
|
128 |
+
|
129 |
+
# fractions
|
130 |
+
1/2
|
131 |
+
[0.5]
|
132 |
+
|
133 |
+
-3/4
|
134 |
+
[-0.75]
|
135 |
+
|
136 |
+
# mixed fractions
|
137 |
+
1
|
138 |
+
[1]
|
139 |
+
|
140 |
+
1/2
|
141 |
+
[0.5]
|
142 |
+
|
143 |
+
-3/4
|
144 |
+
[-0.75]
|
145 |
+
|
146 |
+
1-3/4
|
147 |
+
[1.75]
|
148 |
+
|
149 |
+
# uuid
|
150 |
+
12345678-1234-5678-1234-567812345678
|
151 |
+
[UUID('12345678-1234-5678-1234-567812345678')]
|
152 |
+
"""
|
153 |
+
|
154 |
+
convert_to_integer = token_map(int)
|
155 |
+
"""
|
156 |
+
Parse action for converting parsed integers to Python int
|
157 |
+
"""
|
158 |
+
|
159 |
+
convert_to_float = token_map(float)
|
160 |
+
"""
|
161 |
+
Parse action for converting parsed numbers to Python float
|
162 |
+
"""
|
163 |
+
|
164 |
+
integer = Word(nums).set_name("integer").set_parse_action(convert_to_integer)
|
165 |
+
"""expression that parses an unsigned integer, returns an int"""
|
166 |
+
|
167 |
+
hex_integer = (
|
168 |
+
Word(hexnums).set_name("hex integer").set_parse_action(token_map(int, 16))
|
169 |
+
)
|
170 |
+
"""expression that parses a hexadecimal integer, returns an int"""
|
171 |
+
|
172 |
+
signed_integer = (
|
173 |
+
Regex(r"[+-]?\d+")
|
174 |
+
.set_name("signed integer")
|
175 |
+
.set_parse_action(convert_to_integer)
|
176 |
+
)
|
177 |
+
"""expression that parses an integer with optional leading sign, returns an int"""
|
178 |
+
|
179 |
+
fraction = (
|
180 |
+
signed_integer().set_parse_action(convert_to_float)
|
181 |
+
+ "/"
|
182 |
+
+ signed_integer().set_parse_action(convert_to_float)
|
183 |
+
).set_name("fraction")
|
184 |
+
"""fractional expression of an integer divided by an integer, returns a float"""
|
185 |
+
fraction.add_parse_action(lambda tt: tt[0] / tt[-1])
|
186 |
+
|
187 |
+
mixed_integer = (
|
188 |
+
fraction | signed_integer + Opt(Opt("-").suppress() + fraction)
|
189 |
+
).set_name("fraction or mixed integer-fraction")
|
190 |
+
"""mixed integer of the form 'integer - fraction', with optional leading integer, returns float"""
|
191 |
+
mixed_integer.add_parse_action(sum)
|
192 |
+
|
193 |
+
real = (
|
194 |
+
Regex(r"[+-]?(?:\d+\.\d*|\.\d+)")
|
195 |
+
.set_name("real number")
|
196 |
+
.set_parse_action(convert_to_float)
|
197 |
+
)
|
198 |
+
"""expression that parses a floating point number and returns a float"""
|
199 |
+
|
200 |
+
sci_real = (
|
201 |
+
Regex(r"[+-]?(?:\d+(?:[eE][+-]?\d+)|(?:\d+\.\d*|\.\d+)(?:[eE][+-]?\d+)?)")
|
202 |
+
.set_name("real number with scientific notation")
|
203 |
+
.set_parse_action(convert_to_float)
|
204 |
+
)
|
205 |
+
"""expression that parses a floating point number with optional
|
206 |
+
scientific notation and returns a float"""
|
207 |
+
|
208 |
+
# streamlining this expression makes the docs nicer-looking
|
209 |
+
number = (sci_real | real | signed_integer).setName("number").streamline()
|
210 |
+
"""any numeric expression, returns the corresponding Python type"""
|
211 |
+
|
212 |
+
fnumber = (
|
213 |
+
Regex(r"[+-]?\d+\.?\d*([eE][+-]?\d+)?")
|
214 |
+
.set_name("fnumber")
|
215 |
+
.set_parse_action(convert_to_float)
|
216 |
+
)
|
217 |
+
"""any int or real number, returned as float"""
|
218 |
+
|
219 |
+
identifier = Word(identchars, identbodychars).set_name("identifier")
|
220 |
+
"""typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')"""
|
221 |
+
|
222 |
+
ipv4_address = Regex(
|
223 |
+
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}"
|
224 |
+
).set_name("IPv4 address")
|
225 |
+
"IPv4 address (``0.0.0.0 - 255.255.255.255``)"
|
226 |
+
|
227 |
+
_ipv6_part = Regex(r"[0-9a-fA-F]{1,4}").set_name("hex_integer")
|
228 |
+
_full_ipv6_address = (_ipv6_part + (":" + _ipv6_part) * 7).set_name(
|
229 |
+
"full IPv6 address"
|
230 |
+
)
|
231 |
+
_short_ipv6_address = (
|
232 |
+
Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6))
|
233 |
+
+ "::"
|
234 |
+
+ Opt(_ipv6_part + (":" + _ipv6_part) * (0, 6))
|
235 |
+
).set_name("short IPv6 address")
|
236 |
+
_short_ipv6_address.add_condition(
|
237 |
+
lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8
|
238 |
+
)
|
239 |
+
_mixed_ipv6_address = ("::ffff:" + ipv4_address).set_name("mixed IPv6 address")
|
240 |
+
ipv6_address = Combine(
|
241 |
+
(_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).set_name(
|
242 |
+
"IPv6 address"
|
243 |
+
)
|
244 |
+
).set_name("IPv6 address")
|
245 |
+
"IPv6 address (long, short, or mixed form)"
|
246 |
+
|
247 |
+
mac_address = Regex(
|
248 |
+
r"[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}"
|
249 |
+
).set_name("MAC address")
|
250 |
+
"MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)"
|
251 |
+
|
252 |
+
@staticmethod
|
253 |
+
def convert_to_date(fmt: str = "%Y-%m-%d"):
|
254 |
+
"""
|
255 |
+
Helper to create a parse action for converting parsed date string to Python datetime.date
|
256 |
+
|
257 |
+
Params -
|
258 |
+
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)
|
259 |
+
|
260 |
+
Example::
|
261 |
+
|
262 |
+
date_expr = pyparsing_common.iso8601_date.copy()
|
263 |
+
date_expr.setParseAction(pyparsing_common.convertToDate())
|
264 |
+
print(date_expr.parseString("1999-12-31"))
|
265 |
+
|
266 |
+
prints::
|
267 |
+
|
268 |
+
[datetime.date(1999, 12, 31)]
|
269 |
+
"""
|
270 |
+
|
271 |
+
def cvt_fn(ss, ll, tt):
|
272 |
+
try:
|
273 |
+
return datetime.strptime(tt[0], fmt).date()
|
274 |
+
except ValueError as ve:
|
275 |
+
raise ParseException(ss, ll, str(ve))
|
276 |
+
|
277 |
+
return cvt_fn
|
278 |
+
|
279 |
+
@staticmethod
|
280 |
+
def convert_to_datetime(fmt: str = "%Y-%m-%dT%H:%M:%S.%f"):
|
281 |
+
"""Helper to create a parse action for converting parsed
|
282 |
+
datetime string to Python datetime.datetime
|
283 |
+
|
284 |
+
Params -
|
285 |
+
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``)
|
286 |
+
|
287 |
+
Example::
|
288 |
+
|
289 |
+
dt_expr = pyparsing_common.iso8601_datetime.copy()
|
290 |
+
dt_expr.setParseAction(pyparsing_common.convertToDatetime())
|
291 |
+
print(dt_expr.parseString("1999-12-31T23:59:59.999"))
|
292 |
+
|
293 |
+
prints::
|
294 |
+
|
295 |
+
[datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
|
296 |
+
"""
|
297 |
+
|
298 |
+
def cvt_fn(s, l, t):
|
299 |
+
try:
|
300 |
+
return datetime.strptime(t[0], fmt)
|
301 |
+
except ValueError as ve:
|
302 |
+
raise ParseException(s, l, str(ve))
|
303 |
+
|
304 |
+
return cvt_fn
|
305 |
+
|
306 |
+
iso8601_date = Regex(
|
307 |
+
r"(?P<year>\d{4})(?:-(?P<month>\d\d)(?:-(?P<day>\d\d))?)?"
|
308 |
+
).set_name("ISO8601 date")
|
309 |
+
"ISO8601 date (``yyyy-mm-dd``)"
|
310 |
+
|
311 |
+
iso8601_datetime = Regex(
|
312 |
+
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)?"
|
313 |
+
).set_name("ISO8601 datetime")
|
314 |
+
"ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``"
|
315 |
+
|
316 |
+
uuid = Regex(r"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}").set_name("UUID")
|
317 |
+
"UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)"
|
318 |
+
|
319 |
+
_html_stripper = any_open_tag.suppress() | any_close_tag.suppress()
|
320 |
+
|
321 |
+
@staticmethod
|
322 |
+
def strip_html_tags(s: str, l: int, tokens: ParseResults):
|
323 |
+
"""Parse action to remove HTML tags from web page HTML source
|
324 |
+
|
325 |
+
Example::
|
326 |
+
|
327 |
+
# strip HTML links from normal text
|
328 |
+
text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>'
|
329 |
+
td, td_end = makeHTMLTags("TD")
|
330 |
+
table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end
|
331 |
+
print(table_text.parseString(text).body)
|
332 |
+
|
333 |
+
Prints::
|
334 |
+
|
335 |
+
More info at the pyparsing wiki page
|
336 |
+
"""
|
337 |
+
return pyparsing_common._html_stripper.transform_string(tokens[0])
|
338 |
+
|
339 |
+
_commasepitem = (
|
340 |
+
Combine(
|
341 |
+
OneOrMore(
|
342 |
+
~Literal(",")
|
343 |
+
+ ~LineEnd()
|
344 |
+
+ Word(printables, exclude_chars=",")
|
345 |
+
+ Opt(White(" \t") + ~FollowedBy(LineEnd() | ","))
|
346 |
+
)
|
347 |
+
)
|
348 |
+
.streamline()
|
349 |
+
.set_name("commaItem")
|
350 |
+
)
|
351 |
+
comma_separated_list = delimited_list(
|
352 |
+
Opt(quoted_string.copy() | _commasepitem, default="")
|
353 |
+
).set_name("comma separated list")
|
354 |
+
"""Predefined expression of 1 or more printable words or quoted strings, separated by commas."""
|
355 |
+
|
356 |
+
upcase_tokens = staticmethod(token_map(lambda t: t.upper()))
|
357 |
+
"""Parse action to convert tokens to upper case."""
|
358 |
+
|
359 |
+
downcase_tokens = staticmethod(token_map(lambda t: t.lower()))
|
360 |
+
"""Parse action to convert tokens to lower case."""
|
361 |
+
|
362 |
+
# fmt: off
|
363 |
+
url = Regex(
|
364 |
+
# https://mathiasbynens.be/demo/url-regex
|
365 |
+
# https://gist.github.com/dperini/729294
|
366 |
+
r"^" +
|
367 |
+
# protocol identifier (optional)
|
368 |
+
# short syntax // still required
|
369 |
+
r"(?:(?:(?P<scheme>https?|ftp):)?\/\/)" +
|
370 |
+
# user:pass BasicAuth (optional)
|
371 |
+
r"(?:(?P<auth>\S+(?::\S*)?)@)?" +
|
372 |
+
r"(?P<host>" +
|
373 |
+
# IP address exclusion
|
374 |
+
# private & local networks
|
375 |
+
r"(?!(?:10|127)(?:\.\d{1,3}){3})" +
|
376 |
+
r"(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})" +
|
377 |
+
r"(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})" +
|
378 |
+
# IP address dotted notation octets
|
379 |
+
# excludes loopback network 0.0.0.0
|
380 |
+
# excludes reserved space >= 224.0.0.0
|
381 |
+
# excludes network & broadcast addresses
|
382 |
+
# (first & last IP address of each class)
|
383 |
+
r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])" +
|
384 |
+
r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}" +
|
385 |
+
r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))" +
|
386 |
+
r"|" +
|
387 |
+
# host & domain names, may end with dot
|
388 |
+
# can be replaced by a shortest alternative
|
389 |
+
# (?![-_])(?:[-\w\u00a1-\uffff]{0,63}[^-_]\.)+
|
390 |
+
r"(?:" +
|
391 |
+
r"(?:" +
|
392 |
+
r"[a-z0-9\u00a1-\uffff]" +
|
393 |
+
r"[a-z0-9\u00a1-\uffff_-]{0,62}" +
|
394 |
+
r")?" +
|
395 |
+
r"[a-z0-9\u00a1-\uffff]\." +
|
396 |
+
r")+" +
|
397 |
+
# TLD identifier name, may end with dot
|
398 |
+
r"(?:[a-z\u00a1-\uffff]{2,}\.?)" +
|
399 |
+
r")" +
|
400 |
+
# port number (optional)
|
401 |
+
r"(:(?P<port>\d{2,5}))?" +
|
402 |
+
# resource path (optional)
|
403 |
+
r"(?P<path>\/[^?# ]*)?" +
|
404 |
+
# query string (optional)
|
405 |
+
r"(\?(?P<query>[^#]*))?" +
|
406 |
+
# fragment (optional)
|
407 |
+
r"(#(?P<fragment>\S*))?" +
|
408 |
+
r"$"
|
409 |
+
).set_name("url")
|
410 |
+
# fmt: on
|
411 |
+
|
412 |
+
# pre-PEP8 compatibility names
|
413 |
+
convertToInteger = convert_to_integer
|
414 |
+
convertToFloat = convert_to_float
|
415 |
+
convertToDate = convert_to_date
|
416 |
+
convertToDatetime = convert_to_datetime
|
417 |
+
stripHTMLTags = strip_html_tags
|
418 |
+
upcaseTokens = upcase_tokens
|
419 |
+
downcaseTokens = downcase_tokens
|
420 |
+
|
421 |
+
|
422 |
+
_builtin_exprs = [
|
423 |
+
v for v in vars(pyparsing_common).values() if isinstance(v, ParserElement)
|
424 |
+
]
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/core.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/diagram/__init__.py
ADDED
@@ -0,0 +1,593 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import railroad
|
2 |
+
from pip._vendor import pyparsing
|
3 |
+
from pip._vendor.pkg_resources import resource_filename
|
4 |
+
from typing import (
|
5 |
+
List,
|
6 |
+
Optional,
|
7 |
+
NamedTuple,
|
8 |
+
Generic,
|
9 |
+
TypeVar,
|
10 |
+
Dict,
|
11 |
+
Callable,
|
12 |
+
Set,
|
13 |
+
Iterable,
|
14 |
+
)
|
15 |
+
from jinja2 import Template
|
16 |
+
from io import StringIO
|
17 |
+
import inspect
|
18 |
+
|
19 |
+
with open(resource_filename(__name__, "template.jinja2"), encoding="utf-8") as fp:
|
20 |
+
template = Template(fp.read())
|
21 |
+
|
22 |
+
# Note: ideally this would be a dataclass, but we're supporting Python 3.5+ so we can't do this yet
|
23 |
+
NamedDiagram = NamedTuple(
|
24 |
+
"NamedDiagram",
|
25 |
+
[("name", str), ("diagram", Optional[railroad.DiagramItem]), ("index", int)],
|
26 |
+
)
|
27 |
+
"""
|
28 |
+
A simple structure for associating a name with a railroad diagram
|
29 |
+
"""
|
30 |
+
|
31 |
+
T = TypeVar("T")
|
32 |
+
|
33 |
+
|
34 |
+
class EachItem(railroad.Group):
|
35 |
+
"""
|
36 |
+
Custom railroad item to compose a:
|
37 |
+
- Group containing a
|
38 |
+
- OneOrMore containing a
|
39 |
+
- Choice of the elements in the Each
|
40 |
+
with the group label indicating that all must be matched
|
41 |
+
"""
|
42 |
+
|
43 |
+
all_label = "[ALL]"
|
44 |
+
|
45 |
+
def __init__(self, *items):
|
46 |
+
choice_item = railroad.Choice(len(items) - 1, *items)
|
47 |
+
one_or_more_item = railroad.OneOrMore(item=choice_item)
|
48 |
+
super().__init__(one_or_more_item, label=self.all_label)
|
49 |
+
|
50 |
+
|
51 |
+
class AnnotatedItem(railroad.Group):
|
52 |
+
"""
|
53 |
+
Simple subclass of Group that creates an annotation label
|
54 |
+
"""
|
55 |
+
|
56 |
+
def __init__(self, label: str, item):
|
57 |
+
super().__init__(item=item, label="[{}]".format(label))
|
58 |
+
|
59 |
+
|
60 |
+
class EditablePartial(Generic[T]):
|
61 |
+
"""
|
62 |
+
Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been
|
63 |
+
constructed.
|
64 |
+
"""
|
65 |
+
|
66 |
+
# We need this here because the railroad constructors actually transform the data, so can't be called until the
|
67 |
+
# entire tree is assembled
|
68 |
+
|
69 |
+
def __init__(self, func: Callable[..., T], args: list, kwargs: dict):
|
70 |
+
self.func = func
|
71 |
+
self.args = args
|
72 |
+
self.kwargs = kwargs
|
73 |
+
|
74 |
+
@classmethod
|
75 |
+
def from_call(cls, func: Callable[..., T], *args, **kwargs) -> "EditablePartial[T]":
|
76 |
+
"""
|
77 |
+
If you call this function in the same way that you would call the constructor, it will store the arguments
|
78 |
+
as you expect. For example EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)
|
79 |
+
"""
|
80 |
+
return EditablePartial(func=func, args=list(args), kwargs=kwargs)
|
81 |
+
|
82 |
+
@property
|
83 |
+
def name(self):
|
84 |
+
return self.kwargs["name"]
|
85 |
+
|
86 |
+
def __call__(self) -> T:
|
87 |
+
"""
|
88 |
+
Evaluate the partial and return the result
|
89 |
+
"""
|
90 |
+
args = self.args.copy()
|
91 |
+
kwargs = self.kwargs.copy()
|
92 |
+
|
93 |
+
# This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g.
|
94 |
+
# args=['list', 'of', 'things'])
|
95 |
+
arg_spec = inspect.getfullargspec(self.func)
|
96 |
+
if arg_spec.varargs in self.kwargs:
|
97 |
+
args += kwargs.pop(arg_spec.varargs)
|
98 |
+
|
99 |
+
return self.func(*args, **kwargs)
|
100 |
+
|
101 |
+
|
102 |
+
def railroad_to_html(diagrams: List[NamedDiagram], **kwargs) -> str:
|
103 |
+
"""
|
104 |
+
Given a list of NamedDiagram, produce a single HTML string that visualises those diagrams
|
105 |
+
:params kwargs: kwargs to be passed in to the template
|
106 |
+
"""
|
107 |
+
data = []
|
108 |
+
for diagram in diagrams:
|
109 |
+
io = StringIO()
|
110 |
+
diagram.diagram.writeSvg(io.write)
|
111 |
+
title = diagram.name
|
112 |
+
if diagram.index == 0:
|
113 |
+
title += " (root)"
|
114 |
+
data.append({"title": title, "text": "", "svg": io.getvalue()})
|
115 |
+
|
116 |
+
return template.render(diagrams=data, **kwargs)
|
117 |
+
|
118 |
+
|
119 |
+
def resolve_partial(partial: "EditablePartial[T]") -> T:
|
120 |
+
"""
|
121 |
+
Recursively resolves a collection of Partials into whatever type they are
|
122 |
+
"""
|
123 |
+
if isinstance(partial, EditablePartial):
|
124 |
+
partial.args = resolve_partial(partial.args)
|
125 |
+
partial.kwargs = resolve_partial(partial.kwargs)
|
126 |
+
return partial()
|
127 |
+
elif isinstance(partial, list):
|
128 |
+
return [resolve_partial(x) for x in partial]
|
129 |
+
elif isinstance(partial, dict):
|
130 |
+
return {key: resolve_partial(x) for key, x in partial.items()}
|
131 |
+
else:
|
132 |
+
return partial
|
133 |
+
|
134 |
+
|
135 |
+
def to_railroad(
|
136 |
+
element: pyparsing.ParserElement,
|
137 |
+
diagram_kwargs: Optional[dict] = None,
|
138 |
+
vertical: int = 3,
|
139 |
+
show_results_names: bool = False,
|
140 |
+
) -> List[NamedDiagram]:
|
141 |
+
"""
|
142 |
+
Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram
|
143 |
+
creation if you want to access the Railroad tree before it is converted to HTML
|
144 |
+
:param element: base element of the parser being diagrammed
|
145 |
+
:param diagram_kwargs: kwargs to pass to the Diagram() constructor
|
146 |
+
:param vertical: (optional) - int - limit at which number of alternatives should be
|
147 |
+
shown vertically instead of horizontally
|
148 |
+
:param show_results_names - bool to indicate whether results name annotations should be
|
149 |
+
included in the diagram
|
150 |
+
"""
|
151 |
+
# Convert the whole tree underneath the root
|
152 |
+
lookup = ConverterState(diagram_kwargs=diagram_kwargs or {})
|
153 |
+
_to_diagram_element(
|
154 |
+
element,
|
155 |
+
lookup=lookup,
|
156 |
+
parent=None,
|
157 |
+
vertical=vertical,
|
158 |
+
show_results_names=show_results_names,
|
159 |
+
)
|
160 |
+
|
161 |
+
root_id = id(element)
|
162 |
+
# Convert the root if it hasn't been already
|
163 |
+
if root_id in lookup:
|
164 |
+
if not element.customName:
|
165 |
+
lookup[root_id].name = ""
|
166 |
+
lookup[root_id].mark_for_extraction(root_id, lookup, force=True)
|
167 |
+
|
168 |
+
# Now that we're finished, we can convert from intermediate structures into Railroad elements
|
169 |
+
diags = list(lookup.diagrams.values())
|
170 |
+
if len(diags) > 1:
|
171 |
+
# collapse out duplicate diags with the same name
|
172 |
+
seen = set()
|
173 |
+
deduped_diags = []
|
174 |
+
for d in diags:
|
175 |
+
# don't extract SkipTo elements, they are uninformative as subdiagrams
|
176 |
+
if d.name == "...":
|
177 |
+
continue
|
178 |
+
if d.name is not None and d.name not in seen:
|
179 |
+
seen.add(d.name)
|
180 |
+
deduped_diags.append(d)
|
181 |
+
resolved = [resolve_partial(partial) for partial in deduped_diags]
|
182 |
+
else:
|
183 |
+
# special case - if just one diagram, always display it, even if
|
184 |
+
# it has no name
|
185 |
+
resolved = [resolve_partial(partial) for partial in diags]
|
186 |
+
return sorted(resolved, key=lambda diag: diag.index)
|
187 |
+
|
188 |
+
|
189 |
+
def _should_vertical(
|
190 |
+
specification: int, exprs: Iterable[pyparsing.ParserElement]
|
191 |
+
) -> bool:
|
192 |
+
"""
|
193 |
+
Returns true if we should return a vertical list of elements
|
194 |
+
"""
|
195 |
+
if specification is None:
|
196 |
+
return False
|
197 |
+
else:
|
198 |
+
return len(_visible_exprs(exprs)) >= specification
|
199 |
+
|
200 |
+
|
201 |
+
class ElementState:
|
202 |
+
"""
|
203 |
+
State recorded for an individual pyparsing Element
|
204 |
+
"""
|
205 |
+
|
206 |
+
# Note: this should be a dataclass, but we have to support Python 3.5
|
207 |
+
def __init__(
|
208 |
+
self,
|
209 |
+
element: pyparsing.ParserElement,
|
210 |
+
converted: EditablePartial,
|
211 |
+
parent: EditablePartial,
|
212 |
+
number: int,
|
213 |
+
name: str = None,
|
214 |
+
parent_index: Optional[int] = None,
|
215 |
+
):
|
216 |
+
#: The pyparsing element that this represents
|
217 |
+
self.element: pyparsing.ParserElement = element
|
218 |
+
#: The name of the element
|
219 |
+
self.name: str = name
|
220 |
+
#: The output Railroad element in an unconverted state
|
221 |
+
self.converted: EditablePartial = converted
|
222 |
+
#: The parent Railroad element, which we store so that we can extract this if it's duplicated
|
223 |
+
self.parent: EditablePartial = parent
|
224 |
+
#: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram
|
225 |
+
self.number: int = number
|
226 |
+
#: The index of this inside its parent
|
227 |
+
self.parent_index: Optional[int] = parent_index
|
228 |
+
#: If true, we should extract this out into a subdiagram
|
229 |
+
self.extract: bool = False
|
230 |
+
#: If true, all of this element's children have been filled out
|
231 |
+
self.complete: bool = False
|
232 |
+
|
233 |
+
def mark_for_extraction(
|
234 |
+
self, el_id: int, state: "ConverterState", name: str = None, force: bool = False
|
235 |
+
):
|
236 |
+
"""
|
237 |
+
Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram
|
238 |
+
:param el_id: id of the element
|
239 |
+
:param state: element/diagram state tracker
|
240 |
+
:param name: name to use for this element's text
|
241 |
+
:param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the
|
242 |
+
root element when we know we're finished
|
243 |
+
"""
|
244 |
+
self.extract = True
|
245 |
+
|
246 |
+
# Set the name
|
247 |
+
if not self.name:
|
248 |
+
if name:
|
249 |
+
# Allow forcing a custom name
|
250 |
+
self.name = name
|
251 |
+
elif self.element.customName:
|
252 |
+
self.name = self.element.customName
|
253 |
+
else:
|
254 |
+
self.name = ""
|
255 |
+
|
256 |
+
# Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children
|
257 |
+
# to be added
|
258 |
+
# Also, if this is just a string literal etc, don't bother extracting it
|
259 |
+
if force or (self.complete and _worth_extracting(self.element)):
|
260 |
+
state.extract_into_diagram(el_id)
|
261 |
+
|
262 |
+
|
263 |
+
class ConverterState:
|
264 |
+
"""
|
265 |
+
Stores some state that persists between recursions into the element tree
|
266 |
+
"""
|
267 |
+
|
268 |
+
def __init__(self, diagram_kwargs: Optional[dict] = None):
|
269 |
+
#: A dictionary mapping ParserElements to state relating to them
|
270 |
+
self._element_diagram_states: Dict[int, ElementState] = {}
|
271 |
+
#: A dictionary mapping ParserElement IDs to subdiagrams generated from them
|
272 |
+
self.diagrams: Dict[int, EditablePartial[NamedDiagram]] = {}
|
273 |
+
#: The index of the next unnamed element
|
274 |
+
self.unnamed_index: int = 1
|
275 |
+
#: The index of the next element. This is used for sorting
|
276 |
+
self.index: int = 0
|
277 |
+
#: Shared kwargs that are used to customize the construction of diagrams
|
278 |
+
self.diagram_kwargs: dict = diagram_kwargs or {}
|
279 |
+
self.extracted_diagram_names: Set[str] = set()
|
280 |
+
|
281 |
+
def __setitem__(self, key: int, value: ElementState):
|
282 |
+
self._element_diagram_states[key] = value
|
283 |
+
|
284 |
+
def __getitem__(self, key: int) -> ElementState:
|
285 |
+
return self._element_diagram_states[key]
|
286 |
+
|
287 |
+
def __delitem__(self, key: int):
|
288 |
+
del self._element_diagram_states[key]
|
289 |
+
|
290 |
+
def __contains__(self, key: int):
|
291 |
+
return key in self._element_diagram_states
|
292 |
+
|
293 |
+
def generate_unnamed(self) -> int:
|
294 |
+
"""
|
295 |
+
Generate a number used in the name of an otherwise unnamed diagram
|
296 |
+
"""
|
297 |
+
self.unnamed_index += 1
|
298 |
+
return self.unnamed_index
|
299 |
+
|
300 |
+
def generate_index(self) -> int:
|
301 |
+
"""
|
302 |
+
Generate a number used to index a diagram
|
303 |
+
"""
|
304 |
+
self.index += 1
|
305 |
+
return self.index
|
306 |
+
|
307 |
+
def extract_into_diagram(self, el_id: int):
|
308 |
+
"""
|
309 |
+
Used when we encounter the same token twice in the same tree. When this
|
310 |
+
happens, we replace all instances of that token with a terminal, and
|
311 |
+
create a new subdiagram for the token
|
312 |
+
"""
|
313 |
+
position = self[el_id]
|
314 |
+
|
315 |
+
# Replace the original definition of this element with a regular block
|
316 |
+
if position.parent:
|
317 |
+
ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name)
|
318 |
+
if "item" in position.parent.kwargs:
|
319 |
+
position.parent.kwargs["item"] = ret
|
320 |
+
elif "items" in position.parent.kwargs:
|
321 |
+
position.parent.kwargs["items"][position.parent_index] = ret
|
322 |
+
|
323 |
+
# If the element we're extracting is a group, skip to its content but keep the title
|
324 |
+
if position.converted.func == railroad.Group:
|
325 |
+
content = position.converted.kwargs["item"]
|
326 |
+
else:
|
327 |
+
content = position.converted
|
328 |
+
|
329 |
+
self.diagrams[el_id] = EditablePartial.from_call(
|
330 |
+
NamedDiagram,
|
331 |
+
name=position.name,
|
332 |
+
diagram=EditablePartial.from_call(
|
333 |
+
railroad.Diagram, content, **self.diagram_kwargs
|
334 |
+
),
|
335 |
+
index=position.number,
|
336 |
+
)
|
337 |
+
|
338 |
+
del self[el_id]
|
339 |
+
|
340 |
+
|
341 |
+
def _worth_extracting(element: pyparsing.ParserElement) -> bool:
|
342 |
+
"""
|
343 |
+
Returns true if this element is worth having its own sub-diagram. Simply, if any of its children
|
344 |
+
themselves have children, then its complex enough to extract
|
345 |
+
"""
|
346 |
+
children = element.recurse()
|
347 |
+
return any(child.recurse() for child in children)
|
348 |
+
|
349 |
+
|
350 |
+
def _apply_diagram_item_enhancements(fn):
|
351 |
+
"""
|
352 |
+
decorator to ensure enhancements to a diagram item (such as results name annotations)
|
353 |
+
get applied on return from _to_diagram_element (we do this since there are several
|
354 |
+
returns in _to_diagram_element)
|
355 |
+
"""
|
356 |
+
|
357 |
+
def _inner(
|
358 |
+
element: pyparsing.ParserElement,
|
359 |
+
parent: Optional[EditablePartial],
|
360 |
+
lookup: ConverterState = None,
|
361 |
+
vertical: int = None,
|
362 |
+
index: int = 0,
|
363 |
+
name_hint: str = None,
|
364 |
+
show_results_names: bool = False,
|
365 |
+
) -> Optional[EditablePartial]:
|
366 |
+
|
367 |
+
ret = fn(
|
368 |
+
element,
|
369 |
+
parent,
|
370 |
+
lookup,
|
371 |
+
vertical,
|
372 |
+
index,
|
373 |
+
name_hint,
|
374 |
+
show_results_names,
|
375 |
+
)
|
376 |
+
|
377 |
+
# apply annotation for results name, if present
|
378 |
+
if show_results_names and ret is not None:
|
379 |
+
element_results_name = element.resultsName
|
380 |
+
if element_results_name:
|
381 |
+
# add "*" to indicate if this is a "list all results" name
|
382 |
+
element_results_name += "" if element.modalResults else "*"
|
383 |
+
ret = EditablePartial.from_call(
|
384 |
+
railroad.Group, item=ret, label=element_results_name
|
385 |
+
)
|
386 |
+
|
387 |
+
return ret
|
388 |
+
|
389 |
+
return _inner
|
390 |
+
|
391 |
+
|
392 |
+
def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]):
|
393 |
+
non_diagramming_exprs = (
|
394 |
+
pyparsing.ParseElementEnhance,
|
395 |
+
pyparsing.PositionToken,
|
396 |
+
pyparsing.And._ErrorStop,
|
397 |
+
)
|
398 |
+
return [
|
399 |
+
e
|
400 |
+
for e in exprs
|
401 |
+
if not (e.customName or e.resultsName or isinstance(e, non_diagramming_exprs))
|
402 |
+
]
|
403 |
+
|
404 |
+
|
405 |
+
@_apply_diagram_item_enhancements
|
406 |
+
def _to_diagram_element(
|
407 |
+
element: pyparsing.ParserElement,
|
408 |
+
parent: Optional[EditablePartial],
|
409 |
+
lookup: ConverterState = None,
|
410 |
+
vertical: int = None,
|
411 |
+
index: int = 0,
|
412 |
+
name_hint: str = None,
|
413 |
+
show_results_names: bool = False,
|
414 |
+
) -> Optional[EditablePartial]:
|
415 |
+
"""
|
416 |
+
Recursively converts a PyParsing Element to a railroad Element
|
417 |
+
:param lookup: The shared converter state that keeps track of useful things
|
418 |
+
:param index: The index of this element within the parent
|
419 |
+
:param parent: The parent of this element in the output tree
|
420 |
+
:param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),
|
421 |
+
it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never
|
422 |
+
do so
|
423 |
+
:param name_hint: If provided, this will override the generated name
|
424 |
+
:param show_results_names: bool flag indicating whether to add annotations for results names
|
425 |
+
:returns: The converted version of the input element, but as a Partial that hasn't yet been constructed
|
426 |
+
"""
|
427 |
+
exprs = element.recurse()
|
428 |
+
name = name_hint or element.customName or element.__class__.__name__
|
429 |
+
|
430 |
+
# Python's id() is used to provide a unique identifier for elements
|
431 |
+
el_id = id(element)
|
432 |
+
|
433 |
+
element_results_name = element.resultsName
|
434 |
+
|
435 |
+
# Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram
|
436 |
+
if not element.customName:
|
437 |
+
if isinstance(
|
438 |
+
element,
|
439 |
+
(
|
440 |
+
pyparsing.TokenConverter,
|
441 |
+
# pyparsing.Forward,
|
442 |
+
pyparsing.Located,
|
443 |
+
),
|
444 |
+
):
|
445 |
+
# However, if this element has a useful custom name, and its child does not, we can pass it on to the child
|
446 |
+
if exprs:
|
447 |
+
if not exprs[0].customName:
|
448 |
+
propagated_name = name
|
449 |
+
else:
|
450 |
+
propagated_name = None
|
451 |
+
|
452 |
+
return _to_diagram_element(
|
453 |
+
element.expr,
|
454 |
+
parent=parent,
|
455 |
+
lookup=lookup,
|
456 |
+
vertical=vertical,
|
457 |
+
index=index,
|
458 |
+
name_hint=propagated_name,
|
459 |
+
show_results_names=show_results_names,
|
460 |
+
)
|
461 |
+
|
462 |
+
# If the element isn't worth extracting, we always treat it as the first time we say it
|
463 |
+
if _worth_extracting(element):
|
464 |
+
if el_id in lookup:
|
465 |
+
# If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,
|
466 |
+
# so we have to extract it into a new diagram.
|
467 |
+
looked_up = lookup[el_id]
|
468 |
+
looked_up.mark_for_extraction(el_id, lookup, name=name_hint)
|
469 |
+
ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name)
|
470 |
+
return ret
|
471 |
+
|
472 |
+
elif el_id in lookup.diagrams:
|
473 |
+
# If we have seen the element at least twice before, and have already extracted it into a subdiagram, we
|
474 |
+
# just put in a marker element that refers to the sub-diagram
|
475 |
+
ret = EditablePartial.from_call(
|
476 |
+
railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"]
|
477 |
+
)
|
478 |
+
return ret
|
479 |
+
|
480 |
+
# Recursively convert child elements
|
481 |
+
# Here we find the most relevant Railroad element for matching pyparsing Element
|
482 |
+
# We use ``items=[]`` here to hold the place for where the child elements will go once created
|
483 |
+
if isinstance(element, pyparsing.And):
|
484 |
+
# detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat
|
485 |
+
# (all will have the same name, and resultsName)
|
486 |
+
if not exprs:
|
487 |
+
return None
|
488 |
+
if len(set((e.name, e.resultsName) for e in exprs)) == 1:
|
489 |
+
ret = EditablePartial.from_call(
|
490 |
+
railroad.OneOrMore, item="", repeat=str(len(exprs))
|
491 |
+
)
|
492 |
+
elif _should_vertical(vertical, exprs):
|
493 |
+
ret = EditablePartial.from_call(railroad.Stack, items=[])
|
494 |
+
else:
|
495 |
+
ret = EditablePartial.from_call(railroad.Sequence, items=[])
|
496 |
+
elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):
|
497 |
+
if not exprs:
|
498 |
+
return None
|
499 |
+
if _should_vertical(vertical, exprs):
|
500 |
+
ret = EditablePartial.from_call(railroad.Choice, 0, items=[])
|
501 |
+
else:
|
502 |
+
ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])
|
503 |
+
elif isinstance(element, pyparsing.Each):
|
504 |
+
if not exprs:
|
505 |
+
return None
|
506 |
+
ret = EditablePartial.from_call(EachItem, items=[])
|
507 |
+
elif isinstance(element, pyparsing.NotAny):
|
508 |
+
ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="")
|
509 |
+
elif isinstance(element, pyparsing.FollowedBy):
|
510 |
+
ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="")
|
511 |
+
elif isinstance(element, pyparsing.PrecededBy):
|
512 |
+
ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="")
|
513 |
+
elif isinstance(element, pyparsing.Opt):
|
514 |
+
ret = EditablePartial.from_call(railroad.Optional, item="")
|
515 |
+
elif isinstance(element, pyparsing.OneOrMore):
|
516 |
+
ret = EditablePartial.from_call(railroad.OneOrMore, item="")
|
517 |
+
elif isinstance(element, pyparsing.ZeroOrMore):
|
518 |
+
ret = EditablePartial.from_call(railroad.ZeroOrMore, item="")
|
519 |
+
elif isinstance(element, pyparsing.Group):
|
520 |
+
ret = EditablePartial.from_call(
|
521 |
+
railroad.Group, item=None, label=element_results_name
|
522 |
+
)
|
523 |
+
elif isinstance(element, pyparsing.Empty) and not element.customName:
|
524 |
+
# Skip unnamed "Empty" elements
|
525 |
+
ret = None
|
526 |
+
elif len(exprs) > 1:
|
527 |
+
ret = EditablePartial.from_call(railroad.Sequence, items=[])
|
528 |
+
elif len(exprs) > 0 and not element_results_name:
|
529 |
+
ret = EditablePartial.from_call(railroad.Group, item="", label=name)
|
530 |
+
else:
|
531 |
+
terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)
|
532 |
+
ret = terminal
|
533 |
+
|
534 |
+
if ret is None:
|
535 |
+
return
|
536 |
+
|
537 |
+
# Indicate this element's position in the tree so we can extract it if necessary
|
538 |
+
lookup[el_id] = ElementState(
|
539 |
+
element=element,
|
540 |
+
converted=ret,
|
541 |
+
parent=parent,
|
542 |
+
parent_index=index,
|
543 |
+
number=lookup.generate_index(),
|
544 |
+
)
|
545 |
+
if element.customName:
|
546 |
+
lookup[el_id].mark_for_extraction(el_id, lookup, element.customName)
|
547 |
+
|
548 |
+
i = 0
|
549 |
+
for expr in exprs:
|
550 |
+
# Add a placeholder index in case we have to extract the child before we even add it to the parent
|
551 |
+
if "items" in ret.kwargs:
|
552 |
+
ret.kwargs["items"].insert(i, None)
|
553 |
+
|
554 |
+
item = _to_diagram_element(
|
555 |
+
expr,
|
556 |
+
parent=ret,
|
557 |
+
lookup=lookup,
|
558 |
+
vertical=vertical,
|
559 |
+
index=i,
|
560 |
+
show_results_names=show_results_names,
|
561 |
+
)
|
562 |
+
|
563 |
+
# Some elements don't need to be shown in the diagram
|
564 |
+
if item is not None:
|
565 |
+
if "item" in ret.kwargs:
|
566 |
+
ret.kwargs["item"] = item
|
567 |
+
elif "items" in ret.kwargs:
|
568 |
+
# If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal
|
569 |
+
ret.kwargs["items"][i] = item
|
570 |
+
i += 1
|
571 |
+
elif "items" in ret.kwargs:
|
572 |
+
# If we're supposed to skip this element, remove it from the parent
|
573 |
+
del ret.kwargs["items"][i]
|
574 |
+
|
575 |
+
# If all this items children are none, skip this item
|
576 |
+
if ret and (
|
577 |
+
("items" in ret.kwargs and len(ret.kwargs["items"]) == 0)
|
578 |
+
or ("item" in ret.kwargs and ret.kwargs["item"] is None)
|
579 |
+
):
|
580 |
+
ret = EditablePartial.from_call(railroad.Terminal, name)
|
581 |
+
|
582 |
+
# Mark this element as "complete", ie it has all of its children
|
583 |
+
if el_id in lookup:
|
584 |
+
lookup[el_id].complete = True
|
585 |
+
|
586 |
+
if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete:
|
587 |
+
lookup.extract_into_diagram(el_id)
|
588 |
+
if ret is not None:
|
589 |
+
ret = EditablePartial.from_call(
|
590 |
+
railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"]
|
591 |
+
)
|
592 |
+
|
593 |
+
return ret
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/diagram/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (15.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/exceptions.py
ADDED
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# exceptions.py
|
2 |
+
|
3 |
+
import re
|
4 |
+
import sys
|
5 |
+
from typing import Optional
|
6 |
+
|
7 |
+
from .util import col, line, lineno, _collapse_string_to_ranges
|
8 |
+
from .unicode import pyparsing_unicode as ppu
|
9 |
+
|
10 |
+
|
11 |
+
class ExceptionWordUnicode(ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic):
|
12 |
+
pass
|
13 |
+
|
14 |
+
|
15 |
+
_extract_alphanums = _collapse_string_to_ranges(ExceptionWordUnicode.alphanums)
|
16 |
+
_exception_word_extractor = re.compile("([" + _extract_alphanums + "]{1,16})|.")
|
17 |
+
|
18 |
+
|
19 |
+
class ParseBaseException(Exception):
|
20 |
+
"""base exception class for all parsing runtime exceptions"""
|
21 |
+
|
22 |
+
# Performance tuning: we construct a *lot* of these, so keep this
|
23 |
+
# constructor as small and fast as possible
|
24 |
+
def __init__(
|
25 |
+
self,
|
26 |
+
pstr: str,
|
27 |
+
loc: int = 0,
|
28 |
+
msg: Optional[str] = None,
|
29 |
+
elem=None,
|
30 |
+
):
|
31 |
+
self.loc = loc
|
32 |
+
if msg is None:
|
33 |
+
self.msg = pstr
|
34 |
+
self.pstr = ""
|
35 |
+
else:
|
36 |
+
self.msg = msg
|
37 |
+
self.pstr = pstr
|
38 |
+
self.parser_element = self.parserElement = elem
|
39 |
+
self.args = (pstr, loc, msg)
|
40 |
+
|
41 |
+
@staticmethod
|
42 |
+
def explain_exception(exc, depth=16):
|
43 |
+
"""
|
44 |
+
Method to take an exception and translate the Python internal traceback into a list
|
45 |
+
of the pyparsing expressions that caused the exception to be raised.
|
46 |
+
|
47 |
+
Parameters:
|
48 |
+
|
49 |
+
- exc - exception raised during parsing (need not be a ParseException, in support
|
50 |
+
of Python exceptions that might be raised in a parse action)
|
51 |
+
- depth (default=16) - number of levels back in the stack trace to list expression
|
52 |
+
and function names; if None, the full stack trace names will be listed; if 0, only
|
53 |
+
the failing input line, marker, and exception string will be shown
|
54 |
+
|
55 |
+
Returns a multi-line string listing the ParserElements and/or function names in the
|
56 |
+
exception's stack trace.
|
57 |
+
"""
|
58 |
+
import inspect
|
59 |
+
from .core import ParserElement
|
60 |
+
|
61 |
+
if depth is None:
|
62 |
+
depth = sys.getrecursionlimit()
|
63 |
+
ret = []
|
64 |
+
if isinstance(exc, ParseBaseException):
|
65 |
+
ret.append(exc.line)
|
66 |
+
ret.append(" " * (exc.column - 1) + "^")
|
67 |
+
ret.append("{}: {}".format(type(exc).__name__, exc))
|
68 |
+
|
69 |
+
if depth > 0:
|
70 |
+
callers = inspect.getinnerframes(exc.__traceback__, context=depth)
|
71 |
+
seen = set()
|
72 |
+
for i, ff in enumerate(callers[-depth:]):
|
73 |
+
frm = ff[0]
|
74 |
+
|
75 |
+
f_self = frm.f_locals.get("self", None)
|
76 |
+
if isinstance(f_self, ParserElement):
|
77 |
+
if frm.f_code.co_name not in ("parseImpl", "_parseNoCache"):
|
78 |
+
continue
|
79 |
+
if id(f_self) in seen:
|
80 |
+
continue
|
81 |
+
seen.add(id(f_self))
|
82 |
+
|
83 |
+
self_type = type(f_self)
|
84 |
+
ret.append(
|
85 |
+
"{}.{} - {}".format(
|
86 |
+
self_type.__module__, self_type.__name__, f_self
|
87 |
+
)
|
88 |
+
)
|
89 |
+
|
90 |
+
elif f_self is not None:
|
91 |
+
self_type = type(f_self)
|
92 |
+
ret.append("{}.{}".format(self_type.__module__, self_type.__name__))
|
93 |
+
|
94 |
+
else:
|
95 |
+
code = frm.f_code
|
96 |
+
if code.co_name in ("wrapper", "<module>"):
|
97 |
+
continue
|
98 |
+
|
99 |
+
ret.append("{}".format(code.co_name))
|
100 |
+
|
101 |
+
depth -= 1
|
102 |
+
if not depth:
|
103 |
+
break
|
104 |
+
|
105 |
+
return "\n".join(ret)
|
106 |
+
|
107 |
+
@classmethod
|
108 |
+
def _from_exception(cls, pe):
|
109 |
+
"""
|
110 |
+
internal factory method to simplify creating one type of ParseException
|
111 |
+
from another - avoids having __init__ signature conflicts among subclasses
|
112 |
+
"""
|
113 |
+
return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
|
114 |
+
|
115 |
+
@property
|
116 |
+
def line(self) -> str:
|
117 |
+
"""
|
118 |
+
Return the line of text where the exception occurred.
|
119 |
+
"""
|
120 |
+
return line(self.loc, self.pstr)
|
121 |
+
|
122 |
+
@property
|
123 |
+
def lineno(self) -> int:
|
124 |
+
"""
|
125 |
+
Return the 1-based line number of text where the exception occurred.
|
126 |
+
"""
|
127 |
+
return lineno(self.loc, self.pstr)
|
128 |
+
|
129 |
+
@property
|
130 |
+
def col(self) -> int:
|
131 |
+
"""
|
132 |
+
Return the 1-based column on the line of text where the exception occurred.
|
133 |
+
"""
|
134 |
+
return col(self.loc, self.pstr)
|
135 |
+
|
136 |
+
@property
|
137 |
+
def column(self) -> int:
|
138 |
+
"""
|
139 |
+
Return the 1-based column on the line of text where the exception occurred.
|
140 |
+
"""
|
141 |
+
return col(self.loc, self.pstr)
|
142 |
+
|
143 |
+
def __str__(self) -> str:
|
144 |
+
if self.pstr:
|
145 |
+
if self.loc >= len(self.pstr):
|
146 |
+
foundstr = ", found end of text"
|
147 |
+
else:
|
148 |
+
# pull out next word at error location
|
149 |
+
found_match = _exception_word_extractor.match(self.pstr, self.loc)
|
150 |
+
if found_match is not None:
|
151 |
+
found = found_match.group(0)
|
152 |
+
else:
|
153 |
+
found = self.pstr[self.loc : self.loc + 1]
|
154 |
+
foundstr = (", found %r" % found).replace(r"\\", "\\")
|
155 |
+
else:
|
156 |
+
foundstr = ""
|
157 |
+
return "{}{} (at char {}), (line:{}, col:{})".format(
|
158 |
+
self.msg, foundstr, self.loc, self.lineno, self.column
|
159 |
+
)
|
160 |
+
|
161 |
+
def __repr__(self):
|
162 |
+
return str(self)
|
163 |
+
|
164 |
+
def mark_input_line(self, marker_string: str = None, *, markerString=">!<") -> str:
|
165 |
+
"""
|
166 |
+
Extracts the exception line from the input string, and marks
|
167 |
+
the location of the exception with a special symbol.
|
168 |
+
"""
|
169 |
+
markerString = marker_string if marker_string is not None else markerString
|
170 |
+
line_str = self.line
|
171 |
+
line_column = self.column - 1
|
172 |
+
if markerString:
|
173 |
+
line_str = "".join(
|
174 |
+
(line_str[:line_column], markerString, line_str[line_column:])
|
175 |
+
)
|
176 |
+
return line_str.strip()
|
177 |
+
|
178 |
+
def explain(self, depth=16) -> str:
|
179 |
+
"""
|
180 |
+
Method to translate the Python internal traceback into a list
|
181 |
+
of the pyparsing expressions that caused the exception to be raised.
|
182 |
+
|
183 |
+
Parameters:
|
184 |
+
|
185 |
+
- depth (default=16) - number of levels back in the stack trace to list expression
|
186 |
+
and function names; if None, the full stack trace names will be listed; if 0, only
|
187 |
+
the failing input line, marker, and exception string will be shown
|
188 |
+
|
189 |
+
Returns a multi-line string listing the ParserElements and/or function names in the
|
190 |
+
exception's stack trace.
|
191 |
+
|
192 |
+
Example::
|
193 |
+
|
194 |
+
expr = pp.Word(pp.nums) * 3
|
195 |
+
try:
|
196 |
+
expr.parse_string("123 456 A789")
|
197 |
+
except pp.ParseException as pe:
|
198 |
+
print(pe.explain(depth=0))
|
199 |
+
|
200 |
+
prints::
|
201 |
+
|
202 |
+
123 456 A789
|
203 |
+
^
|
204 |
+
ParseException: Expected W:(0-9), found 'A' (at char 8), (line:1, col:9)
|
205 |
+
|
206 |
+
Note: the diagnostic output will include string representations of the expressions
|
207 |
+
that failed to parse. These representations will be more helpful if you use `set_name` to
|
208 |
+
give identifiable names to your expressions. Otherwise they will use the default string
|
209 |
+
forms, which may be cryptic to read.
|
210 |
+
|
211 |
+
Note: pyparsing's default truncation of exception tracebacks may also truncate the
|
212 |
+
stack of expressions that are displayed in the ``explain`` output. To get the full listing
|
213 |
+
of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True``
|
214 |
+
"""
|
215 |
+
return self.explain_exception(self, depth)
|
216 |
+
|
217 |
+
markInputline = mark_input_line
|
218 |
+
|
219 |
+
|
220 |
+
class ParseException(ParseBaseException):
|
221 |
+
"""
|
222 |
+
Exception thrown when a parse expression doesn't match the input string
|
223 |
+
|
224 |
+
Example::
|
225 |
+
|
226 |
+
try:
|
227 |
+
Word(nums).set_name("integer").parse_string("ABC")
|
228 |
+
except ParseException as pe:
|
229 |
+
print(pe)
|
230 |
+
print("column: {}".format(pe.column))
|
231 |
+
|
232 |
+
prints::
|
233 |
+
|
234 |
+
Expected integer (at char 0), (line:1, col:1)
|
235 |
+
column: 1
|
236 |
+
|
237 |
+
"""
|
238 |
+
|
239 |
+
|
240 |
+
class ParseFatalException(ParseBaseException):
|
241 |
+
"""
|
242 |
+
User-throwable exception thrown when inconsistent parse content
|
243 |
+
is found; stops all parsing immediately
|
244 |
+
"""
|
245 |
+
|
246 |
+
|
247 |
+
class ParseSyntaxException(ParseFatalException):
|
248 |
+
"""
|
249 |
+
Just like :class:`ParseFatalException`, but thrown internally
|
250 |
+
when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates
|
251 |
+
that parsing is to stop immediately because an unbacktrackable
|
252 |
+
syntax error has been found.
|
253 |
+
"""
|
254 |
+
|
255 |
+
|
256 |
+
class RecursiveGrammarException(Exception):
|
257 |
+
"""
|
258 |
+
Exception thrown by :class:`ParserElement.validate` if the
|
259 |
+
grammar could be left-recursive; parser may need to enable
|
260 |
+
left recursion using :class:`ParserElement.enable_left_recursion<ParserElement.enable_left_recursion>`
|
261 |
+
"""
|
262 |
+
|
263 |
+
def __init__(self, parseElementList):
|
264 |
+
self.parseElementTrace = parseElementList
|
265 |
+
|
266 |
+
def __str__(self) -> str:
|
267 |
+
return "RecursiveGrammarException: {}".format(self.parseElementTrace)
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/helpers.py
ADDED
@@ -0,0 +1,1069 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# helpers.py
|
2 |
+
import html.entities
|
3 |
+
import re
|
4 |
+
|
5 |
+
from . import __diag__
|
6 |
+
from .core import *
|
7 |
+
from .util import _bslash, _flatten, _escape_regex_range_chars
|
8 |
+
|
9 |
+
|
10 |
+
#
|
11 |
+
# global helpers
|
12 |
+
#
|
13 |
+
def delimited_list(
|
14 |
+
expr: Union[str, ParserElement],
|
15 |
+
delim: Union[str, ParserElement] = ",",
|
16 |
+
combine: bool = False,
|
17 |
+
min: OptionalType[int] = None,
|
18 |
+
max: OptionalType[int] = None,
|
19 |
+
*,
|
20 |
+
allow_trailing_delim: bool = False,
|
21 |
+
) -> ParserElement:
|
22 |
+
"""Helper to define a delimited list of expressions - the delimiter
|
23 |
+
defaults to ','. By default, the list elements and delimiters can
|
24 |
+
have intervening whitespace, and comments, but this can be
|
25 |
+
overridden by passing ``combine=True`` in the constructor. If
|
26 |
+
``combine`` is set to ``True``, the matching tokens are
|
27 |
+
returned as a single token string, with the delimiters included;
|
28 |
+
otherwise, the matching tokens are returned as a list of tokens,
|
29 |
+
with the delimiters suppressed.
|
30 |
+
|
31 |
+
If ``allow_trailing_delim`` is set to True, then the list may end with
|
32 |
+
a delimiter.
|
33 |
+
|
34 |
+
Example::
|
35 |
+
|
36 |
+
delimited_list(Word(alphas)).parse_string("aa,bb,cc") # -> ['aa', 'bb', 'cc']
|
37 |
+
delimited_list(Word(hexnums), delim=':', combine=True).parse_string("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
|
38 |
+
"""
|
39 |
+
if isinstance(expr, str_type):
|
40 |
+
expr = ParserElement._literalStringClass(expr)
|
41 |
+
|
42 |
+
dlName = "{expr} [{delim} {expr}]...{end}".format(
|
43 |
+
expr=str(expr.copy().streamline()),
|
44 |
+
delim=str(delim),
|
45 |
+
end=" [{}]".format(str(delim)) if allow_trailing_delim else "",
|
46 |
+
)
|
47 |
+
|
48 |
+
if not combine:
|
49 |
+
delim = Suppress(delim)
|
50 |
+
|
51 |
+
if min is not None:
|
52 |
+
if min < 1:
|
53 |
+
raise ValueError("min must be greater than 0")
|
54 |
+
min -= 1
|
55 |
+
if max is not None:
|
56 |
+
if min is not None and max <= min:
|
57 |
+
raise ValueError("max must be greater than, or equal to min")
|
58 |
+
max -= 1
|
59 |
+
delimited_list_expr = expr + (delim + expr)[min, max]
|
60 |
+
|
61 |
+
if allow_trailing_delim:
|
62 |
+
delimited_list_expr += Opt(delim)
|
63 |
+
|
64 |
+
if combine:
|
65 |
+
return Combine(delimited_list_expr).set_name(dlName)
|
66 |
+
else:
|
67 |
+
return delimited_list_expr.set_name(dlName)
|
68 |
+
|
69 |
+
|
70 |
+
def counted_array(
|
71 |
+
expr: ParserElement,
|
72 |
+
int_expr: OptionalType[ParserElement] = None,
|
73 |
+
*,
|
74 |
+
intExpr: OptionalType[ParserElement] = None,
|
75 |
+
) -> ParserElement:
|
76 |
+
"""Helper to define a counted list of expressions.
|
77 |
+
|
78 |
+
This helper defines a pattern of the form::
|
79 |
+
|
80 |
+
integer expr expr expr...
|
81 |
+
|
82 |
+
where the leading integer tells how many expr expressions follow.
|
83 |
+
The matched tokens returns the array of expr tokens as a list - the
|
84 |
+
leading count token is suppressed.
|
85 |
+
|
86 |
+
If ``int_expr`` is specified, it should be a pyparsing expression
|
87 |
+
that produces an integer value.
|
88 |
+
|
89 |
+
Example::
|
90 |
+
|
91 |
+
counted_array(Word(alphas)).parse_string('2 ab cd ef') # -> ['ab', 'cd']
|
92 |
+
|
93 |
+
# in this parser, the leading integer value is given in binary,
|
94 |
+
# '10' indicating that 2 values are in the array
|
95 |
+
binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2))
|
96 |
+
counted_array(Word(alphas), int_expr=binary_constant).parse_string('10 ab cd ef') # -> ['ab', 'cd']
|
97 |
+
|
98 |
+
# if other fields must be parsed after the count but before the
|
99 |
+
# list items, give the fields results names and they will
|
100 |
+
# be preserved in the returned ParseResults:
|
101 |
+
count_with_metadata = integer + Word(alphas)("type")
|
102 |
+
typed_array = counted_array(Word(alphanums), int_expr=count_with_metadata)("items")
|
103 |
+
result = typed_array.parse_string("3 bool True True False")
|
104 |
+
print(result.dump())
|
105 |
+
|
106 |
+
# prints
|
107 |
+
# ['True', 'True', 'False']
|
108 |
+
# - items: ['True', 'True', 'False']
|
109 |
+
# - type: 'bool'
|
110 |
+
"""
|
111 |
+
intExpr = intExpr or int_expr
|
112 |
+
array_expr = Forward()
|
113 |
+
|
114 |
+
def count_field_parse_action(s, l, t):
|
115 |
+
nonlocal array_expr
|
116 |
+
n = t[0]
|
117 |
+
array_expr <<= (expr * n) if n else Empty()
|
118 |
+
# clear list contents, but keep any named results
|
119 |
+
del t[:]
|
120 |
+
|
121 |
+
if intExpr is None:
|
122 |
+
intExpr = Word(nums).set_parse_action(lambda t: int(t[0]))
|
123 |
+
else:
|
124 |
+
intExpr = intExpr.copy()
|
125 |
+
intExpr.set_name("arrayLen")
|
126 |
+
intExpr.add_parse_action(count_field_parse_action, call_during_try=True)
|
127 |
+
return (intExpr + array_expr).set_name("(len) " + str(expr) + "...")
|
128 |
+
|
129 |
+
|
130 |
+
def match_previous_literal(expr: ParserElement) -> ParserElement:
|
131 |
+
"""Helper to define an expression that is indirectly defined from
|
132 |
+
the tokens matched in a previous expression, that is, it looks for
|
133 |
+
a 'repeat' of a previous expression. For example::
|
134 |
+
|
135 |
+
first = Word(nums)
|
136 |
+
second = match_previous_literal(first)
|
137 |
+
match_expr = first + ":" + second
|
138 |
+
|
139 |
+
will match ``"1:1"``, but not ``"1:2"``. Because this
|
140 |
+
matches a previous literal, will also match the leading
|
141 |
+
``"1:1"`` in ``"1:10"``. If this is not desired, use
|
142 |
+
:class:`match_previous_expr`. Do *not* use with packrat parsing
|
143 |
+
enabled.
|
144 |
+
"""
|
145 |
+
rep = Forward()
|
146 |
+
|
147 |
+
def copy_token_to_repeater(s, l, t):
|
148 |
+
if t:
|
149 |
+
if len(t) == 1:
|
150 |
+
rep << t[0]
|
151 |
+
else:
|
152 |
+
# flatten t tokens
|
153 |
+
tflat = _flatten(t.as_list())
|
154 |
+
rep << And(Literal(tt) for tt in tflat)
|
155 |
+
else:
|
156 |
+
rep << Empty()
|
157 |
+
|
158 |
+
expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)
|
159 |
+
rep.set_name("(prev) " + str(expr))
|
160 |
+
return rep
|
161 |
+
|
162 |
+
|
163 |
+
def match_previous_expr(expr: ParserElement) -> ParserElement:
|
164 |
+
"""Helper to define an expression that is indirectly defined from
|
165 |
+
the tokens matched in a previous expression, that is, it looks for
|
166 |
+
a 'repeat' of a previous expression. For example::
|
167 |
+
|
168 |
+
first = Word(nums)
|
169 |
+
second = match_previous_expr(first)
|
170 |
+
match_expr = first + ":" + second
|
171 |
+
|
172 |
+
will match ``"1:1"``, but not ``"1:2"``. Because this
|
173 |
+
matches by expressions, will *not* match the leading ``"1:1"``
|
174 |
+
in ``"1:10"``; the expressions are evaluated first, and then
|
175 |
+
compared, so ``"1"`` is compared with ``"10"``. Do *not* use
|
176 |
+
with packrat parsing enabled.
|
177 |
+
"""
|
178 |
+
rep = Forward()
|
179 |
+
e2 = expr.copy()
|
180 |
+
rep <<= e2
|
181 |
+
|
182 |
+
def copy_token_to_repeater(s, l, t):
|
183 |
+
matchTokens = _flatten(t.as_list())
|
184 |
+
|
185 |
+
def must_match_these_tokens(s, l, t):
|
186 |
+
theseTokens = _flatten(t.as_list())
|
187 |
+
if theseTokens != matchTokens:
|
188 |
+
raise ParseException(s, l, "Expected {}, found{}".format(matchTokens, theseTokens))
|
189 |
+
|
190 |
+
rep.set_parse_action(must_match_these_tokens, callDuringTry=True)
|
191 |
+
|
192 |
+
expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)
|
193 |
+
rep.set_name("(prev) " + str(expr))
|
194 |
+
return rep
|
195 |
+
|
196 |
+
|
197 |
+
def one_of(
|
198 |
+
strs: Union[IterableType[str], str],
|
199 |
+
caseless: bool = False,
|
200 |
+
use_regex: bool = True,
|
201 |
+
as_keyword: bool = False,
|
202 |
+
*,
|
203 |
+
useRegex: bool = True,
|
204 |
+
asKeyword: bool = False,
|
205 |
+
) -> ParserElement:
|
206 |
+
"""Helper to quickly define a set of alternative :class:`Literal` s,
|
207 |
+
and makes sure to do longest-first testing when there is a conflict,
|
208 |
+
regardless of the input order, but returns
|
209 |
+
a :class:`MatchFirst` for best performance.
|
210 |
+
|
211 |
+
Parameters:
|
212 |
+
|
213 |
+
- ``strs`` - a string of space-delimited literals, or a collection of
|
214 |
+
string literals
|
215 |
+
- ``caseless`` - treat all literals as caseless - (default= ``False``)
|
216 |
+
- ``use_regex`` - as an optimization, will
|
217 |
+
generate a :class:`Regex` object; otherwise, will generate
|
218 |
+
a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if
|
219 |
+
creating a :class:`Regex` raises an exception) - (default= ``True``)
|
220 |
+
- ``as_keyword`` - enforce :class:`Keyword`-style matching on the
|
221 |
+
generated expressions - (default= ``False``)
|
222 |
+
- ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 compatibility,
|
223 |
+
but will be removed in a future release
|
224 |
+
|
225 |
+
Example::
|
226 |
+
|
227 |
+
comp_oper = one_of("< = > <= >= !=")
|
228 |
+
var = Word(alphas)
|
229 |
+
number = Word(nums)
|
230 |
+
term = var | number
|
231 |
+
comparison_expr = term + comp_oper + term
|
232 |
+
print(comparison_expr.search_string("B = 12 AA=23 B<=AA AA>12"))
|
233 |
+
|
234 |
+
prints::
|
235 |
+
|
236 |
+
[['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]
|
237 |
+
"""
|
238 |
+
asKeyword = asKeyword or as_keyword
|
239 |
+
useRegex = useRegex and use_regex
|
240 |
+
|
241 |
+
if (
|
242 |
+
isinstance(caseless, str_type)
|
243 |
+
and __diag__.warn_on_multiple_string_args_to_oneof
|
244 |
+
):
|
245 |
+
warnings.warn(
|
246 |
+
"More than one string argument passed to one_of, pass"
|
247 |
+
" choices as a list or space-delimited string",
|
248 |
+
stacklevel=2,
|
249 |
+
)
|
250 |
+
|
251 |
+
if caseless:
|
252 |
+
isequal = lambda a, b: a.upper() == b.upper()
|
253 |
+
masks = lambda a, b: b.upper().startswith(a.upper())
|
254 |
+
parseElementClass = CaselessKeyword if asKeyword else CaselessLiteral
|
255 |
+
else:
|
256 |
+
isequal = lambda a, b: a == b
|
257 |
+
masks = lambda a, b: b.startswith(a)
|
258 |
+
parseElementClass = Keyword if asKeyword else Literal
|
259 |
+
|
260 |
+
symbols: List[str] = []
|
261 |
+
if isinstance(strs, str_type):
|
262 |
+
symbols = strs.split()
|
263 |
+
elif isinstance(strs, Iterable):
|
264 |
+
symbols = list(strs)
|
265 |
+
else:
|
266 |
+
raise TypeError("Invalid argument to one_of, expected string or iterable")
|
267 |
+
if not symbols:
|
268 |
+
return NoMatch()
|
269 |
+
|
270 |
+
# reorder given symbols to take care to avoid masking longer choices with shorter ones
|
271 |
+
# (but only if the given symbols are not just single characters)
|
272 |
+
if any(len(sym) > 1 for sym in symbols):
|
273 |
+
i = 0
|
274 |
+
while i < len(symbols) - 1:
|
275 |
+
cur = symbols[i]
|
276 |
+
for j, other in enumerate(symbols[i + 1 :]):
|
277 |
+
if isequal(other, cur):
|
278 |
+
del symbols[i + j + 1]
|
279 |
+
break
|
280 |
+
elif masks(cur, other):
|
281 |
+
del symbols[i + j + 1]
|
282 |
+
symbols.insert(i, other)
|
283 |
+
break
|
284 |
+
else:
|
285 |
+
i += 1
|
286 |
+
|
287 |
+
if useRegex:
|
288 |
+
re_flags: int = re.IGNORECASE if caseless else 0
|
289 |
+
|
290 |
+
try:
|
291 |
+
if all(len(sym) == 1 for sym in symbols):
|
292 |
+
# symbols are just single characters, create range regex pattern
|
293 |
+
patt = "[{}]".format(
|
294 |
+
"".join(_escape_regex_range_chars(sym) for sym in symbols)
|
295 |
+
)
|
296 |
+
else:
|
297 |
+
patt = "|".join(re.escape(sym) for sym in symbols)
|
298 |
+
|
299 |
+
# wrap with \b word break markers if defining as keywords
|
300 |
+
if asKeyword:
|
301 |
+
patt = r"\b(?:{})\b".format(patt)
|
302 |
+
|
303 |
+
ret = Regex(patt, flags=re_flags).set_name(" | ".join(symbols))
|
304 |
+
|
305 |
+
if caseless:
|
306 |
+
# add parse action to return symbols as specified, not in random
|
307 |
+
# casing as found in input string
|
308 |
+
symbol_map = {sym.lower(): sym for sym in symbols}
|
309 |
+
ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()])
|
310 |
+
|
311 |
+
return ret
|
312 |
+
|
313 |
+
except sre_constants.error:
|
314 |
+
warnings.warn(
|
315 |
+
"Exception creating Regex for one_of, building MatchFirst", stacklevel=2
|
316 |
+
)
|
317 |
+
|
318 |
+
# last resort, just use MatchFirst
|
319 |
+
return MatchFirst(parseElementClass(sym) for sym in symbols).set_name(
|
320 |
+
" | ".join(symbols)
|
321 |
+
)
|
322 |
+
|
323 |
+
|
324 |
+
def dict_of(key: ParserElement, value: ParserElement) -> ParserElement:
|
325 |
+
"""Helper to easily and clearly define a dictionary by specifying
|
326 |
+
the respective patterns for the key and value. Takes care of
|
327 |
+
defining the :class:`Dict`, :class:`ZeroOrMore`, and
|
328 |
+
:class:`Group` tokens in the proper order. The key pattern
|
329 |
+
can include delimiting markers or punctuation, as long as they are
|
330 |
+
suppressed, thereby leaving the significant key text. The value
|
331 |
+
pattern can include named results, so that the :class:`Dict` results
|
332 |
+
can include named token fields.
|
333 |
+
|
334 |
+
Example::
|
335 |
+
|
336 |
+
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
|
337 |
+
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))
|
338 |
+
print(OneOrMore(attr_expr).parse_string(text).dump())
|
339 |
+
|
340 |
+
attr_label = label
|
341 |
+
attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)
|
342 |
+
|
343 |
+
# similar to Dict, but simpler call format
|
344 |
+
result = dict_of(attr_label, attr_value).parse_string(text)
|
345 |
+
print(result.dump())
|
346 |
+
print(result['shape'])
|
347 |
+
print(result.shape) # object attribute access works too
|
348 |
+
print(result.as_dict())
|
349 |
+
|
350 |
+
prints::
|
351 |
+
|
352 |
+
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
|
353 |
+
- color: light blue
|
354 |
+
- posn: upper left
|
355 |
+
- shape: SQUARE
|
356 |
+
- texture: burlap
|
357 |
+
SQUARE
|
358 |
+
SQUARE
|
359 |
+
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
|
360 |
+
"""
|
361 |
+
return Dict(OneOrMore(Group(key + value)))
|
362 |
+
|
363 |
+
|
364 |
+
def original_text_for(
|
365 |
+
expr: ParserElement, as_string: bool = True, *, asString: bool = True
|
366 |
+
) -> ParserElement:
|
367 |
+
"""Helper to return the original, untokenized text for a given
|
368 |
+
expression. Useful to restore the parsed fields of an HTML start
|
369 |
+
tag into the raw tag text itself, or to revert separate tokens with
|
370 |
+
intervening whitespace back to the original matching input text. By
|
371 |
+
default, returns astring containing the original parsed text.
|
372 |
+
|
373 |
+
If the optional ``as_string`` argument is passed as
|
374 |
+
``False``, then the return value is
|
375 |
+
a :class:`ParseResults` containing any results names that
|
376 |
+
were originally matched, and a single token containing the original
|
377 |
+
matched text from the input string. So if the expression passed to
|
378 |
+
:class:`original_text_for` contains expressions with defined
|
379 |
+
results names, you must set ``as_string`` to ``False`` if you
|
380 |
+
want to preserve those results name values.
|
381 |
+
|
382 |
+
The ``asString`` pre-PEP8 argument is retained for compatibility,
|
383 |
+
but will be removed in a future release.
|
384 |
+
|
385 |
+
Example::
|
386 |
+
|
387 |
+
src = "this is test <b> bold <i>text</i> </b> normal text "
|
388 |
+
for tag in ("b", "i"):
|
389 |
+
opener, closer = make_html_tags(tag)
|
390 |
+
patt = original_text_for(opener + SkipTo(closer) + closer)
|
391 |
+
print(patt.search_string(src)[0])
|
392 |
+
|
393 |
+
prints::
|
394 |
+
|
395 |
+
['<b> bold <i>text</i> </b>']
|
396 |
+
['<i>text</i>']
|
397 |
+
"""
|
398 |
+
asString = asString and as_string
|
399 |
+
|
400 |
+
locMarker = Empty().set_parse_action(lambda s, loc, t: loc)
|
401 |
+
endlocMarker = locMarker.copy()
|
402 |
+
endlocMarker.callPreparse = False
|
403 |
+
matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
|
404 |
+
if asString:
|
405 |
+
extractText = lambda s, l, t: s[t._original_start : t._original_end]
|
406 |
+
else:
|
407 |
+
|
408 |
+
def extractText(s, l, t):
|
409 |
+
t[:] = [s[t.pop("_original_start") : t.pop("_original_end")]]
|
410 |
+
|
411 |
+
matchExpr.set_parse_action(extractText)
|
412 |
+
matchExpr.ignoreExprs = expr.ignoreExprs
|
413 |
+
matchExpr.suppress_warning(Diagnostics.warn_ungrouped_named_tokens_in_collection)
|
414 |
+
return matchExpr
|
415 |
+
|
416 |
+
|
417 |
+
def ungroup(expr: ParserElement) -> ParserElement:
|
418 |
+
"""Helper to undo pyparsing's default grouping of And expressions,
|
419 |
+
even if all but one are non-empty.
|
420 |
+
"""
|
421 |
+
return TokenConverter(expr).add_parse_action(lambda t: t[0])
|
422 |
+
|
423 |
+
|
424 |
+
def locatedExpr(expr: ParserElement) -> ParserElement:
|
425 |
+
"""
|
426 |
+
(DEPRECATED - future code should use the Located class)
|
427 |
+
Helper to decorate a returned token with its starting and ending
|
428 |
+
locations in the input string.
|
429 |
+
|
430 |
+
This helper adds the following results names:
|
431 |
+
|
432 |
+
- ``locn_start`` - location where matched expression begins
|
433 |
+
- ``locn_end`` - location where matched expression ends
|
434 |
+
- ``value`` - the actual parsed results
|
435 |
+
|
436 |
+
Be careful if the input text contains ``<TAB>`` characters, you
|
437 |
+
may want to call :class:`ParserElement.parseWithTabs`
|
438 |
+
|
439 |
+
Example::
|
440 |
+
|
441 |
+
wd = Word(alphas)
|
442 |
+
for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
|
443 |
+
print(match)
|
444 |
+
|
445 |
+
prints::
|
446 |
+
|
447 |
+
[[0, 'ljsdf', 5]]
|
448 |
+
[[8, 'lksdjjf', 15]]
|
449 |
+
[[18, 'lkkjj', 23]]
|
450 |
+
"""
|
451 |
+
locator = Empty().set_parse_action(lambda ss, ll, tt: ll)
|
452 |
+
return Group(
|
453 |
+
locator("locn_start")
|
454 |
+
+ expr("value")
|
455 |
+
+ locator.copy().leaveWhitespace()("locn_end")
|
456 |
+
)
|
457 |
+
|
458 |
+
|
459 |
+
def nested_expr(
|
460 |
+
opener: Union[str, ParserElement] = "(",
|
461 |
+
closer: Union[str, ParserElement] = ")",
|
462 |
+
content: OptionalType[ParserElement] = None,
|
463 |
+
ignore_expr: ParserElement = quoted_string(),
|
464 |
+
*,
|
465 |
+
ignoreExpr: ParserElement = quoted_string(),
|
466 |
+
) -> ParserElement:
|
467 |
+
"""Helper method for defining nested lists enclosed in opening and
|
468 |
+
closing delimiters (``"("`` and ``")"`` are the default).
|
469 |
+
|
470 |
+
Parameters:
|
471 |
+
- ``opener`` - opening character for a nested list
|
472 |
+
(default= ``"("``); can also be a pyparsing expression
|
473 |
+
- ``closer`` - closing character for a nested list
|
474 |
+
(default= ``")"``); can also be a pyparsing expression
|
475 |
+
- ``content`` - expression for items within the nested lists
|
476 |
+
(default= ``None``)
|
477 |
+
- ``ignore_expr`` - expression for ignoring opening and closing delimiters
|
478 |
+
(default= :class:`quoted_string`)
|
479 |
+
- ``ignoreExpr`` - this pre-PEP8 argument is retained for compatibility
|
480 |
+
but will be removed in a future release
|
481 |
+
|
482 |
+
If an expression is not provided for the content argument, the
|
483 |
+
nested expression will capture all whitespace-delimited content
|
484 |
+
between delimiters as a list of separate values.
|
485 |
+
|
486 |
+
Use the ``ignore_expr`` argument to define expressions that may
|
487 |
+
contain opening or closing characters that should not be treated as
|
488 |
+
opening or closing characters for nesting, such as quoted_string or
|
489 |
+
a comment expression. Specify multiple expressions using an
|
490 |
+
:class:`Or` or :class:`MatchFirst`. The default is
|
491 |
+
:class:`quoted_string`, but if no expressions are to be ignored, then
|
492 |
+
pass ``None`` for this argument.
|
493 |
+
|
494 |
+
Example::
|
495 |
+
|
496 |
+
data_type = one_of("void int short long char float double")
|
497 |
+
decl_data_type = Combine(data_type + Opt(Word('*')))
|
498 |
+
ident = Word(alphas+'_', alphanums+'_')
|
499 |
+
number = pyparsing_common.number
|
500 |
+
arg = Group(decl_data_type + ident)
|
501 |
+
LPAR, RPAR = map(Suppress, "()")
|
502 |
+
|
503 |
+
code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment))
|
504 |
+
|
505 |
+
c_function = (decl_data_type("type")
|
506 |
+
+ ident("name")
|
507 |
+
+ LPAR + Opt(delimited_list(arg), [])("args") + RPAR
|
508 |
+
+ code_body("body"))
|
509 |
+
c_function.ignore(c_style_comment)
|
510 |
+
|
511 |
+
source_code = '''
|
512 |
+
int is_odd(int x) {
|
513 |
+
return (x%2);
|
514 |
+
}
|
515 |
+
|
516 |
+
int dec_to_hex(char hchar) {
|
517 |
+
if (hchar >= '0' && hchar <= '9') {
|
518 |
+
return (ord(hchar)-ord('0'));
|
519 |
+
} else {
|
520 |
+
return (10+ord(hchar)-ord('A'));
|
521 |
+
}
|
522 |
+
}
|
523 |
+
'''
|
524 |
+
for func in c_function.search_string(source_code):
|
525 |
+
print("%(name)s (%(type)s) args: %(args)s" % func)
|
526 |
+
|
527 |
+
|
528 |
+
prints::
|
529 |
+
|
530 |
+
is_odd (int) args: [['int', 'x']]
|
531 |
+
dec_to_hex (int) args: [['char', 'hchar']]
|
532 |
+
"""
|
533 |
+
if ignoreExpr != ignore_expr:
|
534 |
+
ignoreExpr = ignore_expr if ignoreExpr == quoted_string() else ignoreExpr
|
535 |
+
if opener == closer:
|
536 |
+
raise ValueError("opening and closing strings cannot be the same")
|
537 |
+
if content is None:
|
538 |
+
if isinstance(opener, str_type) and isinstance(closer, str_type):
|
539 |
+
if len(opener) == 1 and len(closer) == 1:
|
540 |
+
if ignoreExpr is not None:
|
541 |
+
content = Combine(
|
542 |
+
OneOrMore(
|
543 |
+
~ignoreExpr
|
544 |
+
+ CharsNotIn(
|
545 |
+
opener + closer + ParserElement.DEFAULT_WHITE_CHARS,
|
546 |
+
exact=1,
|
547 |
+
)
|
548 |
+
)
|
549 |
+
).set_parse_action(lambda t: t[0].strip())
|
550 |
+
else:
|
551 |
+
content = empty.copy() + CharsNotIn(
|
552 |
+
opener + closer + ParserElement.DEFAULT_WHITE_CHARS
|
553 |
+
).set_parse_action(lambda t: t[0].strip())
|
554 |
+
else:
|
555 |
+
if ignoreExpr is not None:
|
556 |
+
content = Combine(
|
557 |
+
OneOrMore(
|
558 |
+
~ignoreExpr
|
559 |
+
+ ~Literal(opener)
|
560 |
+
+ ~Literal(closer)
|
561 |
+
+ CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)
|
562 |
+
)
|
563 |
+
).set_parse_action(lambda t: t[0].strip())
|
564 |
+
else:
|
565 |
+
content = Combine(
|
566 |
+
OneOrMore(
|
567 |
+
~Literal(opener)
|
568 |
+
+ ~Literal(closer)
|
569 |
+
+ CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)
|
570 |
+
)
|
571 |
+
).set_parse_action(lambda t: t[0].strip())
|
572 |
+
else:
|
573 |
+
raise ValueError(
|
574 |
+
"opening and closing arguments must be strings if no content expression is given"
|
575 |
+
)
|
576 |
+
ret = Forward()
|
577 |
+
if ignoreExpr is not None:
|
578 |
+
ret <<= Group(
|
579 |
+
Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer)
|
580 |
+
)
|
581 |
+
else:
|
582 |
+
ret <<= Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer))
|
583 |
+
ret.set_name("nested %s%s expression" % (opener, closer))
|
584 |
+
return ret
|
585 |
+
|
586 |
+
|
587 |
+
def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")):
|
588 |
+
"""Internal helper to construct opening and closing tag expressions, given a tag name"""
|
589 |
+
if isinstance(tagStr, str_type):
|
590 |
+
resname = tagStr
|
591 |
+
tagStr = Keyword(tagStr, caseless=not xml)
|
592 |
+
else:
|
593 |
+
resname = tagStr.name
|
594 |
+
|
595 |
+
tagAttrName = Word(alphas, alphanums + "_-:")
|
596 |
+
if xml:
|
597 |
+
tagAttrValue = dbl_quoted_string.copy().set_parse_action(remove_quotes)
|
598 |
+
openTag = (
|
599 |
+
suppress_LT
|
600 |
+
+ tagStr("tag")
|
601 |
+
+ Dict(ZeroOrMore(Group(tagAttrName + Suppress("=") + tagAttrValue)))
|
602 |
+
+ Opt("/", default=[False])("empty").set_parse_action(
|
603 |
+
lambda s, l, t: t[0] == "/"
|
604 |
+
)
|
605 |
+
+ suppress_GT
|
606 |
+
)
|
607 |
+
else:
|
608 |
+
tagAttrValue = quoted_string.copy().set_parse_action(remove_quotes) | Word(
|
609 |
+
printables, exclude_chars=">"
|
610 |
+
)
|
611 |
+
openTag = (
|
612 |
+
suppress_LT
|
613 |
+
+ tagStr("tag")
|
614 |
+
+ Dict(
|
615 |
+
ZeroOrMore(
|
616 |
+
Group(
|
617 |
+
tagAttrName.set_parse_action(lambda t: t[0].lower())
|
618 |
+
+ Opt(Suppress("=") + tagAttrValue)
|
619 |
+
)
|
620 |
+
)
|
621 |
+
)
|
622 |
+
+ Opt("/", default=[False])("empty").set_parse_action(
|
623 |
+
lambda s, l, t: t[0] == "/"
|
624 |
+
)
|
625 |
+
+ suppress_GT
|
626 |
+
)
|
627 |
+
closeTag = Combine(Literal("</") + tagStr + ">", adjacent=False)
|
628 |
+
|
629 |
+
openTag.set_name("<%s>" % resname)
|
630 |
+
# add start<tagname> results name in parse action now that ungrouped names are not reported at two levels
|
631 |
+
openTag.add_parse_action(
|
632 |
+
lambda t: t.__setitem__(
|
633 |
+
"start" + "".join(resname.replace(":", " ").title().split()), t.copy()
|
634 |
+
)
|
635 |
+
)
|
636 |
+
closeTag = closeTag(
|
637 |
+
"end" + "".join(resname.replace(":", " ").title().split())
|
638 |
+
).set_name("</%s>" % resname)
|
639 |
+
openTag.tag = resname
|
640 |
+
closeTag.tag = resname
|
641 |
+
openTag.tag_body = SkipTo(closeTag())
|
642 |
+
return openTag, closeTag
|
643 |
+
|
644 |
+
|
645 |
+
def make_html_tags(
|
646 |
+
tag_str: Union[str, ParserElement]
|
647 |
+
) -> Tuple[ParserElement, ParserElement]:
|
648 |
+
"""Helper to construct opening and closing tag expressions for HTML,
|
649 |
+
given a tag name. Matches tags in either upper or lower case,
|
650 |
+
attributes with namespaces and with quoted or unquoted values.
|
651 |
+
|
652 |
+
Example::
|
653 |
+
|
654 |
+
text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>'
|
655 |
+
# make_html_tags returns pyparsing expressions for the opening and
|
656 |
+
# closing tags as a 2-tuple
|
657 |
+
a, a_end = make_html_tags("A")
|
658 |
+
link_expr = a + SkipTo(a_end)("link_text") + a_end
|
659 |
+
|
660 |
+
for link in link_expr.search_string(text):
|
661 |
+
# attributes in the <A> tag (like "href" shown here) are
|
662 |
+
# also accessible as named results
|
663 |
+
print(link.link_text, '->', link.href)
|
664 |
+
|
665 |
+
prints::
|
666 |
+
|
667 |
+
pyparsing -> https://github.com/pyparsing/pyparsing/wiki
|
668 |
+
"""
|
669 |
+
return _makeTags(tag_str, False)
|
670 |
+
|
671 |
+
|
672 |
+
def make_xml_tags(
|
673 |
+
tag_str: Union[str, ParserElement]
|
674 |
+
) -> Tuple[ParserElement, ParserElement]:
|
675 |
+
"""Helper to construct opening and closing tag expressions for XML,
|
676 |
+
given a tag name. Matches tags only in the given upper/lower case.
|
677 |
+
|
678 |
+
Example: similar to :class:`make_html_tags`
|
679 |
+
"""
|
680 |
+
return _makeTags(tag_str, True)
|
681 |
+
|
682 |
+
|
683 |
+
any_open_tag, any_close_tag = make_html_tags(
|
684 |
+
Word(alphas, alphanums + "_:").set_name("any tag")
|
685 |
+
)
|
686 |
+
|
687 |
+
_htmlEntityMap = {k.rstrip(";"): v for k, v in html.entities.html5.items()}
|
688 |
+
common_html_entity = Regex("&(?P<entity>" + "|".join(_htmlEntityMap) + ");").set_name(
|
689 |
+
"common HTML entity"
|
690 |
+
)
|
691 |
+
|
692 |
+
|
693 |
+
def replace_html_entity(t):
|
694 |
+
"""Helper parser action to replace common HTML entities with their special characters"""
|
695 |
+
return _htmlEntityMap.get(t.entity)
|
696 |
+
|
697 |
+
|
698 |
+
class OpAssoc(Enum):
|
699 |
+
LEFT = 1
|
700 |
+
RIGHT = 2
|
701 |
+
|
702 |
+
|
703 |
+
InfixNotationOperatorArgType = Union[
|
704 |
+
ParserElement, str, Tuple[Union[ParserElement, str], Union[ParserElement, str]]
|
705 |
+
]
|
706 |
+
InfixNotationOperatorSpec = Union[
|
707 |
+
Tuple[
|
708 |
+
InfixNotationOperatorArgType,
|
709 |
+
int,
|
710 |
+
OpAssoc,
|
711 |
+
OptionalType[ParseAction],
|
712 |
+
],
|
713 |
+
Tuple[
|
714 |
+
InfixNotationOperatorArgType,
|
715 |
+
int,
|
716 |
+
OpAssoc,
|
717 |
+
],
|
718 |
+
]
|
719 |
+
|
720 |
+
|
721 |
+
def infix_notation(
|
722 |
+
base_expr: ParserElement,
|
723 |
+
op_list: List[InfixNotationOperatorSpec],
|
724 |
+
lpar: Union[str, ParserElement] = Suppress("("),
|
725 |
+
rpar: Union[str, ParserElement] = Suppress(")"),
|
726 |
+
) -> ParserElement:
|
727 |
+
"""Helper method for constructing grammars of expressions made up of
|
728 |
+
operators working in a precedence hierarchy. Operators may be unary
|
729 |
+
or binary, left- or right-associative. Parse actions can also be
|
730 |
+
attached to operator expressions. The generated parser will also
|
731 |
+
recognize the use of parentheses to override operator precedences
|
732 |
+
(see example below).
|
733 |
+
|
734 |
+
Note: if you define a deep operator list, you may see performance
|
735 |
+
issues when using infix_notation. See
|
736 |
+
:class:`ParserElement.enable_packrat` for a mechanism to potentially
|
737 |
+
improve your parser performance.
|
738 |
+
|
739 |
+
Parameters:
|
740 |
+
- ``base_expr`` - expression representing the most basic operand to
|
741 |
+
be used in the expression
|
742 |
+
- ``op_list`` - list of tuples, one for each operator precedence level
|
743 |
+
in the expression grammar; each tuple is of the form ``(op_expr,
|
744 |
+
num_operands, right_left_assoc, (optional)parse_action)``, where:
|
745 |
+
|
746 |
+
- ``op_expr`` is the pyparsing expression for the operator; may also
|
747 |
+
be a string, which will be converted to a Literal; if ``num_operands``
|
748 |
+
is 3, ``op_expr`` is a tuple of two expressions, for the two
|
749 |
+
operators separating the 3 terms
|
750 |
+
- ``num_operands`` is the number of terms for this operator (must be 1,
|
751 |
+
2, or 3)
|
752 |
+
- ``right_left_assoc`` is the indicator whether the operator is right
|
753 |
+
or left associative, using the pyparsing-defined constants
|
754 |
+
``OpAssoc.RIGHT`` and ``OpAssoc.LEFT``.
|
755 |
+
- ``parse_action`` is the parse action to be associated with
|
756 |
+
expressions matching this operator expression (the parse action
|
757 |
+
tuple member may be omitted); if the parse action is passed
|
758 |
+
a tuple or list of functions, this is equivalent to calling
|
759 |
+
``set_parse_action(*fn)``
|
760 |
+
(:class:`ParserElement.set_parse_action`)
|
761 |
+
- ``lpar`` - expression for matching left-parentheses
|
762 |
+
(default= ``Suppress('(')``)
|
763 |
+
- ``rpar`` - expression for matching right-parentheses
|
764 |
+
(default= ``Suppress(')')``)
|
765 |
+
|
766 |
+
Example::
|
767 |
+
|
768 |
+
# simple example of four-function arithmetic with ints and
|
769 |
+
# variable names
|
770 |
+
integer = pyparsing_common.signed_integer
|
771 |
+
varname = pyparsing_common.identifier
|
772 |
+
|
773 |
+
arith_expr = infix_notation(integer | varname,
|
774 |
+
[
|
775 |
+
('-', 1, OpAssoc.RIGHT),
|
776 |
+
(one_of('* /'), 2, OpAssoc.LEFT),
|
777 |
+
(one_of('+ -'), 2, OpAssoc.LEFT),
|
778 |
+
])
|
779 |
+
|
780 |
+
arith_expr.run_tests('''
|
781 |
+
5+3*6
|
782 |
+
(5+3)*6
|
783 |
+
-2--11
|
784 |
+
''', full_dump=False)
|
785 |
+
|
786 |
+
prints::
|
787 |
+
|
788 |
+
5+3*6
|
789 |
+
[[5, '+', [3, '*', 6]]]
|
790 |
+
|
791 |
+
(5+3)*6
|
792 |
+
[[[5, '+', 3], '*', 6]]
|
793 |
+
|
794 |
+
-2--11
|
795 |
+
[[['-', 2], '-', ['-', 11]]]
|
796 |
+
"""
|
797 |
+
# captive version of FollowedBy that does not do parse actions or capture results names
|
798 |
+
class _FB(FollowedBy):
|
799 |
+
def parseImpl(self, instring, loc, doActions=True):
|
800 |
+
self.expr.try_parse(instring, loc)
|
801 |
+
return loc, []
|
802 |
+
|
803 |
+
_FB.__name__ = "FollowedBy>"
|
804 |
+
|
805 |
+
ret = Forward()
|
806 |
+
lpar = Suppress(lpar)
|
807 |
+
rpar = Suppress(rpar)
|
808 |
+
lastExpr = base_expr | (lpar + ret + rpar)
|
809 |
+
for i, operDef in enumerate(op_list):
|
810 |
+
opExpr, arity, rightLeftAssoc, pa = (operDef + (None,))[:4]
|
811 |
+
if isinstance(opExpr, str_type):
|
812 |
+
opExpr = ParserElement._literalStringClass(opExpr)
|
813 |
+
if arity == 3:
|
814 |
+
if not isinstance(opExpr, (tuple, list)) or len(opExpr) != 2:
|
815 |
+
raise ValueError(
|
816 |
+
"if numterms=3, opExpr must be a tuple or list of two expressions"
|
817 |
+
)
|
818 |
+
opExpr1, opExpr2 = opExpr
|
819 |
+
term_name = "{}{} term".format(opExpr1, opExpr2)
|
820 |
+
else:
|
821 |
+
term_name = "{} term".format(opExpr)
|
822 |
+
|
823 |
+
if not 1 <= arity <= 3:
|
824 |
+
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
|
825 |
+
|
826 |
+
if rightLeftAssoc not in (OpAssoc.LEFT, OpAssoc.RIGHT):
|
827 |
+
raise ValueError("operator must indicate right or left associativity")
|
828 |
+
|
829 |
+
thisExpr = Forward().set_name(term_name)
|
830 |
+
if rightLeftAssoc is OpAssoc.LEFT:
|
831 |
+
if arity == 1:
|
832 |
+
matchExpr = _FB(lastExpr + opExpr) + Group(lastExpr + opExpr[1, ...])
|
833 |
+
elif arity == 2:
|
834 |
+
if opExpr is not None:
|
835 |
+
matchExpr = _FB(lastExpr + opExpr + lastExpr) + Group(
|
836 |
+
lastExpr + (opExpr + lastExpr)[1, ...]
|
837 |
+
)
|
838 |
+
else:
|
839 |
+
matchExpr = _FB(lastExpr + lastExpr) + Group(lastExpr[2, ...])
|
840 |
+
elif arity == 3:
|
841 |
+
matchExpr = _FB(
|
842 |
+
lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr
|
843 |
+
) + Group(lastExpr + OneOrMore(opExpr1 + lastExpr + opExpr2 + lastExpr))
|
844 |
+
elif rightLeftAssoc is OpAssoc.RIGHT:
|
845 |
+
if arity == 1:
|
846 |
+
# try to avoid LR with this extra test
|
847 |
+
if not isinstance(opExpr, Opt):
|
848 |
+
opExpr = Opt(opExpr)
|
849 |
+
matchExpr = _FB(opExpr.expr + thisExpr) + Group(opExpr + thisExpr)
|
850 |
+
elif arity == 2:
|
851 |
+
if opExpr is not None:
|
852 |
+
matchExpr = _FB(lastExpr + opExpr + thisExpr) + Group(
|
853 |
+
lastExpr + (opExpr + thisExpr)[1, ...]
|
854 |
+
)
|
855 |
+
else:
|
856 |
+
matchExpr = _FB(lastExpr + thisExpr) + Group(
|
857 |
+
lastExpr + thisExpr[1, ...]
|
858 |
+
)
|
859 |
+
elif arity == 3:
|
860 |
+
matchExpr = _FB(
|
861 |
+
lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr
|
862 |
+
) + Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr)
|
863 |
+
if pa:
|
864 |
+
if isinstance(pa, (tuple, list)):
|
865 |
+
matchExpr.set_parse_action(*pa)
|
866 |
+
else:
|
867 |
+
matchExpr.set_parse_action(pa)
|
868 |
+
thisExpr <<= (matchExpr | lastExpr).setName(term_name)
|
869 |
+
lastExpr = thisExpr
|
870 |
+
ret <<= lastExpr
|
871 |
+
return ret
|
872 |
+
|
873 |
+
|
874 |
+
def indentedBlock(blockStatementExpr, indentStack, indent=True, backup_stacks=[]):
|
875 |
+
"""
|
876 |
+
(DEPRECATED - use IndentedBlock class instead)
|
877 |
+
Helper method for defining space-delimited indentation blocks,
|
878 |
+
such as those used to define block statements in Python source code.
|
879 |
+
|
880 |
+
Parameters:
|
881 |
+
|
882 |
+
- ``blockStatementExpr`` - expression defining syntax of statement that
|
883 |
+
is repeated within the indented block
|
884 |
+
- ``indentStack`` - list created by caller to manage indentation stack
|
885 |
+
(multiple ``statementWithIndentedBlock`` expressions within a single
|
886 |
+
grammar should share a common ``indentStack``)
|
887 |
+
- ``indent`` - boolean indicating whether block must be indented beyond
|
888 |
+
the current level; set to ``False`` for block of left-most statements
|
889 |
+
(default= ``True``)
|
890 |
+
|
891 |
+
A valid block must contain at least one ``blockStatement``.
|
892 |
+
|
893 |
+
(Note that indentedBlock uses internal parse actions which make it
|
894 |
+
incompatible with packrat parsing.)
|
895 |
+
|
896 |
+
Example::
|
897 |
+
|
898 |
+
data = '''
|
899 |
+
def A(z):
|
900 |
+
A1
|
901 |
+
B = 100
|
902 |
+
G = A2
|
903 |
+
A2
|
904 |
+
A3
|
905 |
+
B
|
906 |
+
def BB(a,b,c):
|
907 |
+
BB1
|
908 |
+
def BBA():
|
909 |
+
bba1
|
910 |
+
bba2
|
911 |
+
bba3
|
912 |
+
C
|
913 |
+
D
|
914 |
+
def spam(x,y):
|
915 |
+
def eggs(z):
|
916 |
+
pass
|
917 |
+
'''
|
918 |
+
|
919 |
+
|
920 |
+
indentStack = [1]
|
921 |
+
stmt = Forward()
|
922 |
+
|
923 |
+
identifier = Word(alphas, alphanums)
|
924 |
+
funcDecl = ("def" + identifier + Group("(" + Opt(delimitedList(identifier)) + ")") + ":")
|
925 |
+
func_body = indentedBlock(stmt, indentStack)
|
926 |
+
funcDef = Group(funcDecl + func_body)
|
927 |
+
|
928 |
+
rvalue = Forward()
|
929 |
+
funcCall = Group(identifier + "(" + Opt(delimitedList(rvalue)) + ")")
|
930 |
+
rvalue << (funcCall | identifier | Word(nums))
|
931 |
+
assignment = Group(identifier + "=" + rvalue)
|
932 |
+
stmt << (funcDef | assignment | identifier)
|
933 |
+
|
934 |
+
module_body = OneOrMore(stmt)
|
935 |
+
|
936 |
+
parseTree = module_body.parseString(data)
|
937 |
+
parseTree.pprint()
|
938 |
+
|
939 |
+
prints::
|
940 |
+
|
941 |
+
[['def',
|
942 |
+
'A',
|
943 |
+
['(', 'z', ')'],
|
944 |
+
':',
|
945 |
+
[['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
|
946 |
+
'B',
|
947 |
+
['def',
|
948 |
+
'BB',
|
949 |
+
['(', 'a', 'b', 'c', ')'],
|
950 |
+
':',
|
951 |
+
[['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
|
952 |
+
'C',
|
953 |
+
'D',
|
954 |
+
['def',
|
955 |
+
'spam',
|
956 |
+
['(', 'x', 'y', ')'],
|
957 |
+
':',
|
958 |
+
[[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]
|
959 |
+
"""
|
960 |
+
backup_stacks.append(indentStack[:])
|
961 |
+
|
962 |
+
def reset_stack():
|
963 |
+
indentStack[:] = backup_stacks[-1]
|
964 |
+
|
965 |
+
def checkPeerIndent(s, l, t):
|
966 |
+
if l >= len(s):
|
967 |
+
return
|
968 |
+
curCol = col(l, s)
|
969 |
+
if curCol != indentStack[-1]:
|
970 |
+
if curCol > indentStack[-1]:
|
971 |
+
raise ParseException(s, l, "illegal nesting")
|
972 |
+
raise ParseException(s, l, "not a peer entry")
|
973 |
+
|
974 |
+
def checkSubIndent(s, l, t):
|
975 |
+
curCol = col(l, s)
|
976 |
+
if curCol > indentStack[-1]:
|
977 |
+
indentStack.append(curCol)
|
978 |
+
else:
|
979 |
+
raise ParseException(s, l, "not a subentry")
|
980 |
+
|
981 |
+
def checkUnindent(s, l, t):
|
982 |
+
if l >= len(s):
|
983 |
+
return
|
984 |
+
curCol = col(l, s)
|
985 |
+
if not (indentStack and curCol in indentStack):
|
986 |
+
raise ParseException(s, l, "not an unindent")
|
987 |
+
if curCol < indentStack[-1]:
|
988 |
+
indentStack.pop()
|
989 |
+
|
990 |
+
NL = OneOrMore(LineEnd().set_whitespace_chars("\t ").suppress())
|
991 |
+
INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name("INDENT")
|
992 |
+
PEER = Empty().set_parse_action(checkPeerIndent).set_name("")
|
993 |
+
UNDENT = Empty().set_parse_action(checkUnindent).set_name("UNINDENT")
|
994 |
+
if indent:
|
995 |
+
smExpr = Group(
|
996 |
+
Opt(NL)
|
997 |
+
+ INDENT
|
998 |
+
+ OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))
|
999 |
+
+ UNDENT
|
1000 |
+
)
|
1001 |
+
else:
|
1002 |
+
smExpr = Group(
|
1003 |
+
Opt(NL)
|
1004 |
+
+ OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))
|
1005 |
+
+ Opt(UNDENT)
|
1006 |
+
)
|
1007 |
+
|
1008 |
+
# add a parse action to remove backup_stack from list of backups
|
1009 |
+
smExpr.add_parse_action(
|
1010 |
+
lambda: backup_stacks.pop(-1) and None if backup_stacks else None
|
1011 |
+
)
|
1012 |
+
smExpr.set_fail_action(lambda a, b, c, d: reset_stack())
|
1013 |
+
blockStatementExpr.ignore(_bslash + LineEnd())
|
1014 |
+
return smExpr.set_name("indented block")
|
1015 |
+
|
1016 |
+
|
1017 |
+
# it's easy to get these comment structures wrong - they're very common, so may as well make them available
|
1018 |
+
c_style_comment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + "*/").set_name(
|
1019 |
+
"C style comment"
|
1020 |
+
)
|
1021 |
+
"Comment of the form ``/* ... */``"
|
1022 |
+
|
1023 |
+
html_comment = Regex(r"<!--[\s\S]*?-->").set_name("HTML comment")
|
1024 |
+
"Comment of the form ``<!-- ... -->``"
|
1025 |
+
|
1026 |
+
rest_of_line = Regex(r".*").leave_whitespace().set_name("rest of line")
|
1027 |
+
dbl_slash_comment = Regex(r"//(?:\\\n|[^\n])*").set_name("// comment")
|
1028 |
+
"Comment of the form ``// ... (to end of line)``"
|
1029 |
+
|
1030 |
+
cpp_style_comment = Combine(
|
1031 |
+
Regex(r"/\*(?:[^*]|\*(?!/))*") + "*/" | dbl_slash_comment
|
1032 |
+
).set_name("C++ style comment")
|
1033 |
+
"Comment of either form :class:`c_style_comment` or :class:`dbl_slash_comment`"
|
1034 |
+
|
1035 |
+
java_style_comment = cpp_style_comment
|
1036 |
+
"Same as :class:`cpp_style_comment`"
|
1037 |
+
|
1038 |
+
python_style_comment = Regex(r"#.*").set_name("Python style comment")
|
1039 |
+
"Comment of the form ``# ... (to end of line)``"
|
1040 |
+
|
1041 |
+
|
1042 |
+
# build list of built-in expressions, for future reference if a global default value
|
1043 |
+
# gets updated
|
1044 |
+
_builtin_exprs = [v for v in vars().values() if isinstance(v, ParserElement)]
|
1045 |
+
|
1046 |
+
|
1047 |
+
# pre-PEP8 compatible names
|
1048 |
+
delimitedList = delimited_list
|
1049 |
+
countedArray = counted_array
|
1050 |
+
matchPreviousLiteral = match_previous_literal
|
1051 |
+
matchPreviousExpr = match_previous_expr
|
1052 |
+
oneOf = one_of
|
1053 |
+
dictOf = dict_of
|
1054 |
+
originalTextFor = original_text_for
|
1055 |
+
nestedExpr = nested_expr
|
1056 |
+
makeHTMLTags = make_html_tags
|
1057 |
+
makeXMLTags = make_xml_tags
|
1058 |
+
anyOpenTag, anyCloseTag = any_open_tag, any_close_tag
|
1059 |
+
commonHTMLEntity = common_html_entity
|
1060 |
+
replaceHTMLEntity = replace_html_entity
|
1061 |
+
opAssoc = OpAssoc
|
1062 |
+
infixNotation = infix_notation
|
1063 |
+
cStyleComment = c_style_comment
|
1064 |
+
htmlComment = html_comment
|
1065 |
+
restOfLine = rest_of_line
|
1066 |
+
dblSlashComment = dbl_slash_comment
|
1067 |
+
cppStyleComment = cpp_style_comment
|
1068 |
+
javaStyleComment = java_style_comment
|
1069 |
+
pythonStyleComment = python_style_comment
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/results.py
ADDED
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# results.py
|
2 |
+
from collections.abc import MutableMapping, Mapping, MutableSequence, Iterator
|
3 |
+
import pprint
|
4 |
+
from weakref import ref as wkref
|
5 |
+
from typing import Tuple, Any
|
6 |
+
|
7 |
+
str_type: Tuple[type, ...] = (str, bytes)
|
8 |
+
_generator_type = type((_ for _ in ()))
|
9 |
+
|
10 |
+
|
11 |
+
class _ParseResultsWithOffset:
|
12 |
+
__slots__ = ["tup"]
|
13 |
+
|
14 |
+
def __init__(self, p1, p2):
|
15 |
+
self.tup = (p1, p2)
|
16 |
+
|
17 |
+
def __getitem__(self, i):
|
18 |
+
return self.tup[i]
|
19 |
+
|
20 |
+
def __getstate__(self):
|
21 |
+
return self.tup
|
22 |
+
|
23 |
+
def __setstate__(self, *args):
|
24 |
+
self.tup = args[0]
|
25 |
+
|
26 |
+
|
27 |
+
class ParseResults:
|
28 |
+
"""Structured parse results, to provide multiple means of access to
|
29 |
+
the parsed data:
|
30 |
+
|
31 |
+
- as a list (``len(results)``)
|
32 |
+
- by list index (``results[0], results[1]``, etc.)
|
33 |
+
- by attribute (``results.<results_name>`` - see :class:`ParserElement.set_results_name`)
|
34 |
+
|
35 |
+
Example::
|
36 |
+
|
37 |
+
integer = Word(nums)
|
38 |
+
date_str = (integer.set_results_name("year") + '/'
|
39 |
+
+ integer.set_results_name("month") + '/'
|
40 |
+
+ integer.set_results_name("day"))
|
41 |
+
# equivalent form:
|
42 |
+
# date_str = (integer("year") + '/'
|
43 |
+
# + integer("month") + '/'
|
44 |
+
# + integer("day"))
|
45 |
+
|
46 |
+
# parse_string returns a ParseResults object
|
47 |
+
result = date_str.parse_string("1999/12/31")
|
48 |
+
|
49 |
+
def test(s, fn=repr):
|
50 |
+
print("{} -> {}".format(s, fn(eval(s))))
|
51 |
+
test("list(result)")
|
52 |
+
test("result[0]")
|
53 |
+
test("result['month']")
|
54 |
+
test("result.day")
|
55 |
+
test("'month' in result")
|
56 |
+
test("'minutes' in result")
|
57 |
+
test("result.dump()", str)
|
58 |
+
|
59 |
+
prints::
|
60 |
+
|
61 |
+
list(result) -> ['1999', '/', '12', '/', '31']
|
62 |
+
result[0] -> '1999'
|
63 |
+
result['month'] -> '12'
|
64 |
+
result.day -> '31'
|
65 |
+
'month' in result -> True
|
66 |
+
'minutes' in result -> False
|
67 |
+
result.dump() -> ['1999', '/', '12', '/', '31']
|
68 |
+
- day: 31
|
69 |
+
- month: 12
|
70 |
+
- year: 1999
|
71 |
+
"""
|
72 |
+
|
73 |
+
_null_values: Tuple[Any, ...] = (None, [], "", ())
|
74 |
+
|
75 |
+
__slots__ = [
|
76 |
+
"_name",
|
77 |
+
"_parent",
|
78 |
+
"_all_names",
|
79 |
+
"_modal",
|
80 |
+
"_toklist",
|
81 |
+
"_tokdict",
|
82 |
+
"__weakref__",
|
83 |
+
]
|
84 |
+
|
85 |
+
class List(list):
|
86 |
+
"""
|
87 |
+
Simple wrapper class to distinguish parsed list results that should be preserved
|
88 |
+
as actual Python lists, instead of being converted to :class:`ParseResults`:
|
89 |
+
|
90 |
+
LBRACK, RBRACK = map(pp.Suppress, "[]")
|
91 |
+
element = pp.Forward()
|
92 |
+
item = ppc.integer
|
93 |
+
element_list = LBRACK + pp.delimited_list(element) + RBRACK
|
94 |
+
|
95 |
+
# add parse actions to convert from ParseResults to actual Python collection types
|
96 |
+
def as_python_list(t):
|
97 |
+
return pp.ParseResults.List(t.as_list())
|
98 |
+
element_list.add_parse_action(as_python_list)
|
99 |
+
|
100 |
+
element <<= item | element_list
|
101 |
+
|
102 |
+
element.run_tests('''
|
103 |
+
100
|
104 |
+
[2,3,4]
|
105 |
+
[[2, 1],3,4]
|
106 |
+
[(2, 1),3,4]
|
107 |
+
(2,3,4)
|
108 |
+
''', post_parse=lambda s, r: (r[0], type(r[0])))
|
109 |
+
|
110 |
+
prints:
|
111 |
+
|
112 |
+
100
|
113 |
+
(100, <class 'int'>)
|
114 |
+
|
115 |
+
[2,3,4]
|
116 |
+
([2, 3, 4], <class 'list'>)
|
117 |
+
|
118 |
+
[[2, 1],3,4]
|
119 |
+
([[2, 1], 3, 4], <class 'list'>)
|
120 |
+
|
121 |
+
(Used internally by :class:`Group` when `aslist=True`.)
|
122 |
+
"""
|
123 |
+
|
124 |
+
def __new__(cls, contained=None):
|
125 |
+
if contained is None:
|
126 |
+
contained = []
|
127 |
+
|
128 |
+
if not isinstance(contained, list):
|
129 |
+
raise TypeError(
|
130 |
+
"{} may only be constructed with a list,"
|
131 |
+
" not {}".format(cls.__name__, type(contained).__name__)
|
132 |
+
)
|
133 |
+
|
134 |
+
return list.__new__(cls)
|
135 |
+
|
136 |
+
def __new__(cls, toklist=None, name=None, **kwargs):
|
137 |
+
if isinstance(toklist, ParseResults):
|
138 |
+
return toklist
|
139 |
+
self = object.__new__(cls)
|
140 |
+
self._name = None
|
141 |
+
self._parent = None
|
142 |
+
self._all_names = set()
|
143 |
+
|
144 |
+
if toklist is None:
|
145 |
+
self._toklist = []
|
146 |
+
elif isinstance(toklist, (list, _generator_type)):
|
147 |
+
self._toklist = (
|
148 |
+
[toklist[:]]
|
149 |
+
if isinstance(toklist, ParseResults.List)
|
150 |
+
else list(toklist)
|
151 |
+
)
|
152 |
+
else:
|
153 |
+
self._toklist = [toklist]
|
154 |
+
self._tokdict = dict()
|
155 |
+
return self
|
156 |
+
|
157 |
+
# Performance tuning: we construct a *lot* of these, so keep this
|
158 |
+
# constructor as small and fast as possible
|
159 |
+
def __init__(
|
160 |
+
self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance
|
161 |
+
):
|
162 |
+
self._modal = modal
|
163 |
+
if name is not None and name != "":
|
164 |
+
if isinstance(name, int):
|
165 |
+
name = str(name)
|
166 |
+
if not modal:
|
167 |
+
self._all_names = {name}
|
168 |
+
self._name = name
|
169 |
+
if toklist not in self._null_values:
|
170 |
+
if isinstance(toklist, (str_type, type)):
|
171 |
+
toklist = [toklist]
|
172 |
+
if asList:
|
173 |
+
if isinstance(toklist, ParseResults):
|
174 |
+
self[name] = _ParseResultsWithOffset(
|
175 |
+
ParseResults(toklist._toklist), 0
|
176 |
+
)
|
177 |
+
else:
|
178 |
+
self[name] = _ParseResultsWithOffset(
|
179 |
+
ParseResults(toklist[0]), 0
|
180 |
+
)
|
181 |
+
self[name]._name = name
|
182 |
+
else:
|
183 |
+
try:
|
184 |
+
self[name] = toklist[0]
|
185 |
+
except (KeyError, TypeError, IndexError):
|
186 |
+
if toklist is not self:
|
187 |
+
self[name] = toklist
|
188 |
+
else:
|
189 |
+
self._name = name
|
190 |
+
|
191 |
+
def __getitem__(self, i):
|
192 |
+
if isinstance(i, (int, slice)):
|
193 |
+
return self._toklist[i]
|
194 |
+
else:
|
195 |
+
if i not in self._all_names:
|
196 |
+
return self._tokdict[i][-1][0]
|
197 |
+
else:
|
198 |
+
return ParseResults([v[0] for v in self._tokdict[i]])
|
199 |
+
|
200 |
+
def __setitem__(self, k, v, isinstance=isinstance):
|
201 |
+
if isinstance(v, _ParseResultsWithOffset):
|
202 |
+
self._tokdict[k] = self._tokdict.get(k, list()) + [v]
|
203 |
+
sub = v[0]
|
204 |
+
elif isinstance(k, (int, slice)):
|
205 |
+
self._toklist[k] = v
|
206 |
+
sub = v
|
207 |
+
else:
|
208 |
+
self._tokdict[k] = self._tokdict.get(k, list()) + [
|
209 |
+
_ParseResultsWithOffset(v, 0)
|
210 |
+
]
|
211 |
+
sub = v
|
212 |
+
if isinstance(sub, ParseResults):
|
213 |
+
sub._parent = wkref(self)
|
214 |
+
|
215 |
+
def __delitem__(self, i):
|
216 |
+
if isinstance(i, (int, slice)):
|
217 |
+
mylen = len(self._toklist)
|
218 |
+
del self._toklist[i]
|
219 |
+
|
220 |
+
# convert int to slice
|
221 |
+
if isinstance(i, int):
|
222 |
+
if i < 0:
|
223 |
+
i += mylen
|
224 |
+
i = slice(i, i + 1)
|
225 |
+
# get removed indices
|
226 |
+
removed = list(range(*i.indices(mylen)))
|
227 |
+
removed.reverse()
|
228 |
+
# fixup indices in token dictionary
|
229 |
+
for name, occurrences in self._tokdict.items():
|
230 |
+
for j in removed:
|
231 |
+
for k, (value, position) in enumerate(occurrences):
|
232 |
+
occurrences[k] = _ParseResultsWithOffset(
|
233 |
+
value, position - (position > j)
|
234 |
+
)
|
235 |
+
else:
|
236 |
+
del self._tokdict[i]
|
237 |
+
|
238 |
+
def __contains__(self, k) -> bool:
|
239 |
+
return k in self._tokdict
|
240 |
+
|
241 |
+
def __len__(self) -> int:
|
242 |
+
return len(self._toklist)
|
243 |
+
|
244 |
+
def __bool__(self) -> bool:
|
245 |
+
return not not (self._toklist or self._tokdict)
|
246 |
+
|
247 |
+
def __iter__(self) -> Iterator:
|
248 |
+
return iter(self._toklist)
|
249 |
+
|
250 |
+
def __reversed__(self) -> Iterator:
|
251 |
+
return iter(self._toklist[::-1])
|
252 |
+
|
253 |
+
def keys(self):
|
254 |
+
return iter(self._tokdict)
|
255 |
+
|
256 |
+
def values(self):
|
257 |
+
return (self[k] for k in self.keys())
|
258 |
+
|
259 |
+
def items(self):
|
260 |
+
return ((k, self[k]) for k in self.keys())
|
261 |
+
|
262 |
+
def haskeys(self) -> bool:
|
263 |
+
"""
|
264 |
+
Since ``keys()`` returns an iterator, this method is helpful in bypassing
|
265 |
+
code that looks for the existence of any defined results names."""
|
266 |
+
return bool(self._tokdict)
|
267 |
+
|
268 |
+
def pop(self, *args, **kwargs):
|
269 |
+
"""
|
270 |
+
Removes and returns item at specified index (default= ``last``).
|
271 |
+
Supports both ``list`` and ``dict`` semantics for ``pop()``. If
|
272 |
+
passed no argument or an integer argument, it will use ``list``
|
273 |
+
semantics and pop tokens from the list of parsed tokens. If passed
|
274 |
+
a non-integer argument (most likely a string), it will use ``dict``
|
275 |
+
semantics and pop the corresponding value from any defined results
|
276 |
+
names. A second default return value argument is supported, just as in
|
277 |
+
``dict.pop()``.
|
278 |
+
|
279 |
+
Example::
|
280 |
+
|
281 |
+
numlist = Word(nums)[...]
|
282 |
+
print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321']
|
283 |
+
|
284 |
+
def remove_first(tokens):
|
285 |
+
tokens.pop(0)
|
286 |
+
numlist.add_parse_action(remove_first)
|
287 |
+
print(numlist.parse_string("0 123 321")) # -> ['123', '321']
|
288 |
+
|
289 |
+
label = Word(alphas)
|
290 |
+
patt = label("LABEL") + OneOrMore(Word(nums))
|
291 |
+
print(patt.parse_string("AAB 123 321").dump())
|
292 |
+
|
293 |
+
# Use pop() in a parse action to remove named result (note that corresponding value is not
|
294 |
+
# removed from list form of results)
|
295 |
+
def remove_LABEL(tokens):
|
296 |
+
tokens.pop("LABEL")
|
297 |
+
return tokens
|
298 |
+
patt.add_parse_action(remove_LABEL)
|
299 |
+
print(patt.parse_string("AAB 123 321").dump())
|
300 |
+
|
301 |
+
prints::
|
302 |
+
|
303 |
+
['AAB', '123', '321']
|
304 |
+
- LABEL: AAB
|
305 |
+
|
306 |
+
['AAB', '123', '321']
|
307 |
+
"""
|
308 |
+
if not args:
|
309 |
+
args = [-1]
|
310 |
+
for k, v in kwargs.items():
|
311 |
+
if k == "default":
|
312 |
+
args = (args[0], v)
|
313 |
+
else:
|
314 |
+
raise TypeError(
|
315 |
+
"pop() got an unexpected keyword argument {!r}".format(k)
|
316 |
+
)
|
317 |
+
if isinstance(args[0], int) or len(args) == 1 or args[0] in self:
|
318 |
+
index = args[0]
|
319 |
+
ret = self[index]
|
320 |
+
del self[index]
|
321 |
+
return ret
|
322 |
+
else:
|
323 |
+
defaultvalue = args[1]
|
324 |
+
return defaultvalue
|
325 |
+
|
326 |
+
def get(self, key, default_value=None):
|
327 |
+
"""
|
328 |
+
Returns named result matching the given key, or if there is no
|
329 |
+
such name, then returns the given ``default_value`` or ``None`` if no
|
330 |
+
``default_value`` is specified.
|
331 |
+
|
332 |
+
Similar to ``dict.get()``.
|
333 |
+
|
334 |
+
Example::
|
335 |
+
|
336 |
+
integer = Word(nums)
|
337 |
+
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
|
338 |
+
|
339 |
+
result = date_str.parse_string("1999/12/31")
|
340 |
+
print(result.get("year")) # -> '1999'
|
341 |
+
print(result.get("hour", "not specified")) # -> 'not specified'
|
342 |
+
print(result.get("hour")) # -> None
|
343 |
+
"""
|
344 |
+
if key in self:
|
345 |
+
return self[key]
|
346 |
+
else:
|
347 |
+
return default_value
|
348 |
+
|
349 |
+
def insert(self, index, ins_string):
|
350 |
+
"""
|
351 |
+
Inserts new element at location index in the list of parsed tokens.
|
352 |
+
|
353 |
+
Similar to ``list.insert()``.
|
354 |
+
|
355 |
+
Example::
|
356 |
+
|
357 |
+
numlist = Word(nums)[...]
|
358 |
+
print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321']
|
359 |
+
|
360 |
+
# use a parse action to insert the parse location in the front of the parsed results
|
361 |
+
def insert_locn(locn, tokens):
|
362 |
+
tokens.insert(0, locn)
|
363 |
+
numlist.add_parse_action(insert_locn)
|
364 |
+
print(numlist.parse_string("0 123 321")) # -> [0, '0', '123', '321']
|
365 |
+
"""
|
366 |
+
self._toklist.insert(index, ins_string)
|
367 |
+
# fixup indices in token dictionary
|
368 |
+
for name, occurrences in self._tokdict.items():
|
369 |
+
for k, (value, position) in enumerate(occurrences):
|
370 |
+
occurrences[k] = _ParseResultsWithOffset(
|
371 |
+
value, position + (position > index)
|
372 |
+
)
|
373 |
+
|
374 |
+
def append(self, item):
|
375 |
+
"""
|
376 |
+
Add single element to end of ``ParseResults`` list of elements.
|
377 |
+
|
378 |
+
Example::
|
379 |
+
|
380 |
+
numlist = Word(nums)[...]
|
381 |
+
print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321']
|
382 |
+
|
383 |
+
# use a parse action to compute the sum of the parsed integers, and add it to the end
|
384 |
+
def append_sum(tokens):
|
385 |
+
tokens.append(sum(map(int, tokens)))
|
386 |
+
numlist.add_parse_action(append_sum)
|
387 |
+
print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321', 444]
|
388 |
+
"""
|
389 |
+
self._toklist.append(item)
|
390 |
+
|
391 |
+
def extend(self, itemseq):
|
392 |
+
"""
|
393 |
+
Add sequence of elements to end of ``ParseResults`` list of elements.
|
394 |
+
|
395 |
+
Example::
|
396 |
+
|
397 |
+
patt = OneOrMore(Word(alphas))
|
398 |
+
|
399 |
+
# use a parse action to append the reverse of the matched strings, to make a palindrome
|
400 |
+
def make_palindrome(tokens):
|
401 |
+
tokens.extend(reversed([t[::-1] for t in tokens]))
|
402 |
+
return ''.join(tokens)
|
403 |
+
patt.add_parse_action(make_palindrome)
|
404 |
+
print(patt.parse_string("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
|
405 |
+
"""
|
406 |
+
if isinstance(itemseq, ParseResults):
|
407 |
+
self.__iadd__(itemseq)
|
408 |
+
else:
|
409 |
+
self._toklist.extend(itemseq)
|
410 |
+
|
411 |
+
def clear(self):
|
412 |
+
"""
|
413 |
+
Clear all elements and results names.
|
414 |
+
"""
|
415 |
+
del self._toklist[:]
|
416 |
+
self._tokdict.clear()
|
417 |
+
|
418 |
+
def __getattr__(self, name):
|
419 |
+
try:
|
420 |
+
return self[name]
|
421 |
+
except KeyError:
|
422 |
+
if name.startswith("__"):
|
423 |
+
raise AttributeError(name)
|
424 |
+
return ""
|
425 |
+
|
426 |
+
def __add__(self, other) -> "ParseResults":
|
427 |
+
ret = self.copy()
|
428 |
+
ret += other
|
429 |
+
return ret
|
430 |
+
|
431 |
+
def __iadd__(self, other) -> "ParseResults":
|
432 |
+
if other._tokdict:
|
433 |
+
offset = len(self._toklist)
|
434 |
+
addoffset = lambda a: offset if a < 0 else a + offset
|
435 |
+
otheritems = other._tokdict.items()
|
436 |
+
otherdictitems = [
|
437 |
+
(k, _ParseResultsWithOffset(v[0], addoffset(v[1])))
|
438 |
+
for k, vlist in otheritems
|
439 |
+
for v in vlist
|
440 |
+
]
|
441 |
+
for k, v in otherdictitems:
|
442 |
+
self[k] = v
|
443 |
+
if isinstance(v[0], ParseResults):
|
444 |
+
v[0]._parent = wkref(self)
|
445 |
+
|
446 |
+
self._toklist += other._toklist
|
447 |
+
self._all_names |= other._all_names
|
448 |
+
return self
|
449 |
+
|
450 |
+
def __radd__(self, other) -> "ParseResults":
|
451 |
+
if isinstance(other, int) and other == 0:
|
452 |
+
# useful for merging many ParseResults using sum() builtin
|
453 |
+
return self.copy()
|
454 |
+
else:
|
455 |
+
# this may raise a TypeError - so be it
|
456 |
+
return other + self
|
457 |
+
|
458 |
+
def __repr__(self) -> str:
|
459 |
+
return "{}({!r}, {})".format(type(self).__name__, self._toklist, self.as_dict())
|
460 |
+
|
461 |
+
def __str__(self) -> str:
|
462 |
+
return (
|
463 |
+
"["
|
464 |
+
+ ", ".join(
|
465 |
+
[
|
466 |
+
str(i) if isinstance(i, ParseResults) else repr(i)
|
467 |
+
for i in self._toklist
|
468 |
+
]
|
469 |
+
)
|
470 |
+
+ "]"
|
471 |
+
)
|
472 |
+
|
473 |
+
def _asStringList(self, sep=""):
|
474 |
+
out = []
|
475 |
+
for item in self._toklist:
|
476 |
+
if out and sep:
|
477 |
+
out.append(sep)
|
478 |
+
if isinstance(item, ParseResults):
|
479 |
+
out += item._asStringList()
|
480 |
+
else:
|
481 |
+
out.append(str(item))
|
482 |
+
return out
|
483 |
+
|
484 |
+
def as_list(self) -> list:
|
485 |
+
"""
|
486 |
+
Returns the parse results as a nested list of matching tokens, all converted to strings.
|
487 |
+
|
488 |
+
Example::
|
489 |
+
|
490 |
+
patt = OneOrMore(Word(alphas))
|
491 |
+
result = patt.parse_string("sldkj lsdkj sldkj")
|
492 |
+
# even though the result prints in string-like form, it is actually a pyparsing ParseResults
|
493 |
+
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
|
494 |
+
|
495 |
+
# Use as_list() to create an actual list
|
496 |
+
result_list = result.as_list()
|
497 |
+
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
|
498 |
+
"""
|
499 |
+
return [
|
500 |
+
res.as_list() if isinstance(res, ParseResults) else res
|
501 |
+
for res in self._toklist
|
502 |
+
]
|
503 |
+
|
504 |
+
def as_dict(self) -> dict:
|
505 |
+
"""
|
506 |
+
Returns the named parse results as a nested dictionary.
|
507 |
+
|
508 |
+
Example::
|
509 |
+
|
510 |
+
integer = Word(nums)
|
511 |
+
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
|
512 |
+
|
513 |
+
result = date_str.parse_string('12/31/1999')
|
514 |
+
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
|
515 |
+
|
516 |
+
result_dict = result.as_dict()
|
517 |
+
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
|
518 |
+
|
519 |
+
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
|
520 |
+
import json
|
521 |
+
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
|
522 |
+
print(json.dumps(result.as_dict())) # -> {"month": "31", "day": "1999", "year": "12"}
|
523 |
+
"""
|
524 |
+
|
525 |
+
def to_item(obj):
|
526 |
+
if isinstance(obj, ParseResults):
|
527 |
+
return obj.as_dict() if obj.haskeys() else [to_item(v) for v in obj]
|
528 |
+
else:
|
529 |
+
return obj
|
530 |
+
|
531 |
+
return dict((k, to_item(v)) for k, v in self.items())
|
532 |
+
|
533 |
+
def copy(self) -> "ParseResults":
|
534 |
+
"""
|
535 |
+
Returns a new copy of a :class:`ParseResults` object.
|
536 |
+
"""
|
537 |
+
ret = ParseResults(self._toklist)
|
538 |
+
ret._tokdict = self._tokdict.copy()
|
539 |
+
ret._parent = self._parent
|
540 |
+
ret._all_names |= self._all_names
|
541 |
+
ret._name = self._name
|
542 |
+
return ret
|
543 |
+
|
544 |
+
def get_name(self):
|
545 |
+
r"""
|
546 |
+
Returns the results name for this token expression. Useful when several
|
547 |
+
different expressions might match at a particular location.
|
548 |
+
|
549 |
+
Example::
|
550 |
+
|
551 |
+
integer = Word(nums)
|
552 |
+
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
|
553 |
+
house_number_expr = Suppress('#') + Word(nums, alphanums)
|
554 |
+
user_data = (Group(house_number_expr)("house_number")
|
555 |
+
| Group(ssn_expr)("ssn")
|
556 |
+
| Group(integer)("age"))
|
557 |
+
user_info = OneOrMore(user_data)
|
558 |
+
|
559 |
+
result = user_info.parse_string("22 111-22-3333 #221B")
|
560 |
+
for item in result:
|
561 |
+
print(item.get_name(), ':', item[0])
|
562 |
+
|
563 |
+
prints::
|
564 |
+
|
565 |
+
age : 22
|
566 |
+
ssn : 111-22-3333
|
567 |
+
house_number : 221B
|
568 |
+
"""
|
569 |
+
if self._name:
|
570 |
+
return self._name
|
571 |
+
elif self._parent:
|
572 |
+
par = self._parent()
|
573 |
+
|
574 |
+
def find_in_parent(sub):
|
575 |
+
return next(
|
576 |
+
(
|
577 |
+
k
|
578 |
+
for k, vlist in par._tokdict.items()
|
579 |
+
for v, loc in vlist
|
580 |
+
if sub is v
|
581 |
+
),
|
582 |
+
None,
|
583 |
+
)
|
584 |
+
|
585 |
+
return find_in_parent(self) if par else None
|
586 |
+
elif (
|
587 |
+
len(self) == 1
|
588 |
+
and len(self._tokdict) == 1
|
589 |
+
and next(iter(self._tokdict.values()))[0][1] in (0, -1)
|
590 |
+
):
|
591 |
+
return next(iter(self._tokdict.keys()))
|
592 |
+
else:
|
593 |
+
return None
|
594 |
+
|
595 |
+
def dump(self, indent="", full=True, include_list=True, _depth=0) -> str:
|
596 |
+
"""
|
597 |
+
Diagnostic method for listing out the contents of
|
598 |
+
a :class:`ParseResults`. Accepts an optional ``indent`` argument so
|
599 |
+
that this string can be embedded in a nested display of other data.
|
600 |
+
|
601 |
+
Example::
|
602 |
+
|
603 |
+
integer = Word(nums)
|
604 |
+
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
|
605 |
+
|
606 |
+
result = date_str.parse_string('12/31/1999')
|
607 |
+
print(result.dump())
|
608 |
+
|
609 |
+
prints::
|
610 |
+
|
611 |
+
['12', '/', '31', '/', '1999']
|
612 |
+
- day: 1999
|
613 |
+
- month: 31
|
614 |
+
- year: 12
|
615 |
+
"""
|
616 |
+
out = []
|
617 |
+
NL = "\n"
|
618 |
+
out.append(indent + str(self.as_list()) if include_list else "")
|
619 |
+
|
620 |
+
if full:
|
621 |
+
if self.haskeys():
|
622 |
+
items = sorted((str(k), v) for k, v in self.items())
|
623 |
+
for k, v in items:
|
624 |
+
if out:
|
625 |
+
out.append(NL)
|
626 |
+
out.append("{}{}- {}: ".format(indent, (" " * _depth), k))
|
627 |
+
if isinstance(v, ParseResults):
|
628 |
+
if v:
|
629 |
+
out.append(
|
630 |
+
v.dump(
|
631 |
+
indent=indent,
|
632 |
+
full=full,
|
633 |
+
include_list=include_list,
|
634 |
+
_depth=_depth + 1,
|
635 |
+
)
|
636 |
+
)
|
637 |
+
else:
|
638 |
+
out.append(str(v))
|
639 |
+
else:
|
640 |
+
out.append(repr(v))
|
641 |
+
if any(isinstance(vv, ParseResults) for vv in self):
|
642 |
+
v = self
|
643 |
+
for i, vv in enumerate(v):
|
644 |
+
if isinstance(vv, ParseResults):
|
645 |
+
out.append(
|
646 |
+
"\n{}{}[{}]:\n{}{}{}".format(
|
647 |
+
indent,
|
648 |
+
(" " * (_depth)),
|
649 |
+
i,
|
650 |
+
indent,
|
651 |
+
(" " * (_depth + 1)),
|
652 |
+
vv.dump(
|
653 |
+
indent=indent,
|
654 |
+
full=full,
|
655 |
+
include_list=include_list,
|
656 |
+
_depth=_depth + 1,
|
657 |
+
),
|
658 |
+
)
|
659 |
+
)
|
660 |
+
else:
|
661 |
+
out.append(
|
662 |
+
"\n%s%s[%d]:\n%s%s%s"
|
663 |
+
% (
|
664 |
+
indent,
|
665 |
+
(" " * (_depth)),
|
666 |
+
i,
|
667 |
+
indent,
|
668 |
+
(" " * (_depth + 1)),
|
669 |
+
str(vv),
|
670 |
+
)
|
671 |
+
)
|
672 |
+
|
673 |
+
return "".join(out)
|
674 |
+
|
675 |
+
def pprint(self, *args, **kwargs):
|
676 |
+
"""
|
677 |
+
Pretty-printer for parsed results as a list, using the
|
678 |
+
`pprint <https://docs.python.org/3/library/pprint.html>`_ module.
|
679 |
+
Accepts additional positional or keyword args as defined for
|
680 |
+
`pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .
|
681 |
+
|
682 |
+
Example::
|
683 |
+
|
684 |
+
ident = Word(alphas, alphanums)
|
685 |
+
num = Word(nums)
|
686 |
+
func = Forward()
|
687 |
+
term = ident | num | Group('(' + func + ')')
|
688 |
+
func <<= ident + Group(Optional(delimited_list(term)))
|
689 |
+
result = func.parse_string("fna a,b,(fnb c,d,200),100")
|
690 |
+
result.pprint(width=40)
|
691 |
+
|
692 |
+
prints::
|
693 |
+
|
694 |
+
['fna',
|
695 |
+
['a',
|
696 |
+
'b',
|
697 |
+
['(', 'fnb', ['c', 'd', '200'], ')'],
|
698 |
+
'100']]
|
699 |
+
"""
|
700 |
+
pprint.pprint(self.as_list(), *args, **kwargs)
|
701 |
+
|
702 |
+
# add support for pickle protocol
|
703 |
+
def __getstate__(self):
|
704 |
+
return (
|
705 |
+
self._toklist,
|
706 |
+
(
|
707 |
+
self._tokdict.copy(),
|
708 |
+
self._parent is not None and self._parent() or None,
|
709 |
+
self._all_names,
|
710 |
+
self._name,
|
711 |
+
),
|
712 |
+
)
|
713 |
+
|
714 |
+
def __setstate__(self, state):
|
715 |
+
self._toklist, (self._tokdict, par, inAccumNames, self._name) = state
|
716 |
+
self._all_names = set(inAccumNames)
|
717 |
+
if par is not None:
|
718 |
+
self._parent = wkref(par)
|
719 |
+
else:
|
720 |
+
self._parent = None
|
721 |
+
|
722 |
+
def __getnewargs__(self):
|
723 |
+
return self._toklist, self._name
|
724 |
+
|
725 |
+
def __dir__(self):
|
726 |
+
return dir(type(self)) + list(self.keys())
|
727 |
+
|
728 |
+
@classmethod
|
729 |
+
def from_dict(cls, other, name=None) -> "ParseResults":
|
730 |
+
"""
|
731 |
+
Helper classmethod to construct a ``ParseResults`` from a ``dict``, preserving the
|
732 |
+
name-value relations as results names. If an optional ``name`` argument is
|
733 |
+
given, a nested ``ParseResults`` will be returned.
|
734 |
+
"""
|
735 |
+
|
736 |
+
def is_iterable(obj):
|
737 |
+
try:
|
738 |
+
iter(obj)
|
739 |
+
except Exception:
|
740 |
+
return False
|
741 |
+
else:
|
742 |
+
return not isinstance(obj, str_type)
|
743 |
+
|
744 |
+
ret = cls([])
|
745 |
+
for k, v in other.items():
|
746 |
+
if isinstance(v, Mapping):
|
747 |
+
ret += cls.from_dict(v, name=k)
|
748 |
+
else:
|
749 |
+
ret += cls([v], name=k, asList=is_iterable(v))
|
750 |
+
if name is not None:
|
751 |
+
ret = cls([ret], name=name)
|
752 |
+
return ret
|
753 |
+
|
754 |
+
asList = as_list
|
755 |
+
asDict = as_dict
|
756 |
+
getName = get_name
|
757 |
+
|
758 |
+
|
759 |
+
MutableMapping.register(ParseResults)
|
760 |
+
MutableSequence.register(ParseResults)
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/testing.py
ADDED
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# testing.py
|
2 |
+
|
3 |
+
from contextlib import contextmanager
|
4 |
+
from typing import Optional
|
5 |
+
|
6 |
+
from .core import (
|
7 |
+
ParserElement,
|
8 |
+
ParseException,
|
9 |
+
Keyword,
|
10 |
+
__diag__,
|
11 |
+
__compat__,
|
12 |
+
)
|
13 |
+
|
14 |
+
|
15 |
+
class pyparsing_test:
|
16 |
+
"""
|
17 |
+
namespace class for classes useful in writing unit tests
|
18 |
+
"""
|
19 |
+
|
20 |
+
class reset_pyparsing_context:
|
21 |
+
"""
|
22 |
+
Context manager to be used when writing unit tests that modify pyparsing config values:
|
23 |
+
- packrat parsing
|
24 |
+
- bounded recursion parsing
|
25 |
+
- default whitespace characters.
|
26 |
+
- default keyword characters
|
27 |
+
- literal string auto-conversion class
|
28 |
+
- __diag__ settings
|
29 |
+
|
30 |
+
Example::
|
31 |
+
|
32 |
+
with reset_pyparsing_context():
|
33 |
+
# test that literals used to construct a grammar are automatically suppressed
|
34 |
+
ParserElement.inlineLiteralsUsing(Suppress)
|
35 |
+
|
36 |
+
term = Word(alphas) | Word(nums)
|
37 |
+
group = Group('(' + term[...] + ')')
|
38 |
+
|
39 |
+
# assert that the '()' characters are not included in the parsed tokens
|
40 |
+
self.assertParseAndCheckList(group, "(abc 123 def)", ['abc', '123', 'def'])
|
41 |
+
|
42 |
+
# after exiting context manager, literals are converted to Literal expressions again
|
43 |
+
"""
|
44 |
+
|
45 |
+
def __init__(self):
|
46 |
+
self._save_context = {}
|
47 |
+
|
48 |
+
def save(self):
|
49 |
+
self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS
|
50 |
+
self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS
|
51 |
+
|
52 |
+
self._save_context[
|
53 |
+
"literal_string_class"
|
54 |
+
] = ParserElement._literalStringClass
|
55 |
+
|
56 |
+
self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace
|
57 |
+
|
58 |
+
self._save_context["packrat_enabled"] = ParserElement._packratEnabled
|
59 |
+
if ParserElement._packratEnabled:
|
60 |
+
self._save_context[
|
61 |
+
"packrat_cache_size"
|
62 |
+
] = ParserElement.packrat_cache.size
|
63 |
+
else:
|
64 |
+
self._save_context["packrat_cache_size"] = None
|
65 |
+
self._save_context["packrat_parse"] = ParserElement._parse
|
66 |
+
self._save_context[
|
67 |
+
"recursion_enabled"
|
68 |
+
] = ParserElement._left_recursion_enabled
|
69 |
+
|
70 |
+
self._save_context["__diag__"] = {
|
71 |
+
name: getattr(__diag__, name) for name in __diag__._all_names
|
72 |
+
}
|
73 |
+
|
74 |
+
self._save_context["__compat__"] = {
|
75 |
+
"collect_all_And_tokens": __compat__.collect_all_And_tokens
|
76 |
+
}
|
77 |
+
|
78 |
+
return self
|
79 |
+
|
80 |
+
def restore(self):
|
81 |
+
# reset pyparsing global state
|
82 |
+
if (
|
83 |
+
ParserElement.DEFAULT_WHITE_CHARS
|
84 |
+
!= self._save_context["default_whitespace"]
|
85 |
+
):
|
86 |
+
ParserElement.set_default_whitespace_chars(
|
87 |
+
self._save_context["default_whitespace"]
|
88 |
+
)
|
89 |
+
|
90 |
+
ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"]
|
91 |
+
|
92 |
+
Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"]
|
93 |
+
ParserElement.inlineLiteralsUsing(
|
94 |
+
self._save_context["literal_string_class"]
|
95 |
+
)
|
96 |
+
|
97 |
+
for name, value in self._save_context["__diag__"].items():
|
98 |
+
(__diag__.enable if value else __diag__.disable)(name)
|
99 |
+
|
100 |
+
ParserElement._packratEnabled = False
|
101 |
+
if self._save_context["packrat_enabled"]:
|
102 |
+
ParserElement.enable_packrat(self._save_context["packrat_cache_size"])
|
103 |
+
else:
|
104 |
+
ParserElement._parse = self._save_context["packrat_parse"]
|
105 |
+
ParserElement._left_recursion_enabled = self._save_context[
|
106 |
+
"recursion_enabled"
|
107 |
+
]
|
108 |
+
|
109 |
+
__compat__.collect_all_And_tokens = self._save_context["__compat__"]
|
110 |
+
|
111 |
+
return self
|
112 |
+
|
113 |
+
def copy(self):
|
114 |
+
ret = type(self)()
|
115 |
+
ret._save_context.update(self._save_context)
|
116 |
+
return ret
|
117 |
+
|
118 |
+
def __enter__(self):
|
119 |
+
return self.save()
|
120 |
+
|
121 |
+
def __exit__(self, *args):
|
122 |
+
self.restore()
|
123 |
+
|
124 |
+
class TestParseResultsAsserts:
|
125 |
+
"""
|
126 |
+
A mixin class to add parse results assertion methods to normal unittest.TestCase classes.
|
127 |
+
"""
|
128 |
+
|
129 |
+
def assertParseResultsEquals(
|
130 |
+
self, result, expected_list=None, expected_dict=None, msg=None
|
131 |
+
):
|
132 |
+
"""
|
133 |
+
Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``,
|
134 |
+
and compare any defined results names with an optional ``expected_dict``.
|
135 |
+
"""
|
136 |
+
if expected_list is not None:
|
137 |
+
self.assertEqual(expected_list, result.as_list(), msg=msg)
|
138 |
+
if expected_dict is not None:
|
139 |
+
self.assertEqual(expected_dict, result.as_dict(), msg=msg)
|
140 |
+
|
141 |
+
def assertParseAndCheckList(
|
142 |
+
self, expr, test_string, expected_list, msg=None, verbose=True
|
143 |
+
):
|
144 |
+
"""
|
145 |
+
Convenience wrapper assert to test a parser element and input string, and assert that
|
146 |
+
the resulting ``ParseResults.asList()`` is equal to the ``expected_list``.
|
147 |
+
"""
|
148 |
+
result = expr.parse_string(test_string, parse_all=True)
|
149 |
+
if verbose:
|
150 |
+
print(result.dump())
|
151 |
+
else:
|
152 |
+
print(result.as_list())
|
153 |
+
self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg)
|
154 |
+
|
155 |
+
def assertParseAndCheckDict(
|
156 |
+
self, expr, test_string, expected_dict, msg=None, verbose=True
|
157 |
+
):
|
158 |
+
"""
|
159 |
+
Convenience wrapper assert to test a parser element and input string, and assert that
|
160 |
+
the resulting ``ParseResults.asDict()`` is equal to the ``expected_dict``.
|
161 |
+
"""
|
162 |
+
result = expr.parse_string(test_string, parseAll=True)
|
163 |
+
if verbose:
|
164 |
+
print(result.dump())
|
165 |
+
else:
|
166 |
+
print(result.as_list())
|
167 |
+
self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg)
|
168 |
+
|
169 |
+
def assertRunTestResults(
|
170 |
+
self, run_tests_report, expected_parse_results=None, msg=None
|
171 |
+
):
|
172 |
+
"""
|
173 |
+
Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of
|
174 |
+
list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped
|
175 |
+
with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``.
|
176 |
+
Finally, asserts that the overall ``runTests()`` success value is ``True``.
|
177 |
+
|
178 |
+
:param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests
|
179 |
+
:param expected_parse_results (optional): [tuple(str, list, dict, Exception)]
|
180 |
+
"""
|
181 |
+
run_test_success, run_test_results = run_tests_report
|
182 |
+
|
183 |
+
if expected_parse_results is not None:
|
184 |
+
merged = [
|
185 |
+
(*rpt, expected)
|
186 |
+
for rpt, expected in zip(run_test_results, expected_parse_results)
|
187 |
+
]
|
188 |
+
for test_string, result, expected in merged:
|
189 |
+
# expected should be a tuple containing a list and/or a dict or an exception,
|
190 |
+
# and optional failure message string
|
191 |
+
# an empty tuple will skip any result validation
|
192 |
+
fail_msg = next(
|
193 |
+
(exp for exp in expected if isinstance(exp, str)), None
|
194 |
+
)
|
195 |
+
expected_exception = next(
|
196 |
+
(
|
197 |
+
exp
|
198 |
+
for exp in expected
|
199 |
+
if isinstance(exp, type) and issubclass(exp, Exception)
|
200 |
+
),
|
201 |
+
None,
|
202 |
+
)
|
203 |
+
if expected_exception is not None:
|
204 |
+
with self.assertRaises(
|
205 |
+
expected_exception=expected_exception, msg=fail_msg or msg
|
206 |
+
):
|
207 |
+
if isinstance(result, Exception):
|
208 |
+
raise result
|
209 |
+
else:
|
210 |
+
expected_list = next(
|
211 |
+
(exp for exp in expected if isinstance(exp, list)), None
|
212 |
+
)
|
213 |
+
expected_dict = next(
|
214 |
+
(exp for exp in expected if isinstance(exp, dict)), None
|
215 |
+
)
|
216 |
+
if (expected_list, expected_dict) != (None, None):
|
217 |
+
self.assertParseResultsEquals(
|
218 |
+
result,
|
219 |
+
expected_list=expected_list,
|
220 |
+
expected_dict=expected_dict,
|
221 |
+
msg=fail_msg or msg,
|
222 |
+
)
|
223 |
+
else:
|
224 |
+
# warning here maybe?
|
225 |
+
print("no validation for {!r}".format(test_string))
|
226 |
+
|
227 |
+
# do this last, in case some specific test results can be reported instead
|
228 |
+
self.assertTrue(
|
229 |
+
run_test_success, msg=msg if msg is not None else "failed runTests"
|
230 |
+
)
|
231 |
+
|
232 |
+
@contextmanager
|
233 |
+
def assertRaisesParseException(self, exc_type=ParseException, msg=None):
|
234 |
+
with self.assertRaises(exc_type, msg=msg):
|
235 |
+
yield
|
236 |
+
|
237 |
+
@staticmethod
|
238 |
+
def with_line_numbers(
|
239 |
+
s: str,
|
240 |
+
start_line: Optional[int] = None,
|
241 |
+
end_line: Optional[int] = None,
|
242 |
+
expand_tabs: bool = True,
|
243 |
+
eol_mark: str = "|",
|
244 |
+
mark_spaces: Optional[str] = None,
|
245 |
+
mark_control: Optional[str] = None,
|
246 |
+
) -> str:
|
247 |
+
"""
|
248 |
+
Helpful method for debugging a parser - prints a string with line and column numbers.
|
249 |
+
(Line and column numbers are 1-based.)
|
250 |
+
|
251 |
+
:param s: tuple(bool, str - string to be printed with line and column numbers
|
252 |
+
:param start_line: int - (optional) starting line number in s to print (default=1)
|
253 |
+
:param end_line: int - (optional) ending line number in s to print (default=len(s))
|
254 |
+
:param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default
|
255 |
+
:param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default="|")
|
256 |
+
:param mark_spaces: str - (optional) special character to display in place of spaces
|
257 |
+
:param mark_control: str - (optional) convert non-printing control characters to a placeholding
|
258 |
+
character; valid values:
|
259 |
+
- "unicode" - replaces control chars with Unicode symbols, such as "␍" and "␊"
|
260 |
+
- any single character string - replace control characters with given string
|
261 |
+
- None (default) - string is displayed as-is
|
262 |
+
|
263 |
+
:return: str - input string with leading line numbers and column number headers
|
264 |
+
"""
|
265 |
+
if expand_tabs:
|
266 |
+
s = s.expandtabs()
|
267 |
+
if mark_control is not None:
|
268 |
+
if mark_control == "unicode":
|
269 |
+
tbl = str.maketrans(
|
270 |
+
{c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433))}
|
271 |
+
| {127: 0x2421}
|
272 |
+
)
|
273 |
+
eol_mark = ""
|
274 |
+
else:
|
275 |
+
tbl = str.maketrans(
|
276 |
+
{c: mark_control for c in list(range(0, 32)) + [127]}
|
277 |
+
)
|
278 |
+
s = s.translate(tbl)
|
279 |
+
if mark_spaces is not None and mark_spaces != " ":
|
280 |
+
if mark_spaces == "unicode":
|
281 |
+
tbl = str.maketrans({9: 0x2409, 32: 0x2423})
|
282 |
+
s = s.translate(tbl)
|
283 |
+
else:
|
284 |
+
s = s.replace(" ", mark_spaces)
|
285 |
+
if start_line is None:
|
286 |
+
start_line = 1
|
287 |
+
if end_line is None:
|
288 |
+
end_line = len(s)
|
289 |
+
end_line = min(end_line, len(s))
|
290 |
+
start_line = min(max(1, start_line), end_line)
|
291 |
+
|
292 |
+
if mark_control != "unicode":
|
293 |
+
s_lines = s.splitlines()[start_line - 1 : end_line]
|
294 |
+
else:
|
295 |
+
s_lines = [line + "␊" for line in s.split("␊")[start_line - 1 : end_line]]
|
296 |
+
if not s_lines:
|
297 |
+
return ""
|
298 |
+
|
299 |
+
lineno_width = len(str(end_line))
|
300 |
+
max_line_len = max(len(line) for line in s_lines)
|
301 |
+
lead = " " * (lineno_width + 1)
|
302 |
+
if max_line_len >= 99:
|
303 |
+
header0 = (
|
304 |
+
lead
|
305 |
+
+ "".join(
|
306 |
+
"{}{}".format(" " * 99, (i + 1) % 100)
|
307 |
+
for i in range(max(max_line_len // 100, 1))
|
308 |
+
)
|
309 |
+
+ "\n"
|
310 |
+
)
|
311 |
+
else:
|
312 |
+
header0 = ""
|
313 |
+
header1 = (
|
314 |
+
header0
|
315 |
+
+ lead
|
316 |
+
+ "".join(
|
317 |
+
" {}".format((i + 1) % 10)
|
318 |
+
for i in range(-(-max_line_len // 10))
|
319 |
+
)
|
320 |
+
+ "\n"
|
321 |
+
)
|
322 |
+
header2 = lead + "1234567890" * (-(-max_line_len // 10)) + "\n"
|
323 |
+
return (
|
324 |
+
header1
|
325 |
+
+ header2
|
326 |
+
+ "\n".join(
|
327 |
+
"{:{}d}:{}{}".format(i, lineno_width, line, eol_mark)
|
328 |
+
for i, line in enumerate(s_lines, start=start_line)
|
329 |
+
)
|
330 |
+
+ "\n"
|
331 |
+
)
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/unicode.py
ADDED
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# unicode.py
|
2 |
+
|
3 |
+
import sys
|
4 |
+
from itertools import filterfalse
|
5 |
+
from typing import List, Tuple, Union
|
6 |
+
|
7 |
+
|
8 |
+
class _lazyclassproperty:
|
9 |
+
def __init__(self, fn):
|
10 |
+
self.fn = fn
|
11 |
+
self.__doc__ = fn.__doc__
|
12 |
+
self.__name__ = fn.__name__
|
13 |
+
|
14 |
+
def __get__(self, obj, cls):
|
15 |
+
if cls is None:
|
16 |
+
cls = type(obj)
|
17 |
+
if not hasattr(cls, "_intern") or any(
|
18 |
+
cls._intern is getattr(superclass, "_intern", [])
|
19 |
+
for superclass in cls.__mro__[1:]
|
20 |
+
):
|
21 |
+
cls._intern = {}
|
22 |
+
attrname = self.fn.__name__
|
23 |
+
if attrname not in cls._intern:
|
24 |
+
cls._intern[attrname] = self.fn(cls)
|
25 |
+
return cls._intern[attrname]
|
26 |
+
|
27 |
+
|
28 |
+
UnicodeRangeList = List[Union[Tuple[int, int], Tuple[int]]]
|
29 |
+
|
30 |
+
|
31 |
+
class unicode_set:
|
32 |
+
"""
|
33 |
+
A set of Unicode characters, for language-specific strings for
|
34 |
+
``alphas``, ``nums``, ``alphanums``, and ``printables``.
|
35 |
+
A unicode_set is defined by a list of ranges in the Unicode character
|
36 |
+
set, in a class attribute ``_ranges``. Ranges can be specified using
|
37 |
+
2-tuples or a 1-tuple, such as::
|
38 |
+
|
39 |
+
_ranges = [
|
40 |
+
(0x0020, 0x007e),
|
41 |
+
(0x00a0, 0x00ff),
|
42 |
+
(0x0100,),
|
43 |
+
]
|
44 |
+
|
45 |
+
Ranges are left- and right-inclusive. A 1-tuple of (x,) is treated as (x, x).
|
46 |
+
|
47 |
+
A unicode set can also be defined using multiple inheritance of other unicode sets::
|
48 |
+
|
49 |
+
class CJK(Chinese, Japanese, Korean):
|
50 |
+
pass
|
51 |
+
"""
|
52 |
+
|
53 |
+
_ranges: UnicodeRangeList = []
|
54 |
+
|
55 |
+
@_lazyclassproperty
|
56 |
+
def _chars_for_ranges(cls):
|
57 |
+
ret = []
|
58 |
+
for cc in cls.__mro__:
|
59 |
+
if cc is unicode_set:
|
60 |
+
break
|
61 |
+
for rr in getattr(cc, "_ranges", ()):
|
62 |
+
ret.extend(range(rr[0], rr[-1] + 1))
|
63 |
+
return [chr(c) for c in sorted(set(ret))]
|
64 |
+
|
65 |
+
@_lazyclassproperty
|
66 |
+
def printables(cls):
|
67 |
+
"all non-whitespace characters in this range"
|
68 |
+
return "".join(filterfalse(str.isspace, cls._chars_for_ranges))
|
69 |
+
|
70 |
+
@_lazyclassproperty
|
71 |
+
def alphas(cls):
|
72 |
+
"all alphabetic characters in this range"
|
73 |
+
return "".join(filter(str.isalpha, cls._chars_for_ranges))
|
74 |
+
|
75 |
+
@_lazyclassproperty
|
76 |
+
def nums(cls):
|
77 |
+
"all numeric digit characters in this range"
|
78 |
+
return "".join(filter(str.isdigit, cls._chars_for_ranges))
|
79 |
+
|
80 |
+
@_lazyclassproperty
|
81 |
+
def alphanums(cls):
|
82 |
+
"all alphanumeric characters in this range"
|
83 |
+
return cls.alphas + cls.nums
|
84 |
+
|
85 |
+
@_lazyclassproperty
|
86 |
+
def identchars(cls):
|
87 |
+
"all characters in this range that are valid identifier characters, plus underscore '_'"
|
88 |
+
return "".join(
|
89 |
+
sorted(
|
90 |
+
set(
|
91 |
+
"".join(filter(str.isidentifier, cls._chars_for_ranges))
|
92 |
+
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzªµº"
|
93 |
+
+ "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ"
|
94 |
+
+ "_"
|
95 |
+
)
|
96 |
+
)
|
97 |
+
)
|
98 |
+
|
99 |
+
@_lazyclassproperty
|
100 |
+
def identbodychars(cls):
|
101 |
+
"""
|
102 |
+
all characters in this range that are valid identifier body characters,
|
103 |
+
plus the digits 0-9
|
104 |
+
"""
|
105 |
+
return "".join(
|
106 |
+
sorted(
|
107 |
+
set(
|
108 |
+
cls.identchars
|
109 |
+
+ "0123456789"
|
110 |
+
+ "".join(
|
111 |
+
[c for c in cls._chars_for_ranges if ("_" + c).isidentifier()]
|
112 |
+
)
|
113 |
+
)
|
114 |
+
)
|
115 |
+
)
|
116 |
+
|
117 |
+
|
118 |
+
class pyparsing_unicode(unicode_set):
|
119 |
+
"""
|
120 |
+
A namespace class for defining common language unicode_sets.
|
121 |
+
"""
|
122 |
+
|
123 |
+
_ranges: UnicodeRangeList = [(32, sys.maxunicode)]
|
124 |
+
|
125 |
+
class Latin1(unicode_set):
|
126 |
+
"Unicode set for Latin-1 Unicode Character Range"
|
127 |
+
_ranges: UnicodeRangeList = [
|
128 |
+
(0x0020, 0x007E),
|
129 |
+
(0x00A0, 0x00FF),
|
130 |
+
]
|
131 |
+
|
132 |
+
class LatinA(unicode_set):
|
133 |
+
"Unicode set for Latin-A Unicode Character Range"
|
134 |
+
_ranges: UnicodeRangeList = [
|
135 |
+
(0x0100, 0x017F),
|
136 |
+
]
|
137 |
+
|
138 |
+
class LatinB(unicode_set):
|
139 |
+
"Unicode set for Latin-B Unicode Character Range"
|
140 |
+
_ranges: UnicodeRangeList = [
|
141 |
+
(0x0180, 0x024F),
|
142 |
+
]
|
143 |
+
|
144 |
+
class Greek(unicode_set):
|
145 |
+
"Unicode set for Greek Unicode Character Ranges"
|
146 |
+
_ranges: UnicodeRangeList = [
|
147 |
+
(0x0342, 0x0345),
|
148 |
+
(0x0370, 0x0377),
|
149 |
+
(0x037A, 0x037F),
|
150 |
+
(0x0384, 0x038A),
|
151 |
+
(0x038C,),
|
152 |
+
(0x038E, 0x03A1),
|
153 |
+
(0x03A3, 0x03E1),
|
154 |
+
(0x03F0, 0x03FF),
|
155 |
+
(0x1D26, 0x1D2A),
|
156 |
+
(0x1D5E,),
|
157 |
+
(0x1D60,),
|
158 |
+
(0x1D66, 0x1D6A),
|
159 |
+
(0x1F00, 0x1F15),
|
160 |
+
(0x1F18, 0x1F1D),
|
161 |
+
(0x1F20, 0x1F45),
|
162 |
+
(0x1F48, 0x1F4D),
|
163 |
+
(0x1F50, 0x1F57),
|
164 |
+
(0x1F59,),
|
165 |
+
(0x1F5B,),
|
166 |
+
(0x1F5D,),
|
167 |
+
(0x1F5F, 0x1F7D),
|
168 |
+
(0x1F80, 0x1FB4),
|
169 |
+
(0x1FB6, 0x1FC4),
|
170 |
+
(0x1FC6, 0x1FD3),
|
171 |
+
(0x1FD6, 0x1FDB),
|
172 |
+
(0x1FDD, 0x1FEF),
|
173 |
+
(0x1FF2, 0x1FF4),
|
174 |
+
(0x1FF6, 0x1FFE),
|
175 |
+
(0x2129,),
|
176 |
+
(0x2719, 0x271A),
|
177 |
+
(0xAB65,),
|
178 |
+
(0x10140, 0x1018D),
|
179 |
+
(0x101A0,),
|
180 |
+
(0x1D200, 0x1D245),
|
181 |
+
(0x1F7A1, 0x1F7A7),
|
182 |
+
]
|
183 |
+
|
184 |
+
class Cyrillic(unicode_set):
|
185 |
+
"Unicode set for Cyrillic Unicode Character Range"
|
186 |
+
_ranges: UnicodeRangeList = [
|
187 |
+
(0x0400, 0x052F),
|
188 |
+
(0x1C80, 0x1C88),
|
189 |
+
(0x1D2B,),
|
190 |
+
(0x1D78,),
|
191 |
+
(0x2DE0, 0x2DFF),
|
192 |
+
(0xA640, 0xA672),
|
193 |
+
(0xA674, 0xA69F),
|
194 |
+
(0xFE2E, 0xFE2F),
|
195 |
+
]
|
196 |
+
|
197 |
+
class Chinese(unicode_set):
|
198 |
+
"Unicode set for Chinese Unicode Character Range"
|
199 |
+
_ranges: UnicodeRangeList = [
|
200 |
+
(0x2E80, 0x2E99),
|
201 |
+
(0x2E9B, 0x2EF3),
|
202 |
+
(0x31C0, 0x31E3),
|
203 |
+
(0x3400, 0x4DB5),
|
204 |
+
(0x4E00, 0x9FEF),
|
205 |
+
(0xA700, 0xA707),
|
206 |
+
(0xF900, 0xFA6D),
|
207 |
+
(0xFA70, 0xFAD9),
|
208 |
+
(0x16FE2, 0x16FE3),
|
209 |
+
(0x1F210, 0x1F212),
|
210 |
+
(0x1F214, 0x1F23B),
|
211 |
+
(0x1F240, 0x1F248),
|
212 |
+
(0x20000, 0x2A6D6),
|
213 |
+
(0x2A700, 0x2B734),
|
214 |
+
(0x2B740, 0x2B81D),
|
215 |
+
(0x2B820, 0x2CEA1),
|
216 |
+
(0x2CEB0, 0x2EBE0),
|
217 |
+
(0x2F800, 0x2FA1D),
|
218 |
+
]
|
219 |
+
|
220 |
+
class Japanese(unicode_set):
|
221 |
+
"Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges"
|
222 |
+
_ranges: UnicodeRangeList = []
|
223 |
+
|
224 |
+
class Kanji(unicode_set):
|
225 |
+
"Unicode set for Kanji Unicode Character Range"
|
226 |
+
_ranges: UnicodeRangeList = [
|
227 |
+
(0x4E00, 0x9FBF),
|
228 |
+
(0x3000, 0x303F),
|
229 |
+
]
|
230 |
+
|
231 |
+
class Hiragana(unicode_set):
|
232 |
+
"Unicode set for Hiragana Unicode Character Range"
|
233 |
+
_ranges: UnicodeRangeList = [
|
234 |
+
(0x3041, 0x3096),
|
235 |
+
(0x3099, 0x30A0),
|
236 |
+
(0x30FC,),
|
237 |
+
(0xFF70,),
|
238 |
+
(0x1B001,),
|
239 |
+
(0x1B150, 0x1B152),
|
240 |
+
(0x1F200,),
|
241 |
+
]
|
242 |
+
|
243 |
+
class Katakana(unicode_set):
|
244 |
+
"Unicode set for Katakana Unicode Character Range"
|
245 |
+
_ranges: UnicodeRangeList = [
|
246 |
+
(0x3099, 0x309C),
|
247 |
+
(0x30A0, 0x30FF),
|
248 |
+
(0x31F0, 0x31FF),
|
249 |
+
(0x32D0, 0x32FE),
|
250 |
+
(0xFF65, 0xFF9F),
|
251 |
+
(0x1B000,),
|
252 |
+
(0x1B164, 0x1B167),
|
253 |
+
(0x1F201, 0x1F202),
|
254 |
+
(0x1F213,),
|
255 |
+
]
|
256 |
+
|
257 |
+
class Hangul(unicode_set):
|
258 |
+
"Unicode set for Hangul (Korean) Unicode Character Range"
|
259 |
+
_ranges: UnicodeRangeList = [
|
260 |
+
(0x1100, 0x11FF),
|
261 |
+
(0x302E, 0x302F),
|
262 |
+
(0x3131, 0x318E),
|
263 |
+
(0x3200, 0x321C),
|
264 |
+
(0x3260, 0x327B),
|
265 |
+
(0x327E,),
|
266 |
+
(0xA960, 0xA97C),
|
267 |
+
(0xAC00, 0xD7A3),
|
268 |
+
(0xD7B0, 0xD7C6),
|
269 |
+
(0xD7CB, 0xD7FB),
|
270 |
+
(0xFFA0, 0xFFBE),
|
271 |
+
(0xFFC2, 0xFFC7),
|
272 |
+
(0xFFCA, 0xFFCF),
|
273 |
+
(0xFFD2, 0xFFD7),
|
274 |
+
(0xFFDA, 0xFFDC),
|
275 |
+
]
|
276 |
+
|
277 |
+
Korean = Hangul
|
278 |
+
|
279 |
+
class CJK(Chinese, Japanese, Hangul):
|
280 |
+
"Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range"
|
281 |
+
pass
|
282 |
+
|
283 |
+
class Thai(unicode_set):
|
284 |
+
"Unicode set for Thai Unicode Character Range"
|
285 |
+
_ranges: UnicodeRangeList = [(0x0E01, 0x0E3A), (0x0E3F, 0x0E5B)]
|
286 |
+
|
287 |
+
class Arabic(unicode_set):
|
288 |
+
"Unicode set for Arabic Unicode Character Range"
|
289 |
+
_ranges: UnicodeRangeList = [
|
290 |
+
(0x0600, 0x061B),
|
291 |
+
(0x061E, 0x06FF),
|
292 |
+
(0x0700, 0x077F),
|
293 |
+
]
|
294 |
+
|
295 |
+
class Hebrew(unicode_set):
|
296 |
+
"Unicode set for Hebrew Unicode Character Range"
|
297 |
+
_ranges: UnicodeRangeList = [
|
298 |
+
(0x0591, 0x05C7),
|
299 |
+
(0x05D0, 0x05EA),
|
300 |
+
(0x05EF, 0x05F4),
|
301 |
+
(0xFB1D, 0xFB36),
|
302 |
+
(0xFB38, 0xFB3C),
|
303 |
+
(0xFB3E,),
|
304 |
+
(0xFB40, 0xFB41),
|
305 |
+
(0xFB43, 0xFB44),
|
306 |
+
(0xFB46, 0xFB4F),
|
307 |
+
]
|
308 |
+
|
309 |
+
class Devanagari(unicode_set):
|
310 |
+
"Unicode set for Devanagari Unicode Character Range"
|
311 |
+
_ranges: UnicodeRangeList = [(0x0900, 0x097F), (0xA8E0, 0xA8FF)]
|
312 |
+
|
313 |
+
|
314 |
+
pyparsing_unicode.Japanese._ranges = (
|
315 |
+
pyparsing_unicode.Japanese.Kanji._ranges
|
316 |
+
+ pyparsing_unicode.Japanese.Hiragana._ranges
|
317 |
+
+ pyparsing_unicode.Japanese.Katakana._ranges
|
318 |
+
)
|
319 |
+
|
320 |
+
# define ranges in language character sets
|
321 |
+
pyparsing_unicode.العربية = pyparsing_unicode.Arabic
|
322 |
+
pyparsing_unicode.中文 = pyparsing_unicode.Chinese
|
323 |
+
pyparsing_unicode.кириллица = pyparsing_unicode.Cyrillic
|
324 |
+
pyparsing_unicode.Ελληνικά = pyparsing_unicode.Greek
|
325 |
+
pyparsing_unicode.עִברִית = pyparsing_unicode.Hebrew
|
326 |
+
pyparsing_unicode.日本語 = pyparsing_unicode.Japanese
|
327 |
+
pyparsing_unicode.Japanese.漢字 = pyparsing_unicode.Japanese.Kanji
|
328 |
+
pyparsing_unicode.Japanese.カタカナ = pyparsing_unicode.Japanese.Katakana
|
329 |
+
pyparsing_unicode.Japanese.ひらがな = pyparsing_unicode.Japanese.Hiragana
|
330 |
+
pyparsing_unicode.한국어 = pyparsing_unicode.Korean
|
331 |
+
pyparsing_unicode.ไทย = pyparsing_unicode.Thai
|
332 |
+
pyparsing_unicode.देवनागरी = pyparsing_unicode.Devanagari
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/pyparsing/util.py
ADDED
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# util.py
|
2 |
+
import warnings
|
3 |
+
import types
|
4 |
+
import collections
|
5 |
+
import itertools
|
6 |
+
from functools import lru_cache
|
7 |
+
from typing import List, Union, Iterable
|
8 |
+
|
9 |
+
_bslash = chr(92)
|
10 |
+
|
11 |
+
|
12 |
+
class __config_flags:
|
13 |
+
"""Internal class for defining compatibility and debugging flags"""
|
14 |
+
|
15 |
+
_all_names: List[str] = []
|
16 |
+
_fixed_names: List[str] = []
|
17 |
+
_type_desc = "configuration"
|
18 |
+
|
19 |
+
@classmethod
|
20 |
+
def _set(cls, dname, value):
|
21 |
+
if dname in cls._fixed_names:
|
22 |
+
warnings.warn(
|
23 |
+
"{}.{} {} is {} and cannot be overridden".format(
|
24 |
+
cls.__name__,
|
25 |
+
dname,
|
26 |
+
cls._type_desc,
|
27 |
+
str(getattr(cls, dname)).upper(),
|
28 |
+
)
|
29 |
+
)
|
30 |
+
return
|
31 |
+
if dname in cls._all_names:
|
32 |
+
setattr(cls, dname, value)
|
33 |
+
else:
|
34 |
+
raise ValueError("no such {} {!r}".format(cls._type_desc, dname))
|
35 |
+
|
36 |
+
enable = classmethod(lambda cls, name: cls._set(name, True))
|
37 |
+
disable = classmethod(lambda cls, name: cls._set(name, False))
|
38 |
+
|
39 |
+
|
40 |
+
@lru_cache(maxsize=128)
|
41 |
+
def col(loc: int, strg: str) -> int:
|
42 |
+
"""
|
43 |
+
Returns current column within a string, counting newlines as line separators.
|
44 |
+
The first column is number 1.
|
45 |
+
|
46 |
+
Note: the default parsing behavior is to expand tabs in the input string
|
47 |
+
before starting the parsing process. See
|
48 |
+
:class:`ParserElement.parseString` for more
|
49 |
+
information on parsing strings containing ``<TAB>`` s, and suggested
|
50 |
+
methods to maintain a consistent view of the parsed string, the parse
|
51 |
+
location, and line and column positions within the parsed string.
|
52 |
+
"""
|
53 |
+
s = strg
|
54 |
+
return 1 if 0 < loc < len(s) and s[loc - 1] == "\n" else loc - s.rfind("\n", 0, loc)
|
55 |
+
|
56 |
+
|
57 |
+
@lru_cache(maxsize=128)
|
58 |
+
def lineno(loc: int, strg: str) -> int:
|
59 |
+
"""Returns current line number within a string, counting newlines as line separators.
|
60 |
+
The first line is number 1.
|
61 |
+
|
62 |
+
Note - the default parsing behavior is to expand tabs in the input string
|
63 |
+
before starting the parsing process. See :class:`ParserElement.parseString`
|
64 |
+
for more information on parsing strings containing ``<TAB>`` s, and
|
65 |
+
suggested methods to maintain a consistent view of the parsed string, the
|
66 |
+
parse location, and line and column positions within the parsed string.
|
67 |
+
"""
|
68 |
+
return strg.count("\n", 0, loc) + 1
|
69 |
+
|
70 |
+
|
71 |
+
@lru_cache(maxsize=128)
|
72 |
+
def line(loc: int, strg: str) -> str:
|
73 |
+
"""
|
74 |
+
Returns the line of text containing loc within a string, counting newlines as line separators.
|
75 |
+
"""
|
76 |
+
last_cr = strg.rfind("\n", 0, loc)
|
77 |
+
next_cr = strg.find("\n", loc)
|
78 |
+
return strg[last_cr + 1 : next_cr] if next_cr >= 0 else strg[last_cr + 1 :]
|
79 |
+
|
80 |
+
|
81 |
+
class _UnboundedCache:
|
82 |
+
def __init__(self):
|
83 |
+
cache = {}
|
84 |
+
cache_get = cache.get
|
85 |
+
self.not_in_cache = not_in_cache = object()
|
86 |
+
|
87 |
+
def get(_, key):
|
88 |
+
return cache_get(key, not_in_cache)
|
89 |
+
|
90 |
+
def set_(_, key, value):
|
91 |
+
cache[key] = value
|
92 |
+
|
93 |
+
def clear(_):
|
94 |
+
cache.clear()
|
95 |
+
|
96 |
+
self.size = None
|
97 |
+
self.get = types.MethodType(get, self)
|
98 |
+
self.set = types.MethodType(set_, self)
|
99 |
+
self.clear = types.MethodType(clear, self)
|
100 |
+
|
101 |
+
|
102 |
+
class _FifoCache:
|
103 |
+
def __init__(self, size):
|
104 |
+
self.not_in_cache = not_in_cache = object()
|
105 |
+
cache = collections.OrderedDict()
|
106 |
+
cache_get = cache.get
|
107 |
+
|
108 |
+
def get(_, key):
|
109 |
+
return cache_get(key, not_in_cache)
|
110 |
+
|
111 |
+
def set_(_, key, value):
|
112 |
+
cache[key] = value
|
113 |
+
while len(cache) > size:
|
114 |
+
cache.popitem(last=False)
|
115 |
+
|
116 |
+
def clear(_):
|
117 |
+
cache.clear()
|
118 |
+
|
119 |
+
self.size = size
|
120 |
+
self.get = types.MethodType(get, self)
|
121 |
+
self.set = types.MethodType(set_, self)
|
122 |
+
self.clear = types.MethodType(clear, self)
|
123 |
+
|
124 |
+
|
125 |
+
class LRUMemo:
|
126 |
+
"""
|
127 |
+
A memoizing mapping that retains `capacity` deleted items
|
128 |
+
|
129 |
+
The memo tracks retained items by their access order; once `capacity` items
|
130 |
+
are retained, the least recently used item is discarded.
|
131 |
+
"""
|
132 |
+
|
133 |
+
def __init__(self, capacity):
|
134 |
+
self._capacity = capacity
|
135 |
+
self._active = {}
|
136 |
+
self._memory = collections.OrderedDict()
|
137 |
+
|
138 |
+
def __getitem__(self, key):
|
139 |
+
try:
|
140 |
+
return self._active[key]
|
141 |
+
except KeyError:
|
142 |
+
self._memory.move_to_end(key)
|
143 |
+
return self._memory[key]
|
144 |
+
|
145 |
+
def __setitem__(self, key, value):
|
146 |
+
self._memory.pop(key, None)
|
147 |
+
self._active[key] = value
|
148 |
+
|
149 |
+
def __delitem__(self, key):
|
150 |
+
try:
|
151 |
+
value = self._active.pop(key)
|
152 |
+
except KeyError:
|
153 |
+
pass
|
154 |
+
else:
|
155 |
+
while len(self._memory) >= self._capacity:
|
156 |
+
self._memory.popitem(last=False)
|
157 |
+
self._memory[key] = value
|
158 |
+
|
159 |
+
def clear(self):
|
160 |
+
self._active.clear()
|
161 |
+
self._memory.clear()
|
162 |
+
|
163 |
+
|
164 |
+
class UnboundedMemo(dict):
|
165 |
+
"""
|
166 |
+
A memoizing mapping that retains all deleted items
|
167 |
+
"""
|
168 |
+
|
169 |
+
def __delitem__(self, key):
|
170 |
+
pass
|
171 |
+
|
172 |
+
|
173 |
+
def _escape_regex_range_chars(s: str) -> str:
|
174 |
+
# escape these chars: ^-[]
|
175 |
+
for c in r"\^-[]":
|
176 |
+
s = s.replace(c, _bslash + c)
|
177 |
+
s = s.replace("\n", r"\n")
|
178 |
+
s = s.replace("\t", r"\t")
|
179 |
+
return str(s)
|
180 |
+
|
181 |
+
|
182 |
+
def _collapse_string_to_ranges(
|
183 |
+
s: Union[str, Iterable[str]], re_escape: bool = True
|
184 |
+
) -> str:
|
185 |
+
def is_consecutive(c):
|
186 |
+
c_int = ord(c)
|
187 |
+
is_consecutive.prev, prev = c_int, is_consecutive.prev
|
188 |
+
if c_int - prev > 1:
|
189 |
+
is_consecutive.value = next(is_consecutive.counter)
|
190 |
+
return is_consecutive.value
|
191 |
+
|
192 |
+
is_consecutive.prev = 0
|
193 |
+
is_consecutive.counter = itertools.count()
|
194 |
+
is_consecutive.value = -1
|
195 |
+
|
196 |
+
def escape_re_range_char(c):
|
197 |
+
return "\\" + c if c in r"\^-][" else c
|
198 |
+
|
199 |
+
def no_escape_re_range_char(c):
|
200 |
+
return c
|
201 |
+
|
202 |
+
if not re_escape:
|
203 |
+
escape_re_range_char = no_escape_re_range_char
|
204 |
+
|
205 |
+
ret = []
|
206 |
+
s = "".join(sorted(set(s)))
|
207 |
+
if len(s) > 3:
|
208 |
+
for _, chars in itertools.groupby(s, key=is_consecutive):
|
209 |
+
first = last = next(chars)
|
210 |
+
last = collections.deque(
|
211 |
+
itertools.chain(iter([last]), chars), maxlen=1
|
212 |
+
).pop()
|
213 |
+
if first == last:
|
214 |
+
ret.append(escape_re_range_char(first))
|
215 |
+
else:
|
216 |
+
sep = "" if ord(last) == ord(first) + 1 else "-"
|
217 |
+
ret.append(
|
218 |
+
"{}{}{}".format(
|
219 |
+
escape_re_range_char(first), sep, escape_re_range_char(last)
|
220 |
+
)
|
221 |
+
)
|
222 |
+
else:
|
223 |
+
ret = [escape_re_range_char(c) for c in s]
|
224 |
+
|
225 |
+
return "".join(ret)
|
226 |
+
|
227 |
+
|
228 |
+
def _flatten(ll: list) -> list:
|
229 |
+
ret = []
|
230 |
+
for i in ll:
|
231 |
+
if isinstance(i, list):
|
232 |
+
ret.extend(_flatten(i))
|
233 |
+
else:
|
234 |
+
ret.append(i)
|
235 |
+
return ret
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/tenacity/__init__.py
ADDED
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2016-2018 Julien Danjou
|
2 |
+
# Copyright 2017 Elisey Zanko
|
3 |
+
# Copyright 2016 Étienne Bersac
|
4 |
+
# Copyright 2016 Joshua Harlow
|
5 |
+
# Copyright 2013-2014 Ray Holder
|
6 |
+
#
|
7 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
8 |
+
# you may not use this file except in compliance with the License.
|
9 |
+
# You may obtain a copy of the License at
|
10 |
+
#
|
11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
12 |
+
#
|
13 |
+
# Unless required by applicable law or agreed to in writing, software
|
14 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
15 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
16 |
+
# See the License for the specific language governing permissions and
|
17 |
+
# limitations under the License.
|
18 |
+
|
19 |
+
import functools
|
20 |
+
import sys
|
21 |
+
import threading
|
22 |
+
import time
|
23 |
+
import typing as t
|
24 |
+
import warnings
|
25 |
+
from abc import ABC, abstractmethod
|
26 |
+
from concurrent import futures
|
27 |
+
from inspect import iscoroutinefunction
|
28 |
+
|
29 |
+
# Import all built-in retry strategies for easier usage.
|
30 |
+
from .retry import retry_base # noqa
|
31 |
+
from .retry import retry_all # noqa
|
32 |
+
from .retry import retry_always # noqa
|
33 |
+
from .retry import retry_any # noqa
|
34 |
+
from .retry import retry_if_exception # noqa
|
35 |
+
from .retry import retry_if_exception_type # noqa
|
36 |
+
from .retry import retry_if_not_exception_type # noqa
|
37 |
+
from .retry import retry_if_not_result # noqa
|
38 |
+
from .retry import retry_if_result # noqa
|
39 |
+
from .retry import retry_never # noqa
|
40 |
+
from .retry import retry_unless_exception_type # noqa
|
41 |
+
from .retry import retry_if_exception_message # noqa
|
42 |
+
from .retry import retry_if_not_exception_message # noqa
|
43 |
+
|
44 |
+
# Import all nap strategies for easier usage.
|
45 |
+
from .nap import sleep # noqa
|
46 |
+
from .nap import sleep_using_event # noqa
|
47 |
+
|
48 |
+
# Import all built-in stop strategies for easier usage.
|
49 |
+
from .stop import stop_after_attempt # noqa
|
50 |
+
from .stop import stop_after_delay # noqa
|
51 |
+
from .stop import stop_all # noqa
|
52 |
+
from .stop import stop_any # noqa
|
53 |
+
from .stop import stop_never # noqa
|
54 |
+
from .stop import stop_when_event_set # noqa
|
55 |
+
|
56 |
+
# Import all built-in wait strategies for easier usage.
|
57 |
+
from .wait import wait_chain # noqa
|
58 |
+
from .wait import wait_combine # noqa
|
59 |
+
from .wait import wait_exponential # noqa
|
60 |
+
from .wait import wait_fixed # noqa
|
61 |
+
from .wait import wait_incrementing # noqa
|
62 |
+
from .wait import wait_none # noqa
|
63 |
+
from .wait import wait_random # noqa
|
64 |
+
from .wait import wait_random_exponential # noqa
|
65 |
+
from .wait import wait_random_exponential as wait_full_jitter # noqa
|
66 |
+
|
67 |
+
# Import all built-in before strategies for easier usage.
|
68 |
+
from .before import before_log # noqa
|
69 |
+
from .before import before_nothing # noqa
|
70 |
+
|
71 |
+
# Import all built-in after strategies for easier usage.
|
72 |
+
from .after import after_log # noqa
|
73 |
+
from .after import after_nothing # noqa
|
74 |
+
|
75 |
+
# Import all built-in after strategies for easier usage.
|
76 |
+
from .before_sleep import before_sleep_log # noqa
|
77 |
+
from .before_sleep import before_sleep_nothing # noqa
|
78 |
+
|
79 |
+
# Replace a conditional import with a hard-coded None so that pip does
|
80 |
+
# not attempt to use tornado even if it is present in the environment.
|
81 |
+
# If tornado is non-None, tenacity will attempt to execute some code
|
82 |
+
# that is sensitive to the version of tornado, which could break pip
|
83 |
+
# if an old version is found.
|
84 |
+
tornado = None # type: ignore
|
85 |
+
|
86 |
+
if t.TYPE_CHECKING:
|
87 |
+
import types
|
88 |
+
|
89 |
+
from .wait import wait_base
|
90 |
+
from .stop import stop_base
|
91 |
+
|
92 |
+
|
93 |
+
WrappedFn = t.TypeVar("WrappedFn", bound=t.Callable)
|
94 |
+
_RetValT = t.TypeVar("_RetValT")
|
95 |
+
|
96 |
+
|
97 |
+
@t.overload
|
98 |
+
def retry(fn: WrappedFn) -> WrappedFn:
|
99 |
+
pass
|
100 |
+
|
101 |
+
|
102 |
+
@t.overload
|
103 |
+
def retry(*dargs: t.Any, **dkw: t.Any) -> t.Callable[[WrappedFn], WrappedFn]: # noqa
|
104 |
+
pass
|
105 |
+
|
106 |
+
|
107 |
+
def retry(*dargs: t.Any, **dkw: t.Any) -> t.Union[WrappedFn, t.Callable[[WrappedFn], WrappedFn]]: # noqa
|
108 |
+
"""Wrap a function with a new `Retrying` object.
|
109 |
+
|
110 |
+
:param dargs: positional arguments passed to Retrying object
|
111 |
+
:param dkw: keyword arguments passed to the Retrying object
|
112 |
+
"""
|
113 |
+
# support both @retry and @retry() as valid syntax
|
114 |
+
if len(dargs) == 1 and callable(dargs[0]):
|
115 |
+
return retry()(dargs[0])
|
116 |
+
else:
|
117 |
+
|
118 |
+
def wrap(f: WrappedFn) -> WrappedFn:
|
119 |
+
if isinstance(f, retry_base):
|
120 |
+
warnings.warn(
|
121 |
+
f"Got retry_base instance ({f.__class__.__name__}) as callable argument, "
|
122 |
+
f"this will probably hang indefinitely (did you mean retry={f.__class__.__name__}(...)?)"
|
123 |
+
)
|
124 |
+
if iscoroutinefunction(f):
|
125 |
+
r: "BaseRetrying" = AsyncRetrying(*dargs, **dkw)
|
126 |
+
elif tornado and hasattr(tornado.gen, "is_coroutine_function") and tornado.gen.is_coroutine_function(f):
|
127 |
+
r = TornadoRetrying(*dargs, **dkw)
|
128 |
+
else:
|
129 |
+
r = Retrying(*dargs, **dkw)
|
130 |
+
|
131 |
+
return r.wraps(f)
|
132 |
+
|
133 |
+
return wrap
|
134 |
+
|
135 |
+
|
136 |
+
class TryAgain(Exception):
|
137 |
+
"""Always retry the executed function when raised."""
|
138 |
+
|
139 |
+
|
140 |
+
NO_RESULT = object()
|
141 |
+
|
142 |
+
|
143 |
+
class DoAttempt:
|
144 |
+
pass
|
145 |
+
|
146 |
+
|
147 |
+
class DoSleep(float):
|
148 |
+
pass
|
149 |
+
|
150 |
+
|
151 |
+
class BaseAction:
|
152 |
+
"""Base class for representing actions to take by retry object.
|
153 |
+
|
154 |
+
Concrete implementations must define:
|
155 |
+
- __init__: to initialize all necessary fields
|
156 |
+
- REPR_FIELDS: class variable specifying attributes to include in repr(self)
|
157 |
+
- NAME: for identification in retry object methods and callbacks
|
158 |
+
"""
|
159 |
+
|
160 |
+
REPR_FIELDS: t.Sequence[str] = ()
|
161 |
+
NAME: t.Optional[str] = None
|
162 |
+
|
163 |
+
def __repr__(self) -> str:
|
164 |
+
state_str = ", ".join(f"{field}={getattr(self, field)!r}" for field in self.REPR_FIELDS)
|
165 |
+
return f"{self.__class__.__name__}({state_str})"
|
166 |
+
|
167 |
+
def __str__(self) -> str:
|
168 |
+
return repr(self)
|
169 |
+
|
170 |
+
|
171 |
+
class RetryAction(BaseAction):
|
172 |
+
REPR_FIELDS = ("sleep",)
|
173 |
+
NAME = "retry"
|
174 |
+
|
175 |
+
def __init__(self, sleep: t.SupportsFloat) -> None:
|
176 |
+
self.sleep = float(sleep)
|
177 |
+
|
178 |
+
|
179 |
+
_unset = object()
|
180 |
+
|
181 |
+
|
182 |
+
def _first_set(first: t.Union[t.Any, object], second: t.Any) -> t.Any:
|
183 |
+
return second if first is _unset else first
|
184 |
+
|
185 |
+
|
186 |
+
class RetryError(Exception):
|
187 |
+
"""Encapsulates the last attempt instance right before giving up."""
|
188 |
+
|
189 |
+
def __init__(self, last_attempt: "Future") -> None:
|
190 |
+
self.last_attempt = last_attempt
|
191 |
+
super().__init__(last_attempt)
|
192 |
+
|
193 |
+
def reraise(self) -> "t.NoReturn":
|
194 |
+
if self.last_attempt.failed:
|
195 |
+
raise self.last_attempt.result()
|
196 |
+
raise self
|
197 |
+
|
198 |
+
def __str__(self) -> str:
|
199 |
+
return f"{self.__class__.__name__}[{self.last_attempt}]"
|
200 |
+
|
201 |
+
|
202 |
+
class AttemptManager:
|
203 |
+
"""Manage attempt context."""
|
204 |
+
|
205 |
+
def __init__(self, retry_state: "RetryCallState"):
|
206 |
+
self.retry_state = retry_state
|
207 |
+
|
208 |
+
def __enter__(self) -> None:
|
209 |
+
pass
|
210 |
+
|
211 |
+
def __exit__(
|
212 |
+
self,
|
213 |
+
exc_type: t.Optional[t.Type[BaseException]],
|
214 |
+
exc_value: t.Optional[BaseException],
|
215 |
+
traceback: t.Optional["types.TracebackType"],
|
216 |
+
) -> t.Optional[bool]:
|
217 |
+
if isinstance(exc_value, BaseException):
|
218 |
+
self.retry_state.set_exception((exc_type, exc_value, traceback))
|
219 |
+
return True # Swallow exception.
|
220 |
+
else:
|
221 |
+
# We don't have the result, actually.
|
222 |
+
self.retry_state.set_result(None)
|
223 |
+
return None
|
224 |
+
|
225 |
+
|
226 |
+
class BaseRetrying(ABC):
|
227 |
+
def __init__(
|
228 |
+
self,
|
229 |
+
sleep: t.Callable[[t.Union[int, float]], None] = sleep,
|
230 |
+
stop: "stop_base" = stop_never,
|
231 |
+
wait: "wait_base" = wait_none(),
|
232 |
+
retry: retry_base = retry_if_exception_type(),
|
233 |
+
before: t.Callable[["RetryCallState"], None] = before_nothing,
|
234 |
+
after: t.Callable[["RetryCallState"], None] = after_nothing,
|
235 |
+
before_sleep: t.Optional[t.Callable[["RetryCallState"], None]] = None,
|
236 |
+
reraise: bool = False,
|
237 |
+
retry_error_cls: t.Type[RetryError] = RetryError,
|
238 |
+
retry_error_callback: t.Optional[t.Callable[["RetryCallState"], t.Any]] = None,
|
239 |
+
):
|
240 |
+
self.sleep = sleep
|
241 |
+
self.stop = stop
|
242 |
+
self.wait = wait
|
243 |
+
self.retry = retry
|
244 |
+
self.before = before
|
245 |
+
self.after = after
|
246 |
+
self.before_sleep = before_sleep
|
247 |
+
self.reraise = reraise
|
248 |
+
self._local = threading.local()
|
249 |
+
self.retry_error_cls = retry_error_cls
|
250 |
+
self.retry_error_callback = retry_error_callback
|
251 |
+
|
252 |
+
def copy(
|
253 |
+
self,
|
254 |
+
sleep: t.Union[t.Callable[[t.Union[int, float]], None], object] = _unset,
|
255 |
+
stop: t.Union["stop_base", object] = _unset,
|
256 |
+
wait: t.Union["wait_base", object] = _unset,
|
257 |
+
retry: t.Union[retry_base, object] = _unset,
|
258 |
+
before: t.Union[t.Callable[["RetryCallState"], None], object] = _unset,
|
259 |
+
after: t.Union[t.Callable[["RetryCallState"], None], object] = _unset,
|
260 |
+
before_sleep: t.Union[t.Optional[t.Callable[["RetryCallState"], None]], object] = _unset,
|
261 |
+
reraise: t.Union[bool, object] = _unset,
|
262 |
+
retry_error_cls: t.Union[t.Type[RetryError], object] = _unset,
|
263 |
+
retry_error_callback: t.Union[t.Optional[t.Callable[["RetryCallState"], t.Any]], object] = _unset,
|
264 |
+
) -> "BaseRetrying":
|
265 |
+
"""Copy this object with some parameters changed if needed."""
|
266 |
+
return self.__class__(
|
267 |
+
sleep=_first_set(sleep, self.sleep),
|
268 |
+
stop=_first_set(stop, self.stop),
|
269 |
+
wait=_first_set(wait, self.wait),
|
270 |
+
retry=_first_set(retry, self.retry),
|
271 |
+
before=_first_set(before, self.before),
|
272 |
+
after=_first_set(after, self.after),
|
273 |
+
before_sleep=_first_set(before_sleep, self.before_sleep),
|
274 |
+
reraise=_first_set(reraise, self.reraise),
|
275 |
+
retry_error_cls=_first_set(retry_error_cls, self.retry_error_cls),
|
276 |
+
retry_error_callback=_first_set(retry_error_callback, self.retry_error_callback),
|
277 |
+
)
|
278 |
+
|
279 |
+
def __repr__(self) -> str:
|
280 |
+
return (
|
281 |
+
f"<{self.__class__.__name__} object at 0x{id(self):x} ("
|
282 |
+
f"stop={self.stop}, "
|
283 |
+
f"wait={self.wait}, "
|
284 |
+
f"sleep={self.sleep}, "
|
285 |
+
f"retry={self.retry}, "
|
286 |
+
f"before={self.before}, "
|
287 |
+
f"after={self.after})>"
|
288 |
+
)
|
289 |
+
|
290 |
+
@property
|
291 |
+
def statistics(self) -> t.Dict[str, t.Any]:
|
292 |
+
"""Return a dictionary of runtime statistics.
|
293 |
+
|
294 |
+
This dictionary will be empty when the controller has never been
|
295 |
+
ran. When it is running or has ran previously it should have (but
|
296 |
+
may not) have useful and/or informational keys and values when
|
297 |
+
running is underway and/or completed.
|
298 |
+
|
299 |
+
.. warning:: The keys in this dictionary **should** be some what
|
300 |
+
stable (not changing), but there existence **may**
|
301 |
+
change between major releases as new statistics are
|
302 |
+
gathered or removed so before accessing keys ensure that
|
303 |
+
they actually exist and handle when they do not.
|
304 |
+
|
305 |
+
.. note:: The values in this dictionary are local to the thread
|
306 |
+
running call (so if multiple threads share the same retrying
|
307 |
+
object - either directly or indirectly) they will each have
|
308 |
+
there own view of statistics they have collected (in the
|
309 |
+
future we may provide a way to aggregate the various
|
310 |
+
statistics from each thread).
|
311 |
+
"""
|
312 |
+
try:
|
313 |
+
return self._local.statistics
|
314 |
+
except AttributeError:
|
315 |
+
self._local.statistics = {}
|
316 |
+
return self._local.statistics
|
317 |
+
|
318 |
+
def wraps(self, f: WrappedFn) -> WrappedFn:
|
319 |
+
"""Wrap a function for retrying.
|
320 |
+
|
321 |
+
:param f: A function to wraps for retrying.
|
322 |
+
"""
|
323 |
+
|
324 |
+
@functools.wraps(f)
|
325 |
+
def wrapped_f(*args: t.Any, **kw: t.Any) -> t.Any:
|
326 |
+
return self(f, *args, **kw)
|
327 |
+
|
328 |
+
def retry_with(*args: t.Any, **kwargs: t.Any) -> WrappedFn:
|
329 |
+
return self.copy(*args, **kwargs).wraps(f)
|
330 |
+
|
331 |
+
wrapped_f.retry = self
|
332 |
+
wrapped_f.retry_with = retry_with
|
333 |
+
|
334 |
+
return wrapped_f
|
335 |
+
|
336 |
+
def begin(self) -> None:
|
337 |
+
self.statistics.clear()
|
338 |
+
self.statistics["start_time"] = time.monotonic()
|
339 |
+
self.statistics["attempt_number"] = 1
|
340 |
+
self.statistics["idle_for"] = 0
|
341 |
+
|
342 |
+
def iter(self, retry_state: "RetryCallState") -> t.Union[DoAttempt, DoSleep, t.Any]: # noqa
|
343 |
+
fut = retry_state.outcome
|
344 |
+
if fut is None:
|
345 |
+
if self.before is not None:
|
346 |
+
self.before(retry_state)
|
347 |
+
return DoAttempt()
|
348 |
+
|
349 |
+
is_explicit_retry = retry_state.outcome.failed and isinstance(retry_state.outcome.exception(), TryAgain)
|
350 |
+
if not (is_explicit_retry or self.retry(retry_state=retry_state)):
|
351 |
+
return fut.result()
|
352 |
+
|
353 |
+
if self.after is not None:
|
354 |
+
self.after(retry_state)
|
355 |
+
|
356 |
+
self.statistics["delay_since_first_attempt"] = retry_state.seconds_since_start
|
357 |
+
if self.stop(retry_state=retry_state):
|
358 |
+
if self.retry_error_callback:
|
359 |
+
return self.retry_error_callback(retry_state)
|
360 |
+
retry_exc = self.retry_error_cls(fut)
|
361 |
+
if self.reraise:
|
362 |
+
raise retry_exc.reraise()
|
363 |
+
raise retry_exc from fut.exception()
|
364 |
+
|
365 |
+
if self.wait:
|
366 |
+
sleep = self.wait(retry_state=retry_state)
|
367 |
+
else:
|
368 |
+
sleep = 0.0
|
369 |
+
retry_state.next_action = RetryAction(sleep)
|
370 |
+
retry_state.idle_for += sleep
|
371 |
+
self.statistics["idle_for"] += sleep
|
372 |
+
self.statistics["attempt_number"] += 1
|
373 |
+
|
374 |
+
if self.before_sleep is not None:
|
375 |
+
self.before_sleep(retry_state)
|
376 |
+
|
377 |
+
return DoSleep(sleep)
|
378 |
+
|
379 |
+
def __iter__(self) -> t.Generator[AttemptManager, None, None]:
|
380 |
+
self.begin()
|
381 |
+
|
382 |
+
retry_state = RetryCallState(self, fn=None, args=(), kwargs={})
|
383 |
+
while True:
|
384 |
+
do = self.iter(retry_state=retry_state)
|
385 |
+
if isinstance(do, DoAttempt):
|
386 |
+
yield AttemptManager(retry_state=retry_state)
|
387 |
+
elif isinstance(do, DoSleep):
|
388 |
+
retry_state.prepare_for_next_attempt()
|
389 |
+
self.sleep(do)
|
390 |
+
else:
|
391 |
+
break
|
392 |
+
|
393 |
+
@abstractmethod
|
394 |
+
def __call__(self, fn: t.Callable[..., _RetValT], *args: t.Any, **kwargs: t.Any) -> _RetValT:
|
395 |
+
pass
|
396 |
+
|
397 |
+
|
398 |
+
class Retrying(BaseRetrying):
|
399 |
+
"""Retrying controller."""
|
400 |
+
|
401 |
+
def __call__(self, fn: t.Callable[..., _RetValT], *args: t.Any, **kwargs: t.Any) -> _RetValT:
|
402 |
+
self.begin()
|
403 |
+
|
404 |
+
retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs)
|
405 |
+
while True:
|
406 |
+
do = self.iter(retry_state=retry_state)
|
407 |
+
if isinstance(do, DoAttempt):
|
408 |
+
try:
|
409 |
+
result = fn(*args, **kwargs)
|
410 |
+
except BaseException: # noqa: B902
|
411 |
+
retry_state.set_exception(sys.exc_info())
|
412 |
+
else:
|
413 |
+
retry_state.set_result(result)
|
414 |
+
elif isinstance(do, DoSleep):
|
415 |
+
retry_state.prepare_for_next_attempt()
|
416 |
+
self.sleep(do)
|
417 |
+
else:
|
418 |
+
return do
|
419 |
+
|
420 |
+
|
421 |
+
class Future(futures.Future):
|
422 |
+
"""Encapsulates a (future or past) attempted call to a target function."""
|
423 |
+
|
424 |
+
def __init__(self, attempt_number: int) -> None:
|
425 |
+
super().__init__()
|
426 |
+
self.attempt_number = attempt_number
|
427 |
+
|
428 |
+
@property
|
429 |
+
def failed(self) -> bool:
|
430 |
+
"""Return whether a exception is being held in this future."""
|
431 |
+
return self.exception() is not None
|
432 |
+
|
433 |
+
@classmethod
|
434 |
+
def construct(cls, attempt_number: int, value: t.Any, has_exception: bool) -> "Future":
|
435 |
+
"""Construct a new Future object."""
|
436 |
+
fut = cls(attempt_number)
|
437 |
+
if has_exception:
|
438 |
+
fut.set_exception(value)
|
439 |
+
else:
|
440 |
+
fut.set_result(value)
|
441 |
+
return fut
|
442 |
+
|
443 |
+
|
444 |
+
class RetryCallState:
|
445 |
+
"""State related to a single call wrapped with Retrying."""
|
446 |
+
|
447 |
+
def __init__(
|
448 |
+
self,
|
449 |
+
retry_object: BaseRetrying,
|
450 |
+
fn: t.Optional[WrappedFn],
|
451 |
+
args: t.Any,
|
452 |
+
kwargs: t.Any,
|
453 |
+
) -> None:
|
454 |
+
#: Retry call start timestamp
|
455 |
+
self.start_time = time.monotonic()
|
456 |
+
#: Retry manager object
|
457 |
+
self.retry_object = retry_object
|
458 |
+
#: Function wrapped by this retry call
|
459 |
+
self.fn = fn
|
460 |
+
#: Arguments of the function wrapped by this retry call
|
461 |
+
self.args = args
|
462 |
+
#: Keyword arguments of the function wrapped by this retry call
|
463 |
+
self.kwargs = kwargs
|
464 |
+
|
465 |
+
#: The number of the current attempt
|
466 |
+
self.attempt_number: int = 1
|
467 |
+
#: Last outcome (result or exception) produced by the function
|
468 |
+
self.outcome: t.Optional[Future] = None
|
469 |
+
#: Timestamp of the last outcome
|
470 |
+
self.outcome_timestamp: t.Optional[float] = None
|
471 |
+
#: Time spent sleeping in retries
|
472 |
+
self.idle_for: float = 0.0
|
473 |
+
#: Next action as decided by the retry manager
|
474 |
+
self.next_action: t.Optional[RetryAction] = None
|
475 |
+
|
476 |
+
@property
|
477 |
+
def seconds_since_start(self) -> t.Optional[float]:
|
478 |
+
if self.outcome_timestamp is None:
|
479 |
+
return None
|
480 |
+
return self.outcome_timestamp - self.start_time
|
481 |
+
|
482 |
+
def prepare_for_next_attempt(self) -> None:
|
483 |
+
self.outcome = None
|
484 |
+
self.outcome_timestamp = None
|
485 |
+
self.attempt_number += 1
|
486 |
+
self.next_action = None
|
487 |
+
|
488 |
+
def set_result(self, val: t.Any) -> None:
|
489 |
+
ts = time.monotonic()
|
490 |
+
fut = Future(self.attempt_number)
|
491 |
+
fut.set_result(val)
|
492 |
+
self.outcome, self.outcome_timestamp = fut, ts
|
493 |
+
|
494 |
+
def set_exception(self, exc_info: t.Tuple[t.Type[BaseException], BaseException, "types.TracebackType"]) -> None:
|
495 |
+
ts = time.monotonic()
|
496 |
+
fut = Future(self.attempt_number)
|
497 |
+
fut.set_exception(exc_info[1])
|
498 |
+
self.outcome, self.outcome_timestamp = fut, ts
|
499 |
+
|
500 |
+
def __repr__(self):
|
501 |
+
if self.outcome is None:
|
502 |
+
result = "none yet"
|
503 |
+
elif self.outcome.failed:
|
504 |
+
exception = self.outcome.exception()
|
505 |
+
result = f"failed ({exception.__class__.__name__} {exception})"
|
506 |
+
else:
|
507 |
+
result = f"returned {self.outcome.result()}"
|
508 |
+
|
509 |
+
slept = float(round(self.idle_for, 2))
|
510 |
+
clsname = self.__class__.__name__
|
511 |
+
return f"<{clsname} {id(self)}: attempt #{self.attempt_number}; slept for {slept}; last result: {result}>"
|
512 |
+
|
513 |
+
|
514 |
+
from pip._vendor.tenacity._asyncio import AsyncRetrying # noqa:E402,I100
|
515 |
+
|
516 |
+
if tornado:
|
517 |
+
from pip._vendor.tenacity.tornadoweb import TornadoRetrying
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/tenacity/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (16.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pip/_vendor/tenacity/__pycache__/_asyncio.cpython-310.pyc
ADDED
Binary file (2.62 kB). View file
|
|