Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/INSTALLER +1 -0
- vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/LICENSE +35 -0
- vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/METADATA +280 -0
- vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/REQUESTED +0 -0
- vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/WHEEL +5 -0
- vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/top_level.txt +1 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/ast_utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/common.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/exceptions.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/grammar.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/indenter.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/lark.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/lexer.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/load_grammar.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/parse_tree_builder.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/parser_frontends.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/reconstruct.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/tree.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/tree_matcher.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/tree_templates.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pycache__/visitors.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pyinstaller/__init__.py +6 -0
- vllm/lib/python3.10/site-packages/lark/__pyinstaller/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pyinstaller/__pycache__/hook-lark.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/__pyinstaller/hook-lark.py +14 -0
- vllm/lib/python3.10/site-packages/lark/ast_utils.py +59 -0
- vllm/lib/python3.10/site-packages/lark/common.py +86 -0
- vllm/lib/python3.10/site-packages/lark/grammar.py +130 -0
- vllm/lib/python3.10/site-packages/lark/grammars/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/lark/grammars/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/grammars/common.lark +59 -0
- vllm/lib/python3.10/site-packages/lark/grammars/lark.lark +62 -0
- vllm/lib/python3.10/site-packages/lark/grammars/python.lark +302 -0
- vllm/lib/python3.10/site-packages/lark/grammars/unicode.lark +7 -0
- vllm/lib/python3.10/site-packages/lark/lark.py +658 -0
- vllm/lib/python3.10/site-packages/lark/lexer.py +678 -0
- vllm/lib/python3.10/site-packages/lark/load_grammar.py +1428 -0
- vllm/lib/python3.10/site-packages/lark/parse_tree_builder.py +391 -0
- vllm/lib/python3.10/site-packages/lark/parser_frontends.py +257 -0
- vllm/lib/python3.10/site-packages/lark/parsers/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/cyk.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/earley.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/earley_common.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/earley_forest.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/grammar_analysis.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/lalr_analysis.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -1560,3 +1560,4 @@ vllm/lib/python3.10/site-packages/triton/backends/nvidia/lib/libdevice.10.bc fil
|
|
| 1560 |
vllm/lib/python3.10/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text
|
| 1561 |
vllm/lib/python3.10/site-packages/triton/backends/amd/lib/ockl.bc filter=lfs diff=lfs merge=lfs -text
|
| 1562 |
vllm/lib/python3.10/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 1560 |
vllm/lib/python3.10/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text
|
| 1561 |
vllm/lib/python3.10/site-packages/triton/backends/amd/lib/ockl.bc filter=lfs diff=lfs merge=lfs -text
|
| 1562 |
vllm/lib/python3.10/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
|
| 1563 |
+
vllm/lib/python3.10/site-packages/torio/lib/libtorio_ffmpeg5.so filter=lfs diff=lfs merge=lfs -text
|
vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2004-2016 California Institute of Technology.
|
| 2 |
+
Copyright (c) 2016-2024 The Uncertainty Quantification Foundation.
|
| 3 |
+
All rights reserved.
|
| 4 |
+
|
| 5 |
+
This software is available subject to the conditions and terms laid
|
| 6 |
+
out below. By downloading and using this software you are agreeing
|
| 7 |
+
to the following conditions.
|
| 8 |
+
|
| 9 |
+
Redistribution and use in source and binary forms, with or without
|
| 10 |
+
modification, are permitted provided that the following conditions
|
| 11 |
+
are met:
|
| 12 |
+
|
| 13 |
+
- Redistributions of source code must retain the above copyright
|
| 14 |
+
notice, this list of conditions and the following disclaimer.
|
| 15 |
+
|
| 16 |
+
- Redistributions in binary form must reproduce the above copyright
|
| 17 |
+
notice, this list of conditions and the following disclaimer in the
|
| 18 |
+
documentation and/or other materials provided with the distribution.
|
| 19 |
+
|
| 20 |
+
- Neither the names of the copyright holders nor the names of any of
|
| 21 |
+
the contributors may be used to endorse or promote products derived
|
| 22 |
+
from this software without specific prior written permission.
|
| 23 |
+
|
| 24 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 25 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
| 26 |
+
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 27 |
+
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
| 28 |
+
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
| 29 |
+
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
| 30 |
+
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
|
| 31 |
+
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
| 32 |
+
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
| 33 |
+
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
|
| 34 |
+
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 35 |
+
|
vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/METADATA
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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dill
|
| 6 |
+
Author: Mike McKerns
|
| 7 |
+
Author-email: mmckerns@uqfoundation.org
|
| 8 |
+
Maintainer: Mike McKerns
|
| 9 |
+
Maintainer-email: mmckerns@uqfoundation.org
|
| 10 |
+
License: BSD-3-Clause
|
| 11 |
+
Download-URL: https://pypi.org/project/dill/#files
|
| 12 |
+
Project-URL: Documentation, http://dill.rtfd.io
|
| 13 |
+
Project-URL: Source Code, https://github.com/uqfoundation/dill
|
| 14 |
+
Project-URL: Bug Tracker, https://github.com/uqfoundation/dill/issues
|
| 15 |
+
Platform: Linux
|
| 16 |
+
Platform: Windows
|
| 17 |
+
Platform: Mac
|
| 18 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 19 |
+
Classifier: Intended Audience :: Developers
|
| 20 |
+
Classifier: Intended Audience :: Science/Research
|
| 21 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 22 |
+
Classifier: Programming Language :: Python :: 3
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 26 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 27 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 28 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 29 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 30 |
+
Classifier: Topic :: Scientific/Engineering
|
| 31 |
+
Classifier: Topic :: Software Development
|
| 32 |
+
Requires-Python: >=3.8
|
| 33 |
+
Provides-Extra: graph
|
| 34 |
+
Requires-Dist: objgraph (>=1.7.2) ; extra == 'graph'
|
| 35 |
+
Provides-Extra: profile
|
| 36 |
+
Requires-Dist: gprof2dot (>=2022.7.29) ; extra == 'profile'
|
| 37 |
+
Provides-Extra: readline
|
| 38 |
+
|
| 39 |
+
-----------------------------
|
| 40 |
+
dill: serialize all of Python
|
| 41 |
+
-----------------------------
|
| 42 |
+
|
| 43 |
+
About Dill
|
| 44 |
+
==========
|
| 45 |
+
|
| 46 |
+
``dill`` extends Python's ``pickle`` module for serializing and de-serializing
|
| 47 |
+
Python objects to the majority of the built-in Python types. Serialization
|
| 48 |
+
is the process of converting an object to a byte stream, and the inverse
|
| 49 |
+
of which is converting a byte stream back to a Python object hierarchy.
|
| 50 |
+
|
| 51 |
+
``dill`` provides the user the same interface as the ``pickle`` module, and
|
| 52 |
+
also includes some additional features. In addition to pickling Python
|
| 53 |
+
objects, ``dill`` provides the ability to save the state of an interpreter
|
| 54 |
+
session in a single command. Hence, it would be feasible to save an
|
| 55 |
+
interpreter session, close the interpreter, ship the pickled file to
|
| 56 |
+
another computer, open a new interpreter, unpickle the session and
|
| 57 |
+
thus continue from the 'saved' state of the original interpreter
|
| 58 |
+
session.
|
| 59 |
+
|
| 60 |
+
``dill`` can be used to store Python objects to a file, but the primary
|
| 61 |
+
usage is to send Python objects across the network as a byte stream.
|
| 62 |
+
``dill`` is quite flexible, and allows arbitrary user defined classes
|
| 63 |
+
and functions to be serialized. Thus ``dill`` is not intended to be
|
| 64 |
+
secure against erroneously or maliciously constructed data. It is
|
| 65 |
+
left to the user to decide whether the data they unpickle is from
|
| 66 |
+
a trustworthy source.
|
| 67 |
+
|
| 68 |
+
``dill`` is part of ``pathos``, a Python framework for heterogeneous computing.
|
| 69 |
+
``dill`` is in active development, so any user feedback, bug reports, comments,
|
| 70 |
+
or suggestions are highly appreciated. A list of issues is located at
|
| 71 |
+
https://github.com/uqfoundation/dill/issues, with a legacy list maintained at
|
| 72 |
+
https://uqfoundation.github.io/project/pathos/query.
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
Major Features
|
| 76 |
+
==============
|
| 77 |
+
|
| 78 |
+
``dill`` can pickle the following standard types:
|
| 79 |
+
|
| 80 |
+
- none, type, bool, int, float, complex, bytes, str,
|
| 81 |
+
- tuple, list, dict, file, buffer, builtin,
|
| 82 |
+
- Python classes, namedtuples, dataclasses, metaclasses,
|
| 83 |
+
- instances of classes,
|
| 84 |
+
- set, frozenset, array, functions, exceptions
|
| 85 |
+
|
| 86 |
+
``dill`` can also pickle more 'exotic' standard types:
|
| 87 |
+
|
| 88 |
+
- functions with yields, nested functions, lambdas,
|
| 89 |
+
- cell, method, unboundmethod, module, code, methodwrapper,
|
| 90 |
+
- methoddescriptor, getsetdescriptor, memberdescriptor, wrapperdescriptor,
|
| 91 |
+
- dictproxy, slice, notimplemented, ellipsis, quit
|
| 92 |
+
|
| 93 |
+
``dill`` cannot yet pickle these standard types:
|
| 94 |
+
|
| 95 |
+
- frame, generator, traceback
|
| 96 |
+
|
| 97 |
+
``dill`` also provides the capability to:
|
| 98 |
+
|
| 99 |
+
- save and load Python interpreter sessions
|
| 100 |
+
- save and extract the source code from functions and classes
|
| 101 |
+
- interactively diagnose pickling errors
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
Current Release
|
| 105 |
+
===============
|
| 106 |
+
|
| 107 |
+
The latest released version of ``dill`` is available from:
|
| 108 |
+
|
| 109 |
+
https://pypi.org/project/dill
|
| 110 |
+
|
| 111 |
+
``dill`` is distributed under a 3-clause BSD license.
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
Development Version
|
| 115 |
+
===================
|
| 116 |
+
|
| 117 |
+
You can get the latest development version with all the shiny new features at:
|
| 118 |
+
|
| 119 |
+
https://github.com/uqfoundation
|
| 120 |
+
|
| 121 |
+
If you have a new contribution, please submit a pull request.
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
Installation
|
| 125 |
+
============
|
| 126 |
+
|
| 127 |
+
``dill`` can be installed with ``pip``::
|
| 128 |
+
|
| 129 |
+
$ pip install dill
|
| 130 |
+
|
| 131 |
+
To optionally include the ``objgraph`` diagnostic tool in the install::
|
| 132 |
+
|
| 133 |
+
$ pip install dill[graph]
|
| 134 |
+
|
| 135 |
+
To optionally include the ``gprof2dot`` diagnostic tool in the install::
|
| 136 |
+
|
| 137 |
+
$ pip install dill[profile]
|
| 138 |
+
|
| 139 |
+
For windows users, to optionally install session history tools::
|
| 140 |
+
|
| 141 |
+
$ pip install dill[readline]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
Requirements
|
| 145 |
+
============
|
| 146 |
+
|
| 147 |
+
``dill`` requires:
|
| 148 |
+
|
| 149 |
+
- ``python`` (or ``pypy``), **>=3.8**
|
| 150 |
+
- ``setuptools``, **>=42**
|
| 151 |
+
|
| 152 |
+
Optional requirements:
|
| 153 |
+
|
| 154 |
+
- ``objgraph``, **>=1.7.2**
|
| 155 |
+
- ``gprof2dot``, **>=2022.7.29**
|
| 156 |
+
- ``pyreadline``, **>=1.7.1** (on windows)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
Basic Usage
|
| 160 |
+
===========
|
| 161 |
+
|
| 162 |
+
``dill`` is a drop-in replacement for ``pickle``. Existing code can be
|
| 163 |
+
updated to allow complete pickling using::
|
| 164 |
+
|
| 165 |
+
>>> import dill as pickle
|
| 166 |
+
|
| 167 |
+
or::
|
| 168 |
+
|
| 169 |
+
>>> from dill import dumps, loads
|
| 170 |
+
|
| 171 |
+
``dumps`` converts the object to a unique byte string, and ``loads`` performs
|
| 172 |
+
the inverse operation::
|
| 173 |
+
|
| 174 |
+
>>> squared = lambda x: x**2
|
| 175 |
+
>>> loads(dumps(squared))(3)
|
| 176 |
+
9
|
| 177 |
+
|
| 178 |
+
There are a number of options to control serialization which are provided
|
| 179 |
+
as keyword arguments to several ``dill`` functions:
|
| 180 |
+
|
| 181 |
+
* with *protocol*, the pickle protocol level can be set. This uses the
|
| 182 |
+
same value as the ``pickle`` module, *DEFAULT_PROTOCOL*.
|
| 183 |
+
* with *byref=True*, ``dill`` to behave a lot more like pickle with
|
| 184 |
+
certain objects (like modules) pickled by reference as opposed to
|
| 185 |
+
attempting to pickle the object itself.
|
| 186 |
+
* with *recurse=True*, objects referred to in the global dictionary are
|
| 187 |
+
recursively traced and pickled, instead of the default behavior of
|
| 188 |
+
attempting to store the entire global dictionary.
|
| 189 |
+
* with *fmode*, the contents of the file can be pickled along with the file
|
| 190 |
+
handle, which is useful if the object is being sent over the wire to a
|
| 191 |
+
remote system which does not have the original file on disk. Options are
|
| 192 |
+
*HANDLE_FMODE* for just the handle, *CONTENTS_FMODE* for the file content
|
| 193 |
+
and *FILE_FMODE* for content and handle.
|
| 194 |
+
* with *ignore=False*, objects reconstructed with types defined in the
|
| 195 |
+
top-level script environment use the existing type in the environment
|
| 196 |
+
rather than a possibly different reconstructed type.
|
| 197 |
+
|
| 198 |
+
The default serialization can also be set globally in *dill.settings*.
|
| 199 |
+
Thus, we can modify how ``dill`` handles references to the global dictionary
|
| 200 |
+
locally or globally::
|
| 201 |
+
|
| 202 |
+
>>> import dill.settings
|
| 203 |
+
>>> dumps(absolute) == dumps(absolute, recurse=True)
|
| 204 |
+
False
|
| 205 |
+
>>> dill.settings['recurse'] = True
|
| 206 |
+
>>> dumps(absolute) == dumps(absolute, recurse=True)
|
| 207 |
+
True
|
| 208 |
+
|
| 209 |
+
``dill`` also includes source code inspection, as an alternate to pickling::
|
| 210 |
+
|
| 211 |
+
>>> import dill.source
|
| 212 |
+
>>> print(dill.source.getsource(squared))
|
| 213 |
+
squared = lambda x:x**2
|
| 214 |
+
|
| 215 |
+
To aid in debugging pickling issues, use *dill.detect* which provides
|
| 216 |
+
tools like pickle tracing::
|
| 217 |
+
|
| 218 |
+
>>> import dill.detect
|
| 219 |
+
>>> with dill.detect.trace():
|
| 220 |
+
>>> dumps(squared)
|
| 221 |
+
┬ F1: <function <lambda> at 0x7fe074f8c280>
|
| 222 |
+
├┬ F2: <function _create_function at 0x7fe074c49c10>
|
| 223 |
+
│└ # F2 [34 B]
|
| 224 |
+
├┬ Co: <code object <lambda> at 0x7fe07501eb30, file "<stdin>", line 1>
|
| 225 |
+
│├┬ F2: <function _create_code at 0x7fe074c49ca0>
|
| 226 |
+
││└ # F2 [19 B]
|
| 227 |
+
│└ # Co [87 B]
|
| 228 |
+
├┬ D1: <dict object at 0x7fe0750d4680>
|
| 229 |
+
│└ # D1 [22 B]
|
| 230 |
+
├┬ D2: <dict object at 0x7fe074c5a1c0>
|
| 231 |
+
│└ # D2 [2 B]
|
| 232 |
+
├┬ D2: <dict object at 0x7fe074f903c0>
|
| 233 |
+
│├┬ D2: <dict object at 0x7fe074f8ebc0>
|
| 234 |
+
││└ # D2 [2 B]
|
| 235 |
+
│└ # D2 [23 B]
|
| 236 |
+
└ # F1 [180 B]
|
| 237 |
+
|
| 238 |
+
With trace, we see how ``dill`` stored the lambda (``F1``) by first storing
|
| 239 |
+
``_create_function``, the underlying code object (``Co``) and ``_create_code``
|
| 240 |
+
(which is used to handle code objects), then we handle the reference to
|
| 241 |
+
the global dict (``D2``) plus other dictionaries (``D1`` and ``D2``) that
|
| 242 |
+
save the lambda object's state. A ``#`` marks when the object is actually stored.
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
More Information
|
| 246 |
+
================
|
| 247 |
+
|
| 248 |
+
Probably the best way to get started is to look at the documentation at
|
| 249 |
+
http://dill.rtfd.io. Also see ``dill.tests`` for a set of scripts that
|
| 250 |
+
demonstrate how ``dill`` can serialize different Python objects. You can
|
| 251 |
+
run the test suite with ``python -m dill.tests``. The contents of any
|
| 252 |
+
pickle file can be examined with ``undill``. As ``dill`` conforms to
|
| 253 |
+
the ``pickle`` interface, the examples and documentation found at
|
| 254 |
+
http://docs.python.org/library/pickle.html also apply to ``dill``
|
| 255 |
+
if one will ``import dill as pickle``. The source code is also generally
|
| 256 |
+
well documented, so further questions may be resolved by inspecting the
|
| 257 |
+
code itself. Please feel free to submit a ticket on github, or ask a
|
| 258 |
+
question on stackoverflow (**@Mike McKerns**).
|
| 259 |
+
If you would like to share how you use ``dill`` in your work, please send
|
| 260 |
+
an email (to **mmckerns at uqfoundation dot org**).
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
Citation
|
| 264 |
+
========
|
| 265 |
+
|
| 266 |
+
If you use ``dill`` to do research that leads to publication, we ask that you
|
| 267 |
+
acknowledge use of ``dill`` by citing the following in your publication::
|
| 268 |
+
|
| 269 |
+
M.M. McKerns, L. Strand, T. Sullivan, A. Fang, M.A.G. Aivazis,
|
| 270 |
+
"Building a framework for predictive science", Proceedings of
|
| 271 |
+
the 10th Python in Science Conference, 2011;
|
| 272 |
+
http://arxiv.org/pdf/1202.1056
|
| 273 |
+
|
| 274 |
+
Michael McKerns and Michael Aivazis,
|
| 275 |
+
"pathos: a framework for heterogeneous computing", 2010- ;
|
| 276 |
+
https://uqfoundation.github.io/project/pathos
|
| 277 |
+
|
| 278 |
+
Please see https://uqfoundation.github.io/project/pathos or
|
| 279 |
+
http://arxiv.org/pdf/1202.1056 for further information.
|
| 280 |
+
|
vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/REQUESTED
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.37.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
vllm/lib/python3.10/site-packages/dill-0.3.8.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
dill
|
vllm/lib/python3.10/site-packages/lark/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (827 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/ast_utils.cpython-310.pyc
ADDED
|
Binary file (2.59 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/common.cpython-310.pyc
ADDED
|
Binary file (3.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/exceptions.cpython-310.pyc
ADDED
|
Binary file (10.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/grammar.cpython-310.pyc
ADDED
|
Binary file (4.97 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/indenter.cpython-310.pyc
ADDED
|
Binary file (4.57 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/lark.cpython-310.pyc
ADDED
|
Binary file (22.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/lexer.cpython-310.pyc
ADDED
|
Binary file (24 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/load_grammar.cpython-310.pyc
ADDED
|
Binary file (47.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/parse_tree_builder.cpython-310.pyc
ADDED
|
Binary file (12.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/parser_frontends.cpython-310.pyc
ADDED
|
Binary file (9.83 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/reconstruct.cpython-310.pyc
ADDED
|
Binary file (4.03 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/tree.cpython-310.pyc
ADDED
|
Binary file (10.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/tree_matcher.cpython-310.pyc
ADDED
|
Binary file (6.66 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/tree_templates.cpython-310.pyc
ADDED
|
Binary file (6.79 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (13.4 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pycache__/visitors.cpython-310.pyc
ADDED
|
Binary file (22.4 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pyinstaller/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# For usage of lark with PyInstaller. See https://pyinstaller-sample-hook.readthedocs.io/en/latest/index.html
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
def get_hook_dirs():
|
| 6 |
+
return [os.path.dirname(__file__)]
|
vllm/lib/python3.10/site-packages/lark/__pyinstaller/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (327 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pyinstaller/__pycache__/hook-lark.cpython-310.pyc
ADDED
|
Binary file (258 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/__pyinstaller/hook-lark.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#-----------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) 2017-2020, PyInstaller Development Team.
|
| 3 |
+
#
|
| 4 |
+
# Distributed under the terms of the GNU General Public License (version 2
|
| 5 |
+
# or later) with exception for distributing the bootloader.
|
| 6 |
+
#
|
| 7 |
+
# The full license is in the file COPYING.txt, distributed with this software.
|
| 8 |
+
#
|
| 9 |
+
# SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
|
| 10 |
+
#-----------------------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
from PyInstaller.utils.hooks import collect_data_files
|
| 13 |
+
|
| 14 |
+
datas = collect_data_files('lark')
|
vllm/lib/python3.10/site-packages/lark/ast_utils.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module of utilities for transforming a lark.Tree into a custom Abstract Syntax Tree (AST defined in classes)
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import inspect, re
|
| 6 |
+
import types
|
| 7 |
+
from typing import Optional, Callable
|
| 8 |
+
|
| 9 |
+
from lark import Transformer, v_args
|
| 10 |
+
|
| 11 |
+
class Ast:
|
| 12 |
+
"""Abstract class
|
| 13 |
+
|
| 14 |
+
Subclasses will be collected by `create_transformer()`
|
| 15 |
+
"""
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
class AsList:
|
| 19 |
+
"""Abstract class
|
| 20 |
+
|
| 21 |
+
Subclasses will be instantiated with the parse results as a single list, instead of as arguments.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
class WithMeta:
|
| 25 |
+
"""Abstract class
|
| 26 |
+
|
| 27 |
+
Subclasses will be instantiated with the Meta instance of the tree. (see ``v_args`` for more detail)
|
| 28 |
+
"""
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
def camel_to_snake(name):
|
| 32 |
+
return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
|
| 33 |
+
|
| 34 |
+
def create_transformer(ast_module: types.ModuleType,
|
| 35 |
+
transformer: Optional[Transformer]=None,
|
| 36 |
+
decorator_factory: Callable=v_args) -> Transformer:
|
| 37 |
+
"""Collects `Ast` subclasses from the given module, and creates a Lark transformer that builds the AST.
|
| 38 |
+
|
| 39 |
+
For each class, we create a corresponding rule in the transformer, with a matching name.
|
| 40 |
+
CamelCase names will be converted into snake_case. Example: "CodeBlock" -> "code_block".
|
| 41 |
+
|
| 42 |
+
Classes starting with an underscore (`_`) will be skipped.
|
| 43 |
+
|
| 44 |
+
Parameters:
|
| 45 |
+
ast_module: A Python module containing all the subclasses of ``ast_utils.Ast``
|
| 46 |
+
transformer (Optional[Transformer]): An initial transformer. Its attributes may be overwritten.
|
| 47 |
+
decorator_factory (Callable): An optional callable accepting two booleans, inline, and meta,
|
| 48 |
+
and returning a decorator for the methods of ``transformer``. (default: ``v_args``).
|
| 49 |
+
"""
|
| 50 |
+
t = transformer or Transformer()
|
| 51 |
+
|
| 52 |
+
for name, obj in inspect.getmembers(ast_module):
|
| 53 |
+
if not name.startswith('_') and inspect.isclass(obj):
|
| 54 |
+
if issubclass(obj, Ast):
|
| 55 |
+
wrapper = decorator_factory(inline=not issubclass(obj, AsList), meta=issubclass(obj, WithMeta))
|
| 56 |
+
obj = wrapper(obj).__get__(t)
|
| 57 |
+
setattr(t, camel_to_snake(name), obj)
|
| 58 |
+
|
| 59 |
+
return t
|
vllm/lib/python3.10/site-packages/lark/common.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
import sys
|
| 3 |
+
from types import ModuleType
|
| 4 |
+
from typing import Callable, Collection, Dict, Optional, TYPE_CHECKING, List
|
| 5 |
+
|
| 6 |
+
if TYPE_CHECKING:
|
| 7 |
+
from .lark import PostLex
|
| 8 |
+
from .lexer import Lexer
|
| 9 |
+
from .grammar import Rule
|
| 10 |
+
from typing import Union, Type
|
| 11 |
+
from typing import Literal
|
| 12 |
+
if sys.version_info >= (3, 10):
|
| 13 |
+
from typing import TypeAlias
|
| 14 |
+
else:
|
| 15 |
+
from typing_extensions import TypeAlias
|
| 16 |
+
|
| 17 |
+
from .utils import Serialize
|
| 18 |
+
from .lexer import TerminalDef, Token
|
| 19 |
+
|
| 20 |
+
###{standalone
|
| 21 |
+
|
| 22 |
+
_ParserArgType: 'TypeAlias' = 'Literal["earley", "lalr", "cyk", "auto"]'
|
| 23 |
+
_LexerArgType: 'TypeAlias' = 'Union[Literal["auto", "basic", "contextual", "dynamic", "dynamic_complete"], Type[Lexer]]'
|
| 24 |
+
_LexerCallback = Callable[[Token], Token]
|
| 25 |
+
ParserCallbacks = Dict[str, Callable]
|
| 26 |
+
|
| 27 |
+
class LexerConf(Serialize):
|
| 28 |
+
__serialize_fields__ = 'terminals', 'ignore', 'g_regex_flags', 'use_bytes', 'lexer_type'
|
| 29 |
+
__serialize_namespace__ = TerminalDef,
|
| 30 |
+
|
| 31 |
+
terminals: Collection[TerminalDef]
|
| 32 |
+
re_module: ModuleType
|
| 33 |
+
ignore: Collection[str]
|
| 34 |
+
postlex: 'Optional[PostLex]'
|
| 35 |
+
callbacks: Dict[str, _LexerCallback]
|
| 36 |
+
g_regex_flags: int
|
| 37 |
+
skip_validation: bool
|
| 38 |
+
use_bytes: bool
|
| 39 |
+
lexer_type: Optional[_LexerArgType]
|
| 40 |
+
strict: bool
|
| 41 |
+
|
| 42 |
+
def __init__(self, terminals: Collection[TerminalDef], re_module: ModuleType, ignore: Collection[str]=(), postlex: 'Optional[PostLex]'=None,
|
| 43 |
+
callbacks: Optional[Dict[str, _LexerCallback]]=None, g_regex_flags: int=0, skip_validation: bool=False, use_bytes: bool=False, strict: bool=False):
|
| 44 |
+
self.terminals = terminals
|
| 45 |
+
self.terminals_by_name = {t.name: t for t in self.terminals}
|
| 46 |
+
assert len(self.terminals) == len(self.terminals_by_name)
|
| 47 |
+
self.ignore = ignore
|
| 48 |
+
self.postlex = postlex
|
| 49 |
+
self.callbacks = callbacks or {}
|
| 50 |
+
self.g_regex_flags = g_regex_flags
|
| 51 |
+
self.re_module = re_module
|
| 52 |
+
self.skip_validation = skip_validation
|
| 53 |
+
self.use_bytes = use_bytes
|
| 54 |
+
self.strict = strict
|
| 55 |
+
self.lexer_type = None
|
| 56 |
+
|
| 57 |
+
def _deserialize(self):
|
| 58 |
+
self.terminals_by_name = {t.name: t for t in self.terminals}
|
| 59 |
+
|
| 60 |
+
def __deepcopy__(self, memo=None):
|
| 61 |
+
return type(self)(
|
| 62 |
+
deepcopy(self.terminals, memo),
|
| 63 |
+
self.re_module,
|
| 64 |
+
deepcopy(self.ignore, memo),
|
| 65 |
+
deepcopy(self.postlex, memo),
|
| 66 |
+
deepcopy(self.callbacks, memo),
|
| 67 |
+
deepcopy(self.g_regex_flags, memo),
|
| 68 |
+
deepcopy(self.skip_validation, memo),
|
| 69 |
+
deepcopy(self.use_bytes, memo),
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
class ParserConf(Serialize):
|
| 73 |
+
__serialize_fields__ = 'rules', 'start', 'parser_type'
|
| 74 |
+
|
| 75 |
+
rules: List['Rule']
|
| 76 |
+
callbacks: ParserCallbacks
|
| 77 |
+
start: List[str]
|
| 78 |
+
parser_type: _ParserArgType
|
| 79 |
+
|
| 80 |
+
def __init__(self, rules: List['Rule'], callbacks: ParserCallbacks, start: List[str]):
|
| 81 |
+
assert isinstance(start, list)
|
| 82 |
+
self.rules = rules
|
| 83 |
+
self.callbacks = callbacks
|
| 84 |
+
self.start = start
|
| 85 |
+
|
| 86 |
+
###}
|
vllm/lib/python3.10/site-packages/lark/grammar.py
ADD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
+
is_term: ClassVar[bool] = NotImplemented
|
| 14 |
+
|
| 15 |
+
def __init__(self, name: str) -> None:
|
| 16 |
+
self.name = name
|
| 17 |
+
|
| 18 |
+
def __eq__(self, other):
|
| 19 |
+
assert isinstance(other, Symbol), other
|
| 20 |
+
return self.is_term == other.is_term and self.name == other.name
|
| 21 |
+
|
| 22 |
+
def __ne__(self, other):
|
| 23 |
+
return not (self == other)
|
| 24 |
+
|
| 25 |
+
def __hash__(self):
|
| 26 |
+
return hash(self.name)
|
| 27 |
+
|
| 28 |
+
def __repr__(self):
|
| 29 |
+
return '%s(%r)' % (type(self).__name__, self.name)
|
| 30 |
+
|
| 31 |
+
fullrepr = property(__repr__)
|
| 32 |
+
|
| 33 |
+
def renamed(self, f):
|
| 34 |
+
return type(self)(f(self.name))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Terminal(Symbol):
|
| 38 |
+
__serialize_fields__ = 'name', 'filter_out'
|
| 39 |
+
|
| 40 |
+
is_term: ClassVar[bool] = True
|
| 41 |
+
|
| 42 |
+
def __init__(self, name, filter_out=False):
|
| 43 |
+
self.name = name
|
| 44 |
+
self.filter_out = filter_out
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def fullrepr(self):
|
| 48 |
+
return '%s(%r, %r)' % (type(self).__name__, self.name, self.filter_out)
|
| 49 |
+
|
| 50 |
+
def renamed(self, f):
|
| 51 |
+
return type(self)(f(self.name), self.filter_out)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class NonTerminal(Symbol):
|
| 55 |
+
__serialize_fields__ = 'name',
|
| 56 |
+
|
| 57 |
+
is_term: ClassVar[bool] = False
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class RuleOptions(Serialize):
|
| 61 |
+
__serialize_fields__ = 'keep_all_tokens', 'expand1', 'priority', 'template_source', 'empty_indices'
|
| 62 |
+
|
| 63 |
+
keep_all_tokens: bool
|
| 64 |
+
expand1: bool
|
| 65 |
+
priority: Optional[int]
|
| 66 |
+
template_source: Optional[str]
|
| 67 |
+
empty_indices: Tuple[bool, ...]
|
| 68 |
+
|
| 69 |
+
def __init__(self, keep_all_tokens: bool=False, expand1: bool=False, priority: Optional[int]=None, template_source: Optional[str]=None, empty_indices: Tuple[bool, ...]=()) -> None:
|
| 70 |
+
self.keep_all_tokens = keep_all_tokens
|
| 71 |
+
self.expand1 = expand1
|
| 72 |
+
self.priority = priority
|
| 73 |
+
self.template_source = template_source
|
| 74 |
+
self.empty_indices = empty_indices
|
| 75 |
+
|
| 76 |
+
def __repr__(self):
|
| 77 |
+
return 'RuleOptions(%r, %r, %r, %r)' % (
|
| 78 |
+
self.keep_all_tokens,
|
| 79 |
+
self.expand1,
|
| 80 |
+
self.priority,
|
| 81 |
+
self.template_source
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class Rule(Serialize):
|
| 86 |
+
"""
|
| 87 |
+
origin : a symbol
|
| 88 |
+
expansion : a list of symbols
|
| 89 |
+
order : index of this expansion amongst all rules of the same name
|
| 90 |
+
"""
|
| 91 |
+
__slots__ = ('origin', 'expansion', 'alias', 'options', 'order', '_hash')
|
| 92 |
+
|
| 93 |
+
__serialize_fields__ = 'origin', 'expansion', 'order', 'alias', 'options'
|
| 94 |
+
__serialize_namespace__ = Terminal, NonTerminal, RuleOptions
|
| 95 |
+
|
| 96 |
+
origin: NonTerminal
|
| 97 |
+
expansion: Sequence[Symbol]
|
| 98 |
+
order: int
|
| 99 |
+
alias: Optional[str]
|
| 100 |
+
options: RuleOptions
|
| 101 |
+
_hash: int
|
| 102 |
+
|
| 103 |
+
def __init__(self, origin: NonTerminal, expansion: Sequence[Symbol],
|
| 104 |
+
order: int=0, alias: Optional[str]=None, options: Optional[RuleOptions]=None):
|
| 105 |
+
self.origin = origin
|
| 106 |
+
self.expansion = expansion
|
| 107 |
+
self.alias = alias
|
| 108 |
+
self.order = order
|
| 109 |
+
self.options = options or RuleOptions()
|
| 110 |
+
self._hash = hash((self.origin, tuple(self.expansion)))
|
| 111 |
+
|
| 112 |
+
def _deserialize(self):
|
| 113 |
+
self._hash = hash((self.origin, tuple(self.expansion)))
|
| 114 |
+
|
| 115 |
+
def __str__(self):
|
| 116 |
+
return '<%s : %s>' % (self.origin.name, ' '.join(x.name for x in self.expansion))
|
| 117 |
+
|
| 118 |
+
def __repr__(self):
|
| 119 |
+
return 'Rule(%r, %r, %r, %r)' % (self.origin, self.expansion, self.alias, self.options)
|
| 120 |
+
|
| 121 |
+
def __hash__(self):
|
| 122 |
+
return self._hash
|
| 123 |
+
|
| 124 |
+
def __eq__(self, other):
|
| 125 |
+
if not isinstance(other, Rule):
|
| 126 |
+
return False
|
| 127 |
+
return self.origin == other.origin and self.expansion == other.expansion
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
###}
|
vllm/lib/python3.10/site-packages/lark/grammars/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/lark/grammars/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (163 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/grammars/common.lark
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Basic terminals for common use
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
//
|
| 5 |
+
// Numbers
|
| 6 |
+
//
|
| 7 |
+
|
| 8 |
+
DIGIT: "0".."9"
|
| 9 |
+
HEXDIGIT: "a".."f"|"A".."F"|DIGIT
|
| 10 |
+
|
| 11 |
+
INT: DIGIT+
|
| 12 |
+
SIGNED_INT: ["+"|"-"] INT
|
| 13 |
+
DECIMAL: INT "." INT? | "." INT
|
| 14 |
+
|
| 15 |
+
// float = /-?\d+(\.\d+)?([eE][+-]?\d+)?/
|
| 16 |
+
_EXP: ("e"|"E") SIGNED_INT
|
| 17 |
+
FLOAT: INT _EXP | DECIMAL _EXP?
|
| 18 |
+
SIGNED_FLOAT: ["+"|"-"] FLOAT
|
| 19 |
+
|
| 20 |
+
NUMBER: FLOAT | INT
|
| 21 |
+
SIGNED_NUMBER: ["+"|"-"] NUMBER
|
| 22 |
+
|
| 23 |
+
//
|
| 24 |
+
// Strings
|
| 25 |
+
//
|
| 26 |
+
_STRING_INNER: /.*?/
|
| 27 |
+
_STRING_ESC_INNER: _STRING_INNER /(?<!\\)(\\\\)*?/
|
| 28 |
+
|
| 29 |
+
ESCAPED_STRING : "\"" _STRING_ESC_INNER "\""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
//
|
| 33 |
+
// Names (Variables)
|
| 34 |
+
//
|
| 35 |
+
LCASE_LETTER: "a".."z"
|
| 36 |
+
UCASE_LETTER: "A".."Z"
|
| 37 |
+
|
| 38 |
+
LETTER: UCASE_LETTER | LCASE_LETTER
|
| 39 |
+
WORD: LETTER+
|
| 40 |
+
|
| 41 |
+
CNAME: ("_"|LETTER) ("_"|LETTER|DIGIT)*
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
//
|
| 45 |
+
// Whitespace
|
| 46 |
+
//
|
| 47 |
+
WS_INLINE: (" "|/\t/)+
|
| 48 |
+
WS: /[ \t\f\r\n]/+
|
| 49 |
+
|
| 50 |
+
CR : /\r/
|
| 51 |
+
LF : /\n/
|
| 52 |
+
NEWLINE: (CR? LF)+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
// Comments
|
| 56 |
+
SH_COMMENT: /#[^\n]*/
|
| 57 |
+
CPP_COMMENT: /\/\/[^\n]*/
|
| 58 |
+
C_COMMENT: "/*" /(.|\n)*?/ "*/"
|
| 59 |
+
SQL_COMMENT: /--[^\n]*/
|
vllm/lib/python3.10/site-packages/lark/grammars/lark.lark
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Lark grammar of Lark's syntax
|
| 2 |
+
# Note: Lark is not bootstrapped, its parser is implemented in load_grammar.py
|
| 3 |
+
|
| 4 |
+
start: (_item? _NL)* _item?
|
| 5 |
+
|
| 6 |
+
_item: rule
|
| 7 |
+
| token
|
| 8 |
+
| statement
|
| 9 |
+
|
| 10 |
+
rule: RULE rule_params priority? ":" expansions
|
| 11 |
+
token: TOKEN token_params priority? ":" expansions
|
| 12 |
+
|
| 13 |
+
rule_params: ["{" RULE ("," RULE)* "}"]
|
| 14 |
+
token_params: ["{" TOKEN ("," TOKEN)* "}"]
|
| 15 |
+
|
| 16 |
+
priority: "." NUMBER
|
| 17 |
+
|
| 18 |
+
statement: "%ignore" expansions -> ignore
|
| 19 |
+
| "%import" import_path ["->" name] -> import
|
| 20 |
+
| "%import" import_path name_list -> multi_import
|
| 21 |
+
| "%override" rule -> override_rule
|
| 22 |
+
| "%declare" name+ -> declare
|
| 23 |
+
|
| 24 |
+
!import_path: "."? name ("." name)*
|
| 25 |
+
name_list: "(" name ("," name)* ")"
|
| 26 |
+
|
| 27 |
+
?expansions: alias (_VBAR alias)*
|
| 28 |
+
|
| 29 |
+
?alias: expansion ["->" RULE]
|
| 30 |
+
|
| 31 |
+
?expansion: expr*
|
| 32 |
+
|
| 33 |
+
?expr: atom [OP | "~" NUMBER [".." NUMBER]]
|
| 34 |
+
|
| 35 |
+
?atom: "(" expansions ")"
|
| 36 |
+
| "[" expansions "]" -> maybe
|
| 37 |
+
| value
|
| 38 |
+
|
| 39 |
+
?value: STRING ".." STRING -> literal_range
|
| 40 |
+
| name
|
| 41 |
+
| (REGEXP | STRING) -> literal
|
| 42 |
+
| name "{" value ("," value)* "}" -> template_usage
|
| 43 |
+
|
| 44 |
+
name: RULE
|
| 45 |
+
| TOKEN
|
| 46 |
+
|
| 47 |
+
_VBAR: _NL? "|"
|
| 48 |
+
OP: /[+*]|[?](?![a-z])/
|
| 49 |
+
RULE: /!?[_?]?[a-z][_a-z0-9]*/
|
| 50 |
+
TOKEN: /_?[A-Z][_A-Z0-9]*/
|
| 51 |
+
STRING: _STRING "i"?
|
| 52 |
+
REGEXP: /\/(?!\/)(\\\/|\\\\|[^\/])*?\/[imslux]*/
|
| 53 |
+
_NL: /(\r?\n)+\s*/
|
| 54 |
+
|
| 55 |
+
%import common.ESCAPED_STRING -> _STRING
|
| 56 |
+
%import common.SIGNED_INT -> NUMBER
|
| 57 |
+
%import common.WS_INLINE
|
| 58 |
+
|
| 59 |
+
COMMENT: /\s*/ "//" /[^\n]/* | /\s*/ "#" /[^\n]/*
|
| 60 |
+
|
| 61 |
+
%ignore WS_INLINE
|
| 62 |
+
%ignore COMMENT
|
vllm/lib/python3.10/site-packages/lark/grammars/python.lark
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Python 3 grammar for Lark
|
| 2 |
+
|
| 3 |
+
// This grammar should parse all python 3.x code successfully.
|
| 4 |
+
|
| 5 |
+
// Adapted from: https://docs.python.org/3/reference/grammar.html
|
| 6 |
+
|
| 7 |
+
// Start symbols for the grammar:
|
| 8 |
+
// single_input is a single interactive statement;
|
| 9 |
+
// file_input is a module or sequence of commands read from an input file;
|
| 10 |
+
// eval_input is the input for the eval() functions.
|
| 11 |
+
// NB: compound_stmt in single_input is followed by extra NEWLINE!
|
| 12 |
+
//
|
| 13 |
+
|
| 14 |
+
single_input: _NEWLINE | simple_stmt | compound_stmt _NEWLINE
|
| 15 |
+
file_input: (_NEWLINE | stmt)*
|
| 16 |
+
eval_input: testlist _NEWLINE*
|
| 17 |
+
|
| 18 |
+
decorator: "@" dotted_name [ "(" [arguments] ")" ] _NEWLINE
|
| 19 |
+
decorators: decorator+
|
| 20 |
+
decorated: decorators (classdef | funcdef | async_funcdef)
|
| 21 |
+
|
| 22 |
+
async_funcdef: "async" funcdef
|
| 23 |
+
funcdef: "def" name "(" [parameters] ")" ["->" test] ":" suite
|
| 24 |
+
|
| 25 |
+
parameters: paramvalue ("," paramvalue)* ["," SLASH ("," paramvalue)*] ["," [starparams | kwparams]]
|
| 26 |
+
| starparams
|
| 27 |
+
| kwparams
|
| 28 |
+
|
| 29 |
+
SLASH: "/" // Otherwise the it will completely disappear and it will be undisguisable in the result
|
| 30 |
+
starparams: (starparam | starguard) poststarparams
|
| 31 |
+
starparam: "*" typedparam
|
| 32 |
+
starguard: "*"
|
| 33 |
+
poststarparams: ("," paramvalue)* ["," kwparams]
|
| 34 |
+
kwparams: "**" typedparam ","?
|
| 35 |
+
|
| 36 |
+
?paramvalue: typedparam ("=" test)?
|
| 37 |
+
?typedparam: name (":" test)?
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
lambdef: "lambda" [lambda_params] ":" test
|
| 41 |
+
lambdef_nocond: "lambda" [lambda_params] ":" test_nocond
|
| 42 |
+
lambda_params: lambda_paramvalue ("," lambda_paramvalue)* ["," [lambda_starparams | lambda_kwparams]]
|
| 43 |
+
| lambda_starparams
|
| 44 |
+
| lambda_kwparams
|
| 45 |
+
?lambda_paramvalue: name ("=" test)?
|
| 46 |
+
lambda_starparams: "*" [name] ("," lambda_paramvalue)* ["," [lambda_kwparams]]
|
| 47 |
+
lambda_kwparams: "**" name ","?
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
?stmt: simple_stmt | compound_stmt
|
| 51 |
+
?simple_stmt: small_stmt (";" small_stmt)* [";"] _NEWLINE
|
| 52 |
+
?small_stmt: (expr_stmt | assign_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
|
| 53 |
+
expr_stmt: testlist_star_expr
|
| 54 |
+
assign_stmt: annassign | augassign | assign
|
| 55 |
+
|
| 56 |
+
annassign: testlist_star_expr ":" test ["=" test]
|
| 57 |
+
assign: testlist_star_expr ("=" (yield_expr|testlist_star_expr))+
|
| 58 |
+
augassign: testlist_star_expr augassign_op (yield_expr|testlist)
|
| 59 |
+
!augassign_op: "+=" | "-=" | "*=" | "@=" | "/=" | "%=" | "&=" | "|=" | "^=" | "<<=" | ">>=" | "**=" | "//="
|
| 60 |
+
?testlist_star_expr: test_or_star_expr
|
| 61 |
+
| test_or_star_expr ("," test_or_star_expr)+ ","? -> tuple
|
| 62 |
+
| test_or_star_expr "," -> tuple
|
| 63 |
+
|
| 64 |
+
// For normal and annotated assignments, additional restrictions enforced by the interpreter
|
| 65 |
+
del_stmt: "del" exprlist
|
| 66 |
+
pass_stmt: "pass"
|
| 67 |
+
?flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
|
| 68 |
+
break_stmt: "break"
|
| 69 |
+
continue_stmt: "continue"
|
| 70 |
+
return_stmt: "return" [testlist]
|
| 71 |
+
yield_stmt: yield_expr
|
| 72 |
+
raise_stmt: "raise" [test ["from" test]]
|
| 73 |
+
import_stmt: import_name | import_from
|
| 74 |
+
import_name: "import" dotted_as_names
|
| 75 |
+
// note below: the ("." | "...") is necessary because "..." is tokenized as ELLIPSIS
|
| 76 |
+
import_from: "from" (dots? dotted_name | dots) "import" ("*" | "(" import_as_names ")" | import_as_names)
|
| 77 |
+
!dots: "."+
|
| 78 |
+
import_as_name: name ["as" name]
|
| 79 |
+
dotted_as_name: dotted_name ["as" name]
|
| 80 |
+
import_as_names: import_as_name ("," import_as_name)* [","]
|
| 81 |
+
dotted_as_names: dotted_as_name ("," dotted_as_name)*
|
| 82 |
+
dotted_name: name ("." name)*
|
| 83 |
+
global_stmt: "global" name ("," name)*
|
| 84 |
+
nonlocal_stmt: "nonlocal" name ("," name)*
|
| 85 |
+
assert_stmt: "assert" test ["," test]
|
| 86 |
+
|
| 87 |
+
?compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | match_stmt
|
| 88 |
+
| with_stmt | funcdef | classdef | decorated | async_stmt
|
| 89 |
+
async_stmt: "async" (funcdef | with_stmt | for_stmt)
|
| 90 |
+
if_stmt: "if" test ":" suite elifs ["else" ":" suite]
|
| 91 |
+
elifs: elif_*
|
| 92 |
+
elif_: "elif" test ":" suite
|
| 93 |
+
while_stmt: "while" test ":" suite ["else" ":" suite]
|
| 94 |
+
for_stmt: "for" exprlist "in" testlist ":" suite ["else" ":" suite]
|
| 95 |
+
try_stmt: "try" ":" suite except_clauses ["else" ":" suite] [finally]
|
| 96 |
+
| "try" ":" suite finally -> try_finally
|
| 97 |
+
finally: "finally" ":" suite
|
| 98 |
+
except_clauses: except_clause+
|
| 99 |
+
except_clause: "except" [test ["as" name]] ":" suite
|
| 100 |
+
// NB compile.c makes sure that the default except clause is last
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
with_stmt: "with" with_items ":" suite
|
| 104 |
+
with_items: with_item ("," with_item)*
|
| 105 |
+
with_item: test ["as" name]
|
| 106 |
+
|
| 107 |
+
match_stmt: "match" test ":" _NEWLINE _INDENT case+ _DEDENT
|
| 108 |
+
|
| 109 |
+
case: "case" pattern ["if" test] ":" suite
|
| 110 |
+
|
| 111 |
+
?pattern: sequence_item_pattern "," _sequence_pattern -> sequence_pattern
|
| 112 |
+
| as_pattern
|
| 113 |
+
?as_pattern: or_pattern ("as" NAME)?
|
| 114 |
+
?or_pattern: closed_pattern ("|" closed_pattern)*
|
| 115 |
+
?closed_pattern: literal_pattern
|
| 116 |
+
| NAME -> capture_pattern
|
| 117 |
+
| "_" -> any_pattern
|
| 118 |
+
| attr_pattern
|
| 119 |
+
| "(" as_pattern ")"
|
| 120 |
+
| "[" _sequence_pattern "]" -> sequence_pattern
|
| 121 |
+
| "(" (sequence_item_pattern "," _sequence_pattern)? ")" -> sequence_pattern
|
| 122 |
+
| "{" (mapping_item_pattern ("," mapping_item_pattern)* ","?)?"}" -> mapping_pattern
|
| 123 |
+
| "{" (mapping_item_pattern ("," mapping_item_pattern)* ",")? "**" NAME ","? "}" -> mapping_star_pattern
|
| 124 |
+
| class_pattern
|
| 125 |
+
|
| 126 |
+
literal_pattern: inner_literal_pattern
|
| 127 |
+
|
| 128 |
+
?inner_literal_pattern: "None" -> const_none
|
| 129 |
+
| "True" -> const_true
|
| 130 |
+
| "False" -> const_false
|
| 131 |
+
| STRING -> string
|
| 132 |
+
| number
|
| 133 |
+
|
| 134 |
+
attr_pattern: NAME ("." NAME)+ -> value
|
| 135 |
+
|
| 136 |
+
name_or_attr_pattern: NAME ("." NAME)* -> value
|
| 137 |
+
|
| 138 |
+
mapping_item_pattern: (literal_pattern|attr_pattern) ":" as_pattern
|
| 139 |
+
|
| 140 |
+
_sequence_pattern: (sequence_item_pattern ("," sequence_item_pattern)* ","?)?
|
| 141 |
+
?sequence_item_pattern: as_pattern
|
| 142 |
+
| "*" NAME -> star_pattern
|
| 143 |
+
|
| 144 |
+
class_pattern: name_or_attr_pattern "(" [arguments_pattern ","?] ")"
|
| 145 |
+
arguments_pattern: pos_arg_pattern ["," keyws_arg_pattern]
|
| 146 |
+
| keyws_arg_pattern -> no_pos_arguments
|
| 147 |
+
|
| 148 |
+
pos_arg_pattern: as_pattern ("," as_pattern)*
|
| 149 |
+
keyws_arg_pattern: keyw_arg_pattern ("," keyw_arg_pattern)*
|
| 150 |
+
keyw_arg_pattern: NAME "=" as_pattern
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
suite: simple_stmt | _NEWLINE _INDENT stmt+ _DEDENT
|
| 155 |
+
|
| 156 |
+
?test: or_test ("if" or_test "else" test)?
|
| 157 |
+
| lambdef
|
| 158 |
+
| assign_expr
|
| 159 |
+
|
| 160 |
+
assign_expr: name ":=" test
|
| 161 |
+
|
| 162 |
+
?test_nocond: or_test | lambdef_nocond
|
| 163 |
+
|
| 164 |
+
?or_test: and_test ("or" and_test)*
|
| 165 |
+
?and_test: not_test_ ("and" not_test_)*
|
| 166 |
+
?not_test_: "not" not_test_ -> not_test
|
| 167 |
+
| comparison
|
| 168 |
+
?comparison: expr (comp_op expr)*
|
| 169 |
+
star_expr: "*" expr
|
| 170 |
+
|
| 171 |
+
?expr: or_expr
|
| 172 |
+
?or_expr: xor_expr ("|" xor_expr)*
|
| 173 |
+
?xor_expr: and_expr ("^" and_expr)*
|
| 174 |
+
?and_expr: shift_expr ("&" shift_expr)*
|
| 175 |
+
?shift_expr: arith_expr (_shift_op arith_expr)*
|
| 176 |
+
?arith_expr: term (_add_op term)*
|
| 177 |
+
?term: factor (_mul_op factor)*
|
| 178 |
+
?factor: _unary_op factor | power
|
| 179 |
+
|
| 180 |
+
!_unary_op: "+"|"-"|"~"
|
| 181 |
+
!_add_op: "+"|"-"
|
| 182 |
+
!_shift_op: "<<"|">>"
|
| 183 |
+
!_mul_op: "*"|"@"|"/"|"%"|"//"
|
| 184 |
+
// <> isn't actually a valid comparison operator in Python. It's here for the
|
| 185 |
+
// sake of a __future__ import described in PEP 401 (which really works :-)
|
| 186 |
+
!comp_op: "<"|">"|"=="|">="|"<="|"<>"|"!="|"in"|"not" "in"|"is"|"is" "not"
|
| 187 |
+
|
| 188 |
+
?power: await_expr ("**" factor)?
|
| 189 |
+
?await_expr: AWAIT? atom_expr
|
| 190 |
+
AWAIT: "await"
|
| 191 |
+
|
| 192 |
+
?atom_expr: atom_expr "(" [arguments] ")" -> funccall
|
| 193 |
+
| atom_expr "[" subscriptlist "]" -> getitem
|
| 194 |
+
| atom_expr "." name -> getattr
|
| 195 |
+
| atom
|
| 196 |
+
|
| 197 |
+
?atom: "(" yield_expr ")"
|
| 198 |
+
| "(" _tuple_inner? ")" -> tuple
|
| 199 |
+
| "(" comprehension{test_or_star_expr} ")" -> tuple_comprehension
|
| 200 |
+
| "[" _exprlist? "]" -> list
|
| 201 |
+
| "[" comprehension{test_or_star_expr} "]" -> list_comprehension
|
| 202 |
+
| "{" _dict_exprlist? "}" -> dict
|
| 203 |
+
| "{" comprehension{key_value} "}" -> dict_comprehension
|
| 204 |
+
| "{" _exprlist "}" -> set
|
| 205 |
+
| "{" comprehension{test} "}" -> set_comprehension
|
| 206 |
+
| name -> var
|
| 207 |
+
| number
|
| 208 |
+
| string_concat
|
| 209 |
+
| "(" test ")"
|
| 210 |
+
| "..." -> ellipsis
|
| 211 |
+
| "None" -> const_none
|
| 212 |
+
| "True" -> const_true
|
| 213 |
+
| "False" -> const_false
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
?string_concat: string+
|
| 217 |
+
|
| 218 |
+
_tuple_inner: test_or_star_expr (("," test_or_star_expr)+ [","] | ",")
|
| 219 |
+
|
| 220 |
+
?test_or_star_expr: test
|
| 221 |
+
| star_expr
|
| 222 |
+
|
| 223 |
+
?subscriptlist: subscript
|
| 224 |
+
| subscript (("," subscript)+ [","] | ",") -> subscript_tuple
|
| 225 |
+
?subscript: test | ([test] ":" [test] [sliceop]) -> slice
|
| 226 |
+
sliceop: ":" [test]
|
| 227 |
+
?exprlist: (expr|star_expr)
|
| 228 |
+
| (expr|star_expr) (("," (expr|star_expr))+ [","]|",")
|
| 229 |
+
?testlist: test | testlist_tuple
|
| 230 |
+
testlist_tuple: test (("," test)+ [","] | ",")
|
| 231 |
+
_dict_exprlist: (key_value | "**" expr) ("," (key_value | "**" expr))* [","]
|
| 232 |
+
|
| 233 |
+
key_value: test ":" test
|
| 234 |
+
|
| 235 |
+
_exprlist: test_or_star_expr ("," test_or_star_expr)* [","]
|
| 236 |
+
|
| 237 |
+
classdef: "class" name ["(" [arguments] ")"] ":" suite
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
arguments: argvalue ("," argvalue)* ("," [ starargs | kwargs])?
|
| 242 |
+
| starargs
|
| 243 |
+
| kwargs
|
| 244 |
+
| comprehension{test}
|
| 245 |
+
|
| 246 |
+
starargs: stararg ("," stararg)* ("," argvalue)* ["," kwargs]
|
| 247 |
+
stararg: "*" test
|
| 248 |
+
kwargs: "**" test ("," argvalue)*
|
| 249 |
+
|
| 250 |
+
?argvalue: test ("=" test)?
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
comprehension{comp_result}: comp_result comp_fors [comp_if]
|
| 254 |
+
comp_fors: comp_for+
|
| 255 |
+
comp_for: [ASYNC] "for" exprlist "in" or_test
|
| 256 |
+
ASYNC: "async"
|
| 257 |
+
?comp_if: "if" test_nocond
|
| 258 |
+
|
| 259 |
+
// not used in grammar, but may appear in "node" passed from Parser to Compiler
|
| 260 |
+
encoding_decl: name
|
| 261 |
+
|
| 262 |
+
yield_expr: "yield" [testlist]
|
| 263 |
+
| "yield" "from" test -> yield_from
|
| 264 |
+
|
| 265 |
+
number: DEC_NUMBER | HEX_NUMBER | BIN_NUMBER | OCT_NUMBER | FLOAT_NUMBER | IMAG_NUMBER
|
| 266 |
+
string: STRING | LONG_STRING
|
| 267 |
+
|
| 268 |
+
// Other terminals
|
| 269 |
+
|
| 270 |
+
_NEWLINE: ( /\r?\n[\t ]*/ | COMMENT )+
|
| 271 |
+
|
| 272 |
+
%ignore /[\t \f]+/ // WS
|
| 273 |
+
%ignore /\\[\t \f]*\r?\n/ // LINE_CONT
|
| 274 |
+
%ignore COMMENT
|
| 275 |
+
%declare _INDENT _DEDENT
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
// Python terminals
|
| 279 |
+
|
| 280 |
+
!name: NAME | "match" | "case"
|
| 281 |
+
NAME: /[^\W\d]\w*/
|
| 282 |
+
COMMENT: /#[^\n]*/
|
| 283 |
+
|
| 284 |
+
STRING: /([ubf]?r?|r[ubf])("(?!"").*?(?<!\\)(\\\\)*?"|'(?!'').*?(?<!\\)(\\\\)*?')/i
|
| 285 |
+
LONG_STRING: /([ubf]?r?|r[ubf])(""".*?(?<!\\)(\\\\)*?"""|'''.*?(?<!\\)(\\\\)*?''')/is
|
| 286 |
+
|
| 287 |
+
_SPECIAL_DEC: "0".."9" ("_"? "0".."9" )*
|
| 288 |
+
DEC_NUMBER: "1".."9" ("_"? "0".."9" )*
|
| 289 |
+
| "0" ("_"? "0" )* /(?![1-9])/
|
| 290 |
+
HEX_NUMBER.2: "0" ("x" | "X") ("_"? ("0".."9" | "a".."f" | "A".."F"))+
|
| 291 |
+
OCT_NUMBER.2: "0" ("o" | "O") ("_"? "0".."7" )+
|
| 292 |
+
BIN_NUMBER.2: "0" ("b" | "B") ("_"? "0".."1" )+
|
| 293 |
+
|
| 294 |
+
_EXP: ("e"|"E") ["+" | "-"] _SPECIAL_DEC
|
| 295 |
+
DECIMAL: "." _SPECIAL_DEC | _SPECIAL_DEC "." _SPECIAL_DEC?
|
| 296 |
+
FLOAT_NUMBER.2: _SPECIAL_DEC _EXP | DECIMAL _EXP?
|
| 297 |
+
IMAG_NUMBER.2: (_SPECIAL_DEC | FLOAT_NUMBER) ("J" | "j")
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
// Comma-separated list (with an optional trailing comma)
|
| 301 |
+
cs_list{item}: item ("," item)* ","?
|
| 302 |
+
_cs_list{item}: item ("," item)* ","?
|
vllm/lib/python3.10/site-packages/lark/grammars/unicode.lark
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// TODO: LETTER, WORD, etc.
|
| 2 |
+
|
| 3 |
+
//
|
| 4 |
+
// Whitespace
|
| 5 |
+
//
|
| 6 |
+
WS_INLINE: /[ \t\xa0]/+
|
| 7 |
+
WS: /[ \t\xa0\f\r\n]/+
|
vllm/lib/python3.10/site-packages/lark/lark.py
ADDED
|
@@ -0,0 +1,658 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
import getpass
|
| 3 |
+
import sys, os, pickle
|
| 4 |
+
import tempfile
|
| 5 |
+
import types
|
| 6 |
+
import re
|
| 7 |
+
from typing import (
|
| 8 |
+
TypeVar, Type, List, Dict, Iterator, Callable, Union, Optional, Sequence,
|
| 9 |
+
Tuple, Iterable, IO, Any, TYPE_CHECKING, Collection
|
| 10 |
+
)
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from .parsers.lalr_interactive_parser import InteractiveParser
|
| 13 |
+
from .tree import ParseTree
|
| 14 |
+
from .visitors import Transformer
|
| 15 |
+
from typing import Literal
|
| 16 |
+
from .parser_frontends import ParsingFrontend
|
| 17 |
+
|
| 18 |
+
from .exceptions import ConfigurationError, assert_config, UnexpectedInput
|
| 19 |
+
from .utils import Serialize, SerializeMemoizer, FS, logger
|
| 20 |
+
from .load_grammar import load_grammar, FromPackageLoader, Grammar, verify_used_files, PackageResource, sha256_digest
|
| 21 |
+
from .tree import Tree
|
| 22 |
+
from .common import LexerConf, ParserConf, _ParserArgType, _LexerArgType
|
| 23 |
+
|
| 24 |
+
from .lexer import Lexer, BasicLexer, TerminalDef, LexerThread, Token
|
| 25 |
+
from .parse_tree_builder import ParseTreeBuilder
|
| 26 |
+
from .parser_frontends import _validate_frontend_args, _get_lexer_callbacks, _deserialize_parsing_frontend, _construct_parsing_frontend
|
| 27 |
+
from .grammar import Rule
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
import regex
|
| 32 |
+
_has_regex = True
|
| 33 |
+
except ImportError:
|
| 34 |
+
_has_regex = False
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
###{standalone
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class PostLex(ABC):
|
| 41 |
+
@abstractmethod
|
| 42 |
+
def process(self, stream: Iterator[Token]) -> Iterator[Token]:
|
| 43 |
+
return stream
|
| 44 |
+
|
| 45 |
+
always_accept: Iterable[str] = ()
|
| 46 |
+
|
| 47 |
+
class LarkOptions(Serialize):
|
| 48 |
+
"""Specifies the options for Lark
|
| 49 |
+
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
start: List[str]
|
| 53 |
+
debug: bool
|
| 54 |
+
strict: bool
|
| 55 |
+
transformer: 'Optional[Transformer]'
|
| 56 |
+
propagate_positions: Union[bool, str]
|
| 57 |
+
maybe_placeholders: bool
|
| 58 |
+
cache: Union[bool, str]
|
| 59 |
+
regex: bool
|
| 60 |
+
g_regex_flags: int
|
| 61 |
+
keep_all_tokens: bool
|
| 62 |
+
tree_class: Optional[Callable[[str, List], Any]]
|
| 63 |
+
parser: _ParserArgType
|
| 64 |
+
lexer: _LexerArgType
|
| 65 |
+
ambiguity: 'Literal["auto", "resolve", "explicit", "forest"]'
|
| 66 |
+
postlex: Optional[PostLex]
|
| 67 |
+
priority: 'Optional[Literal["auto", "normal", "invert"]]'
|
| 68 |
+
lexer_callbacks: Dict[str, Callable[[Token], Token]]
|
| 69 |
+
use_bytes: bool
|
| 70 |
+
ordered_sets: bool
|
| 71 |
+
edit_terminals: Optional[Callable[[TerminalDef], TerminalDef]]
|
| 72 |
+
import_paths: 'List[Union[str, Callable[[Union[None, str, PackageResource], str], Tuple[str, str]]]]'
|
| 73 |
+
source_path: Optional[str]
|
| 74 |
+
|
| 75 |
+
OPTIONS_DOC = r"""
|
| 76 |
+
**=== General Options ===**
|
| 77 |
+
|
| 78 |
+
start
|
| 79 |
+
The start symbol. Either a string, or a list of strings for multiple possible starts (Default: "start")
|
| 80 |
+
debug
|
| 81 |
+
Display debug information and extra warnings. Use only when debugging (Default: ``False``)
|
| 82 |
+
When used with Earley, it generates a forest graph as "sppf.png", if 'dot' is installed.
|
| 83 |
+
strict
|
| 84 |
+
Throw an exception on any potential ambiguity, including shift/reduce conflicts, and regex collisions.
|
| 85 |
+
transformer
|
| 86 |
+
Applies the transformer to every parse tree (equivalent to applying it after the parse, but faster)
|
| 87 |
+
propagate_positions
|
| 88 |
+
Propagates positional attributes into the 'meta' attribute of all tree branches.
|
| 89 |
+
Sets attributes: (line, column, end_line, end_column, start_pos, end_pos,
|
| 90 |
+
container_line, container_column, container_end_line, container_end_column)
|
| 91 |
+
Accepts ``False``, ``True``, or a callable, which will filter which nodes to ignore when propagating.
|
| 92 |
+
maybe_placeholders
|
| 93 |
+
When ``True``, the ``[]`` operator returns ``None`` when not matched.
|
| 94 |
+
When ``False``, ``[]`` behaves like the ``?`` operator, and returns no value at all.
|
| 95 |
+
(default= ``True``)
|
| 96 |
+
cache
|
| 97 |
+
Cache the results of the Lark grammar analysis, for x2 to x3 faster loading. LALR only for now.
|
| 98 |
+
|
| 99 |
+
- When ``False``, does nothing (default)
|
| 100 |
+
- When ``True``, caches to a temporary file in the local directory
|
| 101 |
+
- When given a string, caches to the path pointed by the string
|
| 102 |
+
regex
|
| 103 |
+
When True, uses the ``regex`` module instead of the stdlib ``re``.
|
| 104 |
+
g_regex_flags
|
| 105 |
+
Flags that are applied to all terminals (both regex and strings)
|
| 106 |
+
keep_all_tokens
|
| 107 |
+
Prevent the tree builder from automagically removing "punctuation" tokens (Default: ``False``)
|
| 108 |
+
tree_class
|
| 109 |
+
Lark will produce trees comprised of instances of this class instead of the default ``lark.Tree``.
|
| 110 |
+
|
| 111 |
+
**=== Algorithm Options ===**
|
| 112 |
+
|
| 113 |
+
parser
|
| 114 |
+
Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley").
|
| 115 |
+
(there is also a "cyk" option for legacy)
|
| 116 |
+
lexer
|
| 117 |
+
Decides whether or not to use a lexer stage
|
| 118 |
+
|
| 119 |
+
- "auto" (default): Choose for me based on the parser
|
| 120 |
+
- "basic": Use a basic lexer
|
| 121 |
+
- "contextual": Stronger lexer (only works with parser="lalr")
|
| 122 |
+
- "dynamic": Flexible and powerful (only with parser="earley")
|
| 123 |
+
- "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible.
|
| 124 |
+
ambiguity
|
| 125 |
+
Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
|
| 126 |
+
|
| 127 |
+
- "resolve": The parser will automatically choose the simplest derivation
|
| 128 |
+
(it chooses consistently: greedy for tokens, non-greedy for rules)
|
| 129 |
+
- "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
|
| 130 |
+
- "forest": The parser will return the root of the shared packed parse forest.
|
| 131 |
+
|
| 132 |
+
**=== Misc. / Domain Specific Options ===**
|
| 133 |
+
|
| 134 |
+
postlex
|
| 135 |
+
Lexer post-processing (Default: ``None``) Only works with the basic and contextual lexers.
|
| 136 |
+
priority
|
| 137 |
+
How priorities should be evaluated - "auto", ``None``, "normal", "invert" (Default: "auto")
|
| 138 |
+
lexer_callbacks
|
| 139 |
+
Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
|
| 140 |
+
use_bytes
|
| 141 |
+
Accept an input of type ``bytes`` instead of ``str``.
|
| 142 |
+
ordered_sets
|
| 143 |
+
Should Earley use ordered-sets to achieve stable output (~10% slower than regular sets. Default: True)
|
| 144 |
+
edit_terminals
|
| 145 |
+
A callback for editing the terminals before parse.
|
| 146 |
+
import_paths
|
| 147 |
+
A List of either paths or loader functions to specify from where grammars are imported
|
| 148 |
+
source_path
|
| 149 |
+
Override the source of from where the grammar was loaded. Useful for relative imports and unconventional grammar loading
|
| 150 |
+
**=== End of Options ===**
|
| 151 |
+
"""
|
| 152 |
+
if __doc__:
|
| 153 |
+
__doc__ += OPTIONS_DOC
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# Adding a new option needs to be done in multiple places:
|
| 157 |
+
# - In the dictionary below. This is the primary truth of which options `Lark.__init__` accepts
|
| 158 |
+
# - In the docstring above. It is used both for the docstring of `LarkOptions` and `Lark`, and in readthedocs
|
| 159 |
+
# - As an attribute of `LarkOptions` above
|
| 160 |
+
# - Potentially in `_LOAD_ALLOWED_OPTIONS` below this class, when the option doesn't change how the grammar is loaded
|
| 161 |
+
# - Potentially in `lark.tools.__init__`, if it makes sense, and it can easily be passed as a cmd argument
|
| 162 |
+
_defaults: Dict[str, Any] = {
|
| 163 |
+
'debug': False,
|
| 164 |
+
'strict': False,
|
| 165 |
+
'keep_all_tokens': False,
|
| 166 |
+
'tree_class': None,
|
| 167 |
+
'cache': False,
|
| 168 |
+
'postlex': None,
|
| 169 |
+
'parser': 'earley',
|
| 170 |
+
'lexer': 'auto',
|
| 171 |
+
'transformer': None,
|
| 172 |
+
'start': 'start',
|
| 173 |
+
'priority': 'auto',
|
| 174 |
+
'ambiguity': 'auto',
|
| 175 |
+
'regex': False,
|
| 176 |
+
'propagate_positions': False,
|
| 177 |
+
'lexer_callbacks': {},
|
| 178 |
+
'maybe_placeholders': True,
|
| 179 |
+
'edit_terminals': None,
|
| 180 |
+
'g_regex_flags': 0,
|
| 181 |
+
'use_bytes': False,
|
| 182 |
+
'ordered_sets': True,
|
| 183 |
+
'import_paths': [],
|
| 184 |
+
'source_path': None,
|
| 185 |
+
'_plugins': {},
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
def __init__(self, options_dict: Dict[str, Any]) -> None:
|
| 189 |
+
o = dict(options_dict)
|
| 190 |
+
|
| 191 |
+
options = {}
|
| 192 |
+
for name, default in self._defaults.items():
|
| 193 |
+
if name in o:
|
| 194 |
+
value = o.pop(name)
|
| 195 |
+
if isinstance(default, bool) and name not in ('cache', 'use_bytes', 'propagate_positions'):
|
| 196 |
+
value = bool(value)
|
| 197 |
+
else:
|
| 198 |
+
value = default
|
| 199 |
+
|
| 200 |
+
options[name] = value
|
| 201 |
+
|
| 202 |
+
if isinstance(options['start'], str):
|
| 203 |
+
options['start'] = [options['start']]
|
| 204 |
+
|
| 205 |
+
self.__dict__['options'] = options
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
assert_config(self.parser, ('earley', 'lalr', 'cyk', None))
|
| 209 |
+
|
| 210 |
+
if self.parser == 'earley' and self.transformer:
|
| 211 |
+
raise ConfigurationError('Cannot specify an embedded transformer when using the Earley algorithm. '
|
| 212 |
+
'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)')
|
| 213 |
+
|
| 214 |
+
if o:
|
| 215 |
+
raise ConfigurationError("Unknown options: %s" % o.keys())
|
| 216 |
+
|
| 217 |
+
def __getattr__(self, name: str) -> Any:
|
| 218 |
+
try:
|
| 219 |
+
return self.__dict__['options'][name]
|
| 220 |
+
except KeyError as e:
|
| 221 |
+
raise AttributeError(e)
|
| 222 |
+
|
| 223 |
+
def __setattr__(self, name: str, value: str) -> None:
|
| 224 |
+
assert_config(name, self.options.keys(), "%r isn't a valid option. Expected one of: %s")
|
| 225 |
+
self.options[name] = value
|
| 226 |
+
|
| 227 |
+
def serialize(self, memo = None) -> Dict[str, Any]:
|
| 228 |
+
return self.options
|
| 229 |
+
|
| 230 |
+
@classmethod
|
| 231 |
+
def deserialize(cls, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]]) -> "LarkOptions":
|
| 232 |
+
return cls(data)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# Options that can be passed to the Lark parser, even when it was loaded from cache/standalone.
|
| 236 |
+
# These options are only used outside of `load_grammar`.
|
| 237 |
+
_LOAD_ALLOWED_OPTIONS = {'postlex', 'transformer', 'lexer_callbacks', 'use_bytes', 'debug', 'g_regex_flags', 'regex', 'propagate_positions', 'tree_class', '_plugins'}
|
| 238 |
+
|
| 239 |
+
_VALID_PRIORITY_OPTIONS = ('auto', 'normal', 'invert', None)
|
| 240 |
+
_VALID_AMBIGUITY_OPTIONS = ('auto', 'resolve', 'explicit', 'forest')
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
_T = TypeVar('_T', bound="Lark")
|
| 244 |
+
|
| 245 |
+
class Lark(Serialize):
|
| 246 |
+
"""Main interface for the library.
|
| 247 |
+
|
| 248 |
+
It's mostly a thin wrapper for the many different parsers, and for the tree constructor.
|
| 249 |
+
|
| 250 |
+
Parameters:
|
| 251 |
+
grammar: a string or file-object containing the grammar spec (using Lark's ebnf syntax)
|
| 252 |
+
options: a dictionary controlling various aspects of Lark.
|
| 253 |
+
|
| 254 |
+
Example:
|
| 255 |
+
>>> Lark(r'''start: "foo" ''')
|
| 256 |
+
Lark(...)
|
| 257 |
+
"""
|
| 258 |
+
|
| 259 |
+
source_path: str
|
| 260 |
+
source_grammar: str
|
| 261 |
+
grammar: 'Grammar'
|
| 262 |
+
options: LarkOptions
|
| 263 |
+
lexer: Lexer
|
| 264 |
+
parser: 'ParsingFrontend'
|
| 265 |
+
terminals: Collection[TerminalDef]
|
| 266 |
+
|
| 267 |
+
def __init__(self, grammar: 'Union[Grammar, str, IO[str]]', **options) -> None:
|
| 268 |
+
self.options = LarkOptions(options)
|
| 269 |
+
re_module: types.ModuleType
|
| 270 |
+
|
| 271 |
+
# Set regex or re module
|
| 272 |
+
use_regex = self.options.regex
|
| 273 |
+
if use_regex:
|
| 274 |
+
if _has_regex:
|
| 275 |
+
re_module = regex
|
| 276 |
+
else:
|
| 277 |
+
raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.')
|
| 278 |
+
else:
|
| 279 |
+
re_module = re
|
| 280 |
+
|
| 281 |
+
# Some, but not all file-like objects have a 'name' attribute
|
| 282 |
+
if self.options.source_path is None:
|
| 283 |
+
try:
|
| 284 |
+
self.source_path = grammar.name # type: ignore[union-attr]
|
| 285 |
+
except AttributeError:
|
| 286 |
+
self.source_path = '<string>'
|
| 287 |
+
else:
|
| 288 |
+
self.source_path = self.options.source_path
|
| 289 |
+
|
| 290 |
+
# Drain file-like objects to get their contents
|
| 291 |
+
try:
|
| 292 |
+
read = grammar.read # type: ignore[union-attr]
|
| 293 |
+
except AttributeError:
|
| 294 |
+
pass
|
| 295 |
+
else:
|
| 296 |
+
grammar = read()
|
| 297 |
+
|
| 298 |
+
cache_fn = None
|
| 299 |
+
cache_sha256 = None
|
| 300 |
+
if isinstance(grammar, str):
|
| 301 |
+
self.source_grammar = grammar
|
| 302 |
+
if self.options.use_bytes:
|
| 303 |
+
if not grammar.isascii():
|
| 304 |
+
raise ConfigurationError("Grammar must be ascii only, when use_bytes=True")
|
| 305 |
+
|
| 306 |
+
if self.options.cache:
|
| 307 |
+
if self.options.parser != 'lalr':
|
| 308 |
+
raise ConfigurationError("cache only works with parser='lalr' for now")
|
| 309 |
+
|
| 310 |
+
unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals', '_plugins')
|
| 311 |
+
options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
|
| 312 |
+
from . import __version__
|
| 313 |
+
s = grammar + options_str + __version__ + str(sys.version_info[:2])
|
| 314 |
+
cache_sha256 = sha256_digest(s)
|
| 315 |
+
|
| 316 |
+
if isinstance(self.options.cache, str):
|
| 317 |
+
cache_fn = self.options.cache
|
| 318 |
+
else:
|
| 319 |
+
if self.options.cache is not True:
|
| 320 |
+
raise ConfigurationError("cache argument must be bool or str")
|
| 321 |
+
|
| 322 |
+
try:
|
| 323 |
+
username = getpass.getuser()
|
| 324 |
+
except Exception:
|
| 325 |
+
# The exception raised may be ImportError or OSError in
|
| 326 |
+
# the future. For the cache, we don't care about the
|
| 327 |
+
# specific reason - we just want a username.
|
| 328 |
+
username = "unknown"
|
| 329 |
+
|
| 330 |
+
cache_fn = tempfile.gettempdir() + "/.lark_cache_%s_%s_%s_%s.tmp" % (username, cache_sha256, *sys.version_info[:2])
|
| 331 |
+
|
| 332 |
+
old_options = self.options
|
| 333 |
+
try:
|
| 334 |
+
with FS.open(cache_fn, 'rb') as f:
|
| 335 |
+
logger.debug('Loading grammar from cache: %s', cache_fn)
|
| 336 |
+
# Remove options that aren't relevant for loading from cache
|
| 337 |
+
for name in (set(options) - _LOAD_ALLOWED_OPTIONS):
|
| 338 |
+
del options[name]
|
| 339 |
+
file_sha256 = f.readline().rstrip(b'\n')
|
| 340 |
+
cached_used_files = pickle.load(f)
|
| 341 |
+
if file_sha256 == cache_sha256.encode('utf8') and verify_used_files(cached_used_files):
|
| 342 |
+
cached_parser_data = pickle.load(f)
|
| 343 |
+
self._load(cached_parser_data, **options)
|
| 344 |
+
return
|
| 345 |
+
except FileNotFoundError:
|
| 346 |
+
# The cache file doesn't exist; parse and compose the grammar as normal
|
| 347 |
+
pass
|
| 348 |
+
except Exception: # We should probably narrow done which errors we catch here.
|
| 349 |
+
logger.exception("Failed to load Lark from cache: %r. We will try to carry on.", cache_fn)
|
| 350 |
+
|
| 351 |
+
# In theory, the Lark instance might have been messed up by the call to `_load`.
|
| 352 |
+
# In practice the only relevant thing that might have been overwritten should be `options`
|
| 353 |
+
self.options = old_options
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# Parse the grammar file and compose the grammars
|
| 357 |
+
self.grammar, used_files = load_grammar(grammar, self.source_path, self.options.import_paths, self.options.keep_all_tokens)
|
| 358 |
+
else:
|
| 359 |
+
assert isinstance(grammar, Grammar)
|
| 360 |
+
self.grammar = grammar
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
if self.options.lexer == 'auto':
|
| 364 |
+
if self.options.parser == 'lalr':
|
| 365 |
+
self.options.lexer = 'contextual'
|
| 366 |
+
elif self.options.parser == 'earley':
|
| 367 |
+
if self.options.postlex is not None:
|
| 368 |
+
logger.info("postlex can't be used with the dynamic lexer, so we use 'basic' instead. "
|
| 369 |
+
"Consider using lalr with contextual instead of earley")
|
| 370 |
+
self.options.lexer = 'basic'
|
| 371 |
+
else:
|
| 372 |
+
self.options.lexer = 'dynamic'
|
| 373 |
+
elif self.options.parser == 'cyk':
|
| 374 |
+
self.options.lexer = 'basic'
|
| 375 |
+
else:
|
| 376 |
+
assert False, self.options.parser
|
| 377 |
+
lexer = self.options.lexer
|
| 378 |
+
if isinstance(lexer, type):
|
| 379 |
+
assert issubclass(lexer, Lexer) # XXX Is this really important? Maybe just ensure interface compliance
|
| 380 |
+
else:
|
| 381 |
+
assert_config(lexer, ('basic', 'contextual', 'dynamic', 'dynamic_complete'))
|
| 382 |
+
if self.options.postlex is not None and 'dynamic' in lexer:
|
| 383 |
+
raise ConfigurationError("Can't use postlex with a dynamic lexer. Use basic or contextual instead")
|
| 384 |
+
|
| 385 |
+
if self.options.ambiguity == 'auto':
|
| 386 |
+
if self.options.parser == 'earley':
|
| 387 |
+
self.options.ambiguity = 'resolve'
|
| 388 |
+
else:
|
| 389 |
+
assert_config(self.options.parser, ('earley', 'cyk'), "%r doesn't support disambiguation. Use one of these parsers instead: %s")
|
| 390 |
+
|
| 391 |
+
if self.options.priority == 'auto':
|
| 392 |
+
self.options.priority = 'normal'
|
| 393 |
+
|
| 394 |
+
if self.options.priority not in _VALID_PRIORITY_OPTIONS:
|
| 395 |
+
raise ConfigurationError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS))
|
| 396 |
+
if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS:
|
| 397 |
+
raise ConfigurationError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS))
|
| 398 |
+
|
| 399 |
+
if self.options.parser is None:
|
| 400 |
+
terminals_to_keep = '*'
|
| 401 |
+
elif self.options.postlex is not None:
|
| 402 |
+
terminals_to_keep = set(self.options.postlex.always_accept)
|
| 403 |
+
else:
|
| 404 |
+
terminals_to_keep = set()
|
| 405 |
+
|
| 406 |
+
# Compile the EBNF grammar into BNF
|
| 407 |
+
self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep)
|
| 408 |
+
|
| 409 |
+
if self.options.edit_terminals:
|
| 410 |
+
for t in self.terminals:
|
| 411 |
+
self.options.edit_terminals(t)
|
| 412 |
+
|
| 413 |
+
self._terminals_dict = {t.name: t for t in self.terminals}
|
| 414 |
+
|
| 415 |
+
# If the user asked to invert the priorities, negate them all here.
|
| 416 |
+
if self.options.priority == 'invert':
|
| 417 |
+
for rule in self.rules:
|
| 418 |
+
if rule.options.priority is not None:
|
| 419 |
+
rule.options.priority = -rule.options.priority
|
| 420 |
+
for term in self.terminals:
|
| 421 |
+
term.priority = -term.priority
|
| 422 |
+
# Else, if the user asked to disable priorities, strip them from the
|
| 423 |
+
# rules and terminals. This allows the Earley parsers to skip an extra forest walk
|
| 424 |
+
# for improved performance, if you don't need them (or didn't specify any).
|
| 425 |
+
elif self.options.priority is None:
|
| 426 |
+
for rule in self.rules:
|
| 427 |
+
if rule.options.priority is not None:
|
| 428 |
+
rule.options.priority = None
|
| 429 |
+
for term in self.terminals:
|
| 430 |
+
term.priority = 0
|
| 431 |
+
|
| 432 |
+
# TODO Deprecate lexer_callbacks?
|
| 433 |
+
self.lexer_conf = LexerConf(
|
| 434 |
+
self.terminals, re_module, self.ignore_tokens, self.options.postlex,
|
| 435 |
+
self.options.lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes, strict=self.options.strict
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
if self.options.parser:
|
| 439 |
+
self.parser = self._build_parser()
|
| 440 |
+
elif lexer:
|
| 441 |
+
self.lexer = self._build_lexer()
|
| 442 |
+
|
| 443 |
+
if cache_fn:
|
| 444 |
+
logger.debug('Saving grammar to cache: %s', cache_fn)
|
| 445 |
+
try:
|
| 446 |
+
with FS.open(cache_fn, 'wb') as f:
|
| 447 |
+
assert cache_sha256 is not None
|
| 448 |
+
f.write(cache_sha256.encode('utf8') + b'\n')
|
| 449 |
+
pickle.dump(used_files, f)
|
| 450 |
+
self.save(f, _LOAD_ALLOWED_OPTIONS)
|
| 451 |
+
except IOError as e:
|
| 452 |
+
logger.exception("Failed to save Lark to cache: %r.", cache_fn, e)
|
| 453 |
+
|
| 454 |
+
if __doc__:
|
| 455 |
+
__doc__ += "\n\n" + LarkOptions.OPTIONS_DOC
|
| 456 |
+
|
| 457 |
+
__serialize_fields__ = 'parser', 'rules', 'options'
|
| 458 |
+
|
| 459 |
+
def _build_lexer(self, dont_ignore: bool=False) -> BasicLexer:
|
| 460 |
+
lexer_conf = self.lexer_conf
|
| 461 |
+
if dont_ignore:
|
| 462 |
+
from copy import copy
|
| 463 |
+
lexer_conf = copy(lexer_conf)
|
| 464 |
+
lexer_conf.ignore = ()
|
| 465 |
+
return BasicLexer(lexer_conf)
|
| 466 |
+
|
| 467 |
+
def _prepare_callbacks(self) -> None:
|
| 468 |
+
self._callbacks = {}
|
| 469 |
+
# we don't need these callbacks if we aren't building a tree
|
| 470 |
+
if self.options.ambiguity != 'forest':
|
| 471 |
+
self._parse_tree_builder = ParseTreeBuilder(
|
| 472 |
+
self.rules,
|
| 473 |
+
self.options.tree_class or Tree,
|
| 474 |
+
self.options.propagate_positions,
|
| 475 |
+
self.options.parser != 'lalr' and self.options.ambiguity == 'explicit',
|
| 476 |
+
self.options.maybe_placeholders
|
| 477 |
+
)
|
| 478 |
+
self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
|
| 479 |
+
self._callbacks.update(_get_lexer_callbacks(self.options.transformer, self.terminals))
|
| 480 |
+
|
| 481 |
+
def _build_parser(self) -> "ParsingFrontend":
|
| 482 |
+
self._prepare_callbacks()
|
| 483 |
+
_validate_frontend_args(self.options.parser, self.options.lexer)
|
| 484 |
+
parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
|
| 485 |
+
return _construct_parsing_frontend(
|
| 486 |
+
self.options.parser,
|
| 487 |
+
self.options.lexer,
|
| 488 |
+
self.lexer_conf,
|
| 489 |
+
parser_conf,
|
| 490 |
+
options=self.options
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
def save(self, f, exclude_options: Collection[str] = ()) -> None:
|
| 494 |
+
"""Saves the instance into the given file object
|
| 495 |
+
|
| 496 |
+
Useful for caching and multiprocessing.
|
| 497 |
+
"""
|
| 498 |
+
if self.options.parser != 'lalr':
|
| 499 |
+
raise NotImplementedError("Lark.save() is only implemented for the LALR(1) parser.")
|
| 500 |
+
data, m = self.memo_serialize([TerminalDef, Rule])
|
| 501 |
+
if exclude_options:
|
| 502 |
+
data["options"] = {n: v for n, v in data["options"].items() if n not in exclude_options}
|
| 503 |
+
pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL)
|
| 504 |
+
|
| 505 |
+
@classmethod
|
| 506 |
+
def load(cls: Type[_T], f) -> _T:
|
| 507 |
+
"""Loads an instance from the given file object
|
| 508 |
+
|
| 509 |
+
Useful for caching and multiprocessing.
|
| 510 |
+
"""
|
| 511 |
+
inst = cls.__new__(cls)
|
| 512 |
+
return inst._load(f)
|
| 513 |
+
|
| 514 |
+
def _deserialize_lexer_conf(self, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]], options: LarkOptions) -> LexerConf:
|
| 515 |
+
lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo)
|
| 516 |
+
lexer_conf.callbacks = options.lexer_callbacks or {}
|
| 517 |
+
lexer_conf.re_module = regex if options.regex else re
|
| 518 |
+
lexer_conf.use_bytes = options.use_bytes
|
| 519 |
+
lexer_conf.g_regex_flags = options.g_regex_flags
|
| 520 |
+
lexer_conf.skip_validation = True
|
| 521 |
+
lexer_conf.postlex = options.postlex
|
| 522 |
+
return lexer_conf
|
| 523 |
+
|
| 524 |
+
def _load(self: _T, f: Any, **kwargs) -> _T:
|
| 525 |
+
if isinstance(f, dict):
|
| 526 |
+
d = f
|
| 527 |
+
else:
|
| 528 |
+
d = pickle.load(f)
|
| 529 |
+
memo_json = d['memo']
|
| 530 |
+
data = d['data']
|
| 531 |
+
|
| 532 |
+
assert memo_json
|
| 533 |
+
memo = SerializeMemoizer.deserialize(memo_json, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
|
| 534 |
+
options = dict(data['options'])
|
| 535 |
+
if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults):
|
| 536 |
+
raise ConfigurationError("Some options are not allowed when loading a Parser: {}"
|
| 537 |
+
.format(set(kwargs) - _LOAD_ALLOWED_OPTIONS))
|
| 538 |
+
options.update(kwargs)
|
| 539 |
+
self.options = LarkOptions.deserialize(options, memo)
|
| 540 |
+
self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
|
| 541 |
+
self.source_path = '<deserialized>'
|
| 542 |
+
_validate_frontend_args(self.options.parser, self.options.lexer)
|
| 543 |
+
self.lexer_conf = self._deserialize_lexer_conf(data['parser'], memo, self.options)
|
| 544 |
+
self.terminals = self.lexer_conf.terminals
|
| 545 |
+
self._prepare_callbacks()
|
| 546 |
+
self._terminals_dict = {t.name: t for t in self.terminals}
|
| 547 |
+
self.parser = _deserialize_parsing_frontend(
|
| 548 |
+
data['parser'],
|
| 549 |
+
memo,
|
| 550 |
+
self.lexer_conf,
|
| 551 |
+
self._callbacks,
|
| 552 |
+
self.options, # Not all, but multiple attributes are used
|
| 553 |
+
)
|
| 554 |
+
return self
|
| 555 |
+
|
| 556 |
+
@classmethod
|
| 557 |
+
def _load_from_dict(cls, data, memo, **kwargs):
|
| 558 |
+
inst = cls.__new__(cls)
|
| 559 |
+
return inst._load({'data': data, 'memo': memo}, **kwargs)
|
| 560 |
+
|
| 561 |
+
@classmethod
|
| 562 |
+
def open(cls: Type[_T], grammar_filename: str, rel_to: Optional[str]=None, **options) -> _T:
|
| 563 |
+
"""Create an instance of Lark with the grammar given by its filename
|
| 564 |
+
|
| 565 |
+
If ``rel_to`` is provided, the function will find the grammar filename in relation to it.
|
| 566 |
+
|
| 567 |
+
Example:
|
| 568 |
+
|
| 569 |
+
>>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
|
| 570 |
+
Lark(...)
|
| 571 |
+
|
| 572 |
+
"""
|
| 573 |
+
if rel_to:
|
| 574 |
+
basepath = os.path.dirname(rel_to)
|
| 575 |
+
grammar_filename = os.path.join(basepath, grammar_filename)
|
| 576 |
+
with open(grammar_filename, encoding='utf8') as f:
|
| 577 |
+
return cls(f, **options)
|
| 578 |
+
|
| 579 |
+
@classmethod
|
| 580 |
+
def open_from_package(cls: Type[_T], package: str, grammar_path: str, search_paths: 'Sequence[str]'=[""], **options) -> _T:
|
| 581 |
+
"""Create an instance of Lark with the grammar loaded from within the package `package`.
|
| 582 |
+
This allows grammar loading from zipapps.
|
| 583 |
+
|
| 584 |
+
Imports in the grammar will use the `package` and `search_paths` provided, through `FromPackageLoader`
|
| 585 |
+
|
| 586 |
+
Example:
|
| 587 |
+
|
| 588 |
+
Lark.open_from_package(__name__, "example.lark", ("grammars",), parser=...)
|
| 589 |
+
"""
|
| 590 |
+
package_loader = FromPackageLoader(package, search_paths)
|
| 591 |
+
full_path, text = package_loader(None, grammar_path)
|
| 592 |
+
options.setdefault('source_path', full_path)
|
| 593 |
+
options.setdefault('import_paths', [])
|
| 594 |
+
options['import_paths'].append(package_loader)
|
| 595 |
+
return cls(text, **options)
|
| 596 |
+
|
| 597 |
+
def __repr__(self):
|
| 598 |
+
return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source_path, self.options.parser, self.options.lexer)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def lex(self, text: str, dont_ignore: bool=False) -> Iterator[Token]:
|
| 602 |
+
"""Only lex (and postlex) the text, without parsing it. Only relevant when lexer='basic'
|
| 603 |
+
|
| 604 |
+
When dont_ignore=True, the lexer will return all tokens, even those marked for %ignore.
|
| 605 |
+
|
| 606 |
+
:raises UnexpectedCharacters: In case the lexer cannot find a suitable match.
|
| 607 |
+
"""
|
| 608 |
+
lexer: Lexer
|
| 609 |
+
if not hasattr(self, 'lexer') or dont_ignore:
|
| 610 |
+
lexer = self._build_lexer(dont_ignore)
|
| 611 |
+
else:
|
| 612 |
+
lexer = self.lexer
|
| 613 |
+
lexer_thread = LexerThread.from_text(lexer, text)
|
| 614 |
+
stream = lexer_thread.lex(None)
|
| 615 |
+
if self.options.postlex:
|
| 616 |
+
return self.options.postlex.process(stream)
|
| 617 |
+
return stream
|
| 618 |
+
|
| 619 |
+
def get_terminal(self, name: str) -> TerminalDef:
|
| 620 |
+
"""Get information about a terminal"""
|
| 621 |
+
return self._terminals_dict[name]
|
| 622 |
+
|
| 623 |
+
def parse_interactive(self, text: Optional[str]=None, start: Optional[str]=None) -> 'InteractiveParser':
|
| 624 |
+
"""Start an interactive parsing session.
|
| 625 |
+
|
| 626 |
+
Parameters:
|
| 627 |
+
text (str, optional): Text to be parsed. Required for ``resume_parse()``.
|
| 628 |
+
start (str, optional): Start symbol
|
| 629 |
+
|
| 630 |
+
Returns:
|
| 631 |
+
A new InteractiveParser instance.
|
| 632 |
+
|
| 633 |
+
See Also: ``Lark.parse()``
|
| 634 |
+
"""
|
| 635 |
+
return self.parser.parse_interactive(text, start=start)
|
| 636 |
+
|
| 637 |
+
def parse(self, text: str, start: Optional[str]=None, on_error: 'Optional[Callable[[UnexpectedInput], bool]]'=None) -> 'ParseTree':
|
| 638 |
+
"""Parse the given text, according to the options provided.
|
| 639 |
+
|
| 640 |
+
Parameters:
|
| 641 |
+
text (str): Text to be parsed.
|
| 642 |
+
start (str, optional): Required if Lark was given multiple possible start symbols (using the start option).
|
| 643 |
+
on_error (function, optional): if provided, will be called on UnexpectedToken error. Return true to resume parsing.
|
| 644 |
+
LALR only. See examples/advanced/error_handling.py for an example of how to use on_error.
|
| 645 |
+
|
| 646 |
+
Returns:
|
| 647 |
+
If a transformer is supplied to ``__init__``, returns whatever is the
|
| 648 |
+
result of the transformation. Otherwise, returns a Tree instance.
|
| 649 |
+
|
| 650 |
+
:raises UnexpectedInput: On a parse error, one of these sub-exceptions will rise:
|
| 651 |
+
``UnexpectedCharacters``, ``UnexpectedToken``, or ``UnexpectedEOF``.
|
| 652 |
+
For convenience, these sub-exceptions also inherit from ``ParserError`` and ``LexerError``.
|
| 653 |
+
|
| 654 |
+
"""
|
| 655 |
+
return self.parser.parse(text, start=start, on_error=on_error)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
###}
|
vllm/lib/python3.10/site-packages/lark/lexer.py
ADDED
|
@@ -0,0 +1,678 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Lexer Implementation
|
| 2 |
+
|
| 3 |
+
from abc import abstractmethod, ABC
|
| 4 |
+
import re
|
| 5 |
+
from contextlib import suppress
|
| 6 |
+
from typing import (
|
| 7 |
+
TypeVar, Type, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
|
| 8 |
+
ClassVar, TYPE_CHECKING, overload
|
| 9 |
+
)
|
| 10 |
+
from types import ModuleType
|
| 11 |
+
import warnings
|
| 12 |
+
try:
|
| 13 |
+
import interegular
|
| 14 |
+
except ImportError:
|
| 15 |
+
pass
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from .common import LexerConf
|
| 18 |
+
from .parsers.lalr_parser_state import ParserState
|
| 19 |
+
|
| 20 |
+
from .utils import classify, get_regexp_width, Serialize, logger
|
| 21 |
+
from .exceptions import UnexpectedCharacters, LexError, UnexpectedToken
|
| 22 |
+
from .grammar import TOKEN_DEFAULT_PRIORITY
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
###{standalone
|
| 26 |
+
from copy import copy
|
| 27 |
+
|
| 28 |
+
try: # For the standalone parser, we need to make sure that has_interegular is False to avoid NameErrors later on
|
| 29 |
+
has_interegular = bool(interegular)
|
| 30 |
+
except NameError:
|
| 31 |
+
has_interegular = False
|
| 32 |
+
|
| 33 |
+
class Pattern(Serialize, ABC):
|
| 34 |
+
"An abstraction over regular expressions."
|
| 35 |
+
|
| 36 |
+
value: str
|
| 37 |
+
flags: Collection[str]
|
| 38 |
+
raw: Optional[str]
|
| 39 |
+
type: ClassVar[str]
|
| 40 |
+
|
| 41 |
+
def __init__(self, value: str, flags: Collection[str] = (), raw: Optional[str] = None) -> None:
|
| 42 |
+
self.value = value
|
| 43 |
+
self.flags = frozenset(flags)
|
| 44 |
+
self.raw = raw
|
| 45 |
+
|
| 46 |
+
def __repr__(self):
|
| 47 |
+
return repr(self.to_regexp())
|
| 48 |
+
|
| 49 |
+
# Pattern Hashing assumes all subclasses have a different priority!
|
| 50 |
+
def __hash__(self):
|
| 51 |
+
return hash((type(self), self.value, self.flags))
|
| 52 |
+
|
| 53 |
+
def __eq__(self, other):
|
| 54 |
+
return type(self) == type(other) and self.value == other.value and self.flags == other.flags
|
| 55 |
+
|
| 56 |
+
@abstractmethod
|
| 57 |
+
def to_regexp(self) -> str:
|
| 58 |
+
raise NotImplementedError()
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
@abstractmethod
|
| 62 |
+
def min_width(self) -> int:
|
| 63 |
+
raise NotImplementedError()
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
@abstractmethod
|
| 67 |
+
def max_width(self) -> int:
|
| 68 |
+
raise NotImplementedError()
|
| 69 |
+
|
| 70 |
+
def _get_flags(self, value):
|
| 71 |
+
for f in self.flags:
|
| 72 |
+
value = ('(?%s:%s)' % (f, value))
|
| 73 |
+
return value
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class PatternStr(Pattern):
|
| 77 |
+
__serialize_fields__ = 'value', 'flags', 'raw'
|
| 78 |
+
|
| 79 |
+
type: ClassVar[str] = "str"
|
| 80 |
+
|
| 81 |
+
def to_regexp(self) -> str:
|
| 82 |
+
return self._get_flags(re.escape(self.value))
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def min_width(self) -> int:
|
| 86 |
+
return len(self.value)
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def max_width(self) -> int:
|
| 90 |
+
return len(self.value)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class PatternRE(Pattern):
|
| 94 |
+
__serialize_fields__ = 'value', 'flags', 'raw', '_width'
|
| 95 |
+
|
| 96 |
+
type: ClassVar[str] = "re"
|
| 97 |
+
|
| 98 |
+
def to_regexp(self) -> str:
|
| 99 |
+
return self._get_flags(self.value)
|
| 100 |
+
|
| 101 |
+
_width = None
|
| 102 |
+
def _get_width(self):
|
| 103 |
+
if self._width is None:
|
| 104 |
+
self._width = get_regexp_width(self.to_regexp())
|
| 105 |
+
return self._width
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def min_width(self) -> int:
|
| 109 |
+
return self._get_width()[0]
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def max_width(self) -> int:
|
| 113 |
+
return self._get_width()[1]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class TerminalDef(Serialize):
|
| 117 |
+
"A definition of a terminal"
|
| 118 |
+
__serialize_fields__ = 'name', 'pattern', 'priority'
|
| 119 |
+
__serialize_namespace__ = PatternStr, PatternRE
|
| 120 |
+
|
| 121 |
+
name: str
|
| 122 |
+
pattern: Pattern
|
| 123 |
+
priority: int
|
| 124 |
+
|
| 125 |
+
def __init__(self, name: str, pattern: Pattern, priority: int = TOKEN_DEFAULT_PRIORITY) -> None:
|
| 126 |
+
assert isinstance(pattern, Pattern), pattern
|
| 127 |
+
self.name = name
|
| 128 |
+
self.pattern = pattern
|
| 129 |
+
self.priority = priority
|
| 130 |
+
|
| 131 |
+
def __repr__(self):
|
| 132 |
+
return '%s(%r, %r)' % (type(self).__name__, self.name, self.pattern)
|
| 133 |
+
|
| 134 |
+
def user_repr(self) -> str:
|
| 135 |
+
if self.name.startswith('__'): # We represent a generated terminal
|
| 136 |
+
return self.pattern.raw or self.name
|
| 137 |
+
else:
|
| 138 |
+
return self.name
|
| 139 |
+
|
| 140 |
+
_T = TypeVar('_T', bound="Token")
|
| 141 |
+
|
| 142 |
+
class Token(str):
|
| 143 |
+
"""A string with meta-information, that is produced by the lexer.
|
| 144 |
+
|
| 145 |
+
When parsing text, the resulting chunks of the input that haven't been discarded,
|
| 146 |
+
will end up in the tree as Token instances. The Token class inherits from Python's ``str``,
|
| 147 |
+
so normal string comparisons and operations will work as expected.
|
| 148 |
+
|
| 149 |
+
Attributes:
|
| 150 |
+
type: Name of the token (as specified in grammar)
|
| 151 |
+
value: Value of the token (redundant, as ``token.value == token`` will always be true)
|
| 152 |
+
start_pos: The index of the token in the text
|
| 153 |
+
line: The line of the token in the text (starting with 1)
|
| 154 |
+
column: The column of the token in the text (starting with 1)
|
| 155 |
+
end_line: The line where the token ends
|
| 156 |
+
end_column: The next column after the end of the token. For example,
|
| 157 |
+
if the token is a single character with a column value of 4,
|
| 158 |
+
end_column will be 5.
|
| 159 |
+
end_pos: the index where the token ends (basically ``start_pos + len(token)``)
|
| 160 |
+
"""
|
| 161 |
+
__slots__ = ('type', 'start_pos', 'value', 'line', 'column', 'end_line', 'end_column', 'end_pos')
|
| 162 |
+
|
| 163 |
+
__match_args__ = ('type', 'value')
|
| 164 |
+
|
| 165 |
+
type: str
|
| 166 |
+
start_pos: Optional[int]
|
| 167 |
+
value: Any
|
| 168 |
+
line: Optional[int]
|
| 169 |
+
column: Optional[int]
|
| 170 |
+
end_line: Optional[int]
|
| 171 |
+
end_column: Optional[int]
|
| 172 |
+
end_pos: Optional[int]
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@overload
|
| 176 |
+
def __new__(
|
| 177 |
+
cls,
|
| 178 |
+
type: str,
|
| 179 |
+
value: Any,
|
| 180 |
+
start_pos: Optional[int] = None,
|
| 181 |
+
line: Optional[int] = None,
|
| 182 |
+
column: Optional[int] = None,
|
| 183 |
+
end_line: Optional[int] = None,
|
| 184 |
+
end_column: Optional[int] = None,
|
| 185 |
+
end_pos: Optional[int] = None
|
| 186 |
+
) -> 'Token':
|
| 187 |
+
...
|
| 188 |
+
|
| 189 |
+
@overload
|
| 190 |
+
def __new__(
|
| 191 |
+
cls,
|
| 192 |
+
type_: str,
|
| 193 |
+
value: Any,
|
| 194 |
+
start_pos: Optional[int] = None,
|
| 195 |
+
line: Optional[int] = None,
|
| 196 |
+
column: Optional[int] = None,
|
| 197 |
+
end_line: Optional[int] = None,
|
| 198 |
+
end_column: Optional[int] = None,
|
| 199 |
+
end_pos: Optional[int] = None
|
| 200 |
+
) -> 'Token': ...
|
| 201 |
+
|
| 202 |
+
def __new__(cls, *args, **kwargs):
|
| 203 |
+
if "type_" in kwargs:
|
| 204 |
+
warnings.warn("`type_` is deprecated use `type` instead", DeprecationWarning)
|
| 205 |
+
|
| 206 |
+
if "type" in kwargs:
|
| 207 |
+
raise TypeError("Error: using both 'type' and the deprecated 'type_' as arguments.")
|
| 208 |
+
kwargs["type"] = kwargs.pop("type_")
|
| 209 |
+
|
| 210 |
+
return cls._future_new(*args, **kwargs)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@classmethod
|
| 214 |
+
def _future_new(cls, type, value, start_pos=None, line=None, column=None, end_line=None, end_column=None, end_pos=None):
|
| 215 |
+
inst = super(Token, cls).__new__(cls, value)
|
| 216 |
+
|
| 217 |
+
inst.type = type
|
| 218 |
+
inst.start_pos = start_pos
|
| 219 |
+
inst.value = value
|
| 220 |
+
inst.line = line
|
| 221 |
+
inst.column = column
|
| 222 |
+
inst.end_line = end_line
|
| 223 |
+
inst.end_column = end_column
|
| 224 |
+
inst.end_pos = end_pos
|
| 225 |
+
return inst
|
| 226 |
+
|
| 227 |
+
@overload
|
| 228 |
+
def update(self, type: Optional[str] = None, value: Optional[Any] = None) -> 'Token':
|
| 229 |
+
...
|
| 230 |
+
|
| 231 |
+
@overload
|
| 232 |
+
def update(self, type_: Optional[str] = None, value: Optional[Any] = None) -> 'Token':
|
| 233 |
+
...
|
| 234 |
+
|
| 235 |
+
def update(self, *args, **kwargs):
|
| 236 |
+
if "type_" in kwargs:
|
| 237 |
+
warnings.warn("`type_` is deprecated use `type` instead", DeprecationWarning)
|
| 238 |
+
|
| 239 |
+
if "type" in kwargs:
|
| 240 |
+
raise TypeError("Error: using both 'type' and the deprecated 'type_' as arguments.")
|
| 241 |
+
kwargs["type"] = kwargs.pop("type_")
|
| 242 |
+
|
| 243 |
+
return self._future_update(*args, **kwargs)
|
| 244 |
+
|
| 245 |
+
def _future_update(self, type: Optional[str] = None, value: Optional[Any] = None) -> 'Token':
|
| 246 |
+
return Token.new_borrow_pos(
|
| 247 |
+
type if type is not None else self.type,
|
| 248 |
+
value if value is not None else self.value,
|
| 249 |
+
self
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
@classmethod
|
| 253 |
+
def new_borrow_pos(cls: Type[_T], type_: str, value: Any, borrow_t: 'Token') -> _T:
|
| 254 |
+
return cls(type_, value, borrow_t.start_pos, borrow_t.line, borrow_t.column, borrow_t.end_line, borrow_t.end_column, borrow_t.end_pos)
|
| 255 |
+
|
| 256 |
+
def __reduce__(self):
|
| 257 |
+
return (self.__class__, (self.type, self.value, self.start_pos, self.line, self.column))
|
| 258 |
+
|
| 259 |
+
def __repr__(self):
|
| 260 |
+
return 'Token(%r, %r)' % (self.type, self.value)
|
| 261 |
+
|
| 262 |
+
def __deepcopy__(self, memo):
|
| 263 |
+
return Token(self.type, self.value, self.start_pos, self.line, self.column)
|
| 264 |
+
|
| 265 |
+
def __eq__(self, other):
|
| 266 |
+
if isinstance(other, Token) and self.type != other.type:
|
| 267 |
+
return False
|
| 268 |
+
|
| 269 |
+
return str.__eq__(self, other)
|
| 270 |
+
|
| 271 |
+
__hash__ = str.__hash__
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class LineCounter:
|
| 275 |
+
"A utility class for keeping track of line & column information"
|
| 276 |
+
|
| 277 |
+
__slots__ = 'char_pos', 'line', 'column', 'line_start_pos', 'newline_char'
|
| 278 |
+
|
| 279 |
+
def __init__(self, newline_char):
|
| 280 |
+
self.newline_char = newline_char
|
| 281 |
+
self.char_pos = 0
|
| 282 |
+
self.line = 1
|
| 283 |
+
self.column = 1
|
| 284 |
+
self.line_start_pos = 0
|
| 285 |
+
|
| 286 |
+
def __eq__(self, other):
|
| 287 |
+
if not isinstance(other, LineCounter):
|
| 288 |
+
return NotImplemented
|
| 289 |
+
|
| 290 |
+
return self.char_pos == other.char_pos and self.newline_char == other.newline_char
|
| 291 |
+
|
| 292 |
+
def feed(self, token: Token, test_newline=True):
|
| 293 |
+
"""Consume a token and calculate the new line & column.
|
| 294 |
+
|
| 295 |
+
As an optional optimization, set test_newline=False if token doesn't contain a newline.
|
| 296 |
+
"""
|
| 297 |
+
if test_newline:
|
| 298 |
+
newlines = token.count(self.newline_char)
|
| 299 |
+
if newlines:
|
| 300 |
+
self.line += newlines
|
| 301 |
+
self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1
|
| 302 |
+
|
| 303 |
+
self.char_pos += len(token)
|
| 304 |
+
self.column = self.char_pos - self.line_start_pos + 1
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class UnlessCallback:
|
| 308 |
+
def __init__(self, scanner):
|
| 309 |
+
self.scanner = scanner
|
| 310 |
+
|
| 311 |
+
def __call__(self, t):
|
| 312 |
+
res = self.scanner.match(t.value, 0)
|
| 313 |
+
if res:
|
| 314 |
+
_value, t.type = res
|
| 315 |
+
return t
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class CallChain:
|
| 319 |
+
def __init__(self, callback1, callback2, cond):
|
| 320 |
+
self.callback1 = callback1
|
| 321 |
+
self.callback2 = callback2
|
| 322 |
+
self.cond = cond
|
| 323 |
+
|
| 324 |
+
def __call__(self, t):
|
| 325 |
+
t2 = self.callback1(t)
|
| 326 |
+
return self.callback2(t) if self.cond(t2) else t2
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _get_match(re_, regexp, s, flags):
|
| 330 |
+
m = re_.match(regexp, s, flags)
|
| 331 |
+
if m:
|
| 332 |
+
return m.group(0)
|
| 333 |
+
|
| 334 |
+
def _create_unless(terminals, g_regex_flags, re_, use_bytes):
|
| 335 |
+
tokens_by_type = classify(terminals, lambda t: type(t.pattern))
|
| 336 |
+
assert len(tokens_by_type) <= 2, tokens_by_type.keys()
|
| 337 |
+
embedded_strs = set()
|
| 338 |
+
callback = {}
|
| 339 |
+
for retok in tokens_by_type.get(PatternRE, []):
|
| 340 |
+
unless = []
|
| 341 |
+
for strtok in tokens_by_type.get(PatternStr, []):
|
| 342 |
+
if strtok.priority != retok.priority:
|
| 343 |
+
continue
|
| 344 |
+
s = strtok.pattern.value
|
| 345 |
+
if s == _get_match(re_, retok.pattern.to_regexp(), s, g_regex_flags):
|
| 346 |
+
unless.append(strtok)
|
| 347 |
+
if strtok.pattern.flags <= retok.pattern.flags:
|
| 348 |
+
embedded_strs.add(strtok)
|
| 349 |
+
if unless:
|
| 350 |
+
callback[retok.name] = UnlessCallback(Scanner(unless, g_regex_flags, re_, match_whole=True, use_bytes=use_bytes))
|
| 351 |
+
|
| 352 |
+
new_terminals = [t for t in terminals if t not in embedded_strs]
|
| 353 |
+
return new_terminals, callback
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class Scanner:
|
| 357 |
+
def __init__(self, terminals, g_regex_flags, re_, use_bytes, match_whole=False):
|
| 358 |
+
self.terminals = terminals
|
| 359 |
+
self.g_regex_flags = g_regex_flags
|
| 360 |
+
self.re_ = re_
|
| 361 |
+
self.use_bytes = use_bytes
|
| 362 |
+
self.match_whole = match_whole
|
| 363 |
+
|
| 364 |
+
self.allowed_types = {t.name for t in self.terminals}
|
| 365 |
+
|
| 366 |
+
self._mres = self._build_mres(terminals, len(terminals))
|
| 367 |
+
|
| 368 |
+
def _build_mres(self, terminals, max_size):
|
| 369 |
+
# Python sets an unreasonable group limit (currently 100) in its re module
|
| 370 |
+
# Worse, the only way to know we reached it is by catching an AssertionError!
|
| 371 |
+
# This function recursively tries less and less groups until it's successful.
|
| 372 |
+
postfix = '$' if self.match_whole else ''
|
| 373 |
+
mres = []
|
| 374 |
+
while terminals:
|
| 375 |
+
pattern = u'|'.join(u'(?P<%s>%s)' % (t.name, t.pattern.to_regexp() + postfix) for t in terminals[:max_size])
|
| 376 |
+
if self.use_bytes:
|
| 377 |
+
pattern = pattern.encode('latin-1')
|
| 378 |
+
try:
|
| 379 |
+
mre = self.re_.compile(pattern, self.g_regex_flags)
|
| 380 |
+
except AssertionError: # Yes, this is what Python provides us.. :/
|
| 381 |
+
return self._build_mres(terminals, max_size // 2)
|
| 382 |
+
|
| 383 |
+
mres.append(mre)
|
| 384 |
+
terminals = terminals[max_size:]
|
| 385 |
+
return mres
|
| 386 |
+
|
| 387 |
+
def match(self, text, pos):
|
| 388 |
+
for mre in self._mres:
|
| 389 |
+
m = mre.match(text, pos)
|
| 390 |
+
if m:
|
| 391 |
+
return m.group(0), m.lastgroup
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _regexp_has_newline(r: str):
|
| 395 |
+
r"""Expressions that may indicate newlines in a regexp:
|
| 396 |
+
- newlines (\n)
|
| 397 |
+
- escaped newline (\\n)
|
| 398 |
+
- anything but ([^...])
|
| 399 |
+
- any-char (.) when the flag (?s) exists
|
| 400 |
+
- spaces (\s)
|
| 401 |
+
"""
|
| 402 |
+
return '\n' in r or '\\n' in r or '\\s' in r or '[^' in r or ('(?s' in r and '.' in r)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class LexerState:
|
| 406 |
+
"""Represents the current state of the lexer as it scans the text
|
| 407 |
+
(Lexer objects are only instantiated per grammar, not per text)
|
| 408 |
+
"""
|
| 409 |
+
|
| 410 |
+
__slots__ = 'text', 'line_ctr', 'last_token'
|
| 411 |
+
|
| 412 |
+
text: str
|
| 413 |
+
line_ctr: LineCounter
|
| 414 |
+
last_token: Optional[Token]
|
| 415 |
+
|
| 416 |
+
def __init__(self, text: str, line_ctr: Optional[LineCounter]=None, last_token: Optional[Token]=None):
|
| 417 |
+
self.text = text
|
| 418 |
+
self.line_ctr = line_ctr or LineCounter(b'\n' if isinstance(text, bytes) else '\n')
|
| 419 |
+
self.last_token = last_token
|
| 420 |
+
|
| 421 |
+
def __eq__(self, other):
|
| 422 |
+
if not isinstance(other, LexerState):
|
| 423 |
+
return NotImplemented
|
| 424 |
+
|
| 425 |
+
return self.text is other.text and self.line_ctr == other.line_ctr and self.last_token == other.last_token
|
| 426 |
+
|
| 427 |
+
def __copy__(self):
|
| 428 |
+
return type(self)(self.text, copy(self.line_ctr), self.last_token)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class LexerThread:
|
| 432 |
+
"""A thread that ties a lexer instance and a lexer state, to be used by the parser
|
| 433 |
+
"""
|
| 434 |
+
|
| 435 |
+
def __init__(self, lexer: 'Lexer', lexer_state: LexerState):
|
| 436 |
+
self.lexer = lexer
|
| 437 |
+
self.state = lexer_state
|
| 438 |
+
|
| 439 |
+
@classmethod
|
| 440 |
+
def from_text(cls, lexer: 'Lexer', text: str) -> 'LexerThread':
|
| 441 |
+
return cls(lexer, LexerState(text))
|
| 442 |
+
|
| 443 |
+
def lex(self, parser_state):
|
| 444 |
+
return self.lexer.lex(self.state, parser_state)
|
| 445 |
+
|
| 446 |
+
def __copy__(self):
|
| 447 |
+
return type(self)(self.lexer, copy(self.state))
|
| 448 |
+
|
| 449 |
+
_Token = Token
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
_Callback = Callable[[Token], Token]
|
| 453 |
+
|
| 454 |
+
class Lexer(ABC):
|
| 455 |
+
"""Lexer interface
|
| 456 |
+
|
| 457 |
+
Method Signatures:
|
| 458 |
+
lex(self, lexer_state, parser_state) -> Iterator[Token]
|
| 459 |
+
"""
|
| 460 |
+
@abstractmethod
|
| 461 |
+
def lex(self, lexer_state: LexerState, parser_state: Any) -> Iterator[Token]:
|
| 462 |
+
return NotImplemented
|
| 463 |
+
|
| 464 |
+
def make_lexer_state(self, text):
|
| 465 |
+
"Deprecated"
|
| 466 |
+
return LexerState(text)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _check_regex_collisions(terminal_to_regexp: Dict[TerminalDef, str], comparator, strict_mode, max_collisions_to_show=8):
|
| 470 |
+
if not comparator:
|
| 471 |
+
comparator = interegular.Comparator.from_regexes(terminal_to_regexp)
|
| 472 |
+
|
| 473 |
+
# When in strict mode, we only ever try to provide one example, so taking
|
| 474 |
+
# a long time for that should be fine
|
| 475 |
+
max_time = 2 if strict_mode else 0.2
|
| 476 |
+
|
| 477 |
+
# We don't want to show too many collisions.
|
| 478 |
+
if comparator.count_marked_pairs() >= max_collisions_to_show:
|
| 479 |
+
return
|
| 480 |
+
for group in classify(terminal_to_regexp, lambda t: t.priority).values():
|
| 481 |
+
for a, b in comparator.check(group, skip_marked=True):
|
| 482 |
+
assert a.priority == b.priority
|
| 483 |
+
# Mark this pair to not repeat warnings when multiple different BasicLexers see the same collision
|
| 484 |
+
comparator.mark(a, b)
|
| 485 |
+
|
| 486 |
+
# Notify the user
|
| 487 |
+
message = f"Collision between Terminals {a.name} and {b.name}. "
|
| 488 |
+
try:
|
| 489 |
+
example = comparator.get_example_overlap(a, b, max_time).format_multiline()
|
| 490 |
+
except ValueError:
|
| 491 |
+
# Couldn't find an example within max_time steps.
|
| 492 |
+
example = "No example could be found fast enough. However, the collision does still exists"
|
| 493 |
+
if strict_mode:
|
| 494 |
+
raise LexError(f"{message}\n{example}")
|
| 495 |
+
logger.warning("%s The lexer will choose between them arbitrarily.\n%s", message, example)
|
| 496 |
+
if comparator.count_marked_pairs() >= max_collisions_to_show:
|
| 497 |
+
logger.warning("Found 8 regex collisions, will not check for more.")
|
| 498 |
+
return
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
class AbstractBasicLexer(Lexer):
|
| 502 |
+
terminals_by_name: Dict[str, TerminalDef]
|
| 503 |
+
|
| 504 |
+
@abstractmethod
|
| 505 |
+
def __init__(self, conf: 'LexerConf', comparator=None) -> None:
|
| 506 |
+
...
|
| 507 |
+
|
| 508 |
+
@abstractmethod
|
| 509 |
+
def next_token(self, lex_state: LexerState, parser_state: Any = None) -> Token:
|
| 510 |
+
...
|
| 511 |
+
|
| 512 |
+
def lex(self, state: LexerState, parser_state: Any) -> Iterator[Token]:
|
| 513 |
+
with suppress(EOFError):
|
| 514 |
+
while True:
|
| 515 |
+
yield self.next_token(state, parser_state)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
class BasicLexer(AbstractBasicLexer):
|
| 519 |
+
terminals: Collection[TerminalDef]
|
| 520 |
+
ignore_types: FrozenSet[str]
|
| 521 |
+
newline_types: FrozenSet[str]
|
| 522 |
+
user_callbacks: Dict[str, _Callback]
|
| 523 |
+
callback: Dict[str, _Callback]
|
| 524 |
+
re: ModuleType
|
| 525 |
+
|
| 526 |
+
def __init__(self, conf: 'LexerConf', comparator=None) -> None:
|
| 527 |
+
terminals = list(conf.terminals)
|
| 528 |
+
assert all(isinstance(t, TerminalDef) for t in terminals), terminals
|
| 529 |
+
|
| 530 |
+
self.re = conf.re_module
|
| 531 |
+
|
| 532 |
+
if not conf.skip_validation:
|
| 533 |
+
# Sanitization
|
| 534 |
+
terminal_to_regexp = {}
|
| 535 |
+
for t in terminals:
|
| 536 |
+
regexp = t.pattern.to_regexp()
|
| 537 |
+
try:
|
| 538 |
+
self.re.compile(regexp, conf.g_regex_flags)
|
| 539 |
+
except self.re.error:
|
| 540 |
+
raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
|
| 541 |
+
|
| 542 |
+
if t.pattern.min_width == 0:
|
| 543 |
+
raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))
|
| 544 |
+
if t.pattern.type == "re":
|
| 545 |
+
terminal_to_regexp[t] = regexp
|
| 546 |
+
|
| 547 |
+
if not (set(conf.ignore) <= {t.name for t in terminals}):
|
| 548 |
+
raise LexError("Ignore terminals are not defined: %s" % (set(conf.ignore) - {t.name for t in terminals}))
|
| 549 |
+
|
| 550 |
+
if has_interegular:
|
| 551 |
+
_check_regex_collisions(terminal_to_regexp, comparator, conf.strict)
|
| 552 |
+
elif conf.strict:
|
| 553 |
+
raise LexError("interegular must be installed for strict mode. Use `pip install 'lark[interegular]'`.")
|
| 554 |
+
|
| 555 |
+
# Init
|
| 556 |
+
self.newline_types = frozenset(t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp()))
|
| 557 |
+
self.ignore_types = frozenset(conf.ignore)
|
| 558 |
+
|
| 559 |
+
terminals.sort(key=lambda x: (-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
|
| 560 |
+
self.terminals = terminals
|
| 561 |
+
self.user_callbacks = conf.callbacks
|
| 562 |
+
self.g_regex_flags = conf.g_regex_flags
|
| 563 |
+
self.use_bytes = conf.use_bytes
|
| 564 |
+
self.terminals_by_name = conf.terminals_by_name
|
| 565 |
+
|
| 566 |
+
self._scanner = None
|
| 567 |
+
|
| 568 |
+
def _build_scanner(self):
|
| 569 |
+
terminals, self.callback = _create_unless(self.terminals, self.g_regex_flags, self.re, self.use_bytes)
|
| 570 |
+
assert all(self.callback.values())
|
| 571 |
+
|
| 572 |
+
for type_, f in self.user_callbacks.items():
|
| 573 |
+
if type_ in self.callback:
|
| 574 |
+
# Already a callback there, probably UnlessCallback
|
| 575 |
+
self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_)
|
| 576 |
+
else:
|
| 577 |
+
self.callback[type_] = f
|
| 578 |
+
|
| 579 |
+
self._scanner = Scanner(terminals, self.g_regex_flags, self.re, self.use_bytes)
|
| 580 |
+
|
| 581 |
+
@property
|
| 582 |
+
def scanner(self):
|
| 583 |
+
if self._scanner is None:
|
| 584 |
+
self._build_scanner()
|
| 585 |
+
return self._scanner
|
| 586 |
+
|
| 587 |
+
def match(self, text, pos):
|
| 588 |
+
return self.scanner.match(text, pos)
|
| 589 |
+
|
| 590 |
+
def next_token(self, lex_state: LexerState, parser_state: Any = None) -> Token:
|
| 591 |
+
line_ctr = lex_state.line_ctr
|
| 592 |
+
while line_ctr.char_pos < len(lex_state.text):
|
| 593 |
+
res = self.match(lex_state.text, line_ctr.char_pos)
|
| 594 |
+
if not res:
|
| 595 |
+
allowed = self.scanner.allowed_types - self.ignore_types
|
| 596 |
+
if not allowed:
|
| 597 |
+
allowed = {"<END-OF-FILE>"}
|
| 598 |
+
raise UnexpectedCharacters(lex_state.text, line_ctr.char_pos, line_ctr.line, line_ctr.column,
|
| 599 |
+
allowed=allowed, token_history=lex_state.last_token and [lex_state.last_token],
|
| 600 |
+
state=parser_state, terminals_by_name=self.terminals_by_name)
|
| 601 |
+
|
| 602 |
+
value, type_ = res
|
| 603 |
+
|
| 604 |
+
ignored = type_ in self.ignore_types
|
| 605 |
+
t = None
|
| 606 |
+
if not ignored or type_ in self.callback:
|
| 607 |
+
t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
|
| 608 |
+
line_ctr.feed(value, type_ in self.newline_types)
|
| 609 |
+
if t is not None:
|
| 610 |
+
t.end_line = line_ctr.line
|
| 611 |
+
t.end_column = line_ctr.column
|
| 612 |
+
t.end_pos = line_ctr.char_pos
|
| 613 |
+
if t.type in self.callback:
|
| 614 |
+
t = self.callback[t.type](t)
|
| 615 |
+
if not ignored:
|
| 616 |
+
if not isinstance(t, Token):
|
| 617 |
+
raise LexError("Callbacks must return a token (returned %r)" % t)
|
| 618 |
+
lex_state.last_token = t
|
| 619 |
+
return t
|
| 620 |
+
|
| 621 |
+
# EOF
|
| 622 |
+
raise EOFError(self)
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
class ContextualLexer(Lexer):
|
| 626 |
+
lexers: Dict[int, AbstractBasicLexer]
|
| 627 |
+
root_lexer: AbstractBasicLexer
|
| 628 |
+
|
| 629 |
+
BasicLexer: Type[AbstractBasicLexer] = BasicLexer
|
| 630 |
+
|
| 631 |
+
def __init__(self, conf: 'LexerConf', states: Dict[int, Collection[str]], always_accept: Collection[str]=()) -> None:
|
| 632 |
+
terminals = list(conf.terminals)
|
| 633 |
+
terminals_by_name = conf.terminals_by_name
|
| 634 |
+
|
| 635 |
+
trad_conf = copy(conf)
|
| 636 |
+
trad_conf.terminals = terminals
|
| 637 |
+
|
| 638 |
+
if has_interegular and not conf.skip_validation:
|
| 639 |
+
comparator = interegular.Comparator.from_regexes({t: t.pattern.to_regexp() for t in terminals})
|
| 640 |
+
else:
|
| 641 |
+
comparator = None
|
| 642 |
+
lexer_by_tokens: Dict[FrozenSet[str], AbstractBasicLexer] = {}
|
| 643 |
+
self.lexers = {}
|
| 644 |
+
for state, accepts in states.items():
|
| 645 |
+
key = frozenset(accepts)
|
| 646 |
+
try:
|
| 647 |
+
lexer = lexer_by_tokens[key]
|
| 648 |
+
except KeyError:
|
| 649 |
+
accepts = set(accepts) | set(conf.ignore) | set(always_accept)
|
| 650 |
+
lexer_conf = copy(trad_conf)
|
| 651 |
+
lexer_conf.terminals = [terminals_by_name[n] for n in accepts if n in terminals_by_name]
|
| 652 |
+
lexer = self.BasicLexer(lexer_conf, comparator)
|
| 653 |
+
lexer_by_tokens[key] = lexer
|
| 654 |
+
|
| 655 |
+
self.lexers[state] = lexer
|
| 656 |
+
|
| 657 |
+
assert trad_conf.terminals is terminals
|
| 658 |
+
trad_conf.skip_validation = True # We don't need to verify all terminals again
|
| 659 |
+
self.root_lexer = self.BasicLexer(trad_conf, comparator)
|
| 660 |
+
|
| 661 |
+
def lex(self, lexer_state: LexerState, parser_state: 'ParserState') -> Iterator[Token]:
|
| 662 |
+
try:
|
| 663 |
+
while True:
|
| 664 |
+
lexer = self.lexers[parser_state.position]
|
| 665 |
+
yield lexer.next_token(lexer_state, parser_state)
|
| 666 |
+
except EOFError:
|
| 667 |
+
pass
|
| 668 |
+
except UnexpectedCharacters as e:
|
| 669 |
+
# In the contextual lexer, UnexpectedCharacters can mean that the terminal is defined, but not in the current context.
|
| 670 |
+
# This tests the input against the global context, to provide a nicer error.
|
| 671 |
+
try:
|
| 672 |
+
last_token = lexer_state.last_token # Save last_token. Calling root_lexer.next_token will change this to the wrong token
|
| 673 |
+
token = self.root_lexer.next_token(lexer_state, parser_state)
|
| 674 |
+
raise UnexpectedToken(token, e.allowed, state=parser_state, token_history=[last_token], terminals_by_name=self.root_lexer.terminals_by_name)
|
| 675 |
+
except UnexpectedCharacters:
|
| 676 |
+
raise e # Raise the original UnexpectedCharacters. The root lexer raises it with the wrong expected set.
|
| 677 |
+
|
| 678 |
+
###}
|
vllm/lib/python3.10/site-packages/lark/load_grammar.py
ADDED
|
@@ -0,0 +1,1428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 4 |
+
import hashlib
|
| 5 |
+
import os.path
|
| 6 |
+
import sys
|
| 7 |
+
from collections import namedtuple
|
| 8 |
+
from copy import copy, deepcopy
|
| 9 |
+
import pkgutil
|
| 10 |
+
from ast import literal_eval
|
| 11 |
+
from contextlib import suppress
|
| 12 |
+
from typing import List, Tuple, Union, Callable, Dict, Optional, Sequence, Generator
|
| 13 |
+
|
| 14 |
+
from .utils import bfs, logger, classify_bool, is_id_continue, is_id_start, bfs_all_unique, small_factors, OrderedSet
|
| 15 |
+
from .lexer import Token, TerminalDef, PatternStr, PatternRE, Pattern
|
| 16 |
+
|
| 17 |
+
from .parse_tree_builder import ParseTreeBuilder
|
| 18 |
+
from .parser_frontends import ParsingFrontend
|
| 19 |
+
from .common import LexerConf, ParserConf
|
| 20 |
+
from .grammar import RuleOptions, Rule, Terminal, NonTerminal, Symbol, TOKEN_DEFAULT_PRIORITY
|
| 21 |
+
from .utils import classify, dedup_list
|
| 22 |
+
from .exceptions import GrammarError, UnexpectedCharacters, UnexpectedToken, ParseError, UnexpectedInput
|
| 23 |
+
|
| 24 |
+
from .tree import Tree, SlottedTree as ST
|
| 25 |
+
from .visitors import Transformer, Visitor, v_args, Transformer_InPlace, Transformer_NonRecursive
|
| 26 |
+
inline_args = v_args(inline=True)
|
| 27 |
+
|
| 28 |
+
IMPORT_PATHS = ['grammars']
|
| 29 |
+
|
| 30 |
+
EXT = '.lark'
|
| 31 |
+
|
| 32 |
+
_RE_FLAGS = 'imslux'
|
| 33 |
+
|
| 34 |
+
_EMPTY = Symbol('__empty__')
|
| 35 |
+
|
| 36 |
+
_TERMINAL_NAMES = {
|
| 37 |
+
'.' : 'DOT',
|
| 38 |
+
',' : 'COMMA',
|
| 39 |
+
':' : 'COLON',
|
| 40 |
+
';' : 'SEMICOLON',
|
| 41 |
+
'+' : 'PLUS',
|
| 42 |
+
'-' : 'MINUS',
|
| 43 |
+
'*' : 'STAR',
|
| 44 |
+
'/' : 'SLASH',
|
| 45 |
+
'\\' : 'BACKSLASH',
|
| 46 |
+
'|' : 'VBAR',
|
| 47 |
+
'?' : 'QMARK',
|
| 48 |
+
'!' : 'BANG',
|
| 49 |
+
'@' : 'AT',
|
| 50 |
+
'#' : 'HASH',
|
| 51 |
+
'$' : 'DOLLAR',
|
| 52 |
+
'%' : 'PERCENT',
|
| 53 |
+
'^' : 'CIRCUMFLEX',
|
| 54 |
+
'&' : 'AMPERSAND',
|
| 55 |
+
'_' : 'UNDERSCORE',
|
| 56 |
+
'<' : 'LESSTHAN',
|
| 57 |
+
'>' : 'MORETHAN',
|
| 58 |
+
'=' : 'EQUAL',
|
| 59 |
+
'"' : 'DBLQUOTE',
|
| 60 |
+
'\'' : 'QUOTE',
|
| 61 |
+
'`' : 'BACKQUOTE',
|
| 62 |
+
'~' : 'TILDE',
|
| 63 |
+
'(' : 'LPAR',
|
| 64 |
+
')' : 'RPAR',
|
| 65 |
+
'{' : 'LBRACE',
|
| 66 |
+
'}' : 'RBRACE',
|
| 67 |
+
'[' : 'LSQB',
|
| 68 |
+
']' : 'RSQB',
|
| 69 |
+
'\n' : 'NEWLINE',
|
| 70 |
+
'\r\n' : 'CRLF',
|
| 71 |
+
'\t' : 'TAB',
|
| 72 |
+
' ' : 'SPACE',
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
# Grammar Parser
|
| 76 |
+
TERMINALS = {
|
| 77 |
+
'_LPAR': r'\(',
|
| 78 |
+
'_RPAR': r'\)',
|
| 79 |
+
'_LBRA': r'\[',
|
| 80 |
+
'_RBRA': r'\]',
|
| 81 |
+
'_LBRACE': r'\{',
|
| 82 |
+
'_RBRACE': r'\}',
|
| 83 |
+
'OP': '[+*]|[?](?![a-z_])',
|
| 84 |
+
'_COLON': ':',
|
| 85 |
+
'_COMMA': ',',
|
| 86 |
+
'_OR': r'\|',
|
| 87 |
+
'_DOT': r'\.(?!\.)',
|
| 88 |
+
'_DOTDOT': r'\.\.',
|
| 89 |
+
'TILDE': '~',
|
| 90 |
+
'RULE_MODIFIERS': '(!|![?]?|[?]!?)(?=[_a-z])',
|
| 91 |
+
'RULE': '_?[a-z][_a-z0-9]*',
|
| 92 |
+
'TERMINAL': '_?[A-Z][_A-Z0-9]*',
|
| 93 |
+
'STRING': r'"(\\"|\\\\|[^"\n])*?"i?',
|
| 94 |
+
'REGEXP': r'/(?!/)(\\/|\\\\|[^/])*?/[%s]*' % _RE_FLAGS,
|
| 95 |
+
'_NL': r'(\r?\n)+\s*',
|
| 96 |
+
'_NL_OR': r'(\r?\n)+\s*\|',
|
| 97 |
+
'WS': r'[ \t]+',
|
| 98 |
+
'COMMENT': r'\s*//[^\n]*|\s*#[^\n]*',
|
| 99 |
+
'BACKSLASH': r'\\[ ]*\n',
|
| 100 |
+
'_TO': '->',
|
| 101 |
+
'_IGNORE': r'%ignore',
|
| 102 |
+
'_OVERRIDE': r'%override',
|
| 103 |
+
'_DECLARE': r'%declare',
|
| 104 |
+
'_EXTEND': r'%extend',
|
| 105 |
+
'_IMPORT': r'%import',
|
| 106 |
+
'NUMBER': r'[+-]?\d+',
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
RULES = {
|
| 110 |
+
'start': ['_list'],
|
| 111 |
+
'_list': ['_item', '_list _item'],
|
| 112 |
+
'_item': ['rule', 'term', 'ignore', 'import', 'declare', 'override', 'extend', '_NL'],
|
| 113 |
+
|
| 114 |
+
'rule': ['rule_modifiers RULE template_params priority _COLON expansions _NL'],
|
| 115 |
+
'rule_modifiers': ['RULE_MODIFIERS',
|
| 116 |
+
''],
|
| 117 |
+
'priority': ['_DOT NUMBER',
|
| 118 |
+
''],
|
| 119 |
+
'template_params': ['_LBRACE _template_params _RBRACE',
|
| 120 |
+
''],
|
| 121 |
+
'_template_params': ['RULE',
|
| 122 |
+
'_template_params _COMMA RULE'],
|
| 123 |
+
'expansions': ['_expansions'],
|
| 124 |
+
'_expansions': ['alias',
|
| 125 |
+
'_expansions _OR alias',
|
| 126 |
+
'_expansions _NL_OR alias'],
|
| 127 |
+
|
| 128 |
+
'?alias': ['expansion _TO nonterminal', 'expansion'],
|
| 129 |
+
'expansion': ['_expansion'],
|
| 130 |
+
|
| 131 |
+
'_expansion': ['', '_expansion expr'],
|
| 132 |
+
|
| 133 |
+
'?expr': ['atom',
|
| 134 |
+
'atom OP',
|
| 135 |
+
'atom TILDE NUMBER',
|
| 136 |
+
'atom TILDE NUMBER _DOTDOT NUMBER',
|
| 137 |
+
],
|
| 138 |
+
|
| 139 |
+
'?atom': ['_LPAR expansions _RPAR',
|
| 140 |
+
'maybe',
|
| 141 |
+
'value'],
|
| 142 |
+
|
| 143 |
+
'value': ['terminal',
|
| 144 |
+
'nonterminal',
|
| 145 |
+
'literal',
|
| 146 |
+
'range',
|
| 147 |
+
'template_usage'],
|
| 148 |
+
|
| 149 |
+
'terminal': ['TERMINAL'],
|
| 150 |
+
'nonterminal': ['RULE'],
|
| 151 |
+
|
| 152 |
+
'?name': ['RULE', 'TERMINAL'],
|
| 153 |
+
'?symbol': ['terminal', 'nonterminal'],
|
| 154 |
+
|
| 155 |
+
'maybe': ['_LBRA expansions _RBRA'],
|
| 156 |
+
'range': ['STRING _DOTDOT STRING'],
|
| 157 |
+
|
| 158 |
+
'template_usage': ['nonterminal _LBRACE _template_args _RBRACE'],
|
| 159 |
+
'_template_args': ['value',
|
| 160 |
+
'_template_args _COMMA value'],
|
| 161 |
+
|
| 162 |
+
'term': ['TERMINAL _COLON expansions _NL',
|
| 163 |
+
'TERMINAL _DOT NUMBER _COLON expansions _NL'],
|
| 164 |
+
'override': ['_OVERRIDE rule',
|
| 165 |
+
'_OVERRIDE term'],
|
| 166 |
+
'extend': ['_EXTEND rule',
|
| 167 |
+
'_EXTEND term'],
|
| 168 |
+
'ignore': ['_IGNORE expansions _NL'],
|
| 169 |
+
'declare': ['_DECLARE _declare_args _NL'],
|
| 170 |
+
'import': ['_IMPORT _import_path _NL',
|
| 171 |
+
'_IMPORT _import_path _LPAR name_list _RPAR _NL',
|
| 172 |
+
'_IMPORT _import_path _TO name _NL'],
|
| 173 |
+
|
| 174 |
+
'_import_path': ['import_lib', 'import_rel'],
|
| 175 |
+
'import_lib': ['_import_args'],
|
| 176 |
+
'import_rel': ['_DOT _import_args'],
|
| 177 |
+
'_import_args': ['name', '_import_args _DOT name'],
|
| 178 |
+
|
| 179 |
+
'name_list': ['_name_list'],
|
| 180 |
+
'_name_list': ['name', '_name_list _COMMA name'],
|
| 181 |
+
|
| 182 |
+
'_declare_args': ['symbol', '_declare_args symbol'],
|
| 183 |
+
'literal': ['REGEXP', 'STRING'],
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# Value 5 keeps the number of states in the lalr parser somewhat minimal
|
| 188 |
+
# It isn't optimal, but close to it. See PR #949
|
| 189 |
+
SMALL_FACTOR_THRESHOLD = 5
|
| 190 |
+
# The Threshold whether repeat via ~ are split up into different rules
|
| 191 |
+
# 50 is chosen since it keeps the number of states low and therefore lalr analysis time low,
|
| 192 |
+
# while not being to overaggressive and unnecessarily creating rules that might create shift/reduce conflicts.
|
| 193 |
+
# (See PR #949)
|
| 194 |
+
REPEAT_BREAK_THRESHOLD = 50
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class FindRuleSize(Transformer):
|
| 198 |
+
def __init__(self, keep_all_tokens: bool):
|
| 199 |
+
self.keep_all_tokens = keep_all_tokens
|
| 200 |
+
|
| 201 |
+
def _will_not_get_removed(self, sym: Symbol) -> bool:
|
| 202 |
+
if isinstance(sym, NonTerminal):
|
| 203 |
+
return not sym.name.startswith('_')
|
| 204 |
+
if isinstance(sym, Terminal):
|
| 205 |
+
return self.keep_all_tokens or not sym.filter_out
|
| 206 |
+
if sym is _EMPTY:
|
| 207 |
+
return False
|
| 208 |
+
assert False, sym
|
| 209 |
+
|
| 210 |
+
def _args_as_int(self, args: List[Union[int, Symbol]]) -> Generator[int, None, None]:
|
| 211 |
+
for a in args:
|
| 212 |
+
if isinstance(a, int):
|
| 213 |
+
yield a
|
| 214 |
+
elif isinstance(a, Symbol):
|
| 215 |
+
yield 1 if self._will_not_get_removed(a) else 0
|
| 216 |
+
else:
|
| 217 |
+
assert False
|
| 218 |
+
|
| 219 |
+
def expansion(self, args) -> int:
|
| 220 |
+
return sum(self._args_as_int(args))
|
| 221 |
+
|
| 222 |
+
def expansions(self, args) -> int:
|
| 223 |
+
return max(self._args_as_int(args))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@inline_args
|
| 227 |
+
class EBNF_to_BNF(Transformer_InPlace):
|
| 228 |
+
def __init__(self):
|
| 229 |
+
self.new_rules = []
|
| 230 |
+
self.rules_cache = {}
|
| 231 |
+
self.prefix = 'anon'
|
| 232 |
+
self.i = 0
|
| 233 |
+
self.rule_options = None
|
| 234 |
+
|
| 235 |
+
def _name_rule(self, inner: str):
|
| 236 |
+
new_name = '__%s_%s_%d' % (self.prefix, inner, self.i)
|
| 237 |
+
self.i += 1
|
| 238 |
+
return new_name
|
| 239 |
+
|
| 240 |
+
def _add_rule(self, key, name, expansions):
|
| 241 |
+
t = NonTerminal(name)
|
| 242 |
+
self.new_rules.append((name, expansions, self.rule_options))
|
| 243 |
+
self.rules_cache[key] = t
|
| 244 |
+
return t
|
| 245 |
+
|
| 246 |
+
def _add_recurse_rule(self, type_: str, expr: Tree):
|
| 247 |
+
try:
|
| 248 |
+
return self.rules_cache[expr]
|
| 249 |
+
except KeyError:
|
| 250 |
+
new_name = self._name_rule(type_)
|
| 251 |
+
t = NonTerminal(new_name)
|
| 252 |
+
tree = ST('expansions', [
|
| 253 |
+
ST('expansion', [expr]),
|
| 254 |
+
ST('expansion', [t, expr])
|
| 255 |
+
])
|
| 256 |
+
return self._add_rule(expr, new_name, tree)
|
| 257 |
+
|
| 258 |
+
def _add_repeat_rule(self, a, b, target, atom):
|
| 259 |
+
"""Generate a rule that repeats target ``a`` times, and repeats atom ``b`` times.
|
| 260 |
+
|
| 261 |
+
When called recursively (into target), it repeats atom for x(n) times, where:
|
| 262 |
+
x(0) = 1
|
| 263 |
+
x(n) = a(n) * x(n-1) + b
|
| 264 |
+
|
| 265 |
+
Example rule when a=3, b=4:
|
| 266 |
+
|
| 267 |
+
new_rule: target target target atom atom atom atom
|
| 268 |
+
|
| 269 |
+
"""
|
| 270 |
+
key = (a, b, target, atom)
|
| 271 |
+
try:
|
| 272 |
+
return self.rules_cache[key]
|
| 273 |
+
except KeyError:
|
| 274 |
+
new_name = self._name_rule('repeat_a%d_b%d' % (a, b))
|
| 275 |
+
tree = ST('expansions', [ST('expansion', [target] * a + [atom] * b)])
|
| 276 |
+
return self._add_rule(key, new_name, tree)
|
| 277 |
+
|
| 278 |
+
def _add_repeat_opt_rule(self, a, b, target, target_opt, atom):
|
| 279 |
+
"""Creates a rule that matches atom 0 to (a*n+b)-1 times.
|
| 280 |
+
|
| 281 |
+
When target matches n times atom, and target_opt 0 to n-1 times target_opt,
|
| 282 |
+
|
| 283 |
+
First we generate target * i followed by target_opt, for i from 0 to a-1
|
| 284 |
+
These match 0 to n*a - 1 times atom
|
| 285 |
+
|
| 286 |
+
Then we generate target * a followed by atom * i, for i from 0 to b-1
|
| 287 |
+
These match n*a to n*a + b-1 times atom
|
| 288 |
+
|
| 289 |
+
The created rule will not have any shift/reduce conflicts so that it can be used with lalr
|
| 290 |
+
|
| 291 |
+
Example rule when a=3, b=4:
|
| 292 |
+
|
| 293 |
+
new_rule: target_opt
|
| 294 |
+
| target target_opt
|
| 295 |
+
| target target target_opt
|
| 296 |
+
|
| 297 |
+
| target target target
|
| 298 |
+
| target target target atom
|
| 299 |
+
| target target target atom atom
|
| 300 |
+
| target target target atom atom atom
|
| 301 |
+
|
| 302 |
+
"""
|
| 303 |
+
key = (a, b, target, atom, "opt")
|
| 304 |
+
try:
|
| 305 |
+
return self.rules_cache[key]
|
| 306 |
+
except KeyError:
|
| 307 |
+
new_name = self._name_rule('repeat_a%d_b%d_opt' % (a, b))
|
| 308 |
+
tree = ST('expansions', [
|
| 309 |
+
ST('expansion', [target]*i + [target_opt]) for i in range(a)
|
| 310 |
+
] + [
|
| 311 |
+
ST('expansion', [target]*a + [atom]*i) for i in range(b)
|
| 312 |
+
])
|
| 313 |
+
return self._add_rule(key, new_name, tree)
|
| 314 |
+
|
| 315 |
+
def _generate_repeats(self, rule: Tree, mn: int, mx: int):
|
| 316 |
+
"""Generates a rule tree that repeats ``rule`` exactly between ``mn`` to ``mx`` times.
|
| 317 |
+
"""
|
| 318 |
+
# For a small number of repeats, we can take the naive approach
|
| 319 |
+
if mx < REPEAT_BREAK_THRESHOLD:
|
| 320 |
+
return ST('expansions', [ST('expansion', [rule] * n) for n in range(mn, mx + 1)])
|
| 321 |
+
|
| 322 |
+
# For large repeat values, we break the repetition into sub-rules.
|
| 323 |
+
# We treat ``rule~mn..mx`` as ``rule~mn rule~0..(diff=mx-mn)``.
|
| 324 |
+
# We then use small_factors to split up mn and diff up into values [(a, b), ...]
|
| 325 |
+
# This values are used with the help of _add_repeat_rule and _add_repeat_rule_opt
|
| 326 |
+
# to generate a complete rule/expression that matches the corresponding number of repeats
|
| 327 |
+
mn_target = rule
|
| 328 |
+
for a, b in small_factors(mn, SMALL_FACTOR_THRESHOLD):
|
| 329 |
+
mn_target = self._add_repeat_rule(a, b, mn_target, rule)
|
| 330 |
+
if mx == mn:
|
| 331 |
+
return mn_target
|
| 332 |
+
|
| 333 |
+
diff = mx - mn + 1 # We add one because _add_repeat_opt_rule generates rules that match one less
|
| 334 |
+
diff_factors = small_factors(diff, SMALL_FACTOR_THRESHOLD)
|
| 335 |
+
diff_target = rule # Match rule 1 times
|
| 336 |
+
diff_opt_target = ST('expansion', []) # match rule 0 times (e.g. up to 1 -1 times)
|
| 337 |
+
for a, b in diff_factors[:-1]:
|
| 338 |
+
diff_opt_target = self._add_repeat_opt_rule(a, b, diff_target, diff_opt_target, rule)
|
| 339 |
+
diff_target = self._add_repeat_rule(a, b, diff_target, rule)
|
| 340 |
+
|
| 341 |
+
a, b = diff_factors[-1]
|
| 342 |
+
diff_opt_target = self._add_repeat_opt_rule(a, b, diff_target, diff_opt_target, rule)
|
| 343 |
+
|
| 344 |
+
return ST('expansions', [ST('expansion', [mn_target] + [diff_opt_target])])
|
| 345 |
+
|
| 346 |
+
def expr(self, rule: Tree, op: Token, *args):
|
| 347 |
+
if op.value == '?':
|
| 348 |
+
empty = ST('expansion', [])
|
| 349 |
+
return ST('expansions', [rule, empty])
|
| 350 |
+
elif op.value == '+':
|
| 351 |
+
# a : b c+ d
|
| 352 |
+
# -->
|
| 353 |
+
# a : b _c d
|
| 354 |
+
# _c : _c c | c;
|
| 355 |
+
return self._add_recurse_rule('plus', rule)
|
| 356 |
+
elif op.value == '*':
|
| 357 |
+
# a : b c* d
|
| 358 |
+
# -->
|
| 359 |
+
# a : b _c? d
|
| 360 |
+
# _c : _c c | c;
|
| 361 |
+
new_name = self._add_recurse_rule('star', rule)
|
| 362 |
+
return ST('expansions', [new_name, ST('expansion', [])])
|
| 363 |
+
elif op.value == '~':
|
| 364 |
+
if len(args) == 1:
|
| 365 |
+
mn = mx = int(args[0])
|
| 366 |
+
else:
|
| 367 |
+
mn, mx = map(int, args)
|
| 368 |
+
if mx < mn or mn < 0:
|
| 369 |
+
raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (rule, mn, mx))
|
| 370 |
+
|
| 371 |
+
return self._generate_repeats(rule, mn, mx)
|
| 372 |
+
|
| 373 |
+
assert False, op
|
| 374 |
+
|
| 375 |
+
def maybe(self, rule: Tree):
|
| 376 |
+
keep_all_tokens = self.rule_options and self.rule_options.keep_all_tokens
|
| 377 |
+
rule_size = FindRuleSize(keep_all_tokens).transform(rule)
|
| 378 |
+
empty = ST('expansion', [_EMPTY] * rule_size)
|
| 379 |
+
return ST('expansions', [rule, empty])
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
class SimplifyRule_Visitor(Visitor):
|
| 383 |
+
|
| 384 |
+
@staticmethod
|
| 385 |
+
def _flatten(tree: Tree):
|
| 386 |
+
while tree.expand_kids_by_data(tree.data):
|
| 387 |
+
pass
|
| 388 |
+
|
| 389 |
+
def expansion(self, tree: Tree):
|
| 390 |
+
# rules_list unpacking
|
| 391 |
+
# a : b (c|d) e
|
| 392 |
+
# -->
|
| 393 |
+
# a : b c e | b d e
|
| 394 |
+
#
|
| 395 |
+
# In AST terms:
|
| 396 |
+
# expansion(b, expansions(c, d), e)
|
| 397 |
+
# -->
|
| 398 |
+
# expansions( expansion(b, c, e), expansion(b, d, e) )
|
| 399 |
+
|
| 400 |
+
self._flatten(tree)
|
| 401 |
+
|
| 402 |
+
for i, child in enumerate(tree.children):
|
| 403 |
+
if isinstance(child, Tree) and child.data == 'expansions':
|
| 404 |
+
tree.data = 'expansions'
|
| 405 |
+
tree.children = [self.visit(ST('expansion', [option if i == j else other
|
| 406 |
+
for j, other in enumerate(tree.children)]))
|
| 407 |
+
for option in dedup_list(child.children)]
|
| 408 |
+
self._flatten(tree)
|
| 409 |
+
break
|
| 410 |
+
|
| 411 |
+
def alias(self, tree):
|
| 412 |
+
rule, alias_name = tree.children
|
| 413 |
+
if rule.data == 'expansions':
|
| 414 |
+
aliases = []
|
| 415 |
+
for child in tree.children[0].children:
|
| 416 |
+
aliases.append(ST('alias', [child, alias_name]))
|
| 417 |
+
tree.data = 'expansions'
|
| 418 |
+
tree.children = aliases
|
| 419 |
+
|
| 420 |
+
def expansions(self, tree: Tree):
|
| 421 |
+
self._flatten(tree)
|
| 422 |
+
# Ensure all children are unique
|
| 423 |
+
if len(set(tree.children)) != len(tree.children):
|
| 424 |
+
tree.children = dedup_list(tree.children) # dedup is expensive, so try to minimize its use
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class RuleTreeToText(Transformer):
|
| 428 |
+
def expansions(self, x):
|
| 429 |
+
return x
|
| 430 |
+
|
| 431 |
+
def expansion(self, symbols):
|
| 432 |
+
return symbols, None
|
| 433 |
+
|
| 434 |
+
def alias(self, x):
|
| 435 |
+
(expansion, _alias), alias = x
|
| 436 |
+
assert _alias is None, (alias, expansion, '-', _alias) # Double alias not allowed
|
| 437 |
+
return expansion, alias.name
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
class PrepareAnonTerminals(Transformer_InPlace):
|
| 441 |
+
"""Create a unique list of anonymous terminals. Attempt to give meaningful names to them when we add them"""
|
| 442 |
+
|
| 443 |
+
def __init__(self, terminals):
|
| 444 |
+
self.terminals = terminals
|
| 445 |
+
self.term_set = {td.name for td in self.terminals}
|
| 446 |
+
self.term_reverse = {td.pattern: td for td in terminals}
|
| 447 |
+
self.i = 0
|
| 448 |
+
self.rule_options = None
|
| 449 |
+
|
| 450 |
+
@inline_args
|
| 451 |
+
def pattern(self, p):
|
| 452 |
+
value = p.value
|
| 453 |
+
if p in self.term_reverse and p.flags != self.term_reverse[p].pattern.flags:
|
| 454 |
+
raise GrammarError(u'Conflicting flags for the same terminal: %s' % p)
|
| 455 |
+
|
| 456 |
+
term_name = None
|
| 457 |
+
|
| 458 |
+
if isinstance(p, PatternStr):
|
| 459 |
+
try:
|
| 460 |
+
# If already defined, use the user-defined terminal name
|
| 461 |
+
term_name = self.term_reverse[p].name
|
| 462 |
+
except KeyError:
|
| 463 |
+
# Try to assign an indicative anon-terminal name
|
| 464 |
+
try:
|
| 465 |
+
term_name = _TERMINAL_NAMES[value]
|
| 466 |
+
except KeyError:
|
| 467 |
+
if value and is_id_continue(value) and is_id_start(value[0]) and value.upper() not in self.term_set:
|
| 468 |
+
term_name = value.upper()
|
| 469 |
+
|
| 470 |
+
if term_name in self.term_set:
|
| 471 |
+
term_name = None
|
| 472 |
+
|
| 473 |
+
elif isinstance(p, PatternRE):
|
| 474 |
+
if p in self.term_reverse: # Kind of a weird placement.name
|
| 475 |
+
term_name = self.term_reverse[p].name
|
| 476 |
+
else:
|
| 477 |
+
assert False, p
|
| 478 |
+
|
| 479 |
+
if term_name is None:
|
| 480 |
+
term_name = '__ANON_%d' % self.i
|
| 481 |
+
self.i += 1
|
| 482 |
+
|
| 483 |
+
if term_name not in self.term_set:
|
| 484 |
+
assert p not in self.term_reverse
|
| 485 |
+
self.term_set.add(term_name)
|
| 486 |
+
termdef = TerminalDef(term_name, p)
|
| 487 |
+
self.term_reverse[p] = termdef
|
| 488 |
+
self.terminals.append(termdef)
|
| 489 |
+
|
| 490 |
+
filter_out = False if self.rule_options and self.rule_options.keep_all_tokens else isinstance(p, PatternStr)
|
| 491 |
+
|
| 492 |
+
return Terminal(term_name, filter_out=filter_out)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
class _ReplaceSymbols(Transformer_InPlace):
|
| 496 |
+
"""Helper for ApplyTemplates"""
|
| 497 |
+
|
| 498 |
+
def __init__(self):
|
| 499 |
+
self.names = {}
|
| 500 |
+
|
| 501 |
+
def value(self, c):
|
| 502 |
+
if len(c) == 1 and isinstance(c[0], Symbol) and c[0].name in self.names:
|
| 503 |
+
return self.names[c[0].name]
|
| 504 |
+
return self.__default__('value', c, None)
|
| 505 |
+
|
| 506 |
+
def template_usage(self, c):
|
| 507 |
+
name = c[0].name
|
| 508 |
+
if name in self.names:
|
| 509 |
+
return self.__default__('template_usage', [self.names[name]] + c[1:], None)
|
| 510 |
+
return self.__default__('template_usage', c, None)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class ApplyTemplates(Transformer_InPlace):
|
| 514 |
+
"""Apply the templates, creating new rules that represent the used templates"""
|
| 515 |
+
|
| 516 |
+
def __init__(self, rule_defs):
|
| 517 |
+
self.rule_defs = rule_defs
|
| 518 |
+
self.replacer = _ReplaceSymbols()
|
| 519 |
+
self.created_templates = set()
|
| 520 |
+
|
| 521 |
+
def template_usage(self, c):
|
| 522 |
+
name = c[0].name
|
| 523 |
+
args = c[1:]
|
| 524 |
+
result_name = "%s{%s}" % (name, ",".join(a.name for a in args))
|
| 525 |
+
if result_name not in self.created_templates:
|
| 526 |
+
self.created_templates.add(result_name)
|
| 527 |
+
(_n, params, tree, options) ,= (t for t in self.rule_defs if t[0] == name)
|
| 528 |
+
assert len(params) == len(args), args
|
| 529 |
+
result_tree = deepcopy(tree)
|
| 530 |
+
self.replacer.names = dict(zip(params, args))
|
| 531 |
+
self.replacer.transform(result_tree)
|
| 532 |
+
self.rule_defs.append((result_name, [], result_tree, deepcopy(options)))
|
| 533 |
+
return NonTerminal(result_name)
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def _rfind(s, choices):
|
| 537 |
+
return max(s.rfind(c) for c in choices)
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def eval_escaping(s):
|
| 541 |
+
w = ''
|
| 542 |
+
i = iter(s)
|
| 543 |
+
for n in i:
|
| 544 |
+
w += n
|
| 545 |
+
if n == '\\':
|
| 546 |
+
try:
|
| 547 |
+
n2 = next(i)
|
| 548 |
+
except StopIteration:
|
| 549 |
+
raise GrammarError("Literal ended unexpectedly (bad escaping): `%r`" % s)
|
| 550 |
+
if n2 == '\\':
|
| 551 |
+
w += '\\\\'
|
| 552 |
+
elif n2 not in 'Uuxnftr':
|
| 553 |
+
w += '\\'
|
| 554 |
+
w += n2
|
| 555 |
+
w = w.replace('\\"', '"').replace("'", "\\'")
|
| 556 |
+
|
| 557 |
+
to_eval = "u'''%s'''" % w
|
| 558 |
+
try:
|
| 559 |
+
s = literal_eval(to_eval)
|
| 560 |
+
except SyntaxError as e:
|
| 561 |
+
raise GrammarError(s, e)
|
| 562 |
+
|
| 563 |
+
return s
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def _literal_to_pattern(literal):
|
| 567 |
+
assert isinstance(literal, Token)
|
| 568 |
+
v = literal.value
|
| 569 |
+
flag_start = _rfind(v, '/"')+1
|
| 570 |
+
assert flag_start > 0
|
| 571 |
+
flags = v[flag_start:]
|
| 572 |
+
assert all(f in _RE_FLAGS for f in flags), flags
|
| 573 |
+
|
| 574 |
+
if literal.type == 'STRING' and '\n' in v:
|
| 575 |
+
raise GrammarError('You cannot put newlines in string literals')
|
| 576 |
+
|
| 577 |
+
if literal.type == 'REGEXP' and '\n' in v and 'x' not in flags:
|
| 578 |
+
raise GrammarError('You can only use newlines in regular expressions '
|
| 579 |
+
'with the `x` (verbose) flag')
|
| 580 |
+
|
| 581 |
+
v = v[:flag_start]
|
| 582 |
+
assert v[0] == v[-1] and v[0] in '"/'
|
| 583 |
+
x = v[1:-1]
|
| 584 |
+
|
| 585 |
+
s = eval_escaping(x)
|
| 586 |
+
|
| 587 |
+
if s == "":
|
| 588 |
+
raise GrammarError("Empty terminals are not allowed (%s)" % literal)
|
| 589 |
+
|
| 590 |
+
if literal.type == 'STRING':
|
| 591 |
+
s = s.replace('\\\\', '\\')
|
| 592 |
+
return PatternStr(s, flags, raw=literal.value)
|
| 593 |
+
elif literal.type == 'REGEXP':
|
| 594 |
+
return PatternRE(s, flags, raw=literal.value)
|
| 595 |
+
else:
|
| 596 |
+
assert False, 'Invariant failed: literal.type not in ["STRING", "REGEXP"]'
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
@inline_args
|
| 600 |
+
class PrepareLiterals(Transformer_InPlace):
|
| 601 |
+
def literal(self, literal):
|
| 602 |
+
return ST('pattern', [_literal_to_pattern(literal)])
|
| 603 |
+
|
| 604 |
+
def range(self, start, end):
|
| 605 |
+
assert start.type == end.type == 'STRING'
|
| 606 |
+
start = start.value[1:-1]
|
| 607 |
+
end = end.value[1:-1]
|
| 608 |
+
assert len(eval_escaping(start)) == len(eval_escaping(end)) == 1
|
| 609 |
+
regexp = '[%s-%s]' % (start, end)
|
| 610 |
+
return ST('pattern', [PatternRE(regexp)])
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _make_joined_pattern(regexp, flags_set) -> PatternRE:
|
| 614 |
+
return PatternRE(regexp, ())
|
| 615 |
+
|
| 616 |
+
class TerminalTreeToPattern(Transformer_NonRecursive):
|
| 617 |
+
def pattern(self, ps):
|
| 618 |
+
p ,= ps
|
| 619 |
+
return p
|
| 620 |
+
|
| 621 |
+
def expansion(self, items: List[Pattern]) -> Pattern:
|
| 622 |
+
if not items:
|
| 623 |
+
return PatternStr('')
|
| 624 |
+
|
| 625 |
+
if len(items) == 1:
|
| 626 |
+
return items[0]
|
| 627 |
+
|
| 628 |
+
pattern = ''.join(i.to_regexp() for i in items)
|
| 629 |
+
return _make_joined_pattern(pattern, {i.flags for i in items})
|
| 630 |
+
|
| 631 |
+
def expansions(self, exps: List[Pattern]) -> Pattern:
|
| 632 |
+
if len(exps) == 1:
|
| 633 |
+
return exps[0]
|
| 634 |
+
|
| 635 |
+
# Do a bit of sorting to make sure that the longest option is returned
|
| 636 |
+
# (Python's re module otherwise prefers just 'l' when given (l|ll) and both could match)
|
| 637 |
+
exps.sort(key=lambda x: (-x.max_width, -x.min_width, -len(x.value)))
|
| 638 |
+
|
| 639 |
+
pattern = '(?:%s)' % ('|'.join(i.to_regexp() for i in exps))
|
| 640 |
+
return _make_joined_pattern(pattern, {i.flags for i in exps})
|
| 641 |
+
|
| 642 |
+
def expr(self, args) -> Pattern:
|
| 643 |
+
inner: Pattern
|
| 644 |
+
inner, op = args[:2]
|
| 645 |
+
if op == '~':
|
| 646 |
+
if len(args) == 3:
|
| 647 |
+
op = "{%d}" % int(args[2])
|
| 648 |
+
else:
|
| 649 |
+
mn, mx = map(int, args[2:])
|
| 650 |
+
if mx < mn:
|
| 651 |
+
raise GrammarError("Bad Range for %s (%d..%d isn't allowed)" % (inner, mn, mx))
|
| 652 |
+
op = "{%d,%d}" % (mn, mx)
|
| 653 |
+
else:
|
| 654 |
+
assert len(args) == 2
|
| 655 |
+
return PatternRE('(?:%s)%s' % (inner.to_regexp(), op), inner.flags)
|
| 656 |
+
|
| 657 |
+
def maybe(self, expr):
|
| 658 |
+
return self.expr(expr + ['?'])
|
| 659 |
+
|
| 660 |
+
def alias(self, t):
|
| 661 |
+
raise GrammarError("Aliasing not allowed in terminals (You used -> in the wrong place)")
|
| 662 |
+
|
| 663 |
+
def value(self, v):
|
| 664 |
+
return v[0]
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
class ValidateSymbols(Transformer_InPlace):
|
| 668 |
+
def value(self, v):
|
| 669 |
+
v ,= v
|
| 670 |
+
assert isinstance(v, (Tree, Symbol))
|
| 671 |
+
return v
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def nr_deepcopy_tree(t):
|
| 675 |
+
"""Deepcopy tree `t` without recursion"""
|
| 676 |
+
return Transformer_NonRecursive(False).transform(t)
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
class Grammar:
|
| 680 |
+
|
| 681 |
+
term_defs: List[Tuple[str, Tuple[Tree, int]]]
|
| 682 |
+
rule_defs: List[Tuple[str, Tuple[str, ...], Tree, RuleOptions]]
|
| 683 |
+
ignore: List[str]
|
| 684 |
+
|
| 685 |
+
def __init__(self, rule_defs: List[Tuple[str, Tuple[str, ...], Tree, RuleOptions]], term_defs: List[Tuple[str, Tuple[Tree, int]]], ignore: List[str]) -> None:
|
| 686 |
+
self.term_defs = term_defs
|
| 687 |
+
self.rule_defs = rule_defs
|
| 688 |
+
self.ignore = ignore
|
| 689 |
+
|
| 690 |
+
def compile(self, start, terminals_to_keep) -> Tuple[List[TerminalDef], List[Rule], List[str]]:
|
| 691 |
+
# We change the trees in-place (to support huge grammars)
|
| 692 |
+
# So deepcopy allows calling compile more than once.
|
| 693 |
+
term_defs = [(n, (nr_deepcopy_tree(t), p)) for n, (t, p) in self.term_defs]
|
| 694 |
+
rule_defs = [(n, p, nr_deepcopy_tree(t), o) for n, p, t, o in self.rule_defs]
|
| 695 |
+
|
| 696 |
+
# ===================
|
| 697 |
+
# Compile Terminals
|
| 698 |
+
# ===================
|
| 699 |
+
|
| 700 |
+
# Convert terminal-trees to strings/regexps
|
| 701 |
+
|
| 702 |
+
for name, (term_tree, priority) in term_defs:
|
| 703 |
+
if term_tree is None: # Terminal added through %declare
|
| 704 |
+
continue
|
| 705 |
+
expansions = list(term_tree.find_data('expansion'))
|
| 706 |
+
if len(expansions) == 1 and not expansions[0].children:
|
| 707 |
+
raise GrammarError("Terminals cannot be empty (%s)" % name)
|
| 708 |
+
|
| 709 |
+
transformer = PrepareLiterals() * TerminalTreeToPattern()
|
| 710 |
+
terminals = [TerminalDef(name, transformer.transform(term_tree), priority)
|
| 711 |
+
for name, (term_tree, priority) in term_defs if term_tree]
|
| 712 |
+
|
| 713 |
+
# =================
|
| 714 |
+
# Compile Rules
|
| 715 |
+
# =================
|
| 716 |
+
|
| 717 |
+
# 1. Pre-process terminals
|
| 718 |
+
anon_tokens_transf = PrepareAnonTerminals(terminals)
|
| 719 |
+
transformer = PrepareLiterals() * ValidateSymbols() * anon_tokens_transf # Adds to terminals
|
| 720 |
+
|
| 721 |
+
# 2. Inline Templates
|
| 722 |
+
|
| 723 |
+
transformer *= ApplyTemplates(rule_defs)
|
| 724 |
+
|
| 725 |
+
# 3. Convert EBNF to BNF (and apply step 1 & 2)
|
| 726 |
+
ebnf_to_bnf = EBNF_to_BNF()
|
| 727 |
+
rules = []
|
| 728 |
+
i = 0
|
| 729 |
+
while i < len(rule_defs): # We have to do it like this because rule_defs might grow due to templates
|
| 730 |
+
name, params, rule_tree, options = rule_defs[i]
|
| 731 |
+
i += 1
|
| 732 |
+
if len(params) != 0: # Dont transform templates
|
| 733 |
+
continue
|
| 734 |
+
rule_options = RuleOptions(keep_all_tokens=True) if options and options.keep_all_tokens else None
|
| 735 |
+
ebnf_to_bnf.rule_options = rule_options
|
| 736 |
+
ebnf_to_bnf.prefix = name
|
| 737 |
+
anon_tokens_transf.rule_options = rule_options
|
| 738 |
+
tree = transformer.transform(rule_tree)
|
| 739 |
+
res: Tree = ebnf_to_bnf.transform(tree)
|
| 740 |
+
rules.append((name, res, options))
|
| 741 |
+
rules += ebnf_to_bnf.new_rules
|
| 742 |
+
|
| 743 |
+
assert len(rules) == len({name for name, _t, _o in rules}), "Whoops, name collision"
|
| 744 |
+
|
| 745 |
+
# 4. Compile tree to Rule objects
|
| 746 |
+
rule_tree_to_text = RuleTreeToText()
|
| 747 |
+
|
| 748 |
+
simplify_rule = SimplifyRule_Visitor()
|
| 749 |
+
compiled_rules: List[Rule] = []
|
| 750 |
+
for rule_content in rules:
|
| 751 |
+
name, tree, options = rule_content
|
| 752 |
+
simplify_rule.visit(tree)
|
| 753 |
+
expansions = rule_tree_to_text.transform(tree)
|
| 754 |
+
|
| 755 |
+
for i, (expansion, alias) in enumerate(expansions):
|
| 756 |
+
if alias and name.startswith('_'):
|
| 757 |
+
raise GrammarError("Rule %s is marked for expansion (it starts with an underscore) and isn't allowed to have aliases (alias=%s)"% (name, alias))
|
| 758 |
+
|
| 759 |
+
empty_indices = tuple(x==_EMPTY for x in expansion)
|
| 760 |
+
if any(empty_indices):
|
| 761 |
+
exp_options = copy(options) or RuleOptions()
|
| 762 |
+
exp_options.empty_indices = empty_indices
|
| 763 |
+
expansion = [x for x in expansion if x!=_EMPTY]
|
| 764 |
+
else:
|
| 765 |
+
exp_options = options
|
| 766 |
+
|
| 767 |
+
for sym in expansion:
|
| 768 |
+
assert isinstance(sym, Symbol)
|
| 769 |
+
if sym.is_term and exp_options and exp_options.keep_all_tokens:
|
| 770 |
+
assert isinstance(sym, Terminal)
|
| 771 |
+
sym.filter_out = False
|
| 772 |
+
rule = Rule(NonTerminal(name), expansion, i, alias, exp_options)
|
| 773 |
+
compiled_rules.append(rule)
|
| 774 |
+
|
| 775 |
+
# Remove duplicates of empty rules, throw error for non-empty duplicates
|
| 776 |
+
if len(set(compiled_rules)) != len(compiled_rules):
|
| 777 |
+
duplicates = classify(compiled_rules, lambda x: x)
|
| 778 |
+
for dups in duplicates.values():
|
| 779 |
+
if len(dups) > 1:
|
| 780 |
+
if dups[0].expansion:
|
| 781 |
+
raise GrammarError("Rules defined twice: %s\n\n(Might happen due to colliding expansion of optionals: [] or ?)"
|
| 782 |
+
% ''.join('\n * %s' % i for i in dups))
|
| 783 |
+
|
| 784 |
+
# Empty rule; assert all other attributes are equal
|
| 785 |
+
assert len({(r.alias, r.order, r.options) for r in dups}) == len(dups)
|
| 786 |
+
|
| 787 |
+
# Remove duplicates
|
| 788 |
+
compiled_rules = list(OrderedSet(compiled_rules))
|
| 789 |
+
|
| 790 |
+
# Filter out unused rules
|
| 791 |
+
while True:
|
| 792 |
+
c = len(compiled_rules)
|
| 793 |
+
used_rules = {s for r in compiled_rules
|
| 794 |
+
for s in r.expansion
|
| 795 |
+
if isinstance(s, NonTerminal)
|
| 796 |
+
and s != r.origin}
|
| 797 |
+
used_rules |= {NonTerminal(s) for s in start}
|
| 798 |
+
compiled_rules, unused = classify_bool(compiled_rules, lambda r: r.origin in used_rules)
|
| 799 |
+
for r in unused:
|
| 800 |
+
logger.debug("Unused rule: %s", r)
|
| 801 |
+
if len(compiled_rules) == c:
|
| 802 |
+
break
|
| 803 |
+
|
| 804 |
+
# Filter out unused terminals
|
| 805 |
+
if terminals_to_keep != '*':
|
| 806 |
+
used_terms = {t.name for r in compiled_rules
|
| 807 |
+
for t in r.expansion
|
| 808 |
+
if isinstance(t, Terminal)}
|
| 809 |
+
terminals, unused = classify_bool(terminals, lambda t: t.name in used_terms or t.name in self.ignore or t.name in terminals_to_keep)
|
| 810 |
+
if unused:
|
| 811 |
+
logger.debug("Unused terminals: %s", [t.name for t in unused])
|
| 812 |
+
|
| 813 |
+
return terminals, compiled_rules, self.ignore
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
PackageResource = namedtuple('PackageResource', 'pkg_name path')
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
class FromPackageLoader:
|
| 820 |
+
"""
|
| 821 |
+
Provides a simple way of creating custom import loaders that load from packages via ``pkgutil.get_data`` instead of using `open`.
|
| 822 |
+
This allows them to be compatible even from within zip files.
|
| 823 |
+
|
| 824 |
+
Relative imports are handled, so you can just freely use them.
|
| 825 |
+
|
| 826 |
+
pkg_name: The name of the package. You can probably provide `__name__` most of the time
|
| 827 |
+
search_paths: All the path that will be search on absolute imports.
|
| 828 |
+
"""
|
| 829 |
+
|
| 830 |
+
pkg_name: str
|
| 831 |
+
search_paths: Sequence[str]
|
| 832 |
+
|
| 833 |
+
def __init__(self, pkg_name: str, search_paths: Sequence[str]=("", )) -> None:
|
| 834 |
+
self.pkg_name = pkg_name
|
| 835 |
+
self.search_paths = search_paths
|
| 836 |
+
|
| 837 |
+
def __repr__(self):
|
| 838 |
+
return "%s(%r, %r)" % (type(self).__name__, self.pkg_name, self.search_paths)
|
| 839 |
+
|
| 840 |
+
def __call__(self, base_path: Union[None, str, PackageResource], grammar_path: str) -> Tuple[PackageResource, str]:
|
| 841 |
+
if base_path is None:
|
| 842 |
+
to_try = self.search_paths
|
| 843 |
+
else:
|
| 844 |
+
# Check whether or not the importing grammar was loaded by this module.
|
| 845 |
+
if not isinstance(base_path, PackageResource) or base_path.pkg_name != self.pkg_name:
|
| 846 |
+
# Technically false, but FileNotFound doesn't exist in python2.7, and this message should never reach the end user anyway
|
| 847 |
+
raise IOError()
|
| 848 |
+
to_try = [base_path.path]
|
| 849 |
+
|
| 850 |
+
err = None
|
| 851 |
+
for path in to_try:
|
| 852 |
+
full_path = os.path.join(path, grammar_path)
|
| 853 |
+
try:
|
| 854 |
+
text: Optional[bytes] = pkgutil.get_data(self.pkg_name, full_path)
|
| 855 |
+
except IOError as e:
|
| 856 |
+
err = e
|
| 857 |
+
continue
|
| 858 |
+
else:
|
| 859 |
+
return PackageResource(self.pkg_name, full_path), (text.decode() if text else '')
|
| 860 |
+
|
| 861 |
+
raise IOError('Cannot find grammar in given paths') from err
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
stdlib_loader = FromPackageLoader('lark', IMPORT_PATHS)
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
|
| 868 |
+
def resolve_term_references(term_dict):
|
| 869 |
+
# TODO Solve with transitive closure (maybe)
|
| 870 |
+
|
| 871 |
+
while True:
|
| 872 |
+
changed = False
|
| 873 |
+
for name, token_tree in term_dict.items():
|
| 874 |
+
if token_tree is None: # Terminal added through %declare
|
| 875 |
+
continue
|
| 876 |
+
for exp in token_tree.find_data('value'):
|
| 877 |
+
item ,= exp.children
|
| 878 |
+
if isinstance(item, NonTerminal):
|
| 879 |
+
raise GrammarError("Rules aren't allowed inside terminals (%s in %s)" % (item, name))
|
| 880 |
+
elif isinstance(item, Terminal):
|
| 881 |
+
try:
|
| 882 |
+
term_value = term_dict[item.name]
|
| 883 |
+
except KeyError:
|
| 884 |
+
raise GrammarError("Terminal used but not defined: %s" % item.name)
|
| 885 |
+
assert term_value is not None
|
| 886 |
+
exp.children[0] = term_value
|
| 887 |
+
changed = True
|
| 888 |
+
else:
|
| 889 |
+
assert isinstance(item, Tree)
|
| 890 |
+
if not changed:
|
| 891 |
+
break
|
| 892 |
+
|
| 893 |
+
for name, term in term_dict.items():
|
| 894 |
+
if term: # Not just declared
|
| 895 |
+
for child in term.children:
|
| 896 |
+
ids = [id(x) for x in child.iter_subtrees()]
|
| 897 |
+
if id(term) in ids:
|
| 898 |
+
raise GrammarError("Recursion in terminal '%s' (recursion is only allowed in rules, not terminals)" % name)
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
def symbol_from_strcase(s):
|
| 903 |
+
assert isinstance(s, str)
|
| 904 |
+
return Terminal(s, filter_out=s.startswith('_')) if s.isupper() else NonTerminal(s)
|
| 905 |
+
|
| 906 |
+
@inline_args
|
| 907 |
+
class PrepareGrammar(Transformer_InPlace):
|
| 908 |
+
def terminal(self, name):
|
| 909 |
+
return Terminal(str(name), filter_out=name.startswith('_'))
|
| 910 |
+
|
| 911 |
+
def nonterminal(self, name):
|
| 912 |
+
return NonTerminal(name.value)
|
| 913 |
+
|
| 914 |
+
|
| 915 |
+
def _find_used_symbols(tree):
|
| 916 |
+
assert tree.data == 'expansions'
|
| 917 |
+
return {t.name for x in tree.find_data('expansion')
|
| 918 |
+
for t in x.scan_values(lambda t: isinstance(t, Symbol))}
|
| 919 |
+
|
| 920 |
+
|
| 921 |
+
def _get_parser():
|
| 922 |
+
try:
|
| 923 |
+
return _get_parser.cache
|
| 924 |
+
except AttributeError:
|
| 925 |
+
terminals = [TerminalDef(name, PatternRE(value)) for name, value in TERMINALS.items()]
|
| 926 |
+
|
| 927 |
+
rules = [(name.lstrip('?'), x, RuleOptions(expand1=name.startswith('?')))
|
| 928 |
+
for name, x in RULES.items()]
|
| 929 |
+
rules = [Rule(NonTerminal(r), [symbol_from_strcase(s) for s in x.split()], i, None, o)
|
| 930 |
+
for r, xs, o in rules for i, x in enumerate(xs)]
|
| 931 |
+
|
| 932 |
+
callback = ParseTreeBuilder(rules, ST).create_callback()
|
| 933 |
+
import re
|
| 934 |
+
lexer_conf = LexerConf(terminals, re, ['WS', 'COMMENT', 'BACKSLASH'])
|
| 935 |
+
parser_conf = ParserConf(rules, callback, ['start'])
|
| 936 |
+
lexer_conf.lexer_type = 'basic'
|
| 937 |
+
parser_conf.parser_type = 'lalr'
|
| 938 |
+
_get_parser.cache = ParsingFrontend(lexer_conf, parser_conf, None)
|
| 939 |
+
return _get_parser.cache
|
| 940 |
+
|
| 941 |
+
GRAMMAR_ERRORS = [
|
| 942 |
+
('Incorrect type of value', ['a: 1\n']),
|
| 943 |
+
('Unclosed parenthesis', ['a: (\n']),
|
| 944 |
+
('Unmatched closing parenthesis', ['a: )\n', 'a: [)\n', 'a: (]\n']),
|
| 945 |
+
('Expecting rule or terminal definition (missing colon)', ['a\n', 'A\n', 'a->\n', 'A->\n', 'a A\n']),
|
| 946 |
+
('Illegal name for rules or terminals', ['Aa:\n']),
|
| 947 |
+
('Alias expects lowercase name', ['a: -> "a"\n']),
|
| 948 |
+
('Unexpected colon', ['a::\n', 'a: b:\n', 'a: B:\n', 'a: "a":\n']),
|
| 949 |
+
('Misplaced operator', ['a: b??', 'a: b(?)', 'a:+\n', 'a:?\n', 'a:*\n', 'a:|*\n']),
|
| 950 |
+
('Expecting option ("|") or a new rule or terminal definition', ['a:a\n()\n']),
|
| 951 |
+
('Terminal names cannot contain dots', ['A.B\n']),
|
| 952 |
+
('Expecting rule or terminal definition', ['"a"\n']),
|
| 953 |
+
('%import expects a name', ['%import "a"\n']),
|
| 954 |
+
('%ignore expects a value', ['%ignore %import\n']),
|
| 955 |
+
]
|
| 956 |
+
|
| 957 |
+
def _translate_parser_exception(parse, e):
|
| 958 |
+
error = e.match_examples(parse, GRAMMAR_ERRORS, use_accepts=True)
|
| 959 |
+
if error:
|
| 960 |
+
return error
|
| 961 |
+
elif 'STRING' in e.expected:
|
| 962 |
+
return "Expecting a value"
|
| 963 |
+
|
| 964 |
+
def _parse_grammar(text, name, start='start'):
|
| 965 |
+
try:
|
| 966 |
+
tree = _get_parser().parse(text + '\n', start)
|
| 967 |
+
except UnexpectedCharacters as e:
|
| 968 |
+
context = e.get_context(text)
|
| 969 |
+
raise GrammarError("Unexpected input at line %d column %d in %s: \n\n%s" %
|
| 970 |
+
(e.line, e.column, name, context))
|
| 971 |
+
except UnexpectedToken as e:
|
| 972 |
+
context = e.get_context(text)
|
| 973 |
+
error = _translate_parser_exception(_get_parser().parse, e)
|
| 974 |
+
if error:
|
| 975 |
+
raise GrammarError("%s, at line %s column %s\n\n%s" % (error, e.line, e.column, context))
|
| 976 |
+
raise
|
| 977 |
+
|
| 978 |
+
return PrepareGrammar().transform(tree)
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def _error_repr(error):
|
| 982 |
+
if isinstance(error, UnexpectedToken):
|
| 983 |
+
error2 = _translate_parser_exception(_get_parser().parse, error)
|
| 984 |
+
if error2:
|
| 985 |
+
return error2
|
| 986 |
+
expected = ', '.join(error.accepts or error.expected)
|
| 987 |
+
return "Unexpected token %r. Expected one of: {%s}" % (str(error.token), expected)
|
| 988 |
+
else:
|
| 989 |
+
return str(error)
|
| 990 |
+
|
| 991 |
+
def _search_interactive_parser(interactive_parser, predicate):
|
| 992 |
+
def expand(node):
|
| 993 |
+
path, p = node
|
| 994 |
+
for choice in p.choices():
|
| 995 |
+
t = Token(choice, '')
|
| 996 |
+
try:
|
| 997 |
+
new_p = p.feed_token(t)
|
| 998 |
+
except ParseError: # Illegal
|
| 999 |
+
pass
|
| 1000 |
+
else:
|
| 1001 |
+
yield path + (choice,), new_p
|
| 1002 |
+
|
| 1003 |
+
for path, p in bfs_all_unique([((), interactive_parser)], expand):
|
| 1004 |
+
if predicate(p):
|
| 1005 |
+
return path, p
|
| 1006 |
+
|
| 1007 |
+
def find_grammar_errors(text: str, start: str='start') -> List[Tuple[UnexpectedInput, str]]:
|
| 1008 |
+
errors = []
|
| 1009 |
+
def on_error(e):
|
| 1010 |
+
errors.append((e, _error_repr(e)))
|
| 1011 |
+
|
| 1012 |
+
# recover to a new line
|
| 1013 |
+
token_path, _ = _search_interactive_parser(e.interactive_parser.as_immutable(), lambda p: '_NL' in p.choices())
|
| 1014 |
+
for token_type in token_path:
|
| 1015 |
+
e.interactive_parser.feed_token(Token(token_type, ''))
|
| 1016 |
+
e.interactive_parser.feed_token(Token('_NL', '\n'))
|
| 1017 |
+
return True
|
| 1018 |
+
|
| 1019 |
+
_tree = _get_parser().parse(text + '\n', start, on_error=on_error)
|
| 1020 |
+
|
| 1021 |
+
errors_by_line = classify(errors, lambda e: e[0].line)
|
| 1022 |
+
errors = [el[0] for el in errors_by_line.values()] # already sorted
|
| 1023 |
+
|
| 1024 |
+
for e in errors:
|
| 1025 |
+
e[0].interactive_parser = None
|
| 1026 |
+
return errors
|
| 1027 |
+
|
| 1028 |
+
|
| 1029 |
+
def _get_mangle(prefix, aliases, base_mangle=None):
|
| 1030 |
+
def mangle(s):
|
| 1031 |
+
if s in aliases:
|
| 1032 |
+
s = aliases[s]
|
| 1033 |
+
else:
|
| 1034 |
+
if s[0] == '_':
|
| 1035 |
+
s = '_%s__%s' % (prefix, s[1:])
|
| 1036 |
+
else:
|
| 1037 |
+
s = '%s__%s' % (prefix, s)
|
| 1038 |
+
if base_mangle is not None:
|
| 1039 |
+
s = base_mangle(s)
|
| 1040 |
+
return s
|
| 1041 |
+
return mangle
|
| 1042 |
+
|
| 1043 |
+
def _mangle_definition_tree(exp, mangle):
|
| 1044 |
+
if mangle is None:
|
| 1045 |
+
return exp
|
| 1046 |
+
exp = deepcopy(exp) # TODO: is this needed?
|
| 1047 |
+
for t in exp.iter_subtrees():
|
| 1048 |
+
for i, c in enumerate(t.children):
|
| 1049 |
+
if isinstance(c, Symbol):
|
| 1050 |
+
t.children[i] = c.renamed(mangle)
|
| 1051 |
+
|
| 1052 |
+
return exp
|
| 1053 |
+
|
| 1054 |
+
def _make_rule_tuple(modifiers_tree, name, params, priority_tree, expansions):
|
| 1055 |
+
if modifiers_tree.children:
|
| 1056 |
+
m ,= modifiers_tree.children
|
| 1057 |
+
expand1 = '?' in m
|
| 1058 |
+
if expand1 and name.startswith('_'):
|
| 1059 |
+
raise GrammarError("Inlined rules (_rule) cannot use the ?rule modifier.")
|
| 1060 |
+
keep_all_tokens = '!' in m
|
| 1061 |
+
else:
|
| 1062 |
+
keep_all_tokens = False
|
| 1063 |
+
expand1 = False
|
| 1064 |
+
|
| 1065 |
+
if priority_tree.children:
|
| 1066 |
+
p ,= priority_tree.children
|
| 1067 |
+
priority = int(p)
|
| 1068 |
+
else:
|
| 1069 |
+
priority = None
|
| 1070 |
+
|
| 1071 |
+
if params is not None:
|
| 1072 |
+
params = [t.value for t in params.children] # For the grammar parser
|
| 1073 |
+
|
| 1074 |
+
return name, params, expansions, RuleOptions(keep_all_tokens, expand1, priority=priority,
|
| 1075 |
+
template_source=(name if params else None))
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
class Definition:
|
| 1079 |
+
def __init__(self, is_term, tree, params=(), options=None):
|
| 1080 |
+
self.is_term = is_term
|
| 1081 |
+
self.tree = tree
|
| 1082 |
+
self.params = tuple(params)
|
| 1083 |
+
self.options = options
|
| 1084 |
+
|
| 1085 |
+
class GrammarBuilder:
|
| 1086 |
+
|
| 1087 |
+
global_keep_all_tokens: bool
|
| 1088 |
+
import_paths: List[Union[str, Callable]]
|
| 1089 |
+
used_files: Dict[str, str]
|
| 1090 |
+
|
| 1091 |
+
_definitions: Dict[str, Definition]
|
| 1092 |
+
_ignore_names: List[str]
|
| 1093 |
+
|
| 1094 |
+
def __init__(self, global_keep_all_tokens: bool=False, import_paths: Optional[List[Union[str, Callable]]]=None, used_files: Optional[Dict[str, str]]=None) -> None:
|
| 1095 |
+
self.global_keep_all_tokens = global_keep_all_tokens
|
| 1096 |
+
self.import_paths = import_paths or []
|
| 1097 |
+
self.used_files = used_files or {}
|
| 1098 |
+
|
| 1099 |
+
self._definitions: Dict[str, Definition] = {}
|
| 1100 |
+
self._ignore_names: List[str] = []
|
| 1101 |
+
|
| 1102 |
+
def _grammar_error(self, is_term, msg, *names):
|
| 1103 |
+
args = {}
|
| 1104 |
+
for i, name in enumerate(names, start=1):
|
| 1105 |
+
postfix = '' if i == 1 else str(i)
|
| 1106 |
+
args['name' + postfix] = name
|
| 1107 |
+
args['type' + postfix] = lowercase_type = ("rule", "terminal")[is_term]
|
| 1108 |
+
args['Type' + postfix] = lowercase_type.title()
|
| 1109 |
+
raise GrammarError(msg.format(**args))
|
| 1110 |
+
|
| 1111 |
+
def _check_options(self, is_term, options):
|
| 1112 |
+
if is_term:
|
| 1113 |
+
if options is None:
|
| 1114 |
+
options = 1
|
| 1115 |
+
elif not isinstance(options, int):
|
| 1116 |
+
raise GrammarError("Terminal require a single int as 'options' (e.g. priority), got %s" % (type(options),))
|
| 1117 |
+
else:
|
| 1118 |
+
if options is None:
|
| 1119 |
+
options = RuleOptions()
|
| 1120 |
+
elif not isinstance(options, RuleOptions):
|
| 1121 |
+
raise GrammarError("Rules require a RuleOptions instance as 'options'")
|
| 1122 |
+
if self.global_keep_all_tokens:
|
| 1123 |
+
options.keep_all_tokens = True
|
| 1124 |
+
return options
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
def _define(self, name, is_term, exp, params=(), options=None, *, override=False):
|
| 1128 |
+
if name in self._definitions:
|
| 1129 |
+
if not override:
|
| 1130 |
+
self._grammar_error(is_term, "{Type} '{name}' defined more than once", name)
|
| 1131 |
+
elif override:
|
| 1132 |
+
self._grammar_error(is_term, "Cannot override a nonexisting {type} {name}", name)
|
| 1133 |
+
|
| 1134 |
+
if name.startswith('__'):
|
| 1135 |
+
self._grammar_error(is_term, 'Names starting with double-underscore are reserved (Error at {name})', name)
|
| 1136 |
+
|
| 1137 |
+
self._definitions[name] = Definition(is_term, exp, params, self._check_options(is_term, options))
|
| 1138 |
+
|
| 1139 |
+
def _extend(self, name, is_term, exp, params=(), options=None):
|
| 1140 |
+
if name not in self._definitions:
|
| 1141 |
+
self._grammar_error(is_term, "Can't extend {type} {name} as it wasn't defined before", name)
|
| 1142 |
+
|
| 1143 |
+
d = self._definitions[name]
|
| 1144 |
+
|
| 1145 |
+
if is_term != d.is_term:
|
| 1146 |
+
self._grammar_error(is_term, "Cannot extend {type} {name} - one is a terminal, while the other is not.", name)
|
| 1147 |
+
if tuple(params) != d.params:
|
| 1148 |
+
self._grammar_error(is_term, "Cannot extend {type} with different parameters: {name}", name)
|
| 1149 |
+
|
| 1150 |
+
if d.tree is None:
|
| 1151 |
+
self._grammar_error(is_term, "Can't extend {type} {name} - it is abstract.", name)
|
| 1152 |
+
|
| 1153 |
+
# TODO: think about what to do with 'options'
|
| 1154 |
+
base = d.tree
|
| 1155 |
+
|
| 1156 |
+
assert isinstance(base, Tree) and base.data == 'expansions'
|
| 1157 |
+
base.children.insert(0, exp)
|
| 1158 |
+
|
| 1159 |
+
def _ignore(self, exp_or_name):
|
| 1160 |
+
if isinstance(exp_or_name, str):
|
| 1161 |
+
self._ignore_names.append(exp_or_name)
|
| 1162 |
+
else:
|
| 1163 |
+
assert isinstance(exp_or_name, Tree)
|
| 1164 |
+
t = exp_or_name
|
| 1165 |
+
if t.data == 'expansions' and len(t.children) == 1:
|
| 1166 |
+
t2 ,= t.children
|
| 1167 |
+
if t2.data=='expansion' and len(t2.children) == 1:
|
| 1168 |
+
item ,= t2.children
|
| 1169 |
+
if item.data == 'value':
|
| 1170 |
+
item ,= item.children
|
| 1171 |
+
if isinstance(item, Terminal):
|
| 1172 |
+
# Keep terminal name, no need to create a new definition
|
| 1173 |
+
self._ignore_names.append(item.name)
|
| 1174 |
+
return
|
| 1175 |
+
|
| 1176 |
+
name = '__IGNORE_%d'% len(self._ignore_names)
|
| 1177 |
+
self._ignore_names.append(name)
|
| 1178 |
+
self._definitions[name] = Definition(True, t, options=TOKEN_DEFAULT_PRIORITY)
|
| 1179 |
+
|
| 1180 |
+
def _unpack_import(self, stmt, grammar_name):
|
| 1181 |
+
if len(stmt.children) > 1:
|
| 1182 |
+
path_node, arg1 = stmt.children
|
| 1183 |
+
else:
|
| 1184 |
+
path_node, = stmt.children
|
| 1185 |
+
arg1 = None
|
| 1186 |
+
|
| 1187 |
+
if isinstance(arg1, Tree): # Multi import
|
| 1188 |
+
dotted_path = tuple(path_node.children)
|
| 1189 |
+
names = arg1.children
|
| 1190 |
+
aliases = dict(zip(names, names)) # Can't have aliased multi import, so all aliases will be the same as names
|
| 1191 |
+
else: # Single import
|
| 1192 |
+
dotted_path = tuple(path_node.children[:-1])
|
| 1193 |
+
if not dotted_path:
|
| 1194 |
+
name ,= path_node.children
|
| 1195 |
+
raise GrammarError("Nothing was imported from grammar `%s`" % name)
|
| 1196 |
+
name = path_node.children[-1] # Get name from dotted path
|
| 1197 |
+
aliases = {name.value: (arg1 or name).value} # Aliases if exist
|
| 1198 |
+
|
| 1199 |
+
if path_node.data == 'import_lib': # Import from library
|
| 1200 |
+
base_path = None
|
| 1201 |
+
else: # Relative import
|
| 1202 |
+
if grammar_name == '<string>': # Import relative to script file path if grammar is coded in script
|
| 1203 |
+
try:
|
| 1204 |
+
base_file = os.path.abspath(sys.modules['__main__'].__file__)
|
| 1205 |
+
except AttributeError:
|
| 1206 |
+
base_file = None
|
| 1207 |
+
else:
|
| 1208 |
+
base_file = grammar_name # Import relative to grammar file path if external grammar file
|
| 1209 |
+
if base_file:
|
| 1210 |
+
if isinstance(base_file, PackageResource):
|
| 1211 |
+
base_path = PackageResource(base_file.pkg_name, os.path.split(base_file.path)[0])
|
| 1212 |
+
else:
|
| 1213 |
+
base_path = os.path.split(base_file)[0]
|
| 1214 |
+
else:
|
| 1215 |
+
base_path = os.path.abspath(os.path.curdir)
|
| 1216 |
+
|
| 1217 |
+
return dotted_path, base_path, aliases
|
| 1218 |
+
|
| 1219 |
+
def _unpack_definition(self, tree, mangle):
|
| 1220 |
+
|
| 1221 |
+
if tree.data == 'rule':
|
| 1222 |
+
name, params, exp, opts = _make_rule_tuple(*tree.children)
|
| 1223 |
+
is_term = False
|
| 1224 |
+
else:
|
| 1225 |
+
name = tree.children[0].value
|
| 1226 |
+
params = () # TODO terminal templates
|
| 1227 |
+
opts = int(tree.children[1]) if len(tree.children) == 3 else TOKEN_DEFAULT_PRIORITY # priority
|
| 1228 |
+
exp = tree.children[-1]
|
| 1229 |
+
is_term = True
|
| 1230 |
+
|
| 1231 |
+
if mangle is not None:
|
| 1232 |
+
params = tuple(mangle(p) for p in params)
|
| 1233 |
+
name = mangle(name)
|
| 1234 |
+
|
| 1235 |
+
exp = _mangle_definition_tree(exp, mangle)
|
| 1236 |
+
return name, is_term, exp, params, opts
|
| 1237 |
+
|
| 1238 |
+
|
| 1239 |
+
def load_grammar(self, grammar_text: str, grammar_name: str="<?>", mangle: Optional[Callable[[str], str]]=None) -> None:
|
| 1240 |
+
tree = _parse_grammar(grammar_text, grammar_name)
|
| 1241 |
+
|
| 1242 |
+
imports: Dict[Tuple[str, ...], Tuple[Optional[str], Dict[str, str]]] = {}
|
| 1243 |
+
|
| 1244 |
+
for stmt in tree.children:
|
| 1245 |
+
if stmt.data == 'import':
|
| 1246 |
+
dotted_path, base_path, aliases = self._unpack_import(stmt, grammar_name)
|
| 1247 |
+
try:
|
| 1248 |
+
import_base_path, import_aliases = imports[dotted_path]
|
| 1249 |
+
assert base_path == import_base_path, 'Inconsistent base_path for %s.' % '.'.join(dotted_path)
|
| 1250 |
+
import_aliases.update(aliases)
|
| 1251 |
+
except KeyError:
|
| 1252 |
+
imports[dotted_path] = base_path, aliases
|
| 1253 |
+
|
| 1254 |
+
for dotted_path, (base_path, aliases) in imports.items():
|
| 1255 |
+
self.do_import(dotted_path, base_path, aliases, mangle)
|
| 1256 |
+
|
| 1257 |
+
for stmt in tree.children:
|
| 1258 |
+
if stmt.data in ('term', 'rule'):
|
| 1259 |
+
self._define(*self._unpack_definition(stmt, mangle))
|
| 1260 |
+
elif stmt.data == 'override':
|
| 1261 |
+
r ,= stmt.children
|
| 1262 |
+
self._define(*self._unpack_definition(r, mangle), override=True)
|
| 1263 |
+
elif stmt.data == 'extend':
|
| 1264 |
+
r ,= stmt.children
|
| 1265 |
+
self._extend(*self._unpack_definition(r, mangle))
|
| 1266 |
+
elif stmt.data == 'ignore':
|
| 1267 |
+
# if mangle is not None, we shouldn't apply ignore, since we aren't in a toplevel grammar
|
| 1268 |
+
if mangle is None:
|
| 1269 |
+
self._ignore(*stmt.children)
|
| 1270 |
+
elif stmt.data == 'declare':
|
| 1271 |
+
for symbol in stmt.children:
|
| 1272 |
+
assert isinstance(symbol, Symbol), symbol
|
| 1273 |
+
is_term = isinstance(symbol, Terminal)
|
| 1274 |
+
if mangle is None:
|
| 1275 |
+
name = symbol.name
|
| 1276 |
+
else:
|
| 1277 |
+
name = mangle(symbol.name)
|
| 1278 |
+
self._define(name, is_term, None)
|
| 1279 |
+
elif stmt.data == 'import':
|
| 1280 |
+
pass
|
| 1281 |
+
else:
|
| 1282 |
+
assert False, stmt
|
| 1283 |
+
|
| 1284 |
+
|
| 1285 |
+
term_defs = { name: d.tree
|
| 1286 |
+
for name, d in self._definitions.items()
|
| 1287 |
+
if d.is_term
|
| 1288 |
+
}
|
| 1289 |
+
resolve_term_references(term_defs)
|
| 1290 |
+
|
| 1291 |
+
|
| 1292 |
+
def _remove_unused(self, used):
|
| 1293 |
+
def rule_dependencies(symbol):
|
| 1294 |
+
try:
|
| 1295 |
+
d = self._definitions[symbol]
|
| 1296 |
+
except KeyError:
|
| 1297 |
+
return []
|
| 1298 |
+
if d.is_term:
|
| 1299 |
+
return []
|
| 1300 |
+
return _find_used_symbols(d.tree) - set(d.params)
|
| 1301 |
+
|
| 1302 |
+
_used = set(bfs(used, rule_dependencies))
|
| 1303 |
+
self._definitions = {k: v for k, v in self._definitions.items() if k in _used}
|
| 1304 |
+
|
| 1305 |
+
|
| 1306 |
+
def do_import(self, dotted_path: Tuple[str, ...], base_path: Optional[str], aliases: Dict[str, str], base_mangle: Optional[Callable[[str], str]]=None) -> None:
|
| 1307 |
+
assert dotted_path
|
| 1308 |
+
mangle = _get_mangle('__'.join(dotted_path), aliases, base_mangle)
|
| 1309 |
+
grammar_path = os.path.join(*dotted_path) + EXT
|
| 1310 |
+
to_try = self.import_paths + ([base_path] if base_path is not None else []) + [stdlib_loader]
|
| 1311 |
+
for source in to_try:
|
| 1312 |
+
try:
|
| 1313 |
+
if callable(source):
|
| 1314 |
+
joined_path, text = source(base_path, grammar_path)
|
| 1315 |
+
else:
|
| 1316 |
+
joined_path = os.path.join(source, grammar_path)
|
| 1317 |
+
with open(joined_path, encoding='utf8') as f:
|
| 1318 |
+
text = f.read()
|
| 1319 |
+
except IOError:
|
| 1320 |
+
continue
|
| 1321 |
+
else:
|
| 1322 |
+
h = sha256_digest(text)
|
| 1323 |
+
if self.used_files.get(joined_path, h) != h:
|
| 1324 |
+
raise RuntimeError("Grammar file was changed during importing")
|
| 1325 |
+
self.used_files[joined_path] = h
|
| 1326 |
+
|
| 1327 |
+
gb = GrammarBuilder(self.global_keep_all_tokens, self.import_paths, self.used_files)
|
| 1328 |
+
gb.load_grammar(text, joined_path, mangle)
|
| 1329 |
+
gb._remove_unused(map(mangle, aliases))
|
| 1330 |
+
for name in gb._definitions:
|
| 1331 |
+
if name in self._definitions:
|
| 1332 |
+
raise GrammarError("Cannot import '%s' from '%s': Symbol already defined." % (name, grammar_path))
|
| 1333 |
+
|
| 1334 |
+
self._definitions.update(**gb._definitions)
|
| 1335 |
+
break
|
| 1336 |
+
else:
|
| 1337 |
+
# Search failed. Make Python throw a nice error.
|
| 1338 |
+
open(grammar_path, encoding='utf8')
|
| 1339 |
+
assert False, "Couldn't import grammar %s, but a corresponding file was found at a place where lark doesn't search for it" % (dotted_path,)
|
| 1340 |
+
|
| 1341 |
+
|
| 1342 |
+
def validate(self) -> None:
|
| 1343 |
+
for name, d in self._definitions.items():
|
| 1344 |
+
params = d.params
|
| 1345 |
+
exp = d.tree
|
| 1346 |
+
|
| 1347 |
+
for i, p in enumerate(params):
|
| 1348 |
+
if p in self._definitions:
|
| 1349 |
+
raise GrammarError("Template Parameter conflicts with rule %s (in template %s)" % (p, name))
|
| 1350 |
+
if p in params[:i]:
|
| 1351 |
+
raise GrammarError("Duplicate Template Parameter %s (in template %s)" % (p, name))
|
| 1352 |
+
|
| 1353 |
+
if exp is None: # Remaining checks don't apply to abstract rules/terminals (created with %declare)
|
| 1354 |
+
continue
|
| 1355 |
+
|
| 1356 |
+
for temp in exp.find_data('template_usage'):
|
| 1357 |
+
sym = temp.children[0].name
|
| 1358 |
+
args = temp.children[1:]
|
| 1359 |
+
if sym not in params:
|
| 1360 |
+
if sym not in self._definitions:
|
| 1361 |
+
self._grammar_error(d.is_term, "Template '%s' used but not defined (in {type} {name})" % sym, name)
|
| 1362 |
+
if len(args) != len(self._definitions[sym].params):
|
| 1363 |
+
expected, actual = len(self._definitions[sym].params), len(args)
|
| 1364 |
+
self._grammar_error(d.is_term, "Wrong number of template arguments used for {name} "
|
| 1365 |
+
"(expected %s, got %s) (in {type2} {name2})" % (expected, actual), sym, name)
|
| 1366 |
+
|
| 1367 |
+
for sym in _find_used_symbols(exp):
|
| 1368 |
+
if sym not in self._definitions and sym not in params:
|
| 1369 |
+
self._grammar_error(d.is_term, "{Type} '{name}' used but not defined (in {type2} {name2})", sym, name)
|
| 1370 |
+
|
| 1371 |
+
if not set(self._definitions).issuperset(self._ignore_names):
|
| 1372 |
+
raise GrammarError("Terminals %s were marked to ignore but were not defined!" % (set(self._ignore_names) - set(self._definitions)))
|
| 1373 |
+
|
| 1374 |
+
def build(self) -> Grammar:
|
| 1375 |
+
self.validate()
|
| 1376 |
+
rule_defs = []
|
| 1377 |
+
term_defs = []
|
| 1378 |
+
for name, d in self._definitions.items():
|
| 1379 |
+
(params, exp, options) = d.params, d.tree, d.options
|
| 1380 |
+
if d.is_term:
|
| 1381 |
+
assert len(params) == 0
|
| 1382 |
+
term_defs.append((name, (exp, options)))
|
| 1383 |
+
else:
|
| 1384 |
+
rule_defs.append((name, params, exp, options))
|
| 1385 |
+
# resolve_term_references(term_defs)
|
| 1386 |
+
return Grammar(rule_defs, term_defs, self._ignore_names)
|
| 1387 |
+
|
| 1388 |
+
|
| 1389 |
+
def verify_used_files(file_hashes):
|
| 1390 |
+
for path, old in file_hashes.items():
|
| 1391 |
+
text = None
|
| 1392 |
+
if isinstance(path, str) and os.path.exists(path):
|
| 1393 |
+
with open(path, encoding='utf8') as f:
|
| 1394 |
+
text = f.read()
|
| 1395 |
+
elif isinstance(path, PackageResource):
|
| 1396 |
+
with suppress(IOError):
|
| 1397 |
+
text = pkgutil.get_data(*path).decode('utf-8')
|
| 1398 |
+
if text is None: # We don't know how to load the path. ignore it.
|
| 1399 |
+
continue
|
| 1400 |
+
|
| 1401 |
+
current = sha256_digest(text)
|
| 1402 |
+
if old != current:
|
| 1403 |
+
logger.info("File %r changed, rebuilding Parser" % path)
|
| 1404 |
+
return False
|
| 1405 |
+
return True
|
| 1406 |
+
|
| 1407 |
+
def list_grammar_imports(grammar, import_paths=[]):
|
| 1408 |
+
"Returns a list of paths to the lark grammars imported by the given grammar (recursively)"
|
| 1409 |
+
builder = GrammarBuilder(False, import_paths)
|
| 1410 |
+
builder.load_grammar(grammar, '<string>')
|
| 1411 |
+
return list(builder.used_files.keys())
|
| 1412 |
+
|
| 1413 |
+
def load_grammar(grammar, source, import_paths, global_keep_all_tokens):
|
| 1414 |
+
builder = GrammarBuilder(global_keep_all_tokens, import_paths)
|
| 1415 |
+
builder.load_grammar(grammar, source)
|
| 1416 |
+
return builder.build(), builder.used_files
|
| 1417 |
+
|
| 1418 |
+
|
| 1419 |
+
def sha256_digest(s: str) -> str:
|
| 1420 |
+
"""Get the sha256 digest of a string
|
| 1421 |
+
|
| 1422 |
+
Supports the `usedforsecurity` argument for Python 3.9+ to allow running on
|
| 1423 |
+
a FIPS-enabled system.
|
| 1424 |
+
"""
|
| 1425 |
+
if sys.version_info >= (3, 9):
|
| 1426 |
+
return hashlib.sha256(s.encode('utf8'), usedforsecurity=False).hexdigest()
|
| 1427 |
+
else:
|
| 1428 |
+
return hashlib.sha256(s.encode('utf8')).hexdigest()
|
vllm/lib/python3.10/site-packages/lark/parse_tree_builder.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provides functions for the automatic building and shaping of the parse-tree."""
|
| 2 |
+
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from .exceptions import GrammarError, ConfigurationError
|
| 6 |
+
from .lexer import Token
|
| 7 |
+
from .tree import Tree
|
| 8 |
+
from .visitors import Transformer_InPlace
|
| 9 |
+
from .visitors import _vargs_meta, _vargs_meta_inline
|
| 10 |
+
|
| 11 |
+
###{standalone
|
| 12 |
+
from functools import partial, wraps
|
| 13 |
+
from itertools import product
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ExpandSingleChild:
|
| 17 |
+
def __init__(self, node_builder):
|
| 18 |
+
self.node_builder = node_builder
|
| 19 |
+
|
| 20 |
+
def __call__(self, children):
|
| 21 |
+
if len(children) == 1:
|
| 22 |
+
return children[0]
|
| 23 |
+
else:
|
| 24 |
+
return self.node_builder(children)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class PropagatePositions:
|
| 29 |
+
def __init__(self, node_builder, node_filter=None):
|
| 30 |
+
self.node_builder = node_builder
|
| 31 |
+
self.node_filter = node_filter
|
| 32 |
+
|
| 33 |
+
def __call__(self, children):
|
| 34 |
+
res = self.node_builder(children)
|
| 35 |
+
|
| 36 |
+
if isinstance(res, Tree):
|
| 37 |
+
# Calculate positions while the tree is streaming, according to the rule:
|
| 38 |
+
# - nodes start at the start of their first child's container,
|
| 39 |
+
# and end at the end of their last child's container.
|
| 40 |
+
# Containers are nodes that take up space in text, but have been inlined in the tree.
|
| 41 |
+
|
| 42 |
+
res_meta = res.meta
|
| 43 |
+
|
| 44 |
+
first_meta = self._pp_get_meta(children)
|
| 45 |
+
if first_meta is not None:
|
| 46 |
+
if not hasattr(res_meta, 'line'):
|
| 47 |
+
# meta was already set, probably because the rule has been inlined (e.g. `?rule`)
|
| 48 |
+
res_meta.line = getattr(first_meta, 'container_line', first_meta.line)
|
| 49 |
+
res_meta.column = getattr(first_meta, 'container_column', first_meta.column)
|
| 50 |
+
res_meta.start_pos = getattr(first_meta, 'container_start_pos', first_meta.start_pos)
|
| 51 |
+
res_meta.empty = False
|
| 52 |
+
|
| 53 |
+
res_meta.container_line = getattr(first_meta, 'container_line', first_meta.line)
|
| 54 |
+
res_meta.container_column = getattr(first_meta, 'container_column', first_meta.column)
|
| 55 |
+
res_meta.container_start_pos = getattr(first_meta, 'container_start_pos', first_meta.start_pos)
|
| 56 |
+
|
| 57 |
+
last_meta = self._pp_get_meta(reversed(children))
|
| 58 |
+
if last_meta is not None:
|
| 59 |
+
if not hasattr(res_meta, 'end_line'):
|
| 60 |
+
res_meta.end_line = getattr(last_meta, 'container_end_line', last_meta.end_line)
|
| 61 |
+
res_meta.end_column = getattr(last_meta, 'container_end_column', last_meta.end_column)
|
| 62 |
+
res_meta.end_pos = getattr(last_meta, 'container_end_pos', last_meta.end_pos)
|
| 63 |
+
res_meta.empty = False
|
| 64 |
+
|
| 65 |
+
res_meta.container_end_line = getattr(last_meta, 'container_end_line', last_meta.end_line)
|
| 66 |
+
res_meta.container_end_column = getattr(last_meta, 'container_end_column', last_meta.end_column)
|
| 67 |
+
res_meta.container_end_pos = getattr(last_meta, 'container_end_pos', last_meta.end_pos)
|
| 68 |
+
|
| 69 |
+
return res
|
| 70 |
+
|
| 71 |
+
def _pp_get_meta(self, children):
|
| 72 |
+
for c in children:
|
| 73 |
+
if self.node_filter is not None and not self.node_filter(c):
|
| 74 |
+
continue
|
| 75 |
+
if isinstance(c, Tree):
|
| 76 |
+
if not c.meta.empty:
|
| 77 |
+
return c.meta
|
| 78 |
+
elif isinstance(c, Token):
|
| 79 |
+
return c
|
| 80 |
+
elif hasattr(c, '__lark_meta__'):
|
| 81 |
+
return c.__lark_meta__()
|
| 82 |
+
|
| 83 |
+
def make_propagate_positions(option):
|
| 84 |
+
if callable(option):
|
| 85 |
+
return partial(PropagatePositions, node_filter=option)
|
| 86 |
+
elif option is True:
|
| 87 |
+
return PropagatePositions
|
| 88 |
+
elif option is False:
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
raise ConfigurationError('Invalid option for propagate_positions: %r' % option)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class ChildFilter:
|
| 95 |
+
def __init__(self, to_include, append_none, node_builder):
|
| 96 |
+
self.node_builder = node_builder
|
| 97 |
+
self.to_include = to_include
|
| 98 |
+
self.append_none = append_none
|
| 99 |
+
|
| 100 |
+
def __call__(self, children):
|
| 101 |
+
filtered = []
|
| 102 |
+
|
| 103 |
+
for i, to_expand, add_none in self.to_include:
|
| 104 |
+
if add_none:
|
| 105 |
+
filtered += [None] * add_none
|
| 106 |
+
if to_expand:
|
| 107 |
+
filtered += children[i].children
|
| 108 |
+
else:
|
| 109 |
+
filtered.append(children[i])
|
| 110 |
+
|
| 111 |
+
if self.append_none:
|
| 112 |
+
filtered += [None] * self.append_none
|
| 113 |
+
|
| 114 |
+
return self.node_builder(filtered)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class ChildFilterLALR(ChildFilter):
|
| 118 |
+
"""Optimized childfilter for LALR (assumes no duplication in parse tree, so it's safe to change it)"""
|
| 119 |
+
|
| 120 |
+
def __call__(self, children):
|
| 121 |
+
filtered = []
|
| 122 |
+
for i, to_expand, add_none in self.to_include:
|
| 123 |
+
if add_none:
|
| 124 |
+
filtered += [None] * add_none
|
| 125 |
+
if to_expand:
|
| 126 |
+
if filtered:
|
| 127 |
+
filtered += children[i].children
|
| 128 |
+
else: # Optimize for left-recursion
|
| 129 |
+
filtered = children[i].children
|
| 130 |
+
else:
|
| 131 |
+
filtered.append(children[i])
|
| 132 |
+
|
| 133 |
+
if self.append_none:
|
| 134 |
+
filtered += [None] * self.append_none
|
| 135 |
+
|
| 136 |
+
return self.node_builder(filtered)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class ChildFilterLALR_NoPlaceholders(ChildFilter):
|
| 140 |
+
"Optimized childfilter for LALR (assumes no duplication in parse tree, so it's safe to change it)"
|
| 141 |
+
def __init__(self, to_include, node_builder):
|
| 142 |
+
self.node_builder = node_builder
|
| 143 |
+
self.to_include = to_include
|
| 144 |
+
|
| 145 |
+
def __call__(self, children):
|
| 146 |
+
filtered = []
|
| 147 |
+
for i, to_expand in self.to_include:
|
| 148 |
+
if to_expand:
|
| 149 |
+
if filtered:
|
| 150 |
+
filtered += children[i].children
|
| 151 |
+
else: # Optimize for left-recursion
|
| 152 |
+
filtered = children[i].children
|
| 153 |
+
else:
|
| 154 |
+
filtered.append(children[i])
|
| 155 |
+
return self.node_builder(filtered)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _should_expand(sym):
|
| 159 |
+
return not sym.is_term and sym.name.startswith('_')
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def maybe_create_child_filter(expansion, keep_all_tokens, ambiguous, _empty_indices: List[bool]):
|
| 163 |
+
# Prepare empty_indices as: How many Nones to insert at each index?
|
| 164 |
+
if _empty_indices:
|
| 165 |
+
assert _empty_indices.count(False) == len(expansion)
|
| 166 |
+
s = ''.join(str(int(b)) for b in _empty_indices)
|
| 167 |
+
empty_indices = [len(ones) for ones in s.split('0')]
|
| 168 |
+
assert len(empty_indices) == len(expansion)+1, (empty_indices, len(expansion))
|
| 169 |
+
else:
|
| 170 |
+
empty_indices = [0] * (len(expansion)+1)
|
| 171 |
+
|
| 172 |
+
to_include = []
|
| 173 |
+
nones_to_add = 0
|
| 174 |
+
for i, sym in enumerate(expansion):
|
| 175 |
+
nones_to_add += empty_indices[i]
|
| 176 |
+
if keep_all_tokens or not (sym.is_term and sym.filter_out):
|
| 177 |
+
to_include.append((i, _should_expand(sym), nones_to_add))
|
| 178 |
+
nones_to_add = 0
|
| 179 |
+
|
| 180 |
+
nones_to_add += empty_indices[len(expansion)]
|
| 181 |
+
|
| 182 |
+
if _empty_indices or len(to_include) < len(expansion) or any(to_expand for i, to_expand,_ in to_include):
|
| 183 |
+
if _empty_indices or ambiguous:
|
| 184 |
+
return partial(ChildFilter if ambiguous else ChildFilterLALR, to_include, nones_to_add)
|
| 185 |
+
else:
|
| 186 |
+
# LALR without placeholders
|
| 187 |
+
return partial(ChildFilterLALR_NoPlaceholders, [(i, x) for i,x,_ in to_include])
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class AmbiguousExpander:
|
| 191 |
+
"""Deal with the case where we're expanding children ('_rule') into a parent but the children
|
| 192 |
+
are ambiguous. i.e. (parent->_ambig->_expand_this_rule). In this case, make the parent itself
|
| 193 |
+
ambiguous with as many copies as there are ambiguous children, and then copy the ambiguous children
|
| 194 |
+
into the right parents in the right places, essentially shifting the ambiguity up the tree."""
|
| 195 |
+
def __init__(self, to_expand, tree_class, node_builder):
|
| 196 |
+
self.node_builder = node_builder
|
| 197 |
+
self.tree_class = tree_class
|
| 198 |
+
self.to_expand = to_expand
|
| 199 |
+
|
| 200 |
+
def __call__(self, children):
|
| 201 |
+
def _is_ambig_tree(t):
|
| 202 |
+
return hasattr(t, 'data') and t.data == '_ambig'
|
| 203 |
+
|
| 204 |
+
# -- When we're repeatedly expanding ambiguities we can end up with nested ambiguities.
|
| 205 |
+
# All children of an _ambig node should be a derivation of that ambig node, hence
|
| 206 |
+
# it is safe to assume that if we see an _ambig node nested within an ambig node
|
| 207 |
+
# it is safe to simply expand it into the parent _ambig node as an alternative derivation.
|
| 208 |
+
ambiguous = []
|
| 209 |
+
for i, child in enumerate(children):
|
| 210 |
+
if _is_ambig_tree(child):
|
| 211 |
+
if i in self.to_expand:
|
| 212 |
+
ambiguous.append(i)
|
| 213 |
+
|
| 214 |
+
child.expand_kids_by_data('_ambig')
|
| 215 |
+
|
| 216 |
+
if not ambiguous:
|
| 217 |
+
return self.node_builder(children)
|
| 218 |
+
|
| 219 |
+
expand = [child.children if i in ambiguous else (child,) for i, child in enumerate(children)]
|
| 220 |
+
return self.tree_class('_ambig', [self.node_builder(list(f)) for f in product(*expand)])
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def maybe_create_ambiguous_expander(tree_class, expansion, keep_all_tokens):
|
| 224 |
+
to_expand = [i for i, sym in enumerate(expansion)
|
| 225 |
+
if keep_all_tokens or ((not (sym.is_term and sym.filter_out)) and _should_expand(sym))]
|
| 226 |
+
if to_expand:
|
| 227 |
+
return partial(AmbiguousExpander, to_expand, tree_class)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class AmbiguousIntermediateExpander:
|
| 231 |
+
"""
|
| 232 |
+
Propagate ambiguous intermediate nodes and their derivations up to the
|
| 233 |
+
current rule.
|
| 234 |
+
|
| 235 |
+
In general, converts
|
| 236 |
+
|
| 237 |
+
rule
|
| 238 |
+
_iambig
|
| 239 |
+
_inter
|
| 240 |
+
someChildren1
|
| 241 |
+
...
|
| 242 |
+
_inter
|
| 243 |
+
someChildren2
|
| 244 |
+
...
|
| 245 |
+
someChildren3
|
| 246 |
+
...
|
| 247 |
+
|
| 248 |
+
to
|
| 249 |
+
|
| 250 |
+
_ambig
|
| 251 |
+
rule
|
| 252 |
+
someChildren1
|
| 253 |
+
...
|
| 254 |
+
someChildren3
|
| 255 |
+
...
|
| 256 |
+
rule
|
| 257 |
+
someChildren2
|
| 258 |
+
...
|
| 259 |
+
someChildren3
|
| 260 |
+
...
|
| 261 |
+
rule
|
| 262 |
+
childrenFromNestedIambigs
|
| 263 |
+
...
|
| 264 |
+
someChildren3
|
| 265 |
+
...
|
| 266 |
+
...
|
| 267 |
+
|
| 268 |
+
propagating up any nested '_iambig' nodes along the way.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
def __init__(self, tree_class, node_builder):
|
| 272 |
+
self.node_builder = node_builder
|
| 273 |
+
self.tree_class = tree_class
|
| 274 |
+
|
| 275 |
+
def __call__(self, children):
|
| 276 |
+
def _is_iambig_tree(child):
|
| 277 |
+
return hasattr(child, 'data') and child.data == '_iambig'
|
| 278 |
+
|
| 279 |
+
def _collapse_iambig(children):
|
| 280 |
+
"""
|
| 281 |
+
Recursively flatten the derivations of the parent of an '_iambig'
|
| 282 |
+
node. Returns a list of '_inter' nodes guaranteed not
|
| 283 |
+
to contain any nested '_iambig' nodes, or None if children does
|
| 284 |
+
not contain an '_iambig' node.
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
# Due to the structure of the SPPF,
|
| 288 |
+
# an '_iambig' node can only appear as the first child
|
| 289 |
+
if children and _is_iambig_tree(children[0]):
|
| 290 |
+
iambig_node = children[0]
|
| 291 |
+
result = []
|
| 292 |
+
for grandchild in iambig_node.children:
|
| 293 |
+
collapsed = _collapse_iambig(grandchild.children)
|
| 294 |
+
if collapsed:
|
| 295 |
+
for child in collapsed:
|
| 296 |
+
child.children += children[1:]
|
| 297 |
+
result += collapsed
|
| 298 |
+
else:
|
| 299 |
+
new_tree = self.tree_class('_inter', grandchild.children + children[1:])
|
| 300 |
+
result.append(new_tree)
|
| 301 |
+
return result
|
| 302 |
+
|
| 303 |
+
collapsed = _collapse_iambig(children)
|
| 304 |
+
if collapsed:
|
| 305 |
+
processed_nodes = [self.node_builder(c.children) for c in collapsed]
|
| 306 |
+
return self.tree_class('_ambig', processed_nodes)
|
| 307 |
+
|
| 308 |
+
return self.node_builder(children)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def inplace_transformer(func):
|
| 313 |
+
@wraps(func)
|
| 314 |
+
def f(children):
|
| 315 |
+
# function name in a Transformer is a rule name.
|
| 316 |
+
tree = Tree(func.__name__, children)
|
| 317 |
+
return func(tree)
|
| 318 |
+
return f
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def apply_visit_wrapper(func, name, wrapper):
|
| 322 |
+
if wrapper is _vargs_meta or wrapper is _vargs_meta_inline:
|
| 323 |
+
raise NotImplementedError("Meta args not supported for internal transformer")
|
| 324 |
+
|
| 325 |
+
@wraps(func)
|
| 326 |
+
def f(children):
|
| 327 |
+
return wrapper(func, name, children, None)
|
| 328 |
+
return f
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class ParseTreeBuilder:
|
| 332 |
+
def __init__(self, rules, tree_class, propagate_positions=False, ambiguous=False, maybe_placeholders=False):
|
| 333 |
+
self.tree_class = tree_class
|
| 334 |
+
self.propagate_positions = propagate_positions
|
| 335 |
+
self.ambiguous = ambiguous
|
| 336 |
+
self.maybe_placeholders = maybe_placeholders
|
| 337 |
+
|
| 338 |
+
self.rule_builders = list(self._init_builders(rules))
|
| 339 |
+
|
| 340 |
+
def _init_builders(self, rules):
|
| 341 |
+
propagate_positions = make_propagate_positions(self.propagate_positions)
|
| 342 |
+
|
| 343 |
+
for rule in rules:
|
| 344 |
+
options = rule.options
|
| 345 |
+
keep_all_tokens = options.keep_all_tokens
|
| 346 |
+
expand_single_child = options.expand1
|
| 347 |
+
|
| 348 |
+
wrapper_chain = list(filter(None, [
|
| 349 |
+
(expand_single_child and not rule.alias) and ExpandSingleChild,
|
| 350 |
+
maybe_create_child_filter(rule.expansion, keep_all_tokens, self.ambiguous, options.empty_indices if self.maybe_placeholders else None),
|
| 351 |
+
propagate_positions,
|
| 352 |
+
self.ambiguous and maybe_create_ambiguous_expander(self.tree_class, rule.expansion, keep_all_tokens),
|
| 353 |
+
self.ambiguous and partial(AmbiguousIntermediateExpander, self.tree_class)
|
| 354 |
+
]))
|
| 355 |
+
|
| 356 |
+
yield rule, wrapper_chain
|
| 357 |
+
|
| 358 |
+
def create_callback(self, transformer=None):
|
| 359 |
+
callbacks = {}
|
| 360 |
+
|
| 361 |
+
default_handler = getattr(transformer, '__default__', None)
|
| 362 |
+
if default_handler:
|
| 363 |
+
def default_callback(data, children):
|
| 364 |
+
return default_handler(data, children, None)
|
| 365 |
+
else:
|
| 366 |
+
default_callback = self.tree_class
|
| 367 |
+
|
| 368 |
+
for rule, wrapper_chain in self.rule_builders:
|
| 369 |
+
|
| 370 |
+
user_callback_name = rule.alias or rule.options.template_source or rule.origin.name
|
| 371 |
+
try:
|
| 372 |
+
f = getattr(transformer, user_callback_name)
|
| 373 |
+
wrapper = getattr(f, 'visit_wrapper', None)
|
| 374 |
+
if wrapper is not None:
|
| 375 |
+
f = apply_visit_wrapper(f, user_callback_name, wrapper)
|
| 376 |
+
elif isinstance(transformer, Transformer_InPlace):
|
| 377 |
+
f = inplace_transformer(f)
|
| 378 |
+
except AttributeError:
|
| 379 |
+
f = partial(default_callback, user_callback_name)
|
| 380 |
+
|
| 381 |
+
for w in wrapper_chain:
|
| 382 |
+
f = w(f)
|
| 383 |
+
|
| 384 |
+
if rule in callbacks:
|
| 385 |
+
raise GrammarError("Rule '%s' already exists" % (rule,))
|
| 386 |
+
|
| 387 |
+
callbacks[rule] = f
|
| 388 |
+
|
| 389 |
+
return callbacks
|
| 390 |
+
|
| 391 |
+
###}
|
vllm/lib/python3.10/site-packages/lark/parser_frontends.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Callable, Dict, Optional, Collection, Union, TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from .exceptions import ConfigurationError, GrammarError, assert_config
|
| 4 |
+
from .utils import get_regexp_width, Serialize
|
| 5 |
+
from .lexer import LexerThread, BasicLexer, ContextualLexer, Lexer
|
| 6 |
+
from .parsers import earley, xearley, cyk
|
| 7 |
+
from .parsers.lalr_parser import LALR_Parser
|
| 8 |
+
from .tree import Tree
|
| 9 |
+
from .common import LexerConf, ParserConf, _ParserArgType, _LexerArgType
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from .parsers.lalr_analysis import ParseTableBase
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
###{standalone
|
| 16 |
+
|
| 17 |
+
def _wrap_lexer(lexer_class):
|
| 18 |
+
future_interface = getattr(lexer_class, '__future_interface__', False)
|
| 19 |
+
if future_interface:
|
| 20 |
+
return lexer_class
|
| 21 |
+
else:
|
| 22 |
+
class CustomLexerWrapper(Lexer):
|
| 23 |
+
def __init__(self, lexer_conf):
|
| 24 |
+
self.lexer = lexer_class(lexer_conf)
|
| 25 |
+
def lex(self, lexer_state, parser_state):
|
| 26 |
+
return self.lexer.lex(lexer_state.text)
|
| 27 |
+
return CustomLexerWrapper
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _deserialize_parsing_frontend(data, memo, lexer_conf, callbacks, options):
|
| 31 |
+
parser_conf = ParserConf.deserialize(data['parser_conf'], memo)
|
| 32 |
+
cls = (options and options._plugins.get('LALR_Parser')) or LALR_Parser
|
| 33 |
+
parser = cls.deserialize(data['parser'], memo, callbacks, options.debug)
|
| 34 |
+
parser_conf.callbacks = callbacks
|
| 35 |
+
return ParsingFrontend(lexer_conf, parser_conf, options, parser=parser)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
_parser_creators: 'Dict[str, Callable[[LexerConf, Any, Any], Any]]' = {}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ParsingFrontend(Serialize):
|
| 42 |
+
__serialize_fields__ = 'lexer_conf', 'parser_conf', 'parser'
|
| 43 |
+
|
| 44 |
+
lexer_conf: LexerConf
|
| 45 |
+
parser_conf: ParserConf
|
| 46 |
+
options: Any
|
| 47 |
+
|
| 48 |
+
def __init__(self, lexer_conf: LexerConf, parser_conf: ParserConf, options, parser=None):
|
| 49 |
+
self.parser_conf = parser_conf
|
| 50 |
+
self.lexer_conf = lexer_conf
|
| 51 |
+
self.options = options
|
| 52 |
+
|
| 53 |
+
# Set-up parser
|
| 54 |
+
if parser: # From cache
|
| 55 |
+
self.parser = parser
|
| 56 |
+
else:
|
| 57 |
+
create_parser = _parser_creators.get(parser_conf.parser_type)
|
| 58 |
+
assert create_parser is not None, "{} is not supported in standalone mode".format(
|
| 59 |
+
parser_conf.parser_type
|
| 60 |
+
)
|
| 61 |
+
self.parser = create_parser(lexer_conf, parser_conf, options)
|
| 62 |
+
|
| 63 |
+
# Set-up lexer
|
| 64 |
+
lexer_type = lexer_conf.lexer_type
|
| 65 |
+
self.skip_lexer = False
|
| 66 |
+
if lexer_type in ('dynamic', 'dynamic_complete'):
|
| 67 |
+
assert lexer_conf.postlex is None
|
| 68 |
+
self.skip_lexer = True
|
| 69 |
+
return
|
| 70 |
+
|
| 71 |
+
if isinstance(lexer_type, type):
|
| 72 |
+
assert issubclass(lexer_type, Lexer)
|
| 73 |
+
self.lexer = _wrap_lexer(lexer_type)(lexer_conf)
|
| 74 |
+
elif isinstance(lexer_type, str):
|
| 75 |
+
create_lexer = {
|
| 76 |
+
'basic': create_basic_lexer,
|
| 77 |
+
'contextual': create_contextual_lexer,
|
| 78 |
+
}[lexer_type]
|
| 79 |
+
self.lexer = create_lexer(lexer_conf, self.parser, lexer_conf.postlex, options)
|
| 80 |
+
else:
|
| 81 |
+
raise TypeError("Bad value for lexer_type: {lexer_type}")
|
| 82 |
+
|
| 83 |
+
if lexer_conf.postlex:
|
| 84 |
+
self.lexer = PostLexConnector(self.lexer, lexer_conf.postlex)
|
| 85 |
+
|
| 86 |
+
def _verify_start(self, start=None):
|
| 87 |
+
if start is None:
|
| 88 |
+
start_decls = self.parser_conf.start
|
| 89 |
+
if len(start_decls) > 1:
|
| 90 |
+
raise ConfigurationError("Lark initialized with more than 1 possible start rule. Must specify which start rule to parse", start_decls)
|
| 91 |
+
start ,= start_decls
|
| 92 |
+
elif start not in self.parser_conf.start:
|
| 93 |
+
raise ConfigurationError("Unknown start rule %s. Must be one of %r" % (start, self.parser_conf.start))
|
| 94 |
+
return start
|
| 95 |
+
|
| 96 |
+
def _make_lexer_thread(self, text: str) -> Union[str, LexerThread]:
|
| 97 |
+
cls = (self.options and self.options._plugins.get('LexerThread')) or LexerThread
|
| 98 |
+
return text if self.skip_lexer else cls.from_text(self.lexer, text)
|
| 99 |
+
|
| 100 |
+
def parse(self, text: str, start=None, on_error=None):
|
| 101 |
+
chosen_start = self._verify_start(start)
|
| 102 |
+
kw = {} if on_error is None else {'on_error': on_error}
|
| 103 |
+
stream = self._make_lexer_thread(text)
|
| 104 |
+
return self.parser.parse(stream, chosen_start, **kw)
|
| 105 |
+
|
| 106 |
+
def parse_interactive(self, text: Optional[str]=None, start=None):
|
| 107 |
+
# TODO BREAK - Change text from Optional[str] to text: str = ''.
|
| 108 |
+
# Would break behavior of exhaust_lexer(), which currently raises TypeError, and after the change would just return []
|
| 109 |
+
chosen_start = self._verify_start(start)
|
| 110 |
+
if self.parser_conf.parser_type != 'lalr':
|
| 111 |
+
raise ConfigurationError("parse_interactive() currently only works with parser='lalr' ")
|
| 112 |
+
stream = self._make_lexer_thread(text) # type: ignore[arg-type]
|
| 113 |
+
return self.parser.parse_interactive(stream, chosen_start)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _validate_frontend_args(parser, lexer) -> None:
|
| 117 |
+
assert_config(parser, ('lalr', 'earley', 'cyk'))
|
| 118 |
+
if not isinstance(lexer, type): # not custom lexer?
|
| 119 |
+
expected = {
|
| 120 |
+
'lalr': ('basic', 'contextual'),
|
| 121 |
+
'earley': ('basic', 'dynamic', 'dynamic_complete'),
|
| 122 |
+
'cyk': ('basic', ),
|
| 123 |
+
}[parser]
|
| 124 |
+
assert_config(lexer, expected, 'Parser %r does not support lexer %%r, expected one of %%s' % parser)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _get_lexer_callbacks(transformer, terminals):
|
| 128 |
+
result = {}
|
| 129 |
+
for terminal in terminals:
|
| 130 |
+
callback = getattr(transformer, terminal.name, None)
|
| 131 |
+
if callback is not None:
|
| 132 |
+
result[terminal.name] = callback
|
| 133 |
+
return result
|
| 134 |
+
|
| 135 |
+
class PostLexConnector:
|
| 136 |
+
def __init__(self, lexer, postlexer):
|
| 137 |
+
self.lexer = lexer
|
| 138 |
+
self.postlexer = postlexer
|
| 139 |
+
|
| 140 |
+
def lex(self, lexer_state, parser_state):
|
| 141 |
+
i = self.lexer.lex(lexer_state, parser_state)
|
| 142 |
+
return self.postlexer.process(i)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def create_basic_lexer(lexer_conf, parser, postlex, options) -> BasicLexer:
|
| 147 |
+
cls = (options and options._plugins.get('BasicLexer')) or BasicLexer
|
| 148 |
+
return cls(lexer_conf)
|
| 149 |
+
|
| 150 |
+
def create_contextual_lexer(lexer_conf: LexerConf, parser, postlex, options) -> ContextualLexer:
|
| 151 |
+
cls = (options and options._plugins.get('ContextualLexer')) or ContextualLexer
|
| 152 |
+
parse_table: ParseTableBase[int] = parser._parse_table
|
| 153 |
+
states: Dict[int, Collection[str]] = {idx:list(t.keys()) for idx, t in parse_table.states.items()}
|
| 154 |
+
always_accept: Collection[str] = postlex.always_accept if postlex else ()
|
| 155 |
+
return cls(lexer_conf, states, always_accept=always_accept)
|
| 156 |
+
|
| 157 |
+
def create_lalr_parser(lexer_conf: LexerConf, parser_conf: ParserConf, options=None) -> LALR_Parser:
|
| 158 |
+
debug = options.debug if options else False
|
| 159 |
+
strict = options.strict if options else False
|
| 160 |
+
cls = (options and options._plugins.get('LALR_Parser')) or LALR_Parser
|
| 161 |
+
return cls(parser_conf, debug=debug, strict=strict)
|
| 162 |
+
|
| 163 |
+
_parser_creators['lalr'] = create_lalr_parser
|
| 164 |
+
|
| 165 |
+
###}
|
| 166 |
+
|
| 167 |
+
class EarleyRegexpMatcher:
|
| 168 |
+
def __init__(self, lexer_conf):
|
| 169 |
+
self.regexps = {}
|
| 170 |
+
for t in lexer_conf.terminals:
|
| 171 |
+
regexp = t.pattern.to_regexp()
|
| 172 |
+
try:
|
| 173 |
+
width = get_regexp_width(regexp)[0]
|
| 174 |
+
except ValueError:
|
| 175 |
+
raise GrammarError("Bad regexp in token %s: %s" % (t.name, regexp))
|
| 176 |
+
else:
|
| 177 |
+
if width == 0:
|
| 178 |
+
raise GrammarError("Dynamic Earley doesn't allow zero-width regexps", t)
|
| 179 |
+
if lexer_conf.use_bytes:
|
| 180 |
+
regexp = regexp.encode('utf-8')
|
| 181 |
+
|
| 182 |
+
self.regexps[t.name] = lexer_conf.re_module.compile(regexp, lexer_conf.g_regex_flags)
|
| 183 |
+
|
| 184 |
+
def match(self, term, text, index=0):
|
| 185 |
+
return self.regexps[term.name].match(text, index)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def create_earley_parser__dynamic(lexer_conf: LexerConf, parser_conf: ParserConf, **kw):
|
| 189 |
+
if lexer_conf.callbacks:
|
| 190 |
+
raise GrammarError("Earley's dynamic lexer doesn't support lexer_callbacks.")
|
| 191 |
+
|
| 192 |
+
earley_matcher = EarleyRegexpMatcher(lexer_conf)
|
| 193 |
+
return xearley.Parser(lexer_conf, parser_conf, earley_matcher.match, **kw)
|
| 194 |
+
|
| 195 |
+
def _match_earley_basic(term, token):
|
| 196 |
+
return term.name == token.type
|
| 197 |
+
|
| 198 |
+
def create_earley_parser__basic(lexer_conf: LexerConf, parser_conf: ParserConf, **kw):
|
| 199 |
+
return earley.Parser(lexer_conf, parser_conf, _match_earley_basic, **kw)
|
| 200 |
+
|
| 201 |
+
def create_earley_parser(lexer_conf: LexerConf, parser_conf: ParserConf, options) -> earley.Parser:
|
| 202 |
+
resolve_ambiguity = options.ambiguity == 'resolve'
|
| 203 |
+
debug = options.debug if options else False
|
| 204 |
+
tree_class = options.tree_class or Tree if options.ambiguity != 'forest' else None
|
| 205 |
+
|
| 206 |
+
extra = {}
|
| 207 |
+
if lexer_conf.lexer_type == 'dynamic':
|
| 208 |
+
f = create_earley_parser__dynamic
|
| 209 |
+
elif lexer_conf.lexer_type == 'dynamic_complete':
|
| 210 |
+
extra['complete_lex'] = True
|
| 211 |
+
f = create_earley_parser__dynamic
|
| 212 |
+
else:
|
| 213 |
+
f = create_earley_parser__basic
|
| 214 |
+
|
| 215 |
+
return f(lexer_conf, parser_conf, resolve_ambiguity=resolve_ambiguity,
|
| 216 |
+
debug=debug, tree_class=tree_class, ordered_sets=options.ordered_sets, **extra)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class CYK_FrontEnd:
|
| 221 |
+
def __init__(self, lexer_conf, parser_conf, options=None):
|
| 222 |
+
self.parser = cyk.Parser(parser_conf.rules)
|
| 223 |
+
|
| 224 |
+
self.callbacks = parser_conf.callbacks
|
| 225 |
+
|
| 226 |
+
def parse(self, lexer_thread, start):
|
| 227 |
+
tokens = list(lexer_thread.lex(None))
|
| 228 |
+
tree = self.parser.parse(tokens, start)
|
| 229 |
+
return self._transform(tree)
|
| 230 |
+
|
| 231 |
+
def _transform(self, tree):
|
| 232 |
+
subtrees = list(tree.iter_subtrees())
|
| 233 |
+
for subtree in subtrees:
|
| 234 |
+
subtree.children = [self._apply_callback(c) if isinstance(c, Tree) else c for c in subtree.children]
|
| 235 |
+
|
| 236 |
+
return self._apply_callback(tree)
|
| 237 |
+
|
| 238 |
+
def _apply_callback(self, tree):
|
| 239 |
+
return self.callbacks[tree.rule](tree.children)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
_parser_creators['earley'] = create_earley_parser
|
| 243 |
+
_parser_creators['cyk'] = CYK_FrontEnd
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _construct_parsing_frontend(
|
| 247 |
+
parser_type: _ParserArgType,
|
| 248 |
+
lexer_type: _LexerArgType,
|
| 249 |
+
lexer_conf,
|
| 250 |
+
parser_conf,
|
| 251 |
+
options
|
| 252 |
+
):
|
| 253 |
+
assert isinstance(lexer_conf, LexerConf)
|
| 254 |
+
assert isinstance(parser_conf, ParserConf)
|
| 255 |
+
parser_conf.parser_type = parser_type
|
| 256 |
+
lexer_conf.lexer_type = lexer_type
|
| 257 |
+
return ParsingFrontend(lexer_conf, parser_conf, options)
|
vllm/lib/python3.10/site-packages/lark/parsers/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (162 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/cyk.cpython-310.pyc
ADDED
|
Binary file (13.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/earley.cpython-310.pyc
ADDED
|
Binary file (8.82 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/earley_common.cpython-310.pyc
ADDED
|
Binary file (1.93 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/earley_forest.cpython-310.pyc
ADDED
|
Binary file (30.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/grammar_analysis.cpython-310.pyc
ADDED
|
Binary file (7.66 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/lark/parsers/__pycache__/lalr_analysis.cpython-310.pyc
ADDED
|
Binary file (11.6 kB). View file
|
|
|