Decorator to turn a function into a Control class.
When the result is activated (by calling it), we will call the
wrapped function. The name and docstring of the result will be
the same as those of the function.
The result can be made queryable using its "on_query" method;
see the docstring for that method for details.
The args for the wrapped function act differently based on their
names and their annotations. Control.get_arguments_from_parser()
has the canonical explanation of this, but here's an overview.
The parameters are evaluated in order from left to right.
If there's no type annotation, the name of the parameter could be:
- parser: this receives the Parser.
- doc: this receives the Document.
- optional_equals: this consumes "=" if it's the next symbol,
and receives it; if it's not the next symbol, it receives
the empty string.
- reading_all_args, querying_all_args, executing_all_args: if
the next symbol begins a group, these receive the concatenation
of the string values of all symbols in that group. Otherwise,
they receive the string value of the next symbol. The
parser are parsed at the level named in the parameter name.
Any other name raises WeirdControlNameError.
However, if the parameter is annotated with a type, the behaviour
depends on what that type is:
- Value (including Number and Dimen), Filename, Gismo: the
relevant symbol is constructed from the input stream.
- int: as if Number had been specified, except that the result
is immediately cast to an int.
- Token (or any subclass), Control (or any subclass): receives
the next symbol, which must belong to the class specified.
- Location: receives the current location. Nothing is consumed.
Otherwise, we raise WeirdControlNameError.
All args for the decorator itself are set directly on the result.
Some of them also have other effects.
- vertical, horizontal, math: True if the control can be run in
this mode; False if it can't; otherwise, running this control
in the given mode will cause a mode switch, and this is a str
naming the mode to switch to
- conditional (bool): if True, this control affects control flow
- expandable (bool): if True, the result will descend from Expandable;
if False, which is the default, it will descend from
Unexpandable.
- push_result (bool): if True, which is the default, the result
of the wrapped function will be pushed back, and the call
to the control will return None; if False, no push will
be made and the call will return whatever the wrapped function
returned.
- even_if_not_expanding (bool): if True, this control will be run
even if we're currently not running controls in general--
for example, straight after we've seen "\iffalse".
Use with care.
Source code in yex/decorator.py
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223 | def control(
**kwargs,
):
r"""
Decorator to turn a function into a Control class.
When the result is activated (by calling it), we will call the
wrapped function. The name and docstring of the result will be
the same as those of the function.
The result can be made queryable using its "on_query" method;
see the docstring for that method for details.
The args for the wrapped function act differently based on their
names and their annotations. Control.get_arguments_from_parser()
has the canonical explanation of this, but here's an overview.
The parameters are evaluated in order from left to right.
If there's no type annotation, the name of the parameter could be:
- parser: this receives the Parser.
- doc: this receives the Document.
- optional_equals: this consumes "=" if it's the next symbol,
and receives it; if it's not the next symbol, it receives
the empty string.
- reading_all_args, querying_all_args, executing_all_args: if
the next symbol begins a group, these receive the concatenation
of the string values of all symbols in that group. Otherwise,
they receive the string value of the next symbol. The
parser are parsed at the level named in the parameter name.
Any other name raises WeirdControlNameError.
However, if the parameter is annotated with a type, the behaviour
depends on what that type is:
- Value (including Number and Dimen), Filename, Gismo: the
relevant symbol is constructed from the input stream.
- int: as if Number had been specified, except that the result
is immediately cast to an int.
- Token (or any subclass), Control (or any subclass): receives
the next symbol, which must belong to the class specified.
- Location: receives the current location. Nothing is consumed.
Otherwise, we raise WeirdControlNameError.
All args for the decorator itself are set directly on the result.
Some of them also have other effects.
- vertical, horizontal, math: True if the control can be run in
this mode; False if it can't; otherwise, running this control
in the given mode will cause a mode switch, and this is a str
naming the mode to switch to
- conditional (bool): if True, this control affects control flow
- expandable (bool): if True, the result will descend from Expandable;
if False, which is the default, it will descend from
Unexpandable.
- push_result (bool): if True, which is the default, the result
of the wrapped function will be pushed back, and the call
to the control will return None; if False, no push will
be made and the call will return whatever the wrapped function
returned.
- even_if_not_expanding (bool): if True, this control will be run
even if we're currently not running controls in general--
for example, straight after we've seen "\iffalse".
Use with care.
"""
PARAMS = {
'vertical': True,
'horizontal': True,
'math': True,
'expandable': False,
'even_if_not_expanding': False,
'push_result': True,
'conditional': False,
}
for k in kwargs.keys():
if k not in PARAMS:
raise ValueError(
f"yex.decorator.control has no {k} param")
def _control(fn: Callable):
r"""
Transformer from function to wrapped control.
See the docstring of the parent class for why and how.
Args:
fn (function): a function
Returns:
a Control wrapping that function.
"""
from yex.control.control import Expandable, Unexpandable
def native_to_yex(item: Any):
r"""
Turns ints and floats into Numbers.
Passes everything else through unchanged.
"""
import yex.value
if isinstance(item, (int, float)):
return yex.value.Number(item)
else:
return item
if kwargs.get('expandable', False):
parent_class = Expandable
else:
parent_class = Unexpandable
argspec = inspect.getfullargspec(fn)
class _Control(parent_class):
"""
A control to wrap a function.
"""
# attributes in PARAMS are set just after this class definition
def __init__(self, *fn_args, **fn_kwargs):
super().__init__(*fn_args, **fn_kwargs)
def __call__(self, parser: 'yex.parse.Parser'):
try:
fn_args = _argspec_to_fn_args(argspec, parser,
self_object = None,
)
except yex.exception.WeirdControlAnnotationError as e:
e['control'] = fn.__name__
raise
received = fn(*fn_args)
logger.debug("%s: result: %s", self, received)
if received is None:
pass
elif not kwargs.get('push_result', True):
logger.debug(
"%s: -- push_result is False; returning that",
self)
elif isinstance(received, list):
for item in reversed(received):
parser.push(native_to_yex(item),
is_result=True,
)
return None
else:
parser.push(native_to_yex(received),
is_result=True,
)
return None
return received
@classmethod
def on_query(cls):
"""
Decorator to make a class of controls queryable.
The decorated function becomes the query() function
of the class, and the class's is_queryable flag is
set to True.
The parameters of the wrapped function are interpreted
in the same way as in the parent decorator.
"""
import yex
def _prep_control_object(fn):
argspec = inspect.getfullargspec(fn)
def do_query(self, parser: 'yex.parse.Parser'):
try:
fn_args = _argspec_to_fn_args(argspec, parser,
self_object = None,
)
except yex.exception.YexParseError as ype:
ype.mark_as_possible_rvalue(self)
raise
return fn(*fn_args)
nonlocal cls
cls.query = do_query
cls.is_queryable = True
return cls
return _prep_control_object
def __repr__(self):
return '[\\'+fn.__name__.lower()+']'
for f,v in PARAMS.items():
setattr(_Control, f,
kwargs.get(f, v))
fields = dict(vars(_Control))
for field in ['__module__', '__doc__']:
fields[field] = getattr(fn, field)
_Control = type(
fn.__name__.title(),
tuple(_Control.mro()),
fields,
)
return _Control
return _control
|