-
Notifications
You must be signed in to change notification settings - Fork 63
/
PrettyPrinting.jl
1668 lines (1461 loc) · 48.7 KB
/
PrettyPrinting.jl
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
module PrettyPrinting
import ..AbstractAlgebra: RingElem, NCRingElem, MatrixElem
import Base: displaysize
using ..AbstractAlgebra
using Preferences
# printing is done with respect to the following precedences
# There is no point in using the julia values because we add our own ops
const prec_lowest = 0
const prec_inf_Equal = 5 # infix ==
const prec_inf_Plus = 11 # infix a+b+c
const prec_inf_Minus = 11 # infix a-b-c
const prec_inf_Times = 13 # infix a*b*c
const prec_inf_Divide = 13 # infix a/b/c
const prec_inf_DoubleDivide = 14 # infix a//b//c
const prec_inf_CenterDot = 15 # non associative * with spaces, \cdot in latex
const prec_pre_Plus = 20 # prefix +a not used
const prec_pre_Minus = 21 # prefix -a
const prec_pre_Times = 22 # prefix *a not used
const prec_pre_Divide = 23 # prefix /b not used
const prec_inf_Power = 30 # infix a^b
const prec_post_call = 99 # a(b) i.e. whether a+b(c) is (a+b)(c) vs a+(b(c))
const prec_post_ref = 100 # a[b]
const prec_post_FractionBox = 50 # precedence for a/b in 2d form
const prec_post_SuperscriptBox = 51 # precedence for a^b in 2d form
################################################################################
#
# Expression to string
#
################################################################################
function expr_to_string(@nospecialize(obj))
return sprint(show_obj, MIME("text/plain"), obj)
end
function expr_to_latex_string(@nospecialize(obj))
return sprint(show_obj, MIME("text/latex"), obj)
end
function obj_to_string(@nospecialize(obj); context = nothing)
return sprint(show_via_expressify, MIME("text/plain"), obj, context = context)
end
# parenthesize obj as if it were a term in a product
function obj_to_string_wrt_times(@nospecialize(obj); context = nothing)
io = IOBuffer()
S = AbstractAlgebra.printer(io)
print_obj(S, MIME("text/plain"),
canonicalize(expressify(obj, context = context)),
prec_inf_Times, prec_inf_Times)
finish(S)
return String(take!(io))
end
function obj_to_latex_string(@nospecialize(obj); context = nothing)
return sprint(show_via_expressify, MIME("text/latex"), obj, context = context)
end
function Base.show(io::IO, mi::MIME"text/latex", x::Union{RingElem, NCRingElem, MatrixElem})
if isdefined(Main, :IJulia) && Main.IJulia.inited
error("Dummy error for jupyter")
end
show_via_expressify(io, mi, x)
end
function Base.show(io::IO, mi::MIME"text/html", x::Union{RingElem, NCRingElem, MatrixElem})
if isdefined(Main, :IJulia) && Main.IJulia.inited &&
!AbstractAlgebra.get_html_as_latex()
error("Dummy error for jupyter")
end
if AbstractAlgebra.get_html_as_latex()
io = IOContext(io, :size_limit => 1000)
end
show_via_expressify(io, mi, x)
end
function show_via_expressify(io::IO, @nospecialize(obj); context = nothing)
show_via_expressify(io::IO, MIME("text/plain"), obj, context = context)
end
function show_via_expressify(io::IO, mi::MIME, @nospecialize(obj); context = nothing)
show_obj(io, mi, canonicalize(expressify(obj, context = context)))
end
# the low-level workhorse
function show_obj(io::IO, mi::MIME, obj)
S = printer(io)
print_obj(S, mi, obj, prec_lowest, prec_lowest)
finish(S)
end
global _html_as_latex = Ref(false)
@doc raw"""
get_html_as_latex()
Returns whether MIME type `text/html` is printed as `text/latex`.
"""
get_html_as_latex() = _html_as_latex[]
@doc raw"""
set_html_as_latex(fl::Bool)
Toggles whether MIME type `text/html` should be printed as `text/latex`. Note
that this is a global option. The return value is the old value.
"""
function set_html_as_latex(fl::Bool)
old = get_html_as_latex()
_html_as_latex[] = fl
return old
end
function show_obj(io::IO, mi::MIME"text/html", obj)
if _html_as_latex[]
print(io, "\$")
show_obj(io, MIME("text/latex"), obj)
print(io, "\$")
else
#print(io, "<font face=\"mono\">")
show_obj(io, MIME("text/plain"), obj)
#print(io, "</font>")
end
end
################################################################################
#
# Expressify
#
################################################################################
# The definitive guide to how Expr's are printed is the print_obj function
# below. Here is a quick summary of the latex behaviour:
# * Expr(:call, ://, a, b) will create a fraction box
# * Expr(:call, :/, a, b) will not create a fraction box
# * heads :vcat, :hcat, and :row can be used to make arrays
# * Expr(:latex_form, a, b) uses b for latex output and a otherwise
# * Expr(:matrix, m) is a hint that m is a matrix, i.e. enclosed in ()
# * Expr(:text, ...) instructs string arguments to be wrapped in \text{}
# * Symbol leaves themselves have some special transformations:
# Symbol("a") => a
# Symbol("α") => {\alpha}
# Symbol("x1") => \operatorname{x1}
# Symbol("xy_1") => \operatorname{xy}_{1}
# Symbol("sin") => \operatorname{sin}
# Symbol("sin_cos") => \operatorname{sin\_cos}
# Symbol("sin_1") => \operatorname{sin}_{1}
# Symbol("sin_cos_1") => \operatorname{sin\_cos}_{1}
# Symbol("αaβb_1_2") => \operatorname{{\alpha}a{\beta}b}_{1,2}
# * various sequential constructs:
# Expr(:call, a, b, c) => a(b,c)
# Expr(:ref, a, b, c) => a[b,c]
# Expr(:vcat, a, b) => [a;b] (actually vertical in latex)
# Expr(:vect, a, b) => [a,b]
# Expr(:tuple, a, b) => (a,b)
# Expr(:list, a, b) => {a,b}
# Expr(:series, a, b) => a,b
# Expr(:sequence, a, b) => ab
# Expr(:row, a, b) => a b
# Expr(:hcat, a, b) => a b
function expressify(@nospecialize(a); context = nothing)::String
return sprint(print, a; context = context)::String
end
# Only when AbstractAlgebra.expressify(a::T; context = nothing) has been
# defined may enable_all_show_via_expressify be used.
# AA defines Base.show for "text/latex" and "text/html" for a general set
# of x, but for backward compatibility it is not defined for general x and
# "text/plain" or the mime-less version.
# Rationale: when neither Base.show nor AA.expressify is defined for T, then,
# since expressify calls Base.show for backward compatibility, a definition of
# Base.show in terms of expressify would give a stack overflow.
#
# We have to be careful for jupyter. When jupyter prints an object x through
# IJulia.jl, it collects sprint(show, m, x) for all m in
# [ "text/plain", "text/html", "text/latex" ... ]
# and then picks one according to some precedence. If there is a string for
# either "text/html" or "text/latex", it will *not* use "text/plain". But
# "text/plain" is the only thing which will trigger rendering using a monospace
# font (hence it will look like "code"). This explains why all julia base
# objects are printed using monospace: none of these objects has print methods
# for text/html or text/latex.
#
# The challenge for us is that we always want to define text/latex and
# text/html methods for sprint and friends. This has the disadvantage that if
# get_html_as_latex()== false, then our objects will print their ordinary
# string presentation, but since it is coming from text/html, it will be
# rendered using the "normal" font.
#
# Thus, inside IJulia we will throw an error for text/latex (always) and
# text/html (unless get_html_as_latex()).
#
# Super easy!
macro enable_all_show_via_expressify(T)
return quote
function Base.show(io::IO, x::$(esc(T)))
AbstractAlgebra.show_via_expressify(io, x)
end
function Base.show(io::IO, mi::MIME"text/plain", x::$(esc(T)))
AbstractAlgebra.show_via_expressify(io, mi, x)
end
function Base.show(io::IO, mi::MIME"text/latex", x::$(esc(T)))
if isdefined(Main, :IJulia) && Main.IJulia.inited
error("Dummy error for jupyter")
end
return AbstractAlgebra.show_via_expressify(io, mi, x)
end
function Base.show(io::IO, mi::MIME"text/html", x::$(esc(T)))
if isdefined(Main, :IJulia) && Main.IJulia.inited &&
!AbstractAlgebra.get_html_as_latex()
error("Dummy error for jupyter")
end
return AbstractAlgebra.show_via_expressify(io, mi, x)
end
end
end
################################################################################
#
# Canonicalization
#
################################################################################
# Canonicalization performs the following transformations
# a+(b+c) => a+b+c sums are flattened
# a*(b*c) => a*b*c products are flattened
# a*-b*c => -a*b*c unary minus can move freely through products
# (-a)/b => -(a/b) unary minus can move through the numerator of a quotient
# a-b => a + -b subtraction is turned into addition with unary minus
# --a => a
# 0*a => 0
# 0+a => a
# 1*a => a
# since unary minus has a higher precedence than * and /, we maintain
# -a*b*c as (-a)*b*c and not as -(a*b*c) because the former prints without ()
# is obj a call to op with 1 or more arguments
function isaExprOp(@nospecialize(obj), op::Symbol)
return isa(obj, Expr) &&
length(obj.args) > 1 &&
obj.head === :call &&
obj.args[1] === op
end
# is obj a call to op with len arguments
function isaExprOp(@nospecialize(obj), op::Symbol, len::Int)
return isa(obj, Expr) &&
length(obj.args) == len + 1 &&
obj.head === :call &&
obj.args[1] === op
end
# syntactic zeros can be removed from sums and turn a product into 0
is_syntactic_zero(obj::Number) = iszero(obj)
is_syntactic_zero(obj) = false
# syntactic ones can be removed from products
is_syntactic_one(obj::Number) = isone(obj)
is_syntactic_one(obj) = false
function get_syntactic_sign_abs(obj::Number)
return obj < 0 ? (-1, -obj) : (1, obj)
end
function get_syntactic_sign_abs(obj::Expr)
if obj.head !== :call
return (1, obj)
end
if length(obj.args) == 2 && obj.args[1] === :-
# unary minus is negative
(sgn, abs) = get_syntactic_sign_abs(obj.args[2])
return (-sgn, obj.args[2])
elseif length(obj.args) > 2 && obj.args[1] === :*
# product is negative if first term is
(sgn, abs) = get_syntactic_sign_abs(obj.args[2])
if sgn > 0
return (1, obj)
else
newobj = Expr(obj.head)
newobj.args = copy(obj.args)
newobj.args[2] = abs
if is_syntactic_one(newobj.args[2])
deleteat!(newobj.args, 2)
end
if length(newobj.args) == 2
return (sgn, newobj.args[2])
else
return (sgn, newobj)
end
end
elseif length(obj.args) == 3 && (obj.args[1] === :/ || obj.args[1] === ://)
# quotient is negative if numerator is
(sgn, abs) = get_syntactic_sign_abs(obj.args[2])
if sgn > 0
return (1, obj)
else
newobj = Expr(obj.head)
newobj.args = copy(obj.args)
newobj.args[2] = abs
return (sgn, newobj)
end
else
return (1, obj)
end
end
function get_syntactic_sign_abs(obj)
return (1, obj)
end
function syntactic_neg!(obj::Expr)
if isaExprOp(obj, :*) || isaExprOp(obj, :/) || isaExprOp(obj, ://)
obj.args[2] = syntactic_neg!(obj.args[2])
return obj
elseif isaExprOp(obj, :-, 1)
return obj.args[2]
else
return Expr(:call, :-, obj)
end
end
function syntactic_neg!(obj)
return Expr(:call, :-, obj)
end
# not actually implemented recursively to avoid stack overflow
function flatten_recursive!(ans::Expr, obj::Expr, op::Symbol)
stack = reverse(obj.args[2:end])
while !isempty(stack)
top = pop!(stack)
if isaExprOp(top, op)
for i in length(top.args):-1:2
push!(stack, top.args[i])
end
else
push!(ans.args, top)
end
end
end
# op(op(a,b),op(c,d)) => op(a,b,c,d) etc
function flatten_op(obj::Expr, op::Symbol)
if !isaExprOp(obj, op)
return obj
end
for i in 2:length(obj.args)
if isaExprOp(obj.args[i], op)
ans = Expr(:call, op)
flatten_recursive!(ans, obj, op)
return ans
end
end
return obj
end
function canonicalizePlusFinal!(obj::Expr)
@assert obj.head === :call && obj.args[1] === :+
if length(obj.args) < 2
return 0
elseif length(obj.args) == 2
return obj.args[2]
end
obj = flatten_op(obj, :+)
for i in 3:length(obj.args)
(sign, abs) = get_syntactic_sign_abs(obj.args[i])
if sign < 0
obj.args[i] = Expr(:call, :-, abs)
else
obj.args[i] = abs
end
end
return obj
end
function canonicalizePlus(obj::Expr)
@assert obj.head === :call && obj.args[1] === :+
if length(obj.args) < 2
return 0
elseif length(obj.args) == 2
return canonicalize(obj.args[2])
end
# this flatten is just to try to avoid stack overflows in canonicalize
obj = flatten_op(obj, :+)
newobj = Expr(:call, :+)
for i in 2:length(obj.args)
t = canonicalize(obj.args[i])
if !is_syntactic_zero(t)
push!(newobj.args, t)
end
end
# now do the real flatten
return canonicalizePlusFinal!(newobj)
end
function canonicalizeMinus(obj::Expr)
@assert obj.head === :call && obj.args[1] === :-
if length(obj.args) < 2
return 0
elseif length(obj.args) == 2
return syntactic_neg!(canonicalize(obj.args[2]))
end
newobj = Expr(:call, :+)
for i in 2:length(obj.args)
t = canonicalize(obj.args[i])
if !is_syntactic_zero(t)
push!(newobj.args, i > 2 ? syntactic_neg!(t) : t)
end
end
return canonicalizePlusFinal!(newobj)
end
function canonicalizeTimes(obj::Expr)
op = obj.args[1]
@assert obj.head === :call && (op === :* || op === :cdot)
if length(obj.args) < 2
return 1
elseif length(obj.args) == 2
return canonicalize(obj.args[2])
end
if op === :cdot
return canonicalize_general_recursive(obj)
end
obj = flatten_op(obj, op)
newobj = Expr(:call, op)
newsign = 1
for i in 2:length(obj.args)
t = canonicalize(obj.args[i])
if is_syntactic_zero(t)
return 0
else
(sign, abs) = get_syntactic_sign_abs(t)
newsign *= sign
if !is_syntactic_one(abs)
push!(newobj.args, abs)
end
end
end
if length(newobj.args) < 2
newobj = 1
elseif length(newobj.args) == 2
newobj = newobj.args[2]
else
newobj = flatten_op(newobj, op)
end
if newsign < 0
newobj = syntactic_neg!(newobj)
end
return newobj
end
function canonicalize_general_recursive(obj::Expr)
newobj = Expr(obj.head)
for i in obj.args
push!(newobj.args, canonicalize(i))
end
return newobj
end
function canonicalize(obj::Expr)
if obj.head === :call && !isempty(obj.args)
if obj.args[1] === :+
return canonicalizePlus(obj)
elseif obj.args[1] === :-
return canonicalizeMinus(obj)
elseif obj.args[1] === :* || obj.args[1] === :cdot
return canonicalizeTimes(obj)
end
end
return canonicalize_general_recursive(obj)
end
#fallback
function canonicalize(obj)
return obj
end
################################################################################
#
# Printing
#
################################################################################
mutable struct printer
io::IO
array::Vector{String}
terse_level::Int
size_limit_stack::Vector{Int} # >= 0 for loosely-defined limit before ...
# < 0 for unrestricted output
end
function printer(io::IO)
terse_level = get(io, :terse, false) ? 1 : 0
size_limit = get(io, :size_limit, -1)
return printer(io, String[], terse_level, Int[size_limit])
end
# TODO since the subexpressions are not changing much, cache the leaf_count
# so that subexpressions don't have bad quadratic behavior
function leaf_count(S::printer, obj::Expr)
z = 0
for i in obj.args
z += leaf_count(S, i)
end
return z
end
function leaf_count(S::printer, obj)
return 1
end
# terse means a+b instead of a + b
function isterse(S::printer)
return S.terse_level > 0
end
function set_terse(S::printer)
S.terse_level = max(1, S.terse_level + 1)
end
function restore_terse(S::printer)
S.terse_level = S.terse_level - 1
end
# size_limit is a rough limit on the number of leaves printed
function size_limit(S::printer)
return S.size_limit_stack[end]
end
function set_size_limit(S::printer, l::Int)
push!(S.size_limit_stack, l)
end
function restore_size_limit(S::printer)
pop!(S.size_limit_stack)
end
# maintain the last few printed things for token (un)mashing purposes
function push(S::printer, s::String)
while length(S.array) > 3
print(S.io, popfirst!(S.array))
end
push!(S.array, s)
end
function push_left_parenthesis(S::printer, ::MIME)
push(S, "(")
end
function push_right_parenthesis(S::printer, ::MIME)
push(S, ")")
end
function push_left_parenthesis(S::printer, ::MIME"text/latex")
push(S, "\\left(")
end
function push_right_parenthesis(S::printer, ::MIME"text/latex")
push(S, "\\right)")
end
function push_left_bracket(S::printer, ::MIME)
push(S, "[")
end
function push_right_bracket(S::printer, ::MIME)
push(S, "]")
end
function push_left_bracket(S::printer, ::MIME"text/latex")
push(S, "\\left[")
end
function push_right_bracket(S::printer, ::MIME"text/latex")
push(S, "\\right]")
end
function push_left_curly(S::printer, ::MIME)
push(S, "{")
end
function push_right_curly(S::printer, ::MIME)
push(S, "}")
end
function push_left_curly(S::printer, ::MIME"text/latex")
push(S, "\\left{")
end
function push_right_curly(S::printer, ::MIME"text/latex")
push(S, "\\right}")
end
function push_elision(S, ::MIME)
push(S, "...")
end
function push_elision(S, ::MIME"text/latex")
push(S, "{\\ldots}")
end
function finish(S::printer)
while !isempty(S.array)
print(S.io, popfirst!(S.array))
end
end
# determine the limits for the subexpressions of a given expression
# look at obj.args[offset + 1], ..., obj.args[offset + n]
function child_limits(S::printer, obj::Expr, off::Int, n::Int)
l = max(1, size_limit(S))
if n > l
leaf_counts = Int[leaf_count(S, obj.args[off +
(2*i <= l + 1 ? i : i + n - l)]) for i in 1:l]
n = l
else
leaf_counts = Int[leaf_count(S, obj.args[off + i]) for i in 1:n]
end
total_leaf_count = sum(leaf_counts)
a = Int[] # will be limits for the terms from the start
b = Int[] # will be limits for the terms from the end
abtotal = 0
while length(a) + length(b) < n
ai = 1 + length(a)
bi = n - length(b)
if length(a) < length(b) || (length(a) == length(b) &&
leaf_counts[ai] <= leaf_counts[bi])
t = max(min(3, leaf_counts[ai]), div(leaf_counts[ai]*l, total_leaf_count))
if leaf_counts[ai] < l/32
t = max(t, leaf_counts[ai])
end
push!(a, min(t, l))
else
t = max(min(3, leaf_counts[bi]), div(leaf_counts[bi]*l, total_leaf_count))
if leaf_counts[bi] < l/32
t = max(t, leaf_counts[bi])
end
push!(b, min(t, l))
end
abtotal += t
abtotal < l || break
end
return a, b
end
function compare_op_string(mi::MIME, op)
if op === :(==)
return "="
else
return string(op)
end
end
function compare_op_string(mi::MIME"text/latex", op)
if op === :(==)
return "="
elseif op === :(<=)
return "\\le"
elseif op === :(>=)
return "\\ge"
elseif op === :(!=)
return "\\neq"
else
return string(op)
end
end
function print_comparison(S::printer, mi::MIME, obj::Expr,
left::Int, right::Int, prec::Int)
n = length(obj.args)
@assert isodd(n) && n > 1
sep = isterse(S) ? "" : " "
needp = prec <= left || prec <= right
if needp
left = right = prec_lowest
push_left_parenthesis(S, mi)
end
print_obj(S, mi, obj.args[1], left, prec)
for i in 2:2:n-3
push(S, sep*compare_op_string(mi, obj.args[i])*sep)
print_obj(S, mi, obj.args[i+1], prec, prec)
end
push(S, sep*compare_op_string(mi, obj.args[n-1])*sep)
print_obj(S, mi, obj.args[n], prec, right)
if needp
push_right_parenthesis(S, mi)
end
end
# dir > 0 left associate: +, -, *, /
# dir < 0 right associative: ^
# dir = 0 non associative:
function printGenericInfix(S::printer, mi::MIME, obj::Expr,
left::Int, right::Int,
op::String, prec::Int, dir::Int)
n = length(obj.args)
if n < 3
print_call_or_ref(S, mi, obj, left, right)
return
end
needp = prec <= left || prec <= right
if needp
left = right = prec_lowest
push_left_parenthesis(S, mi)
end
if size_limit(S) < 0
# printing with no restriction
print_obj(S, mi, obj.args[2], left, prec - (dir > 0))
for i in 3:(n - 1)
push(S, op)
print_obj(S, mi, obj.args[i], prec, prec)
end
push(S, op)
print_obj(S, mi, obj.args[n], prec - (dir < 0), right)
elseif size_limit(S) == 0
# no space to print anything
push_elision(S, mi)
else
n -= 1
a, b = child_limits(S, obj, 1, n)
wrote_elision = false
for i in 1:n
if i <= length(a)
set_size_limit(S, a[i])
elseif n - i + 1 <= length(b)
set_size_limit(S, b[n - i + 1])
else
if !wrote_elision
i == 1 || push(S, op)
push_elision(S, mi)
end
wrote_elision = true
continue
end
i == 1 || push(S, op)
print_obj(S, mi, obj.args[i + 1],
i == 1 ? left : i == n ? prec - (dir < 0) : prec,
i == 1 ? prec - (dir > 0) : i == n ? right : prec)
restore_size_limit(S)
end
end
if needp
push_right_parenthesis(S, mi)
end
end
function printGenericPrefix(S::printer, mi::MIME, obj::Expr,
left::Int, right::Int,
op::String, prec::Int)
@assert length(obj.args) == 2
needp = prec <= right
if needp
left = right = prec_lowest
push_left_parenthesis(S, mi)
end
push(S, op)
print_obj(S, mi, obj.args[2], prec, right)
if needp
push_right_parenthesis(S, mi)
end
end
function printPlusArg(S::printer, mi::MIME, obj::Expr, i::Int,
left::Int, right::Int, prec::Int)
n = length(obj.args)
if i == 1
print_obj(S, mi, obj.args[2], left, prec - 1)
else
arg = obj.args[i + 1]
if isaExprOp(arg, :-, 1)
push(S, isterse(S) ? "-" : " - ")
arg = arg.args[2]
left_prec = prec_inf_Minus
else
push(S, isterse(S) ? "+" : " + ")
left_prec = prec_inf_Plus
end
right_prec = i + 2 > n ? right :
isaExprOp(obj.args[i + 2], :-, 1) ? prec_inf_Minus :
prec_inf_Plus
print_obj(S, mi, arg, left_prec, right_prec)
end
end
# special override for plus which seeks the sign of its arguments
function printPlus(S::printer, mi::MIME, obj::Expr,
left::Int, right::Int)
n = length(obj.args)
@assert n > 0 && obj.head === :call && obj.args[1] === :+
if n < 2
print_call_or_ref(S, mi, obj, left, right)
return
elseif n == 2
printGenericPrefix(S, mi, obj, left, right, "+", prec_pre_Plus)
return
end
prec = prec_inf_Plus
needp = prec <= left || prec <= right
if needp
left = right = prec_lowest
push_left_parenthesis(S, mi)
end
n -= 1
if size_limit(S) < 0
for i in 1:n
printPlusArg(S, mi, obj, i, left, right, prec)
end
elseif size_limit(S) == 0
push_elision(S, mi)
else
a, b = child_limits(S, obj, 1, n)
wrote_elision = false
for i in 1:n
if i <= length(a)
set_size_limit(S, a[i])
elseif n - i + 1 <= length(b)
set_size_limit(S, b[n - i + 1])
else
if !wrote_elision
i == 1 || push(S, isterse(S) ? "+" : " + ")
push_elision(S, mi)
end
wrote_elision = true
continue
end
printPlusArg(S, mi, obj, i, left, right, prec)
restore_size_limit(S)
end
end
if needp
push_right_parenthesis(S, mi)
end
end
# special override for unary minus
function printMinus(S::printer, mi::MIME, obj::Expr,
left::Int, right::Int)
n = length(obj.args)
@assert n > 0 && obj.head === :call && obj.args[1] === :-
if n < 2
print_call_or_ref(S, mi, obj, left, right)
elseif n == 2
printGenericPrefix(S, mi, obj, left, right, "-", prec_pre_Minus)
else
op = isterse(S) ? "-" : " - "
printGenericInfix(S, mi, obj, left, right, op, prec_inf_Minus, 1)
end
end
function printFraction(S::printer, mi::MIME"text/latex",
@nospecialize(num), @nospecialize(den),
left::Int, right::Int)
prec = prec_post_FractionBox
needp = prec <= left || prec <= right
if needp
left = right = prec_lowest
push_left_parenthesis(S, mi)
end
push(S, "\\frac{")
print_obj(S, mi, num, prec_lowest, prec_lowest)
push(S, "}{")
print_obj(S, mi, den, prec_lowest, prec_lowest)
push(S, "}")
if needp
push_right_parenthesis(S, mi)
end
end
function printDivides(S::printer, mi::MIME"text/latex", obj::Expr,
left::Int, right::Int)
n = length(obj.args)
@assert n > 0 && obj.head === :call && obj.args[1] === ://
if n != 3
printGenericInfix(S, mi, obj, left, right, "//", prec_inf_Divide, +1)
else
(sgn, abs) = get_syntactic_sign_abs(obj.args[2])
if sgn < 0
prec = prec_pre_Minus
needp = prec <= right
if needp
left = right = prec_lowest
push_left_parenthesis(S, mi)
end
push(S, "-")
printFraction(S, mi, abs, obj.args[3], prec, right)
if needp
push_right_parenthesis(S, mi)
end
else
printFraction(S, mi, abs, obj.args[3], left, right)
end
end
end
function printPower(S::printer, mi::MIME"text/latex", obj::Expr,
left::Int, right::Int)
n = length(obj.args)
@assert n > 0 && obj.head === :call && obj.args[1] === :(^)
if n != 3
printGenericInfix(S, mi, obj, left, right, "^", prec_inf_Power, +1)
else
prec = prec_post_SuperscriptBox
needp = prec <= left || prec <= right
if needp
left = right = prec_lowest
push_left_parenthesis(S, mi)
end
print_obj(S, mi, obj.args[2], left, prec)
push(S, "^{")
print_obj(S, mi, obj.args[3], prec_lowest, prec_lowest)
push(S, "}")
if needp
push_right_parenthesis(S, mi)
end
end
end
function print_call_or_ref(S::printer, mi::MIME, obj::Expr,
left::Int, right::Int)
n = length(obj.args)
@assert n > 0 && (obj.head === :call || obj.head === :ref)
prec = obj.head === :call ? prec_post_call : prec_post_ref
needp = prec <= left
if needp
left = prec_lowest
push_left_parenthesis(S, mi)
end
if size_limit(S) < 0
print_obj(S, mi, obj.args[1], left, prec)
obj.head === :call ? push_left_parenthesis(S, mi) : push_left_bracket(S, mi)
for i in 2:n
i == 2 || push(S, isterse(S) ? "," : ", ")
print_obj(S, mi, obj.args[i], prec_lowest, prec_lowest)
end
obj.head === :call ? push_right_parenthesis(S, mi) : push_right_bracket(S, mi)
elseif size_limit(S) == 0
push_elision(S, mi)
else
a, b = child_limits(S, obj, 0, n)
if 1 <= length(a)
set_size_limit(S, a[1])
print_obj(S, mi, obj.args[1], left, prec)
restore_size_limit(S)
else
push_elision(S, mi)
end
obj.head === :call ? push_left_parenthesis(S, mi) : push_left_bracket(S, mi)
wrote_elision = false
for i in 2:n
if i <= length(a)
set_size_limit(S, a[i])
elseif n - i + 1 <= length(b)
set_size_limit(S, b[n - i + 1])
else
if !wrote_elision
i == 2 || push(S, isterse(S) ? "," : ", ")
push_elision(S, mi)
end
wrote_elision = true
continue
end
i == 2 || push(S, isterse(S) ? "," : ", ")
print_obj(S, mi, obj.args[i], prec_lowest, prec_lowest)
restore_size_limit(S)
end
obj.head === :call ? push_right_parenthesis(S, mi) : push_right_bracket(S, mi)
end