-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathExpressionExplorer.pluto.jl
3250 lines (2686 loc) · 112 KB
/
ExpressionExplorer.pluto.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
### A Pluto.jl notebook ###
# v0.14.1
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
el
end
end
# ╔═╡ 51f62e10-9b66-48a9-bd8a-5f7ca47bea12
md"""
# ExpressionExplorer
This notebook is part of Pluto's source code.
"""
# ╔═╡ a35eeaec-6b73-4200-8fe9-e069e0b8dea8
begin
if !@isdefined(PlutoRunner)
import ..PlutoRunner
end
import Markdown
end
# ╔═╡ eb228e68-8bb9-404a-803f-d2cf5622fca3
md"""
## Two state objects
"""
# ╔═╡ 559d35f5-981a-444e-b212-ab32405df12c
# TODO: use GlobalRef instead
FunctionName = Array{Symbol,1}
# ╔═╡ 2391cfeb-311a-461e-8d3c-80cd5f9b599e
struct FunctionNameSignaturePair
name::FunctionName
canonicalized_head::Any
end
# ╔═╡ afe6f8a2-cf1c-48f7-9c9c-23046fd5a33c
Base.:(==)(a::FunctionNameSignaturePair, b::FunctionNameSignaturePair) = a.name == b.name && a.canonicalized_head == b.canonicalized_head
# ╔═╡ 13819d9d-88ca-44d1-bd1d-74a67cfb0d3b
Base.hash(a::FunctionNameSignaturePair, h::UInt) = hash(a.name, hash(a.canonicalized_head, h))
# ╔═╡ e6b7134d-cb5f-49b5-b069-a38ac5645085
"SymbolsState trickles _down_ the ASTree: it carries referenced and defined variables from endpoints down to the root."
Base.@kwdef mutable struct SymbolsState
references::Set{Symbol} = Set{Symbol}()
assignments::Set{Symbol} = Set{Symbol}()
funccalls::Set{FunctionName} = Set{FunctionName}()
funcdefs::Dict{FunctionNameSignaturePair,SymbolsState} = Dict{FunctionNameSignaturePair,SymbolsState}()
end
# ╔═╡ c5ed1623-a68f-4acb-b423-a6d9ade0a7a5
begin
"ScopeState moves _up_ the ASTree: it carries scope information up towards the endpoints."
mutable struct ScopeState
inglobalscope::Bool
exposedglobals::Set{Symbol}
hiddenglobals::Set{Symbol}
definedfuncs::Set{Symbol}
end
ScopeState() = ScopeState(true, Set{Symbol}(), Set{Symbol}(), Set{Symbol}())
end
# ╔═╡ f5fee1ad-bc07-419a-a118-fc552009799a
# The `union` and `union!` overloads define how two `SymbolsState`s or two `ScopeState`s are combined.
function Base.union(a::Dict{FunctionNameSignaturePair,SymbolsState}, bs::Dict{FunctionNameSignaturePair,SymbolsState}...)
union!(Dict{FunctionNameSignaturePair,SymbolsState}(), a, bs...)
end
# ╔═╡ 06e6414d-180a-4088-8d07-9a8e18461969
function Base.union!(a::Dict{FunctionNameSignaturePair,SymbolsState}, bs::Dict{FunctionNameSignaturePair,SymbolsState}...)
for b in bs
for (k, v) in b
if haskey(a, k)
a[k] = union!(a[k], v)
else
a[k] = v
end
end
a
end
return a
end
# ╔═╡ b8b8c77c-0981-41dc-ac0b-6aaf8f03db47
function Base.union(a::SymbolsState, b::SymbolsState)
SymbolsState(a.references ∪ b.references, a.assignments ∪ b.assignments, a.funccalls ∪ b.funccalls, a.funcdefs ∪ b.funcdefs)
end
# ╔═╡ 90da4e3a-1c25-4ad6-904b-4d895786790e
function Base.union!(a::SymbolsState, bs::SymbolsState...)
union!(a.references, (b.references for b in bs)...)
union!(a.assignments, (b.assignments for b in bs)...)
union!(a.funccalls, (b.funccalls for b in bs)...)
union!(a.funcdefs, (b.funcdefs for b in bs)...)
return a
end
# ╔═╡ d703d634-8956-4bda-b0fa-ef011c830459
function Base.union!(a::Tuple{FunctionName,SymbolsState}, bs::Tuple{FunctionName,SymbolsState}...)
a[1], union!(a[2], (b[2] for b in bs)...)
end
# ╔═╡ afdedd6e-7f07-42da-9f36-c45a7ae0210f
function Base.union(a::ScopeState, b::ScopeState)
SymbolsState(a.inglobalscope && b.inglobalscope, a.exposedglobals ∪ b.exposedglobals, a.hiddenglobals ∪ b.hiddenglobals)
end
# ╔═╡ cb3aa97e-2f0b-4b08-be92-3f9350687fdc
function Base.union!(a::ScopeState, bs::ScopeState...)
a.inglobalscope &= all((b.inglobalscope for b in bs)...)
union!(a.exposedglobals, (b.exposedglobals for b in bs)...)
union!(a.hiddenglobals, (b.hiddenglobals for b in bs)...)
union!(a.definedfuncs, (b.definedfuncs for b in bs)...)
return a
end
# ╔═╡ 23b5071f-834a-4c67-bd31-ad46ac710d48
function Base.:(==)(a::SymbolsState, b::SymbolsState)
a.references == b.references && a.assignments == b.assignments && a.funccalls == b.funccalls && a.funcdefs == b.funcdefs
end
# ╔═╡ 10ee2230-f91c-4479-9f2a-d3459a7a5499
Base.push!(x::Set) = x
# ╔═╡ 3c93ed99-6014-48c0-9ed1-79675aedcfe0
md"""
## Helper functions
"""
# ╔═╡ 3e638dc9-11ec-4907-90a8-d92b348c6f4e
# from the source code: https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm#L9
const modifiers = [:(+=), :(-=), :(*=), :(/=), :(//=), :(^=), :(÷=), :(%=), :(<<=), :(>>=), :(>>>=), :(&=), :(⊻=), :(≔), :(⩴), :(≕)]
# ╔═╡ b4cec831-9704-492b-9766-419e01b09d6e
const modifiers_dotprefixed = [Symbol('.' * String(m)) for m in modifiers]
# ╔═╡ 7d40bfbc-c655-4782-8471-2007a48dc0bf
function will_assign_global(assignee::Symbol, scopestate::ScopeState)::Bool
(scopestate.inglobalscope || assignee ∈ scopestate.exposedglobals) && (assignee ∉ scopestate.hiddenglobals || assignee ∈ scopestate.definedfuncs)
end
# ╔═╡ db24e50c-5e4d-471e-9fbe-8831d707696f
function will_assign_global(assignee::Array{Symbol,1}, scopestate::ScopeState)::Bool
if length(assignee) == 0
false
elseif length(assignee) > 1
scopestate.inglobalscope
else
will_assign_global(assignee[1], scopestate)
end
end
# ╔═╡ 2a508120-4687-4697-a039-d4faa7872f52
function get_global_assignees(assignee_exprs, scopestate::ScopeState)::Set{Symbol}
global_assignees = Set{Symbol}()
for ae in assignee_exprs
if isa(ae, Symbol)
will_assign_global(ae, scopestate) && push!(global_assignees, ae)
else
if ae.head == :(::)
will_assign_global(ae.args[1], scopestate) && push!(global_assignees, ae.args[1])
else
@warn "Unknown assignee expression" ae
end
end
end
return global_assignees
end
# ╔═╡ 45283cd1-c459-4e62-b819-a63aa590c363
function get_assignees(ex::Expr)::FunctionName
if ex.head == :tuple
# e.g. (x, y) in the ex (x, y) = (1, 23)
union!(Symbol[], get_assignees.(ex.args)...)
# filter(s->s isa Symbol, ex.args)
elseif ex.head == :(::)
# TODO: type is referenced
Symbol[ex.args[1]]
elseif ex.head == :ref || ex.head == :(.)
Symbol[]
else
@warn "unknown use of `=`. Assignee is unrecognised." ex
Symbol[]
end
end
# ╔═╡ ddf5e84d-bc01-41e3-90fa-5faef4c3b7fc
# When you assign to a datatype like Int, String, or anything bad like that
# e.g. 1 = 2
# This is parsable code, so we have to treat it
get_assignees(::Any) = Symbol[]
# ╔═╡ 026d7dca-6c97-45c2-bfba-c9437f6771ab
all_underscores(s::Symbol) = all(isequal('_'), string(s))
# ╔═╡ 79e948c7-2512-4c34-8598-ad5f10e98d88
# e.g. x = 123, but ignore _ = 456
get_assignees(ex::Symbol) = all_underscores(ex) ? Symbol[] : Symbol[ex]
# ╔═╡ 5f03ef73-eecf-4777-8fe9-9692a255df88
# TODO: this should return a FunctionName, and use `split_funcname`.
"Turn :(A{T}) into :A."
function uncurly!(ex::Expr, scopestate::ScopeState)::Symbol
@assert ex.head == :curly
push!(scopestate.hiddenglobals, (a for a in ex.args[2:end] if a isa Symbol)...)
Symbol(ex.args[1])
end
# ╔═╡ bb2059a3-e789-4101-87a4-37ad6af65d2d
uncurly!(ex::Expr)::Symbol = ex.args[1]
# ╔═╡ a6356c5e-4e44-4376-956f-5f86f4563951
uncurly!(s::Symbol, scopestate=nothing)::Symbol = s
# ╔═╡ 96388cd0-081a-4038-8a70-81a6742a5d8c
"Turn `:(Base.Submodule.f)` into `[:Base, :Submodule, :f]` and `:f` into `[:f]`."
function split_funcname(funcname_ex::Expr)::FunctionName
if funcname_ex.head == :(.)
vcat(split_funcname.(funcname_ex.args)...)
else
# a call to a function that's not a global, like calling an array element: `funcs[12]()`
# TODO: explore symstate!
Symbol[]
end
end
# ╔═╡ 3f1fe13b-d583-48c9-93a9-1b72e4f018eb
function split_funcname(funcname_ex::QuoteNode)::FunctionName
split_funcname(funcname_ex.value)
end
# ╔═╡ faa4068e-f707-4dda-894e-9d555adb5986
function split_funcname(funcname_ex::GlobalRef)::FunctionName
split_funcname(funcname_ex.name)
end
# ╔═╡ c5acddda-d175-4251-816a-8eff1b87eb29
function is_just_dots(ex::Expr)
ex.head == :(.) && all(is_just_dots, ex.args)
end
# ╔═╡ 1fa7e39c-b71f-4c5b-86c2-6ce7c03abe98
is_just_dots(::Union{QuoteNode,Symbol,GlobalRef}) = true
# ╔═╡ e2b0b177-9f46-4a4a-be7b-c209392e2a43
is_just_dots(::Any) = false
# ╔═╡ 8d18d185-2952-463d-864d-f9daeddd6f8f
# this includes GlobalRef - it's fine that we don't recognise it, because you can't assign to a globalref?
function split_funcname(::Any)::FunctionName
Symbol[]
end
# ╔═╡ 671afd70-9c18-413d-9671-875994f0ee5b
"""Turn `Symbol(".+")` into `:(+)`"""
function without_dotprefix(funcname::Symbol)::Symbol
fn_str = String(funcname)
if length(fn_str) > 0 && fn_str[1] == '.'
Symbol(fn_str[2:end])
else
funcname
end
end
# ╔═╡ e2893867-faf9-4246-b5a0-139c5c9713cd
"""Turn `Symbol("sqrt.")` into `:sqrt`"""
function without_dotsuffix(funcname::Symbol)::Symbol
fn_str = String(funcname)
if length(fn_str) > 0 && fn_str[end] == '.'
Symbol(fn_str[1:end - 1])
else
funcname
end
end
# ╔═╡ 7564fc25-b0a4-4e85-880b-0fc5eace7cec
function split_funcname(funcname_ex::Symbol)::FunctionName
Symbol[funcname_ex |> without_dotprefix |> without_dotsuffix]
end
# ╔═╡ a4bbef4f-caad-46e9-80fd-15e0848ed0c4
"""Turn `Symbol[:Module, :func]` into Symbol("Module.func").
This is **not** the same as the expression `:(Module.func)`, but is used to identify the function name using a single `Symbol` (like normal variables).
This means that it is only the inverse of `ExpressionExplorer.split_funcname` iff `length(parts) ≤ 1`."""
function join_funcname_parts(parts::FunctionName)::Symbol
join(parts .|> String, ".") |> Symbol
end
# ╔═╡ 659305a9-92ab-4092-b960-e97b4c14051e
# this is stupid -- désolé
function is_joined_funcname(joined::Symbol)
occursin('.', String(joined))
end
# ╔═╡ f11d9e65-f5ea-4558-9053-49531ca249a2
assign_to_kw(e::Expr) = e.head == :(=) ? Expr(:kw, e.args...) : e
# ╔═╡ 9d79fda8-edc2-4f8e-ae29-44a46fb0004c
assign_to_kw(x::Any) = x
# ╔═╡ 4b6d3266-f0e7-4b98-b43b-3f3c24fdd797
"Turn `A[i] * B[j,K[l+m]]` into `A[0] * B[0,K[0+0]]` to hide loop indices"
function strip_indexing(x, inside::Bool=false)
if Meta.isexpr(x, :ref)
Expr(:ref, strip_indexing(x.args[1]), strip_indexing.(x.args[2:end], true)...)
elseif Meta.isexpr(x, :call)
Expr(x.head, x.args[1], strip_indexing.(x.args[2:end], inside)...)
elseif x isa Symbol && inside
0
else
x
end
end
# ╔═╡ 76c10921-d08e-4878-816d-f222f4068c2c
md"""
## Main recursive function
Spaghetti code for a spaghetti problem 🍝
"""
# ╔═╡ d88e0e06-3943-4a3c-8ac6-d2c4211f1994
# Possible leaf: value
# Like: a = 1
# 1 is a value (Int64)
function explore!(value, scopestate::ScopeState)::SymbolsState
# includes: LineNumberNode, Int64, String,
return SymbolsState()
end
# ╔═╡ 90dfe536-9988-4083-a6c7-e2777ba19af6
# Possible leaf: symbol
# Like a = x
# x is a symbol
# We handle the assignment separately, and explore!(:a, ...) will not be called.
# Therefore, this method only handles _references_, which are added to the symbolstate, depending on the scopestate.
function explore!(sym::Symbol, scopestate::ScopeState)::SymbolsState
if sym ∈ scopestate.hiddenglobals
SymbolsState()
else
SymbolsState(references=Set([sym]))
end
end
# ╔═╡ 47d7e206-7e23-4f98-b488-85d595819212
function explore_funcdef!(ex::QuoteNode, scopestate::ScopeState)::Tuple{FunctionName,SymbolsState}
explore_funcdef!(ex.value, scopestate)
end
# ╔═╡ b7cf3a4d-dbe8-4058-bac1-702e16cef5e7
function explore_funcdef!(ex::Symbol, scopestate::ScopeState)::Tuple{FunctionName,SymbolsState}
push!(scopestate.hiddenglobals, ex)
Symbol[ex |> without_dotprefix |> without_dotsuffix], SymbolsState()
end
# ╔═╡ 8818219e-860a-4556-b5f5-df318dadd381
function explore_funcdef!(::Any, ::ScopeState)::Tuple{FunctionName,SymbolsState}
Symbol[], SymbolsState()
end
# ╔═╡ ca38f86c-a603-47d5-9c97-17919035da9d
const can_macroexpand_no_bind = Set(Symbol.(["@md_str", "Markdown.@md_str", "@gensym", "Base.@gensym", "@kwdef", "Base.@kwdef", "@enum", "Base.@enum", "@cmd"]))
# ╔═╡ 5057dbf0-aca9-4791-9bff-87d080475a45
const can_macroexpand = can_macroexpand_no_bind ∪ Set(Symbol.(["@bind", "PlutoRunner.@bind"]))
# ╔═╡ 02bcbbd4-9e2b-440b-8c8f-d4ba18848197
macro_kwargs_as_kw(ex::Expr) = Expr(:macrocall, ex.args[1:3]..., assign_to_kw.(ex.args[4:end])...)
# ╔═╡ 3e360b8e-9cf0-4c46-bae1-401971e3e944
function symbolics_mockexpand(s::Any)
# goofy implementation of the syntax described in https://symbolics.juliasymbolics.org/dev/manual/variables/
if Meta.isexpr(s, :ref, 2)
:($(s.args[1]) = $(s.args[2]))
elseif Meta.isexpr(s, :call, 2)
second = s.args[2] === Symbol("..") ? 123 : s.args[2]
:($(symbolics_mockexpand(s.args[1])); $(second) = 123)
elseif s isa Symbol
:($(s) = 123)
else
nothing
end
end
# ╔═╡ d4195845-f036-4a11-bc58-32f9b63b3fd8
is_symbolics_arg(s) = symbolics_mockexpand(s) !== nothing
# ╔═╡ 92d79fb3-0438-4e98-b94b-1eeb01046cd9
maybe_untuple(es) = if length(es) == 1 && Meta.isexpr(first(es), :tuple)
first(es).args
else
es
end
# ╔═╡ 8e4a667d-92aa-4ab8-95af-19d2e65aad5e
"""
If the macro is known to Pluto, expand or 'mock expand' it, if not, return the expression.
Macros can transform the expression into anything - the best way to treat them is to `macroexpand`. The problem is that the macro is only available on the worker process, see https://github.com/fonsp/Pluto.jl/issues/196
"""
function maybe_macroexpand(ex::Expr; recursive=false, expand_bind=true)
result = if ex.head === :macrocall
funcname = ex.args[1] |> split_funcname
funcname_joined = join_funcname_parts(funcname)
args = ex.args[3:end]
if funcname_joined ∈ (expand_bind ? can_macroexpand : can_macroexpand_no_bind)
expanded = macroexpand(PlutoRunner, ex; recursive=false)
Expr(:call, ex.args[1], expanded)
elseif !isempty(args) && Meta.isexpr(args[1], :(:=))
ex = macro_kwargs_as_kw(ex)
# macros like @einsum C[i] := A[i,j] are assignment to C, illegal syntax without macro
ein = args[1]
left = if Meta.isexpr(ein.args[1], :ref)
# assign to the symbol, and save LHS indices as fake RHS argument
ex = Expr(ex.head, ex.args..., Expr(:ref, :Float64, ein.args[1].args[2:end]...))
ein.args[1].args[1]
else
ein.args[1] # scalar case `c := A[i,j]`
end
ein_done = Expr(:(=), left, strip_indexing.(ein.args[2:end])...) # i,j etc. are local
Expr(:call, ex.args[1:2]..., ein_done, strip_indexing.(ex.args[4:end])...)
elseif !isempty(args) && funcname_joined === Symbol("@ode_def")
if args[1] isa Symbol
:($(args[1]) = @ode_def 123)
else
:(@ode_def)
end
elseif !isempty(args) && (funcname_joined === Symbol("@functor") || funcname_joined === Symbol("Flux.@functor"))
Expr(:macrocall, ex.args[1:2]..., :($(args[1]) = 123), ex.args[4:end]...)
elseif !isempty(args) && (funcname_joined === Symbol("@variables") || funcname_joined === Symbol("Symbolics.@variables")) && all(is_symbolics_arg, maybe_untuple(args))
Expr(:macrocall, ex.args[1:2]..., symbolics_mockexpand.(maybe_untuple(args))...)
# elseif length(ex.args) >= 4 && (funcname_joined === Symbol("@variable") || funcname_joined === Symbol("JuMP.@variable"))
# if Meta.isexpr(ex.args[4], :comparison)
# parts = ex.args[4].args[1:2:end]
# if length(parts) == 2
# foldl(parts) do (e,next)
# :($(e) = $(next))
# end
# elseif Meta.isexpr(ex.args[4], :block)
# end
# Expr(:macrocall, ex.args[1:3]..., )
# add more macros here
elseif length(args) ≥ 2 && ex.args[1] != GlobalRef(Core, Symbol("@doc"))
# for macros like @test a ≈ b atol=1e-6, read assignment in 2nd & later arg as keywords
macro_kwargs_as_kw(ex)
else
ex
end
else
ex
end
if recursive && (result isa Expr)
Expr(result.head, maybe_macroexpand.(result.args; recursive=recursive, expand_bind=expand_bind)...)
else
result
end
end
# ╔═╡ a221fc38-5a2d-40f3-8529-caf3dc919374
maybe_macroexpand(ex::Any; kwargs...) = ex
# ╔═╡ 28208774-b99c-479b-9e30-07c6dbc482a2
md"""
## Canonicalize function definitions
"""
# ╔═╡ a30532f6-4987-4e6e-b2ac-daffe9e56df3
# for `function g end`
canonalize(::Symbol) = nothing
# ╔═╡ 184b8cc0-414b-4ffa-a6fe-9a67bbfc3ce2
function hide_argument_name(ex::Expr)
if ex.head == :(::) && length(ex.args) > 1
Expr(:(::), nothing, ex.args[2:end]...)
elseif ex.head == :(...)
Expr(:(...), hide_argument_name(ex.args[1]))
elseif ex.head == :kw
Expr(:kw, hide_argument_name(ex.args[1]), nothing)
else
ex
end
end
# ╔═╡ bad85f9a-6c19-4ca3-b7a5-8ef2b83d3b3a
hide_argument_name(::Symbol) = Expr(:(::), nothing, :Any)
# ╔═╡ 29bf7829-ce07-4c98-a9a4-6bcdbc6f5e41
hide_argument_name(x::Any) = x
# ╔═╡ 365f0095-1ee5-4eef-9693-bec0951b5ee4
"""
Turn a function definition expression (`Expr`) into a "canonical" form, in the sense that two methods that would evaluate to the same method signature have the same canonical form. Part of a solution to https://github.com/fonsp/Pluto.jl/issues/177. Such a canonical form cannot be achieved statically with 100% correctness (impossible), but we can make it good enough to be practical.
# Wait, "evaluate to the same method signature"?
In Pluto, you cannot do definitions of **the same global variable** in different cells. This is needed for reactivity to work, and it avoid ambiguous notebooks and stateful stuff. This rule used to also apply to functions: you had to place all methods of a function in one cell. (Go and read more about methods in Julia if you haven't already.) But this is quite annoying, especially because multiple dispatch is so important in Julia code. So we allow methods of the same function to be defined across multiple cells, but we still want to throw errors when you define **multiple methods with the same signature**, because one overrides the other. For example:
```julia
julia> f(x) = 1
f (generic function with 1 method)
julia> f(x) = 2
f (generic function with 1 method)
``
After adding the second method, the function still has only 1 method. This is because the second definition overrides the first one, instead of being added to the method table. This example should be illegal in Julia, for the same reason that `f = 1` and `f = 2` is illegal. So our problem is: how do we know that two cells will define overlapping methods?
Ideally, we would just evaluate the user's code and **count methods** afterwards, letting Julia do the work. Unfortunately, we need to know this info _before_ we run cells, otherwise we don't know in which order to run a notebook! There are ways to break this circle, but it would complicate our process quite a bit.
Instead, we will do _static analysis_ on the function definition expressions to determine whether they overlap. This is non-trivial. For example, `f(x)` and `f(y::Any)` define the same method. Trickier examples are here: https://github.com/fonsp/Pluto.jl/issues/177#issuecomment-645039993
# Wait, "function definition expressions"?
For example:
```julia
e = :(function f(x::Int, y::String)
x + y
end)
dump(e, maxdepth=2)
#=
gives:
Expr
head: Symbol function
args: Array{Any}((2,))
1: Expr
2: Expr
=#
```
This first arg is the function head:
```julia
e.args[1] == :(f(x::Int, y::String))
```
# Mathematics
Our problem is to find a way to compute the equivalence relation ~ on `H × H`, with `H` the set of function head expressions, defined as:
`a ~ b` iff evaluating both expressions results in a function with exactly one method.
_(More precisely, evaluating `Expr(:function, x, Expr(:block))` with `x ∈ {a, b}`.)_
The equivalence sets are isomorphic to the set of possible Julia methods.
Instead of finding a closed form algorithm for `~`, we search for a _canonical form_: a function `canonical: H -> H` that chooses one canonical expression per equivalence class. It has the property
`canonical(a) = canonical(b)` implies `a ~ b`.
We use this **canonical form** of the function's definition expression as its "signature". We compare these canonical forms when determining whether two function expressions will result in overlapping methods.
# Example
```julia
e1 = :(f(x, z::Any))
e2 = :(g(x, y))
canonalize(e1) == canonalize(e2)
```
```julia
e1 = :(f(x))
e2 = :(g(x, y))
canonalize(e1) != canonalize(e2)
```
```julia
e1 = :(f(a::X, b::wow(ie), c, d...; e=f) where T)
e2 = :(g(z::X, z::wow(ie), z::Any, z... ) where T)
canonalize(e1) == canonalize(e2)
```
"""
function canonalize(ex::Expr)
if ex.head == :where
Expr(:where, canonalize(ex.args[1]), ex.args[2:end]...)
elseif ex.head == :call || ex.head == :tuple
skip_index = ex.head == :call ? 2 : 1
# ex.args[1], if ex.head == :call this is the function name, we dont want it
interesting = filter(ex.args[skip_index:end]) do arg
!(arg isa Expr && arg.head == :parameters)
end
hide_argument_name.(interesting)
elseif ex.head == :(::)
canonalize(ex.args[1])
elseif ex.head == :curly || ex.head == :(<:)
# for struct definitions, which we hackily treat as functions
nothing
else
@error "Failed to canonalize this strange looking function" ex
nothing
end
end
# ╔═╡ ecff407d-8e0c-4a72-babd-46545860a547
begin
# General recursive method. Is never a leaf.
# Modifies the `scopestate`.
function explore!(ex::Expr, scopestate::ScopeState)::SymbolsState
if ex.head == :(=)
# Does not create scope
if ex.args[1] isa Expr && (ex.args[1].head == :call || ex.args[1].head == :where || (ex.args[1].head == :(::) && ex.args[1].args[1] isa Expr && ex.args[1].args[1].head == :call))
# f(x, y) = x + y
# Rewrite to:
# function f(x, y) x + y end
return explore!(Expr(:function, ex.args...), scopestate)
end
val = ex.args[2]
# Handle generic types assignments A{B} = C{B, Int}
if ex.args[1] isa Expr && ex.args[1].head == :curly
assignees, symstate = explore_funcdef!(ex.args[1], scopestate)
innersymstate = union!(symstate, explore!(val, scopestate))
else
assignees = get_assignees(ex.args[1])
symstate = innersymstate = explore!(val, scopestate)
end
global_assignees = get_global_assignees(assignees, scopestate)
# If we are _not_ assigning a global variable, then this symbol hides any global definition with that name
push!(scopestate.hiddenglobals, setdiff(assignees, global_assignees)...)
assigneesymstate = explore!(ex.args[1], scopestate)
push!(scopestate.hiddenglobals, global_assignees...)
push!(symstate.assignments, global_assignees...)
push!(symstate.references, setdiff(assigneesymstate.references, global_assignees)...)
filter!(!all_underscores, symstate.references) # Never record _ as a reference
return symstate
elseif ex.head in modifiers
# We change: a[1] += 123
# to: a[1] = a[1] + 123
# We transform the modifier back to its operator
# for when users redefine the + function
operator = let
s = string(ex.head)
Symbol(s[1:prevind(s, lastindex(s))])
end
expanded_expr = Expr(:(=), ex.args[1], Expr(:call, operator, ex.args[1], ex.args[2]))
return explore!(expanded_expr, scopestate)
elseif ex.head in modifiers_dotprefixed
# We change: a[1] .+= 123
# to: a[1] .= a[1] + 123
operator = Symbol(string(ex.head)[2:end - 1])
expanded_expr = Expr(:(.=), ex.args[1], Expr(:call, operator, ex.args[1], ex.args[2]))
return explore!(expanded_expr, scopestate)
elseif ex.head == :let || ex.head == :for || ex.head == :while
# Creates local scope
return explore_inner_scoped(ex, scopestate)
elseif ex.head == :filter
# In a filter, the assignment is the second expression, the condition the first
return mapfoldr(a -> explore!(a, scopestate), union!, ex.args, init=SymbolsState())
elseif ex.head == :generator
# Creates local scope
# In a `generator`, a single expression is followed by the iterator assignments.
# In a `for`, this expression comes at the end.
# This is not strictly the normal form of a `for` but that's okay
return explore!(Expr(:for, ex.args[2:end]..., ex.args[1]), scopestate)
elseif ex.head == :macrocall
# Does not create sccope
new_ex = maybe_macroexpand(ex)
newnew_ex = Meta.isexpr(new_ex, :macrocall) ? Expr(:call, new_ex.args...) : new_ex
return explore!(newnew_ex, scopestate)
elseif ex.head == :call
# Does not create scope
if is_just_dots(ex.args[1])
funcname = ex.args[1] |> split_funcname
symstate = if length(funcname) == 0
explore!(ex.args[1], scopestate)
elseif length(funcname) == 1
if funcname[1] ∈ scopestate.hiddenglobals
SymbolsState()
else
SymbolsState(funccalls=Set{FunctionName}([funcname]))
end
else
SymbolsState(references=Set{Symbol}([funcname[1]]), funccalls=Set{FunctionName}([funcname]))
end
# Explore code inside function arguments:
union!(symstate, explore!(Expr(:block, ex.args[2:end]...), scopestate))
return symstate
else
return explore!(Expr(:block, ex.args...), scopestate)
end
elseif ex.head == :kw
return explore!(ex.args[2], scopestate)
elseif ex.head == :struct
# Creates local scope
structnameexpr = ex.args[2]
structfields = ex.args[3].args
equiv_func = Expr(:function, Expr(:call, structnameexpr, structfields...), Expr(:block, nothing))
# struct should always be in Global state
globalscopestate = deepcopy(scopestate)
globalscopestate.inglobalscope = true
# we register struct definitions as both a variable and a function. This is because deleting a struct is trickier than just deleting its methods.
inner_symstate = explore!(equiv_func, globalscopestate)
structname = first(keys(inner_symstate.funcdefs)).name |> join_funcname_parts
push!(inner_symstate.assignments, structname)
return inner_symstate
elseif ex.head == :abstract
equiv_func = Expr(:function, ex.args...)
inner_symstate = explore!(equiv_func, scopestate)
abstracttypename = first(keys(inner_symstate.funcdefs)).name |> join_funcname_parts
push!(inner_symstate.assignments, abstracttypename)
return inner_symstate
elseif ex.head == :function || ex.head == :macro
symstate = SymbolsState()
# Creates local scope
funcroot = ex.args[1]
# Because we are entering a new scope, we create a copy of the current scope state, and run it through the expressions.
innerscopestate = deepcopy(scopestate)
innerscopestate.inglobalscope = false
funcname, innersymstate = explore_funcdef!(funcroot, innerscopestate)
# Macro are called using @funcname, but defined with funcname. We need to change that in our scopestate
# (The `!= 0` is for when the function named couldn't be parsed)
if ex.head == :macro && length(funcname) != 0
setdiff!(innerscopestate.hiddenglobals, funcname)
funcname = Symbol[Symbol("@$(funcname[1])")]
push!(innerscopestate.hiddenglobals, funcname...)
end
union!(innersymstate, explore!(Expr(:block, ex.args[2:end]...), innerscopestate))
funcnamesig = FunctionNameSignaturePair(funcname, canonalize(funcroot))
if will_assign_global(funcname, scopestate)
symstate.funcdefs[funcnamesig] = innersymstate
if length(funcname) == 1
push!(scopestate.definedfuncs, funcname[end])
push!(scopestate.hiddenglobals, funcname[end])
elseif length(funcname) > 1
push!(symstate.references, funcname[end - 1]) # reference the module of the extended function
end
else
# The function is not defined globally. However, the function can still modify the global scope or reference globals, e.g.
# let
# function f(x)
# global z = x + a
# end
# f(2)
# end
# so we insert the function's inner symbol state here, as if it was a `let` block.
symstate = innersymstate
end
return symstate
elseif ex.head == :try
symstate = SymbolsState()
# Handle catch first
if ex.args[3] != false
union!(symstate, explore_inner_scoped(ex.args[3], scopestate))
# If we catch a symbol, it could shadow a global reference, remove it
if ex.args[2] != false
setdiff!(symstate.references, Symbol[ex.args[2]])
end
end
# Handle the try block
union!(symstate, explore_inner_scoped(ex.args[1], scopestate))
# Finally, handle finally
if length(ex.args) == 4
union!(symstate, explore_inner_scoped(ex.args[4], scopestate))
end
return symstate
elseif ex.head == :(->)
# Creates local scope
tempname = Symbol("anon", rand(UInt64))
# We will rewrite this to a normal function definition, with a temporary name
funcroot = ex.args[1]
args_ex = if funcroot isa Symbol || (funcroot isa Expr && funcroot.head == :(::))
[funcroot]
elseif funcroot.head == :tuple || funcroot.head == :(...) || funcroot.head == :block
funcroot.args
else
@error "Unknown lambda type"
end
equiv_func = Expr(:function, Expr(:call, tempname, args_ex...), ex.args[2])
return explore!(equiv_func, scopestate)
elseif ex.head == :global
# Does not create scope
# We have one of:
# global x;
# global x = 1;
# global x += 1;
# where x can also be a tuple:
# global a,b = 1,2
globalisee = ex.args[1]
if isa(globalisee, Symbol)
push!(scopestate.exposedglobals, globalisee)
return SymbolsState()
elseif isa(globalisee, Expr)
# temporarily set inglobalscope to true
old = scopestate.inglobalscope
scopestate.inglobalscope = true
result = explore!(globalisee, scopestate)
scopestate.inglobalscope = old
return result
else
@error "unknown global use" ex
return explore!(globalisee, scopestate)
end
return symstate
elseif ex.head == :local
# Does not create scope
localisee = ex.args[1]
if isa(localisee, Symbol)
push!(scopestate.hiddenglobals, localisee)
return SymbolsState()
elseif isa(localisee, Expr) && (localisee.head == :(=) || localisee.head in modifiers)
push!(scopestate.hiddenglobals, get_assignees(localisee.args[1])...)
return explore!(localisee, scopestate)
else
@warn "unknown local use" ex
return explore!(localisee, scopestate)
end
elseif ex.head == :tuple
# Does not create scope
# There are three (legal) cases:
# 1. Creating a tuple:
# (a, b, c)
# 2. Creating a named tuple:
# (a=1, b=2, c=3)
# 3. Multiple assignments
# a,b,c = 1,2,3
# This parses to:
# head = :tuple
# args = [:a, :b, :(c=1), :2, :3]
#
# 🤔
# we turn it into two expressions:
#
# (a, b) = (2, 3)
# (c = 1)
#
# and explore those :)
indexoffirstassignment = findfirst(a -> isa(a, Expr) && a.head == :(=), ex.args)
if indexoffirstassignment !== nothing
# we have one of two cases, see next `if`
indexofsecondassignment = findnext(a -> isa(a, Expr) && a.head == :(=), ex.args, indexoffirstassignment + 1)
if length(ex.args) == 1 || indexofsecondassignment !== nothing
# 2.
# we have a named tuple, e.g. (a=1, b=2)
new_args = map(ex.args) do a
(a isa Expr && a.head == :(=)) ? a.args[2] : a
end
return explore!(Expr(:block, new_args...), scopestate)
else
# 3.
# we have a tuple assignment, e.g. `a, (b, c) = [1, [2, 3]]`
before = ex.args[1:indexoffirstassignment - 1]
after = ex.args[indexoffirstassignment + 1:end]
symstate_middle = explore!(ex.args[indexoffirstassignment], scopestate)
symstate_outer = explore!(Expr(:(=), Expr(:tuple, before...), Expr(:block, after...)), scopestate)
return union!(symstate_middle, symstate_outer)
end
else
# 1.
# good ol' tuple
return explore!(Expr(:block, ex.args...), scopestate)
end
elseif ex.head == :(.) && ex.args[2] isa Expr && ex.args[2].head == :tuple
# pointwise function call, e.g. sqrt.(nums)
# we rewrite to a regular call
return explore!(Expr(:call, ex.args[1], ex.args[2].args...), scopestate)
elseif ex.head == :using || ex.head == :import
imports = if ex.args[1].head == :(:)
ex.args[1].args[2:end]
else
ex.args
end
packagenames = map(e -> e.args[end], imports)
return SymbolsState(assignments=Set{Symbol}(packagenames))
elseif ex.head == :quote
# We ignore contents
return SymbolsState()
elseif ex.head == :module
# We ignore contents; the module name is a definition
return SymbolsState(assignments=Set{Symbol}([ex.args[2]]))
else
# fallback, includes:
# begin, block, do, toplevel, const
# (and hopefully much more!)
# Does not create scope (probably)
return mapfoldl(a -> explore!(a, scopestate), union!, ex.args, init=SymbolsState())
end
end
"Return the function name and the SymbolsState from argument defaults. Add arguments as hidden globals to the `scopestate`.
Is also used for `struct` and `abstract`."
function explore_funcdef!(ex::Expr, scopestate::ScopeState)::Tuple{FunctionName,SymbolsState}
if ex.head == :call
params_to_explore = ex.args[2:end]
# Using the keyword args syntax f(;y) the :parameters node is the first arg in the AST when it should
# be explored last. We change from (parameters, ...) to (..., parameters)
if length(params_to_explore) >= 2 && params_to_explore[1] isa Expr && params_to_explore[1].head == :parameters
params_to_explore = [params_to_explore[2:end]..., params_to_explore[1]]
end
# Handle struct as callables, `(obj::MyType)(a, b) = ...`
# or `function (obj::MyType)(a, b) ...; end` by rewriting it as:
# function MyType(obj, a, b) ...; end
funcroot = ex.args[1]
if funcroot isa Expr && funcroot.head == :(::)
return explore_funcdef!(Expr(:call, reverse(funcroot.args)..., params_to_explore...), scopestate)
end
# get the function name
name, symstate = explore_funcdef!(funcroot, scopestate)
# and explore the function arguments
return mapfoldl(a -> explore_funcdef!(a, scopestate), union!, params_to_explore, init=(name, symstate))
elseif ex.head == :(::) || ex.head == :kw || ex.head == :(=)
# account for unnamed params, like in f(::Example) = 1
if ex.head == :(::) && length(ex.args) == 1
symstate = explore!(ex.args[1], scopestate)
return Symbol[], symstate
end
# recurse
name, symstate = explore_funcdef!(ex.args[1], scopestate)
if length(ex.args) > 1
# use `explore!` (not `explore_funcdef!`) to explore the argument's default value - these can contain arbitrary expressions
union!(symstate, explore!(ex.args[2], scopestate))