7802ff158d83eb88e6dbe78d9cd33ca14341662a
[SubU] /
1 # module pyparsing.py
2 #
3 # Copyright (c) 2003-2022  Paul T. McGuire
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining
6 # a copy of this software and associated documentation files (the
7 # "Software"), to deal in the Software without restriction, including
8 # without limitation the rights to use, copy, modify, merge, publish,
9 # distribute, sublicense, and/or sell copies of the Software, and to
10 # permit persons to whom the Software is furnished to do so, subject to
11 # the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be
14 # included in all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #
24
25 __doc__ = """
26 pyparsing module - Classes and methods to define and execute parsing grammars
27 =============================================================================
28
29 The pyparsing module is an alternative approach to creating and
30 executing simple grammars, vs. the traditional lex/yacc approach, or the
31 use of regular expressions.  With pyparsing, you don't need to learn
32 a new syntax for defining grammars or matching expressions - the parsing
33 module provides a library of classes that you use to construct the
34 grammar directly in Python.
35
36 Here is a program to parse "Hello, World!" (or any greeting of the form
37 ``"<salutation>, <addressee>!"``), built up using :class:`Word`,
38 :class:`Literal`, and :class:`And` elements
39 (the :meth:`'+'<ParserElement.__add__>` operators create :class:`And` expressions,
40 and the strings are auto-converted to :class:`Literal` expressions)::
41
42     from pyparsing import Word, alphas
43
44     # define grammar of a greeting
45     greet = Word(alphas) + "," + Word(alphas) + "!"
46
47     hello = "Hello, World!"
48     print(hello, "->", greet.parse_string(hello))
49
50 The program outputs the following::
51
52     Hello, World! -> ['Hello', ',', 'World', '!']
53
54 The Python representation of the grammar is quite readable, owing to the
55 self-explanatory class names, and the use of :class:`'+'<And>`,
56 :class:`'|'<MatchFirst>`, :class:`'^'<Or>` and :class:`'&'<Each>` operators.
57
58 The :class:`ParseResults` object returned from
59 :class:`ParserElement.parseString` can be
60 accessed as a nested list, a dictionary, or an object with named
61 attributes.
62
63 The pyparsing module handles some of the problems that are typically
64 vexing when writing text parsers:
65
66   - extra or missing whitespace (the above program will also handle
67     "Hello,World!", "Hello  ,  World  !", etc.)
68   - quoted strings
69   - embedded comments
70
71
72 Getting Started -
73 -----------------
74 Visit the classes :class:`ParserElement` and :class:`ParseResults` to
75 see the base classes that most other pyparsing
76 classes inherit from. Use the docstrings for examples of how to:
77
78  - construct literal match expressions from :class:`Literal` and
79    :class:`CaselessLiteral` classes
80  - construct character word-group expressions using the :class:`Word`
81    class
82  - see how to create repetitive expressions using :class:`ZeroOrMore`
83    and :class:`OneOrMore` classes
84  - use :class:`'+'<And>`, :class:`'|'<MatchFirst>`, :class:`'^'<Or>`,
85    and :class:`'&'<Each>` operators to combine simple expressions into
86    more complex ones
87  - associate names with your parsed results using
88    :class:`ParserElement.setResultsName`
89  - access the parsed data, which is returned as a :class:`ParseResults`
90    object
91  - find some helpful expression short-cuts like :class:`delimitedList`
92    and :class:`oneOf`
93  - find more useful common expressions in the :class:`pyparsing_common`
94    namespace class
95 """
96 from typing import NamedTuple
97
98
99 class version_info(NamedTuple):
100     major: int
101     minor: int
102     micro: int
103     releaselevel: str
104     serial: int
105
106     @property
107     def __version__(self):
108         return (
109             "{}.{}.{}".format(self.major, self.minor, self.micro)
110             + (
111                 "{}{}{}".format(
112                     "r" if self.releaselevel[0] == "c" else "",
113                     self.releaselevel[0],
114                     self.serial,
115                 ),
116                 "",
117             )[self.releaselevel == "final"]
118         )
119
120     def __str__(self):
121         return "{} {} / {}".format(__name__, self.__version__, __version_time__)
122
123     def __repr__(self):
124         return "{}.{}({})".format(
125             __name__,
126             type(self).__name__,
127             ", ".join("{}={!r}".format(*nv) for nv in zip(self._fields, self)),
128         )
129
130
131 __version_info__ = version_info(3, 0, 9, "final", 0)
132 __version_time__ = "05 May 2022 07:02 UTC"
133 __version__ = __version_info__.__version__
134 __versionTime__ = __version_time__
135 __author__ = "Paul McGuire <ptmcg.gm+pyparsing@gmail.com>"
136
137 from .util import *
138 from .exceptions import *
139 from .actions import *
140 from .core import __diag__, __compat__
141 from .results import *
142 from .core import *
143 from .core import _builtin_exprs as core_builtin_exprs
144 from .helpers import *
145 from .helpers import _builtin_exprs as helper_builtin_exprs
146
147 from .unicode import unicode_set, UnicodeRangeList, pyparsing_unicode as unicode
148 from .testing import pyparsing_test as testing
149 from .common import (
150     pyparsing_common as common,
151     _builtin_exprs as common_builtin_exprs,
152 )
153
154 # define backward compat synonyms
155 if "pyparsing_unicode" not in globals():
156     pyparsing_unicode = unicode
157 if "pyparsing_common" not in globals():
158     pyparsing_common = common
159 if "pyparsing_test" not in globals():
160     pyparsing_test = testing
161
162 core_builtin_exprs += common_builtin_exprs + helper_builtin_exprs
163
164
165 __all__ = [
166     "__version__",
167     "__version_time__",
168     "__author__",
169     "__compat__",
170     "__diag__",
171     "And",
172     "AtLineStart",
173     "AtStringStart",
174     "CaselessKeyword",
175     "CaselessLiteral",
176     "CharsNotIn",
177     "Combine",
178     "Dict",
179     "Each",
180     "Empty",
181     "FollowedBy",
182     "Forward",
183     "GoToColumn",
184     "Group",
185     "IndentedBlock",
186     "Keyword",
187     "LineEnd",
188     "LineStart",
189     "Literal",
190     "Located",
191     "PrecededBy",
192     "MatchFirst",
193     "NoMatch",
194     "NotAny",
195     "OneOrMore",
196     "OnlyOnce",
197     "OpAssoc",
198     "Opt",
199     "Optional",
200     "Or",
201     "ParseBaseException",
202     "ParseElementEnhance",
203     "ParseException",
204     "ParseExpression",
205     "ParseFatalException",
206     "ParseResults",
207     "ParseSyntaxException",
208     "ParserElement",
209     "PositionToken",
210     "QuotedString",
211     "RecursiveGrammarException",
212     "Regex",
213     "SkipTo",
214     "StringEnd",
215     "StringStart",
216     "Suppress",
217     "Token",
218     "TokenConverter",
219     "White",
220     "Word",
221     "WordEnd",
222     "WordStart",
223     "ZeroOrMore",
224     "Char",
225     "alphanums",
226     "alphas",
227     "alphas8bit",
228     "any_close_tag",
229     "any_open_tag",
230     "c_style_comment",
231     "col",
232     "common_html_entity",
233     "counted_array",
234     "cpp_style_comment",
235     "dbl_quoted_string",
236     "dbl_slash_comment",
237     "delimited_list",
238     "dict_of",
239     "empty",
240     "hexnums",
241     "html_comment",
242     "identchars",
243     "identbodychars",
244     "java_style_comment",
245     "line",
246     "line_end",
247     "line_start",
248     "lineno",
249     "make_html_tags",
250     "make_xml_tags",
251     "match_only_at_col",
252     "match_previous_expr",
253     "match_previous_literal",
254     "nested_expr",
255     "null_debug_action",
256     "nums",
257     "one_of",
258     "printables",
259     "punc8bit",
260     "python_style_comment",
261     "quoted_string",
262     "remove_quotes",
263     "replace_with",
264     "replace_html_entity",
265     "rest_of_line",
266     "sgl_quoted_string",
267     "srange",
268     "string_end",
269     "string_start",
270     "trace_parse_action",
271     "unicode_string",
272     "with_attribute",
273     "indentedBlock",
274     "original_text_for",
275     "ungroup",
276     "infix_notation",
277     "locatedExpr",
278     "with_class",
279     "CloseMatch",
280     "token_map",
281     "pyparsing_common",
282     "pyparsing_unicode",
283     "unicode_set",
284     "condition_as_parse_action",
285     "pyparsing_test",
286     # pre-PEP8 compatibility names
287     "__versionTime__",
288     "anyCloseTag",
289     "anyOpenTag",
290     "cStyleComment",
291     "commonHTMLEntity",
292     "countedArray",
293     "cppStyleComment",
294     "dblQuotedString",
295     "dblSlashComment",
296     "delimitedList",
297     "dictOf",
298     "htmlComment",
299     "javaStyleComment",
300     "lineEnd",
301     "lineStart",
302     "makeHTMLTags",
303     "makeXMLTags",
304     "matchOnlyAtCol",
305     "matchPreviousExpr",
306     "matchPreviousLiteral",
307     "nestedExpr",
308     "nullDebugAction",
309     "oneOf",
310     "opAssoc",
311     "pythonStyleComment",
312     "quotedString",
313     "removeQuotes",
314     "replaceHTMLEntity",
315     "replaceWith",
316     "restOfLine",
317     "sglQuotedString",
318     "stringEnd",
319     "stringStart",
320     "traceParseAction",
321     "unicodeString",
322     "withAttribute",
323     "indentedBlock",
324     "originalTextFor",
325     "infixNotation",
326     "locatedExpr",
327     "withClass",
328     "tokenMap",
329     "conditionAsParseAction",
330     "autoname_elements",
331 ]