1# actions.py
2from __future__ import annotations
3
4from typing import Union, Callable, Any
5
6from .exceptions import ParseException
7from .util import col, replaced_by_pep8
8from .results import ParseResults
9
10
11ParseAction = Union[
12 Callable[[], Any],
13 Callable[[ParseResults], Any],
14 Callable[[int, ParseResults], Any],
15 Callable[[str, int, ParseResults], Any],
16]
17
18
19class OnlyOnce:
20 """
21 Wrapper for parse actions, to ensure they are only called once.
22 Note: parse action signature must include all 3 arguments.
23 """
24
25 def __init__(self, method_call: Callable[[str, int, ParseResults], Any]) -> None:
26 from .core import _trim_arity
27
28 self.callable = _trim_arity(method_call)
29 self.called = False
30
31 def __call__(self, s: str, l: int, t: ParseResults) -> ParseResults:
32 if not self.called:
33 results = self.callable(s, l, t)
34 self.called = True
35 return results
36 raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset")
37
38 def reset(self):
39 """
40 Allow the associated parse action to be called once more.
41 """
42
43 self.called = False
44
45
46def match_only_at_col(n: int) -> ParseAction:
47 """
48 Helper method for defining parse actions that require matching at
49 a specific column in the input text.
50 """
51
52 def verify_col(strg: str, locn: int, toks: ParseResults) -> None:
53 if col(locn, strg) != n:
54 raise ParseException(strg, locn, f"matched token not at column {n}")
55
56 return verify_col
57
58
59def replace_with(repl_str: str) -> ParseAction:
60 """
61 Helper method for common parse actions that simply return
62 a literal value. Especially useful when used with
63 :class:`transform_string<ParserElement.transform_string>` ().
64
65 Example::
66
67 num = Word(nums).set_parse_action(lambda toks: int(toks[0]))
68 na = one_of("N/A NA").set_parse_action(replace_with(math.nan))
69 term = na | num
70
71 term[1, ...].parse_string("324 234 N/A 234") # -> [324, 234, nan, 234]
72 """
73 return lambda s, l, t: [repl_str]
74
75
76def remove_quotes(s: str, l: int, t: ParseResults) -> Any:
77 """
78 Helper parse action for removing quotation marks from parsed
79 quoted strings.
80
81 Example::
82
83 # by default, quotation marks are included in parsed results
84 quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
85
86 # use remove_quotes to strip quotation marks from parsed results
87 quoted_string.set_parse_action(remove_quotes)
88 quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
89 """
90 return t[0][1:-1]
91
92
93def with_attribute(*args: tuple[str, str], **attr_dict) -> ParseAction:
94 """
95 Helper to create a validating parse action to be used with start
96 tags created with :class:`make_xml_tags` or
97 :class:`make_html_tags`. Use ``with_attribute`` to qualify
98 a starting tag with a required attribute value, to avoid false
99 matches on common tags such as ``<TD>`` or ``<DIV>``.
100
101 Call ``with_attribute`` with a series of attribute names and
102 values. Specify the list of filter attributes names and values as:
103
104 - keyword arguments, as in ``(align="right")``, or
105 - as an explicit dict with ``**`` operator, when an attribute
106 name is also a Python reserved word, as in ``**{"class":"Customer", "align":"right"}``
107 - a list of name-value tuples, as in ``(("ns1:class", "Customer"), ("ns2:align", "right"))``
108
109 For attribute names with a namespace prefix, you must use the second
110 form. Attribute names are matched insensitive to upper/lower case.
111
112 If just testing for ``class`` (with or without a namespace), use
113 :class:`with_class`.
114
115 To verify that the attribute exists, but without specifying a value,
116 pass ``with_attribute.ANY_VALUE`` as the value.
117
118 Example::
119
120 html = '''
121 <div>
122 Some text
123 <div type="grid">1 4 0 1 0</div>
124 <div type="graph">1,3 2,3 1,1</div>
125 <div>this has no type</div>
126 </div>
127 '''
128 div,div_end = make_html_tags("div")
129
130 # only match div tag having a type attribute with value "grid"
131 div_grid = div().set_parse_action(with_attribute(type="grid"))
132 grid_expr = div_grid + SkipTo(div | div_end)("body")
133 for grid_header in grid_expr.search_string(html):
134 print(grid_header.body)
135
136 # construct a match with any div tag having a type attribute, regardless of the value
137 div_any_type = div().set_parse_action(with_attribute(type=with_attribute.ANY_VALUE))
138 div_expr = div_any_type + SkipTo(div | div_end)("body")
139 for div_header in div_expr.search_string(html):
140 print(div_header.body)
141
142 prints::
143
144 1 4 0 1 0
145
146 1 4 0 1 0
147 1,3 2,3 1,1
148 """
149 attrs_list: list[tuple[str, str]] = []
150 if args:
151 attrs_list.extend(args)
152 else:
153 attrs_list.extend(attr_dict.items())
154
155 def pa(s: str, l: int, tokens: ParseResults) -> None:
156 for attrName, attrValue in attrs_list:
157 if attrName not in tokens:
158 raise ParseException(s, l, "no matching attribute " + attrName)
159 if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue: # type: ignore [attr-defined]
160 raise ParseException(
161 s,
162 l,
163 f"attribute {attrName!r} has value {tokens[attrName]!r}, must be {attrValue!r}",
164 )
165
166 return pa
167
168
169with_attribute.ANY_VALUE = object() # type: ignore [attr-defined]
170
171
172def with_class(classname: str, namespace: str = "") -> ParseAction:
173 """
174 Simplified version of :class:`with_attribute` when
175 matching on a div class - made difficult because ``class`` is
176 a reserved word in Python.
177
178 Example::
179
180 html = '''
181 <div>
182 Some text
183 <div class="grid">1 4 0 1 0</div>
184 <div class="graph">1,3 2,3 1,1</div>
185 <div>this <div> has no class</div>
186 </div>
187
188 '''
189 div,div_end = make_html_tags("div")
190 div_grid = div().set_parse_action(with_class("grid"))
191
192 grid_expr = div_grid + SkipTo(div | div_end)("body")
193 for grid_header in grid_expr.search_string(html):
194 print(grid_header.body)
195
196 div_any_type = div().set_parse_action(with_class(withAttribute.ANY_VALUE))
197 div_expr = div_any_type + SkipTo(div | div_end)("body")
198 for div_header in div_expr.search_string(html):
199 print(div_header.body)
200
201 prints::
202
203 1 4 0 1 0
204
205 1 4 0 1 0
206 1,3 2,3 1,1
207 """
208 classattr = f"{namespace}:class" if namespace else "class"
209 return with_attribute(**{classattr: classname})
210
211
212# Compatibility synonyms
213# fmt: off
214replaceWith = replaced_by_pep8("replaceWith", replace_with)
215removeQuotes = replaced_by_pep8("removeQuotes", remove_quotes)
216withAttribute = replaced_by_pep8("withAttribute", with_attribute)
217withClass = replaced_by_pep8("withClass", with_class)
218matchOnlyAtCol = replaced_by_pep8("matchOnlyAtCol", match_only_at_col)
219# fmt: on