-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathformatvalues.py
More file actions
251 lines (220 loc) · 8.02 KB
/
formatvalues.py
File metadata and controls
251 lines (220 loc) · 8.02 KB
1
2
3
4
5
6
7
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# -*- coding: utf-8 -*-
"""
This module contains basic low-level functions that combine an ``Expression``
with an ``Evaluation`` objects to produce ``BoxExpressions``, following
formatting rules.
"""
from typing import Any, Callable, Dict, List, Optional, Type
from mathics.core.atoms import Complex, Integer, Rational, String, SymbolI
from mathics.core.convert.expression import to_expression_with_specialization
from mathics.core.element import BaseElement, EvalMixin
from mathics.core.evaluation import Evaluation
from mathics.core.expression import Expression
from mathics.core.list import ListExpression
from mathics.core.symbols import (
Atom,
Symbol,
SymbolDivide,
SymbolFullForm,
SymbolGraphics,
SymbolGraphics3D,
SymbolHoldForm,
SymbolList,
SymbolNumberForm,
SymbolPlus,
SymbolPostfix,
SymbolRepeated,
SymbolRepeatedNull,
SymbolTimes,
)
from mathics.core.systemsymbols import SymbolMinus
# These Strings are used in Boxing output
StringElipsis = String("...")
StringLParen = String("(")
StringRParen = String(")")
StringRepeated = String("..")
# do_format_*
_element_formatters: Dict[
Type[BaseElement],
Callable[[BaseElement, Evaluation, Symbol, Optional[str]], Optional[BaseElement]],
] = {}
def do_format(
element: BaseElement,
evaluation: Evaluation,
form: Symbol,
encoding: Optional[str] = None,
) -> BaseElement:
do_format_method = _element_formatters.get(type(element), do_format_element)
result = do_format_method(element, evaluation, form, encoding)
if result is None:
return element
return result
def do_format_element(
element: BaseElement,
evaluation: Evaluation,
form: Symbol,
encoding: Optional[str] = None,
) -> Optional[BaseElement]:
"""
Applies formats associated to the expression and removes
superfluous enclosing formats.
"""
from mathics.core.definitions import OUTPUT_FORMS
head: BaseElement
evaluation.inc_recursion_depth()
try:
expr = element
head = element.get_head() # use element.head
elements = element.get_elements()
include_form = False
# If the expression is enclosed by a Format
# takes the form from the expression and
# removes the format from the expression.
if head in OUTPUT_FORMS and len(elements) == 1 and isinstance(head, Symbol):
expr = elements[0]
if not form.sameQ(head):
form = head
include_form = True
# If form is Fullform, return it without changes
if form is SymbolFullForm:
if include_form:
expr = Expression(form, expr)
return expr
# Repeated and RepeatedNull confuse the formatter,
# so we need to hardlink their format rules:
if head is SymbolRepeated:
if len(elements) == 1:
return Expression(
SymbolHoldForm,
Expression(
SymbolPostfix,
ListExpression(elements[0]),
StringRepeated,
Integer(170),
),
)
else:
return Expression(SymbolHoldForm, expr)
elif head is SymbolRepeatedNull:
if len(elements) == 1:
return Expression(
SymbolHoldForm,
Expression(
SymbolPostfix,
Expression(SymbolList, elements[0]),
StringElipsis,
Integer(170),
),
)
else:
return Expression(SymbolHoldForm, expr)
# If expr is not an atom, looks for formats in its definition
# and apply them.
def format_expr(expr):
if not (isinstance(expr, Atom)) and not (isinstance(expr.head, Atom)):
# expr is of the form f[...][...]
return None
name = expr.get_lookup_name()
format_rules = evaluation.definitions.get_formats(name, form.get_name())
for rule in format_rules:
result = rule.apply(expr, evaluation)
if result is not None and result != expr:
return result.evaluate(evaluation)
return None
formatted = format_expr(expr) if isinstance(expr, EvalMixin) else None
if formatted is not None:
do_format_fn = _element_formatters.get(type(formatted), do_format_element)
result = do_format_fn(formatted, evaluation, form, encoding)
if include_form and result is not None:
result = Expression(form, result)
return result
# If the expression is still enclosed by a Format,
# iterate.
# If the expression is not atomic or of certain
# specific cases, iterate over the elements.
head = expr.get_head()
if head in OUTPUT_FORMS:
# If the expression was of the form
# Form[expr, opts]
# then the format was not stripped. Then,
# just return it as it is.
if len(expr.get_elements()) != 1:
return expr
do_format_fn = _element_formatters.get(type(element), do_format_element)
result = do_format_fn(expr, evaluation, form, encoding)
if isinstance(result, Expression):
expr = result
elif (
head is not SymbolNumberForm
and isinstance(expr, Expression)
and head not in (SymbolGraphics, SymbolGraphics3D)
):
new_elements = tuple(
(
_element_formatters.get(type(element), do_format_element)(
element, evaluation, form, encoding
)
for element in expr.elements
)
)
expr_head = expr.head
do_format = _element_formatters.get(type(expr_head), do_format_element)
head = do_format(expr_head, evaluation, form, encoding) or expr_head
expr = to_expression_with_specialization(head, *new_elements)
if include_form:
expr = Expression(form, expr)
return expr
finally:
evaluation.dec_recursion_depth()
def do_format_rational(
element: BaseElement,
evaluation: Evaluation,
form: Symbol,
encoding: Optional[str] = None,
) -> Optional[BaseElement]:
if not isinstance(element, Rational):
return None
result: BaseElement
numerator = element.numerator()
minus = numerator.value < 0
if minus:
numerator = Integer(-numerator.value)
result = Expression(SymbolDivide, numerator, element.denominator())
if minus:
result = Expression(SymbolMinus, result)
result = Expression(SymbolHoldForm, result)
result = do_format_expression(result, evaluation, form, encoding) or result
return result
def do_format_complex(
element: BaseElement,
evaluation: Evaluation,
form: Symbol,
encoding: Optional[str] = None,
) -> Optional[BaseElement]:
if not isinstance(element, Complex):
return None
parts: List[Any] = []
if element.is_machine_precision() or not element.real.is_zero:
parts.append(element.real)
if element.imag.sameQ(Integer(1)):
parts.append(SymbolI)
else:
parts.append(Expression(SymbolTimes, element.imag, SymbolI))
if len(parts) == 1:
result = parts[0]
else:
result = Expression(SymbolPlus, *parts)
return do_format_expression(
Expression(SymbolHoldForm, result), evaluation, form, encoding
)
def do_format_expression(
element: BaseElement,
evaluation: Evaluation,
form: Symbol,
encoding: Optional[str] = None,
) -> BaseElement:
expr = do_format_element(element, evaluation, form, encoding) or element
return expr
_element_formatters[Rational] = do_format_rational
_element_formatters[Complex] = do_format_complex
_element_formatters[Expression] = do_format_expression