-
-
Notifications
You must be signed in to change notification settings - Fork 205
Expand file tree
/
Copy pathassignment.py
More file actions
1944 lines (1684 loc) · 55.3 KB
/
Copy pathassignment.py
File metadata and controls
1944 lines (1684 loc) · 55.3 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from mathics.version import __version__ # noqa used in loading to check consistency.
from mathics.builtin.base import (
Builtin,
BinaryOperator,
PostfixOperator,
PrefixOperator,
)
from mathics.core.rules import Rule
from mathics.core.expression import (
Expression,
Symbol,
SymbolFailed,
SymbolNull,
valid_context_name,
system_symbols,
String,
)
from mathics.core.definitions import PyMathicsLoadException
from mathics.builtin.lists import walk_parts
from mathics.core.evaluation import MAX_RECURSION_DEPTH, set_python_recursion_limit
def repl_pattern_by_symbol(expr):
leaves = expr.get_leaves()
if len(leaves) == 0:
return expr
headname = expr.get_head_name()
if headname == "System`Pattern":
return leaves[0]
changed = False
newleaves = []
for leave in leaves:
l = repl_pattern_by_symbol(leave)
if not (l is leave):
changed = True
newleaves.append(l)
if changed:
return Expression(headname, *newleaves)
else:
return expr
def get_symbol_list(list, error_callback):
if list.has_form("List", None):
list = list.leaves
else:
list = [list]
values = []
for item in list:
name = item.get_name()
if name:
values.append(name)
else:
error_callback(item)
return None
return values
class _SetOperator(object):
def assign_elementary(self, lhs, rhs, evaluation, tags=None, upset=False):
# TODO: This function should be splitted and simplified
name = lhs.get_head_name()
lhs._format_cache = None
condition = None
# Maybe these first conversions should be a loop...
if name == "System`Condition" and len(lhs.leaves) == 2:
# This handle the case of many sucesive conditions:
# f[x_]/; cond1 /; cond2 ...
# is summarized to a single condition
# f[x_]/; And[cond1, cond2, ...]
condition = [lhs._leaves[1]]
lhs = lhs._leaves[0]
name = lhs.get_head_name()
while name == "System`Condition" and len(lhs.leaves) == 2:
condition.append(lhs._leaves[1])
lhs = lhs._leaves[0]
name = lhs.get_head_name()
if len(condition) > 1:
condition = Expression("System`And", *condition)
else:
condition = condition[0]
condition = Expression("System`Condition", lhs, condition)
name = lhs.get_head_name()
lhs._format_cache = None
if name == "System`Pattern":
lhsleaves = lhs.get_leaves()
lhs = lhsleaves[1]
rulerepl = (lhsleaves[0], repl_pattern_by_symbol(lhs))
rhs, status = rhs.apply_rules([Rule(*rulerepl)], evaluation)
name = lhs.get_head_name()
if name == "System`HoldPattern":
lhs = lhs.leaves[0]
name = lhs.get_head_name()
if name in system_symbols(
"OwnValues",
"DownValues",
"SubValues",
"UpValues",
"NValues",
"Options",
"DefaultValues",
"Attributes",
"Messages",
):
if len(lhs.leaves) != 1:
evaluation.message_args(name, len(lhs.leaves), 1)
return False
tag = lhs.leaves[0].get_name()
if not tag:
evaluation.message(name, "sym", lhs.leaves[0], 1)
return False
if tags is not None and tags != [tag]:
evaluation.message(name, "tag", Symbol(name), Symbol(tag))
return False
if (
name != "System`Attributes"
and "System`Protected" # noqa
in evaluation.definitions.get_attributes(tag)
):
evaluation.message(name, "wrsym", Symbol(tag))
return False
if name == "System`Options":
option_values = rhs.get_option_values(evaluation)
if option_values is None:
evaluation.message(name, "options", rhs)
return False
evaluation.definitions.set_options(tag, option_values)
elif name == "System`Attributes":
attributes = get_symbol_list(
rhs, lambda item: evaluation.message(name, "sym", item, 1)
)
if attributes is None:
return False
if "System`Locked" in evaluation.definitions.get_attributes(tag):
evaluation.message(name, "locked", Symbol(tag))
return False
evaluation.definitions.set_attributes(tag, attributes)
else:
rules = rhs.get_rules_list()
if rules is None:
evaluation.message(name, "vrule", lhs, rhs)
return False
evaluation.definitions.set_values(tag, name, rules)
return True
form = ""
nprec = None
default = False
message = False
allow_custom_tag = False
focus = lhs
if name == "System`N":
if len(lhs.leaves) not in (1, 2):
evaluation.message_args("N", len(lhs.leaves), 1, 2)
return False
if len(lhs.leaves) == 1:
nprec = Symbol("MachinePrecision")
else:
nprec = lhs.leaves[1]
focus = lhs.leaves[0]
lhs = Expression("N", focus, nprec)
elif name == "System`MessageName":
if len(lhs.leaves) != 2:
evaluation.message_args("MessageName", len(lhs.leaves), 2)
return False
focus = lhs.leaves[0]
message = True
elif name == "System`Default":
if len(lhs.leaves) not in (1, 2, 3):
evaluation.message_args("Default", len(lhs.leaves), 1, 2, 3)
return False
focus = lhs.leaves[0]
default = True
elif name == "System`Format":
if len(lhs.leaves) not in (1, 2):
evaluation.message_args("Format", len(lhs.leaves), 1, 2)
return False
if len(lhs.leaves) == 2:
form = lhs.leaves[1].get_name()
if not form:
evaluation.message("Format", "fttp", lhs.leaves[1])
return False
else:
form = system_symbols(
"StandardForm",
"TraditionalForm",
"OutputForm",
"TeXForm",
"MathMLForm",
)
lhs = focus = lhs.leaves[0]
else:
allow_custom_tag = True
focus = focus.evaluate_leaves(evaluation)
if tags is None and not upset:
name = focus.get_lookup_name()
if not name:
evaluation.message(self.get_name(), "setraw", focus)
return False
tags = [name]
elif upset:
if allow_custom_tag:
tags = []
if focus.is_atom():
evaluation.message(self.get_name(), "normal")
return False
for leaf in focus.leaves:
name = leaf.get_lookup_name()
tags.append(name)
else:
tags = [focus.get_lookup_name()]
else:
allowed_names = [focus.get_lookup_name()]
if allow_custom_tag:
for leaf in focus.get_leaves():
if not leaf.is_symbol() and leaf.get_head_name() in (
"System`HoldPattern",
):
leaf = leaf.leaves[0]
if not leaf.is_symbol() and leaf.get_head_name() in (
"System`Pattern",
):
leaf = leaf.leaves[1]
if not leaf.is_symbol() and leaf.get_head_name() in (
"System`Blank",
"System`BlankSequence",
"System`BlankNullSequence",
):
if len(leaf.leaves) == 1:
leaf = leaf.leaves[0]
allowed_names.append(leaf.get_lookup_name())
for name in tags:
if name not in allowed_names:
evaluation.message(self.get_name(), "tagnfd", Symbol(name))
return False
ignore_protection = False
rhs_int_value = rhs.get_int_value()
lhs_name = lhs.get_name()
if lhs_name == "System`$RecursionLimit":
# if (not rhs_int_value or rhs_int_value < 20) and not
# rhs.get_name() == 'System`Infinity':
if (
not rhs_int_value
or rhs_int_value < 20
or rhs_int_value > MAX_RECURSION_DEPTH
): # nopep8
evaluation.message("$RecursionLimit", "limset", rhs)
return False
try:
set_python_recursion_limit(rhs_int_value)
except OverflowError:
# TODO: Message
return False
ignore_protection = True
if lhs_name == "System`$IterationLimit":
if (
not rhs_int_value or rhs_int_value < 20
) and not rhs.get_name() == "System`Infinity":
evaluation.message("$IterationLimit", "limset", rhs)
return False
ignore_protection = True
elif lhs_name == "System`$ModuleNumber":
if not rhs_int_value or rhs_int_value <= 0:
evaluation.message("$ModuleNumber", "set", rhs)
return False
ignore_protection = True
elif lhs_name in ("System`$Line", "System`$HistoryLength"):
if rhs_int_value is None or rhs_int_value < 0:
evaluation.message(lhs_name, "intnn", rhs)
return False
ignore_protection = True
elif lhs_name == "System`$RandomState":
# TODO: allow setting of legal random states!
# (but consider pickle's insecurity!)
evaluation.message("$RandomState", "rndst", rhs)
return False
elif lhs_name == "System`$Context":
new_context = rhs.get_string_value()
if new_context is None or not valid_context_name(
new_context, allow_initial_backquote=True
):
evaluation.message(lhs_name, "cxset", rhs)
return False
# With $Context in Mathematica you can do some strange
# things: e.g. with $Context set to Global`, something
# like:
# $Context = "`test`"; newsym
# is accepted and creates Global`test`newsym.
# Implement this behaviour by interpreting
# $Context = "`test`"
# as
# $Context = $Context <> "test`"
#
if new_context.startswith("`"):
new_context = evaluation.definitions.get_current_context() + new_context.lstrip(
"`"
)
evaluation.definitions.set_current_context(new_context)
ignore_protection = True
return True
elif lhs_name == "System`$ContextPath":
currContext = evaluation.definitions.get_current_context()
context_path = [s.get_string_value() for s in rhs.get_leaves()]
context_path = [
s if (s is None or s[0] != "`") else currContext[:-1] + s
for s in context_path
]
if rhs.has_form("List", None) and all(
valid_context_name(s) for s in context_path
):
evaluation.definitions.set_context_path(context_path)
ignore_protection = True
return True
else:
evaluation.message(lhs_name, "cxlist", rhs)
return False
elif lhs_name == "System`$MinPrecision":
# $MinPrecision = Infinity is not allowed
if rhs_int_value is not None and rhs_int_value >= 0:
ignore_protection = True
max_prec = evaluation.definitions.get_config_value("$MaxPrecision")
if max_prec is not None and max_prec < rhs_int_value:
evaluation.message(
"$MinPrecision", "preccon", Symbol("$MinPrecision")
)
return True
else:
evaluation.message(lhs_name, "precset", lhs, rhs)
return False
elif lhs_name == "System`$MaxPrecision":
if (
rhs.has_form("DirectedInfinity", 1)
and rhs.leaves[0].get_int_value() == 1
):
ignore_protection = True
elif rhs_int_value is not None and rhs_int_value > 0:
ignore_protection = True
min_prec = evaluation.definitions.get_config_value("$MinPrecision")
if min_prec is not None and rhs_int_value < min_prec:
evaluation.message(
"$MaxPrecision", "preccon", Symbol("$MaxPrecision")
)
ignore_protection = True
return True
else:
evaluation.message(lhs_name, "precset", lhs, rhs)
return False
# To Handle `OptionValue` in `Condition`
rulopc = Rule(
Expression(
"OptionValue",
Expression("Pattern", Symbol("$cond$"), Expression("Blank")),
),
Expression("OptionValue", lhs.get_head(), Symbol("$cond$")),
)
rhs_name = rhs.get_head_name()
while rhs_name == "System`Condition":
if len(rhs.leaves) != 2:
evaluation.message_args("Condition", len(rhs.leaves), 2)
return False
else:
lhs = Expression(
"Condition", lhs, rhs.leaves[1].apply_rules([rulopc], evaluation)[0]
)
rhs = rhs.leaves[0]
rhs_name = rhs.get_head_name()
# Now, let's add the conditions on the LHS
if condition:
lhs = Expression(
"Condition",
lhs,
condition.leaves[1].apply_rules([rulopc], evaluation)[0],
)
rule = Rule(lhs, rhs)
count = 0
defs = evaluation.definitions
for tag in tags:
if (
not ignore_protection
and "System`Protected" # noqa
in evaluation.definitions.get_attributes(tag)
):
if lhs.get_name() == tag:
evaluation.message(self.get_name(), "wrsym", Symbol(tag))
else:
evaluation.message(self.get_name(), "write", Symbol(tag), lhs)
continue
count += 1
if form:
defs.add_format(tag, rule, form)
elif nprec:
defs.add_nvalue(tag, rule)
elif default:
defs.add_default(tag, rule)
elif message:
defs.add_message(tag, rule)
else:
if upset:
defs.add_rule(tag, rule, position="up")
else:
defs.add_rule(tag, rule)
if count == 0:
return False
return True
def assign(self, lhs, rhs, evaluation):
lhs._format_cache = None
if lhs.get_head_name() == "System`List":
if not (rhs.get_head_name() == "System`List") or len(lhs.leaves) != len(
rhs.leaves
): # nopep8
evaluation.message(self.get_name(), "shape", lhs, rhs)
return False
else:
result = True
for left, right in zip(lhs.leaves, rhs.leaves):
if not self.assign(left, right, evaluation):
result = False
return result
elif lhs.get_head_name() == "System`Part":
if len(lhs.leaves) < 1:
evaluation.message(self.get_name(), "setp", lhs)
return False
symbol = lhs.leaves[0]
name = symbol.get_name()
if not name:
evaluation.message(self.get_name(), "setps", symbol)
return False
if "System`Protected" in evaluation.definitions.get_attributes(name):
evaluation.message(self.get_name(), "wrsym", symbol)
return False
rule = evaluation.definitions.get_ownvalue(name)
if rule is None:
evaluation.message(self.get_name(), "noval", symbol)
return False
indices = lhs.leaves[1:]
result = walk_parts([rule.replace], indices, evaluation, rhs)
if result:
evaluation.definitions.set_ownvalue(name, result)
else:
return False
else:
return self.assign_elementary(lhs, rhs, evaluation)
class Set(BinaryOperator, _SetOperator):
"""
<dl>
<dt>'Set[$expr$, $value$]'
<dt>$expr$ = $value$
<dd>evaluates $value$ and assigns it to $expr$.
<dt>{$s1$, $s2$, $s3$} = {$v1$, $v2$, $v3$}
<dd>sets multiple symbols ($s1$, $s2$, ...) to the
corresponding values ($v1$, $v2$, ...).
</dl>
'Set' can be used to give a symbol a value:
>> a = 3
= 3
>> a
= 3
An assignment like this creates an ownvalue:
>> OwnValues[a]
= {HoldPattern[a] :> 3}
You can set multiple values at once using lists:
>> {a, b, c} = {10, 2, 3}
= {10, 2, 3}
>> {a, b, {c, {d}}} = {1, 2, {{c1, c2}, {a}}}
= {1, 2, {{c1, c2}, {10}}}
>> d
= 10
'Set' evaluates its right-hand side immediately and assigns it to
the left-hand side:
>> a
= 1
>> x = a
= 1
>> a = 2
= 2
>> x
= 1
'Set' always returns the right-hand side, which you can again use
in an assignment:
>> a = b = c = 2;
>> a == b == c == 2
= True
'Set' supports assignments to parts:
>> A = {{1, 2}, {3, 4}};
>> A[[1, 2]] = 5
= 5
>> A
= {{1, 5}, {3, 4}}
>> A[[;;, 2]] = {6, 7}
= {6, 7}
>> A
= {{1, 6}, {3, 7}}
Set a submatrix:
>> B = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
>> B[[1;;2, 2;;-1]] = {{t, u}, {y, z}};
>> B
= {{1, t, u}, {4, y, z}, {7, 8, 9}}
#> x = Infinity;
"""
operator = "="
precedence = 40
grouping = "Right"
attributes = ("HoldFirst", "SequenceHold")
messages = {
"setraw": "Cannot assign to raw object `1`.",
"shape": "Lists `1` and `2` are not the same shape.",
}
def apply(self, lhs, rhs, evaluation):
"lhs_ = rhs_"
self.assign(lhs, rhs, evaluation)
return rhs
class SetDelayed(Set):
"""
<dl>
<dt>'SetDelayed[$expr$, $value$]'
<dt>$expr$ := $value$
<dd>assigns $value$ to $expr$, without evaluating $value$.
</dl>
'SetDelayed' is like 'Set', except it has attribute 'HoldAll',
thus it does not evaluate the right-hand side immediately, but
evaluates it when needed.
>> Attributes[SetDelayed]
= {HoldAll, Protected, SequenceHold}
>> a = 1
= 1
>> x := a
>> x
= 1
Changing the value of $a$ affects $x$:
>> a = 2
= 2
>> x
= 2
'Condition' ('/;') can be used with 'SetDelayed' to make an
assignment that only holds if a condition is satisfied:
>> f[x_] := p[x] /; x>0
>> f[3]
= p[3]
>> f[-3]
= f[-3]
It also works if the condition is set in the LHS:
>> F[x_, y_] /; x < y /; x>0 := x / y;
>> F[x_, y_] := y / x;
>> F[2, 3]
= 2 / 3
>> F[3, 2]
= 2 / 3
>> F[-3, 2]
= -2 / 3
"""
operator = ":="
attributes = ("HoldAll", "SequenceHold")
def apply(self, lhs, rhs, evaluation):
"lhs_ := rhs_"
if self.assign(lhs, rhs, evaluation):
return Symbol("Null")
else:
return SymbolFailed
class UpSet(BinaryOperator, _SetOperator):
"""
<dl>
<dt>$f$[$x$] ^= $expression$
<dd>evaluates $expression$ and assigns it to the value of
$f$[$x$], associating the value with $x$.
</dl>
'UpSet' creates an upvalue:
>> a[b] ^= 3;
>> DownValues[a]
= {}
>> UpValues[b]
= {HoldPattern[a[b]] :> 3}
>> a ^= 3
: Nonatomic expression expected.
= 3
You can use 'UpSet' to specify special values like format values.
However, these values will not be saved in 'UpValues':
>> Format[r] ^= "custom";
>> r
= custom
>> UpValues[r]
= {}
#> f[g, a + b, h] ^= 2
: Tag Plus in f[g, a + b, h] is Protected.
= 2
#> UpValues[h]
= {HoldPattern[f[g, a + b, h]] :> 2}
"""
operator = "^="
precedence = 40
attributes = ("HoldFirst", "SequenceHold")
grouping = "Right"
def apply(self, lhs, rhs, evaluation):
"lhs_ ^= rhs_"
self.assign_elementary(lhs, rhs, evaluation, upset=True)
return rhs
class UpSetDelayed(UpSet):
"""
<dl>
<dt>'UpSetDelayed[$expression$, $value$]'
<dt>'$expression$ ^:= $value$'
<dd>assigns $expression$ to the value of $f$[$x$] (without
evaluating $expression$), associating the value with $x$.
</dl>
>> a[b] ^:= x
>> x = 2;
>> a[b]
= 2
>> UpValues[b]
= {HoldPattern[a[b]] :> x}
#> f[g, a + b, h] ^:= 2
: Tag Plus in f[g, a + b, h] is Protected.
#> f[a+b] ^:= 2
: Tag Plus in f[a + b] is Protected.
= $Failed
"""
operator = "^:="
attributes = ("HoldAll", "SequenceHold")
def apply(self, lhs, rhs, evaluation):
"lhs_ ^:= rhs_"
if self.assign_elementary(lhs, rhs, evaluation, upset=True):
return Symbol("Null")
else:
return SymbolFailed
class TagSet(Builtin, _SetOperator):
"""
<dl>
<dt>'TagSet[$f$, $expr$, $value$]'
<dt>'$f$ /: $expr$ = $value$'
<dd>assigns $value$ to $expr$, associating the corresponding
rule with the symbol $f$.
</dl>
Create an upvalue without using 'UpSet':
>> x /: f[x] = 2
= 2
>> f[x]
= 2
>> DownValues[f]
= {}
>> UpValues[x]
= {HoldPattern[f[x]] :> 2}
The symbol $f$ must appear as the ultimate head of $lhs$ or as the head of a leaf in $lhs$:
>> x /: f[g[x]] = 3;
: Tag x not found or too deep for an assigned rule.
>> g /: f[g[x]] = 3;
>> f[g[x]]
= 3
"""
attributes = ("HoldAll", "SequenceHold")
messages = {
"tagnfd": "Tag `1` not found or too deep for an assigned rule.",
}
def apply(self, f, lhs, rhs, evaluation):
"f_ /: lhs_ = rhs_"
name = f.get_name()
if not name:
evaluation.message(self.get_name(), "sym", f, 1)
return
rhs = rhs.evaluate(evaluation)
self.assign_elementary(lhs, rhs, evaluation, tags=[name])
return rhs
class TagSetDelayed(TagSet):
"""
<dl>
<dt>'TagSetDelayed[$f$, $expr$, $value$]'
<dt>'$f$ /: $expr$ := $value$'
<dd>is the delayed version of 'TagSet'.
</dl>
"""
attributes = ("HoldAll", "SequenceHold")
def apply(self, f, lhs, rhs, evaluation):
"f_ /: lhs_ := rhs_"
name = f.get_name()
if not name:
evaluation.message(self.get_name(), "sym", f, 1)
return
if self.assign_elementary(lhs, rhs, evaluation, tags=[name]):
return Symbol("Null")
else:
return SymbolFailed
class Definition(Builtin):
"""
<dl>
<dt>'Definition[$symbol$]'
<dd>prints as the user-defined values and rules associated with $symbol$.
</dl>
'Definition' does not print information for 'ReadProtected' symbols.
'Definition' uses 'InputForm' to format values.
>> a = 2;
>> Definition[a]
= a = 2
>> f[x_] := x ^ 2
>> g[f] ^:= 2
>> Definition[f]
= f[x_] = x ^ 2
.
. g[f] ^= 2
Definition of a rather evolved (though meaningless) symbol:
>> Attributes[r] := {Orderless}
>> Format[r[args___]] := Infix[{args}, "~"]
>> N[r] := 3.5
>> Default[r, 1] := 2
>> r::msg := "My message"
>> Options[r] := {Opt -> 3}
>> r[arg_., OptionsPattern[r]] := {arg, OptionValue[Opt]}
Some usage:
>> r[z, x, y]
= x ~ y ~ z
>> N[r]
= 3.5
>> r[]
= {2, 3}
>> r[5, Opt->7]
= {5, 7}
Its definition:
>> Definition[r]
= Attributes[r] = {Orderless}
.
. arg_. ~ OptionsPattern[r] = {arg, OptionValue[Opt]}
.
. N[r, MachinePrecision] = 3.5
.
. Format[args___, MathMLForm] = Infix[{args}, "~"]
.
. Format[args___, OutputForm] = Infix[{args}, "~"]
.
. Format[args___, StandardForm] = Infix[{args}, "~"]
.
. Format[args___, TeXForm] = Infix[{args}, "~"]
.
. Format[args___, TraditionalForm] = Infix[{args}, "~"]
.
. Default[r, 1] = 2
.
. Options[r] = {Opt -> 3}
For 'ReadProtected' symbols, 'Definition' just prints attributes, default values and options:
>> SetAttributes[r, ReadProtected]
>> Definition[r]
= Attributes[r] = {Orderless, ReadProtected}
.
. Default[r, 1] = 2
.
. Options[r] = {Opt -> 3}
This is the same for built-in symbols:
>> Definition[Plus]
= Attributes[Plus] = {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected}
.
. Default[Plus] = 0
>> Definition[Level]
= Attributes[Level] = {Protected}
.
. Options[Level] = {Heads -> False}
'ReadProtected' can be removed, unless the symbol is locked:
>> ClearAttributes[r, ReadProtected]
'Clear' clears values:
>> Clear[r]
>> Definition[r]
= Attributes[r] = {Orderless}
.
. Default[r, 1] = 2
.
. Options[r] = {Opt -> 3}
'ClearAll' clears everything:
>> ClearAll[r]
>> Definition[r]
= Null
If a symbol is not defined at all, 'Null' is printed:
>> Definition[x]
= Null
"""
attributes = ("HoldAll",)
precedence = 670
def format_definition(self, symbol, evaluation, grid=True):
"StandardForm,TraditionalForm,OutputForm: Definition[symbol_]"
lines = []
def print_rule(rule, up=False, lhs=lambda l: l, rhs=lambda r: r):
evaluation.check_stopped()
if isinstance(rule, Rule):
r = rhs(
rule.replace.replace_vars(
{
"System`Definition": Expression(
"HoldForm", Symbol("Definition")
)
},
evaluation,
)
)
lines.append(
Expression(
"HoldForm",
Expression(up and "UpSet" or "Set", lhs(rule.pattern.expr), r),
)
)
name = symbol.get_name()
if not name:
evaluation.message("Definition", "sym", symbol, 1)
return
attributes = evaluation.definitions.get_attributes(name)
definition = evaluation.definitions.get_user_definition(name, create=False)
all = evaluation.definitions.get_definition(name)
if attributes:
attributes = list(attributes)
attributes.sort()
lines.append(
Expression(
"HoldForm",
Expression(
"Set",
Expression("Attributes", symbol),
Expression(
"List", *(Symbol(attribute) for attribute in attributes)
),
),
)
)
if definition is not None and "System`ReadProtected" not in attributes:
for rule in definition.ownvalues:
print_rule(rule)
for rule in definition.downvalues:
print_rule(rule)
for rule in definition.subvalues:
print_rule(rule)
for rule in definition.upvalues:
print_rule(rule, up=True)
for rule in definition.nvalues:
print_rule(rule)
formats = sorted(definition.formatvalues.items())
for format, rules in formats:
for rule in rules:
def lhs(expr):
return Expression("Format", expr, Symbol(format))
def rhs(expr):
if expr.has_form("Infix", None):
expr = Expression(
Expression("HoldForm", expr.head), *expr.leaves
)
return Expression("InputForm", expr)
print_rule(rule, lhs=lhs, rhs=rhs)
for rule in all.defaultvalues:
print_rule(rule)
if all.options:
options = sorted(all.options.items())
lines.append(
Expression(
"HoldForm",
Expression(
"Set",
Expression("Options", symbol),
Expression(
"List",
*(
Expression("Rule", Symbol(name), value)
for name, value in options
)
),
),
)
)
if grid:
if lines:
return Expression(
"Grid",
Expression("List", *(Expression("List", line) for line in lines)),
Expression("Rule", Symbol("ColumnAlignments"), Symbol("Left")),
)
else:
return Symbol("Null")
else:
for line in lines:
evaluation.print_out(Expression("InputForm", line))
return Symbol("Null")
def format_definition_input(self, symbol, evaluation):
"InputForm: Definition[symbol_]"
return self.format_definition(symbol, evaluation, grid=False)
def _get_usage_string(symbol, evaluation, htmlout=False):
"""
Returns a python string with the documentation associated to a given symbol.
"""
definition = evaluation.definitions.get_definition(symbol.name)
ruleusage = definition.get_values_list("messages")
usagetext = None
import re
# First look at user definitions:
for rulemsg in ruleusage:
if rulemsg.pattern.expr.leaves[1].__str__() == '"usage"':
usagetext = rulemsg.replace.value
if usagetext is not None:
# Maybe, if htmltout is True, we should convert
# the value to a HTML form...
return usagetext
# Otherwise, look at the pymathics, and builtin docstrings:
builtins = evaluation.definitions.builtin
pymathics = evaluation.definitions.pymathics
bio = pymathics.get(definition.name)
if bio is None:
bio = builtins.get(definition.name)