-
-
Notifications
You must be signed in to change notification settings - Fork 292
/
Copy pathPlutoRunner.jl
2508 lines (2052 loc) Β· 91 KB
/
PlutoRunner.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
# Will be evaluated _inside_ the workspace process.
# Pluto does most things on process 1 (the server), and it uses little workspace processes to evaluate notebook code in.
# These baby processes don't import Pluto, they only import this module. Functions from this module are called by WorkspaceManager.jl via Distributed
# So when reading this file, pretend that you are living in process 2, and you are communicating with Pluto's server, who lives in process 1.
# The package environment that this file is loaded with is the NotebookProcessProject.toml file in this directory.
# SOME EXTRA NOTES
# 1. The entire PlutoRunner should be a single file.
# 2. We restrict the communication between this PlutoRunner and the Pluto server to only use *Base Julia types*, like `String`, `Dict`, `NamedTuple`, etc.
# These restriction are there to allow flexibility in the way that this file is loaded on a runner process, which is something that we might want to change in the future, like when we make the transition to our own Distributed.
module PlutoRunner
# import these two so that they can be imported from Main on the worker process if it launches without the stdlibs in its LOAD_PATH
import Markdown
import InteractiveUtils
using Markdown
import Markdown: html, htmlinline, LaTeX, withtag, htmlesc
import Distributed
import Base64
import FuzzyCompletions: Completion, BslashCompletion, ModuleCompletion, PropertyCompletion, FieldCompletion, PathCompletion, DictCompletion, completions, completion_text, score
import Base: show, istextmime
import UUIDs: UUID, uuid4
import Dates: DateTime
import Logging
import REPL
export @bind
# This is not a struct to make it easier to pass these objects between distributed processes.
const MimedOutput = Tuple{Union{String,Vector{UInt8},Dict{Symbol,Any}},MIME}
const ObjectID = typeof(objectid("hello computer"))
const ObjectDimPair = Tuple{ObjectID,Int64}
struct CachedMacroExpansion
original_expr_hash::UInt64
expanded_expr::Expr
expansion_duration::UInt64
has_pluto_hook_features::Bool
did_mention_expansion_time::Bool
expansion_logs::Vector{Any}
end
const cell_expanded_exprs = Dict{UUID,CachedMacroExpansion}()
const supported_integration_features = Any[]
abstract type SpecialPlutoExprValue end
struct GiveMeCellID <: SpecialPlutoExprValue end
struct GiveMeRerunCellFunction <: SpecialPlutoExprValue end
struct GiveMeRegisterCleanupFunction <: SpecialPlutoExprValue end
###
# WORKSPACE MANAGER
###
"""
`PlutoRunner.notebook_id[]` gives you the notebook ID used to identify a session.
"""
const notebook_id = Ref{UUID}(uuid4())
function revise_if_possible(m::Module)
# Revise.jl support
if isdefined(m, :Revise) &&
isdefined(m.Revise, :revise) && m.Revise.revise isa Function &&
isdefined(m.Revise, :revision_queue) && m.Revise.revision_queue isa AbstractSet
if !isempty(m.Revise.revision_queue) # to avoid the sleep(0.01) in revise()
m.Revise.revise()
end
end
end
"These expressions get evaluated inside every newly create module inside a `Workspace`."
const workspace_preamble = [
:(using Main.PlutoRunner, Main.PlutoRunner.Markdown, Main.PlutoRunner.InteractiveUtils),
:(show, showable, showerror, repr, string, print, println), # https://github.com/JuliaLang/julia/issues/18181
]
const PLUTO_INNER_MODULE_NAME = Symbol("#___this_pluto_module_name")
const moduleworkspace_count = Ref(0)
function increment_current_module()::Symbol
id = (moduleworkspace_count[] += 1)
new_workspace_name = Symbol("workspace#", id)
Core.eval(Main, :(
module $(new_workspace_name)
$(workspace_preamble...)
const $(PLUTO_INNER_MODULE_NAME) = $(new_workspace_name)
end
))
new_workspace_name
end
function wrap_dot(ref::GlobalRef)
complete_mod_name = fullname(ref.mod) |> wrap_dot
Expr(:(.), complete_mod_name, QuoteNode(ref.name))
end
function wrap_dot(name)
if length(name) == 1
name[1]
else
Expr(:(.), wrap_dot(name[1:end-1]), QuoteNode(name[end]))
end
end
"""
collect_and_eliminate_globalrefs!(ref::Union{GlobalRef,Expr}, mutable_ref_list::Vector{Pair{Symbol,Symbol}}=[])
Goes through an expression and removes all "global" references to workspace modules (e.g. Main.workspace#XXX).
It collects the names that we replaced these references with, so that we can add assignments to these special names later.
This is useful for us because when we macroexpand, the global refs will normally point to the module it was built in.
We don't re-build the macro in every workspace, so we need to remove these refs manually in order to point to the new module instead.
TODO? Don't remove the refs, but instead replace them with a new ref pointing to the new module?
"""
function collect_and_eliminate_globalrefs!(ref::GlobalRef, mutable_ref_list=[])
if is_pluto_workspace(ref.mod)
new_name = gensym(ref.name)
push!(mutable_ref_list, ref.name => new_name)
new_name
else
ref
end
end
function collect_and_eliminate_globalrefs!(expr::Expr, mutable_ref_list=[])
# Fix for .+ and .|> inside macros
# https://github.com/fonsp/Pluto.jl/pull/1032#issuecomment-868819317
# I'm unsure if this was all necessary but π€·ββοΈ
# I take the :call with a GlobalRef to `.|>` or `.+` as args[1],
# and then I convert it into a `:.` expr, which is basically (|>).(args...)
# which is consistent for us to handle.
if expr.head == :call && expr.args[1] isa GlobalRef && startswith(string(expr.args[1].name), ".")
old_globalref = expr.args[1]
non_broadcast_name = string(old_globalref.name)[begin+1:end]
new_globalref = GlobalRef(old_globalref.mod, Symbol(non_broadcast_name))
new_expr = Expr(:., new_globalref, Expr(:tuple, expr.args[begin+1:end]...))
result = collect_and_eliminate_globalrefs!(new_expr, mutable_ref_list)
return result
else
Expr(expr.head, map(arg -> collect_and_eliminate_globalrefs!(arg, mutable_ref_list), expr.args)...)
end
end
collect_and_eliminate_globalrefs!(other, mutable_ref_list=[]) = other
function globalref_to_workspaceref(expr)
mutable_ref_list = Pair{Symbol, Symbol}[]
new_expr = collect_and_eliminate_globalrefs!(expr, mutable_ref_list)
Expr(:block,
# Create new lines to assign to the replaced names of the global refs.
# This way the expression explorer doesn't care (it just sees references to variables outside of the workspace),
# and the variables don't get overwriten by local assigments to the same name (because we have special names).
(mutable_ref_list .|> ref -> :(local $(ref[2])))...,
map(mutable_ref_list) do ref
# I can just do Expr(:isdefined, ref[1]) here, but it feels better to macroexpand,
# because it's more obvious what's going on, and when they ever change the ast, we're safe :D
macroexpand(Main, quote
if @isdefined($(ref[1]))
$(ref[2]) = $(ref[1])
end
end)
end...,
new_expr,
)
end
replace_pluto_properties_in_expr(::GiveMeCellID; cell_id, kwargs...) = cell_id
replace_pluto_properties_in_expr(::GiveMeRerunCellFunction; rerun_cell_function, kwargs...) = rerun_cell_function
replace_pluto_properties_in_expr(::GiveMeRegisterCleanupFunction; register_cleanup_function, kwargs...) = register_cleanup_function
replace_pluto_properties_in_expr(expr::Expr; kwargs...) = Expr(expr.head, map(arg -> replace_pluto_properties_in_expr(arg; kwargs...), expr.args)...)
replace_pluto_properties_in_expr(m::Module; kwargs...) = if is_pluto_workspace(m)
PLUTO_INNER_MODULE_NAME
else
m
end
replace_pluto_properties_in_expr(other; kwargs...) = other
function replace_pluto_properties_in_expr(ln::LineNumberNode; cell_id, kwargs...) # See https://github.com/fonsp/Pluto.jl/pull/2241
file = string(ln.file)
out = if endswith(file, string(cell_id))
# We already have the correct cell_id in this LineNumberNode
ln
else
# We append to the LineNumberNode file #@#==# + cell_id
LineNumberNode(ln.line, Symbol(file * "#@#==#$(cell_id)"))
end
return out
end
"Similar to [`replace_pluto_properties_in_expr`](@ref), but just checks for existance and doesn't check for [`GiveMeCellID`](@ref)"
has_hook_style_pluto_properties_in_expr(::GiveMeRerunCellFunction) = true
has_hook_style_pluto_properties_in_expr(::GiveMeRegisterCleanupFunction) = true
has_hook_style_pluto_properties_in_expr(expr::Expr)::Bool = any(has_hook_style_pluto_properties_in_expr, expr.args)
has_hook_style_pluto_properties_in_expr(other) = false
function sanitize_expr(ref::GlobalRef)
wrap_dot(ref)
end
function sanitize_expr(expr::Expr)
Expr(expr.head, sanitize_expr.(expr.args)...)
end
sanitize_expr(linenumbernode::LineNumberNode) = linenumbernode
sanitize_expr(quoted::QuoteNode) = QuoteNode(sanitize_expr(quoted.value))
sanitize_expr(bool::Bool) = bool
sanitize_expr(symbol::Symbol) = symbol
sanitize_expr(number::Union{Int,Int8,Float32,Float64}) = number
# In all cases of more complex objects, we just don't send it.
# It's not like the expression explorer will look into them at all.
sanitize_expr(other) = nothing
"""
All code necessary for throwing errors when cells return.
Right now it just throws an error from the position of the return,
this is nice because you get to the line number of the return.
However, now it is suddenly possibly to catch the return error...
so we might want to actually return the error instead of throwing it,
and then handle it in `run_expression` or something.
"""
module CantReturnInPluto
struct CantReturnInPlutoException end
function Base.showerror(io::IO, ::CantReturnInPlutoException)
print(io, "Pluto: You can only use return inside a function.")
end
"""
We do macro expansion now, so we can also check for `return` statements "statically".
This method goes through an expression and replaces all `return` statements with `throw(CantReturnInPlutoException())`
"""
function replace_returns_with_error(expr::Expr)::Expr
if expr.head == :return
:(throw($(CantReturnInPlutoException())))
elseif expr.head == :quote
Expr(:quote, replace_returns_with_error_in_interpolation(expr.args[1]))
elseif Meta.isexpr(expr, :(=)) && expr.args[1] isa Expr && (expr.args[1].head == :call || expr.args[1].head == :where || (expr.args[1].head == :(::) && expr.args[1].args[1] isa Expr && expr.args[1].args[1].head == :call))
# f(x) = ...
expr
elseif expr.head == :function || expr.head == :macro || expr.head == :(->)
expr
else
Expr(expr.head, map(arg -> replace_returns_with_error(arg), expr.args)...)
end
end
replace_returns_with_error(other) = other
"Go through a quoted expression and remove returns"
function replace_returns_with_error_in_interpolation(expr::Expr)
if expr.head == :$
Expr(:$, replace_returns_with_error_in_interpolation(expr.args[1]))
else
# We are still in a quote, so we do go deeper, but we keep ignoring everything except :$'s
Expr(expr.head, map(arg -> replace_returns_with_error_in_interpolation(arg), expr.args)...)
end
end
replace_returns_with_error_in_interpolation(ex) = ex
end
function try_macroexpand(mod::Module, notebook_id::UUID, cell_id::UUID, expr; capture_stdout::Bool=true)
# Remove the precvious cached expansion, so when we error somewhere before we update,
# the old one won't linger around and get run accidentally.
pop!(cell_expanded_exprs, cell_id, nothing)
# Remove toplevel block, as that screws with the computer and everything
expr_not_toplevel = if expr.head == :toplevel || expr.head == :block
Expr(:block, expr.args...)
else
@warn "try_macroexpand expression not :toplevel or :block" expr
Expr(:block, expr)
end
logger = get!(() -> PlutoCellLogger(notebook_id, cell_id), pluto_cell_loggers, cell_id)
if logger.workspace_count < moduleworkspace_count[]
logger = pluto_cell_loggers[cell_id] = PlutoCellLogger(notebook_id, cell_id)
end
capture_logger = CaptureLogger(nothing, logger, Dict[])
expanded_expr, elapsed_ns = with_logger_and_io_to_logs(capture_logger; capture_stdout, stdio_loglevel=stdout_log_level) do
elapsed_ns = time_ns()
expanded_expr = macroexpand(mod, expr_not_toplevel)::Expr
elapsed_ns = time_ns() - elapsed_ns
expanded_expr, elapsed_ns
end
logs = capture_logger.logs
# Removes baked in references to the module this was macroexpanded in.
# Fix for https://github.com/fonsp/Pluto.jl/issues/1112
expr_without_return = CantReturnInPluto.replace_returns_with_error(expanded_expr)::Expr
expr_without_globalrefs = globalref_to_workspaceref(expr_without_return)
has_pluto_hook_features = has_hook_style_pluto_properties_in_expr(expr_without_globalrefs)
expr_to_save = replace_pluto_properties_in_expr(expr_without_globalrefs;
cell_id,
rerun_cell_function=() -> rerun_cell_from_notebook(cell_id),
register_cleanup_function=(fn) -> UseEffectCleanups.register_cleanup(fn, cell_id),
)
did_mention_expansion_time = false
cell_expanded_exprs[cell_id] = CachedMacroExpansion(
expr_hash(expr),
expr_to_save,
elapsed_ns,
has_pluto_hook_features,
did_mention_expansion_time,
logs,
)
return (sanitize_expr(expr_to_save), expr_hash(expr_to_save))
end
function get_module_names(workspace_module, module_ex::Expr)
try
Core.eval(workspace_module, Expr(:call, :names, module_ex)) |> Set{Symbol}
catch
Set{Symbol}()
end
end
function collect_soft_definitions(workspace_module, modules::Set{Expr})
mapreduce(module_ex -> get_module_names(workspace_module, module_ex), union!, modules; init=Set{Symbol}())
end
###
# EVALUATING NOTEBOOK CODE
###
struct Computer
f::Function
expr_id::ObjectID
input_globals::Vector{Symbol}
output_globals::Vector{Symbol}
end
expr_hash(e::Expr) = objectid(e.head) + mapreduce(p -> objectid((p[1], expr_hash(p[2]))), +, enumerate(e.args); init=zero(ObjectID))
expr_hash(x) = objectid(x)
const computers = Dict{UUID,Computer}()
const computer_workspace = Main
const cells_with_hook_functionality_active = Set{UUID}()
"Registers a new computer for the cell, cleaning up the old one if there is one."
function register_computer(expr::Expr, key::ObjectID, cell_id::UUID, input_globals::Vector{Symbol}, output_globals::Vector{Symbol})
@gensym result
e = Expr(:function, Expr(:call, gensym(:function_wrapped_cell), input_globals...), Expr(:block,
Expr(:(=), result, timed_expr(expr)),
Expr(:tuple,
result,
Expr(:tuple, map(x -> :(@isdefined($(x)) ? $(x) : $(OutputNotDefined())), output_globals)...)
)
))
f = Core.eval(computer_workspace, e)
if haskey(computers, cell_id)
delete_computer!(computers, cell_id)
end
computers[cell_id] = Computer(f, key, input_globals, output_globals)
end
function delete_computer!(computers::Dict{UUID,Computer}, cell_id::UUID)
computer = pop!(computers, cell_id)
UseEffectCleanups.trigger_cleanup(cell_id)
Base.visit(Base.delete_method, methods(computer.f).mt) # Make the computer function uncallable
end
parse_cell_id(filename::Symbol) = filename |> string |> parse_cell_id
parse_cell_id(filename::AbstractString) =
match(r"#==#(.*)", filename).captures |> only |> UUID
module UseEffectCleanups
import UUIDs: UUID
const cell_cleanup_functions = Dict{UUID,Set{Function}}()
function register_cleanup(f::Function, cell_id::UUID)
cleanup_functions = get!(cell_cleanup_functions, cell_id, Set{Function}())
push!(cleanup_functions, f)
nothing
end
function trigger_cleanup(cell_id::UUID)
for cleanup_func in get!(cell_cleanup_functions, cell_id, Set{Function}())
try
cleanup_func()
catch error
@warn "Cleanup function gave an error" cell_id error stacktrace=stacktrace(catch_backtrace())
end
end
delete!(cell_cleanup_functions, cell_id)
end
end
quote_if_needed(x) = x
quote_if_needed(x::Union{Expr, Symbol, QuoteNode, LineNumberNode}) = QuoteNode(x)
struct OutputNotDefined end
function compute(m::Module, computer::Computer)
# 1. get the referenced global variables
# this might error if the global does not exist, which is exactly what we want
input_global_values = Vector{Any}(undef, length(computer.input_globals))
for (i, s) in enumerate(computer.input_globals)
input_global_values[i] = getfield(m, s)
end
# 2. run the function
out = Base.invokelatest(computer.f, input_global_values...)
result, output_global_values = out
for (name, val) in zip(computer.output_globals, output_global_values)
# Core.eval(m, Expr(:(=), name, quote_if_needed(val)))
Core.eval(m, quote
if $(quote_if_needed(val)) !== $(OutputNotDefined())
$(name) = $(quote_if_needed(val))
end
end)
end
result
end
"Wrap `expr` inside a timing block."
function timed_expr(expr::Expr)::Expr
# @assert ExpressionExplorer.is_toplevel_expr(expr)
@gensym result
@gensym elapsed_ns
# we don't use `quote ... end` here to avoid the LineNumberNodes that it adds (these would taint the stack trace).
Expr(:block,
:(local $elapsed_ns = time_ns()),
:(local $result = $expr),
:($elapsed_ns = time_ns() - $elapsed_ns),
:(($result, $elapsed_ns)),
)
end
"""
Run the expression or function inside a try ... catch block, and verify its "return proof".
"""
function run_inside_trycatch(m::Module, f::Union{Expr,Function})::Tuple{Any,Union{UInt64,Nothing}}
return try
if f isa Expr
# We eval `f` in the global scope of the workspace module:
Core.eval(m, f)
else
# f is a function
f()
end
catch ex
bt = stacktrace(catch_backtrace())
(CapturedException(ex, bt), nothing)
end
end
add_runtimes(::Nothing, ::UInt64) = nothing
add_runtimes(a::UInt64, b::UInt64) = a+b
contains_macrocall(expr::Expr) = if expr.head == :macrocall
true
elseif expr.head == :module
# Modules don't get expanded, sadly, so we don't touch it
false
else
any(arg -> contains_macrocall(arg), expr.args)
end
contains_macrocall(other) = false
"""
Run the given expression in the current workspace module. If the third argument is `nothing`, then the expression will be `Core.eval`ed. The result and runtime are stored inside [`cell_results`](@ref) and [`cell_runtimes`](@ref).
If the third argument is a `Tuple{Set{Symbol}, Set{Symbol}}` containing the referenced and assigned variables of the expression (computed by the ExpressionExplorer), then the expression will be **wrapped inside a function**, with the references as inputs, and the assignments as outputs. Instead of running the expression directly, Pluto will call this function, with the right globals as inputs.
This function is memoized: running the same expression a second time will simply call the same generated function again. This is much faster than evaluating the expression, because the function only needs to be Julia-compiled once. See https://github.com/fonsp/Pluto.jl/pull/720
"""
function run_expression(
m::Module,
expr::Any,
notebook_id::UUID,
cell_id::UUID,
@nospecialize(function_wrapped_info::Union{Nothing,Tuple{Set{Symbol},Set{Symbol}}}=nothing),
@nospecialize(forced_expr_id::Union{ObjectID,Nothing}=nothing);
user_requested_run::Bool=true,
capture_stdout::Bool=true,
)
if user_requested_run
# TODO Time elapsed? Possibly relays errors in cleanup function?
UseEffectCleanups.trigger_cleanup(cell_id)
# TODO Could also put explicit `try_macroexpand` here, to make clear that user_requested_run => fresh macro identity
end
old_currently_running_cell_id = currently_running_cell_id[]
currently_running_cell_id[] = cell_id
logger = get!(() -> PlutoCellLogger(notebook_id, cell_id), pluto_cell_loggers, cell_id)
if logger.workspace_count < moduleworkspace_count[]
logger = pluto_cell_loggers[cell_id] = PlutoCellLogger(notebook_id, cell_id)
end
# reset published objects
cell_published_objects[cell_id] = Dict{String,Any}()
# reset registered bonds
cell_registered_bond_names[cell_id] = Set{Symbol}()
# If the cell contains macro calls, we want those macro calls to preserve their identity,
# so we macroexpand this earlier (during expression explorer stuff), and then we find it here.
# NOTE Turns out sometimes there is no macroexpanded version even though the expression contains macro calls...
# .... So I macroexpand when there is no cached version just to be sure π€·ββοΈ
# NOTE Errors during try_macroexpand will cause no expanded version to be stored.
# .... This is fine, because it allows us to try again here and throw the error...
# .... But ideally we wouldn't re-macroexpand and store the error the first time (TODO-ish)
if !haskey(cell_expanded_exprs, cell_id) || cell_expanded_exprs[cell_id].original_expr_hash != expr_hash(expr)
try
try_macroexpand(m, notebook_id, cell_id, expr; capture_stdout)
catch e
result = CapturedException(e, stacktrace(catch_backtrace()))
cell_results[cell_id], cell_runtimes[cell_id] = (result, nothing)
return (result, nothing)
end
end
# We can be sure there is a cached expression now, yay
expanded_cache = cell_expanded_exprs[cell_id]
original_expr = expr
expr = expanded_cache.expanded_expr
# Re-play logs from expansion cache
for log in expanded_cache.expansion_logs
(level, msg, _module, group, id, file, line, kwargs) = log
Logging.handle_message(logger, level, msg, _module, group, id, file, line; kwargs...)
end
empty!(expanded_cache.expansion_logs)
# We add the time it took to macroexpand to the time for the first call,
# but we make sure we don't mention it on subsequent calls
expansion_runtime = if expanded_cache.did_mention_expansion_time === false
did_mention_expansion_time = true
cell_expanded_exprs[cell_id] = CachedMacroExpansion(
expanded_cache.original_expr_hash,
expanded_cache.expanded_expr,
expanded_cache.expansion_duration,
expanded_cache.has_pluto_hook_features,
did_mention_expansion_time,
expanded_cache.expansion_logs,
)
expanded_cache.expansion_duration
else
zero(UInt64)
end
if contains_macrocall(expr)
@error "Expression contains a macrocall" expr
throw("Expression still contains macro calls!!")
end
result, runtime = with_logger_and_io_to_logs(logger; capture_stdout, stdio_loglevel=stdout_log_level) do # about 200ns + 3ms overhead
if function_wrapped_info === nothing
toplevel_expr = Expr(:toplevel, expr)
wrapped = timed_expr(toplevel_expr)
ans, runtime = run_inside_trycatch(m, wrapped)
(ans, add_runtimes(runtime, expansion_runtime))
else
expr_id = forced_expr_id !== nothing ? forced_expr_id : expr_hash(expr)
local computer = get(computers, cell_id, nothing)
if computer === nothing || computer.expr_id !== expr_id
try
computer = register_computer(expr, expr_id, cell_id, collect.(function_wrapped_info)...)
catch e
# @error "Failed to generate computer function" expr exception=(e,stacktrace(catch_backtrace()))
return run_expression(m, original_expr, notebook_id, cell_id, nothing; user_requested_run=user_requested_run)
end
end
# This check solves the problem of a cell like `false && variable_that_does_not_exist`. This should run without error, but will fail in our function-wrapping-magic because we get the value of `variable_that_does_not_exist` before calling the generated function.
# The fix is to detect this situation and run the expression in the classical way.
ans, runtime = if any(name -> !isdefined(m, name), computer.input_globals)
# Do run_expression but with function_wrapped_info=nothing so it doesn't go in a Computer()
# @warn "Got variables that don't exist, running outside of computer" not_existing=filter(name -> !isdefined(m, name), computer.input_globals)
run_expression(m, original_expr, notebook_id, cell_id; user_requested_run)
else
run_inside_trycatch(m, () -> compute(m, computer))
end
ans, add_runtimes(runtime, expansion_runtime)
end
end
currently_running_cell_id[] = old_currently_running_cell_id
if (result isa CapturedException) && (result.ex isa InterruptException)
throw(result.ex)
end
cell_results[cell_id], cell_runtimes[cell_id] = result, runtime
end
precompile(run_expression, (Module, Expr, UUID, UUID, Nothing, Nothing))
# Channel to trigger implicits run
const run_channel = Channel{UUID}(10)
function rerun_cell_from_notebook(cell_id::UUID)
# make sure only one of this cell_id is in the run channel
# by emptying it and filling it again
new_uuids = UUID[]
while isready(run_channel)
uuid = take!(run_channel)
if uuid != cell_id
push!(new_uuids, uuid)
end
end
for uuid in new_uuids
put!(run_channel, uuid)
end
put!(run_channel, cell_id)
end
###
# DELETING GLOBALS
###
# This function checks whether the symbol provided to it represents a name of a memoized_cache variable from Memoize.jl, see https://github.com/fonsp/Pluto.jl/issues/2305 for more details
is_memoized_cache(s::Symbol) = startswith(string(s), "##") && endswith(string(s), "_memoized_cache")
function do_reimports(workspace_name, module_imports_to_move::Set{Expr})
for expr in module_imports_to_move
try
Core.eval(workspace_name, expr)
catch e end # TODO catch specificallly
end
end
"""
Move some of the globals over from one workspace to another. This is how Pluto "deletes" globals - it doesn't, it just executes your new code in a new module where those globals are not defined.
Notebook code does run in `Main` - it runs in workspace modules. Every time that you run cells, a new module is created, called `Main.workspace123` with `123` an increasing number.
The trick boils down to two things:
1. When we create a new workspace module, we move over some of the global from the old workspace. (But not the ones that we want to 'delete'!)
2. If a function used to be defined, but now we want to delete it, then we go through the method table of that function and snoop out all methods that we defined by us, and not by another package. This is how we reverse extending external functions. For example, if you run a cell with `Base.sqrt(s::String) = "the square root of" * s`, and then delete that cell, then you can still call `sqrt(1)` but `sqrt("one")` will err. Cool right!
"""
function move_vars(
old_workspace_name::Symbol,
new_workspace_name::Symbol,
vars_to_delete::Set{Symbol},
methods_to_delete::Set{Tuple{UUID,Vector{Symbol}}},
module_imports_to_move::Set{Expr},
invalidated_cell_uuids::Set{UUID},
keep_registered::Set{Symbol},
)
old_workspace = getfield(Main, old_workspace_name)
new_workspace = getfield(Main, new_workspace_name)
do_reimports(new_workspace, module_imports_to_move)
for uuid in invalidated_cell_uuids
pop!(cell_expanded_exprs, uuid, nothing)
end
# TODO: delete
Core.eval(new_workspace, :(import ..($(old_workspace_name))))
old_names = names(old_workspace, all=true, imported=true)
funcs_with_no_methods_left = filter(methods_to_delete) do f
!try_delete_toplevel_methods(old_workspace, f)
end
name_symbols_of_funcs_with_no_methods_left = last.(last.(funcs_with_no_methods_left))
for symbol in old_names
if (symbol β vars_to_delete) || (symbol β name_symbols_of_funcs_with_no_methods_left)
# var will be redefined - unreference the value so that GC can snoop it
if haskey(registered_bond_elements, symbol) && symbol β keep_registered
delete!(registered_bond_elements, symbol)
end
# free memory for other variables
# & delete methods created in the old module:
# for example, the old module might extend an imported function:
# `import Base: show; show(io::IO, x::Flower) = print(io, "π·")`
# when you delete/change this cell, you want this extension to disappear.
if isdefined(old_workspace, symbol)
# try_delete_toplevel_methods(old_workspace, symbol)
try
# We are clearing this variable from the notebook, so we need to find it's root
# If its root is "controlled" by Pluto's workspace system (and is not a package module for example),
# we are just clearing out the definition in the old_module, besides giving an error
# (so that's what that `catch; end` is for)
# will not actually free it from Julia, the older module will still have a reference.
module_to_remove_from = which(old_workspace, symbol)
if is_pluto_controlled(module_to_remove_from) && !isconst(module_to_remove_from, symbol)
Core.eval(module_to_remove_from, :($(symbol) = nothing))
end
catch; end # sometimes impossible, eg. when $symbol was constant
end
else
# var will not be redefined in the new workspace, move it over
if !(symbol == :eval || symbol == :include || (string(symbol)[1] == '#' && !is_memoized_cache(symbol)) || startswith(string(symbol), "workspace#"))
try
getfield(old_workspace, symbol)
# Expose the variable in the scope of `new_workspace`
Core.eval(new_workspace, :(import ..($(old_workspace_name)).$(symbol)))
catch ex
if !(ex isa UndefVarError)
@warn "Failed to move variable $(symbol) to new workspace:"
showerror(original_stderr, ex, stacktrace(catch_backtrace()))
end
end
end
end
end
revise_if_possible(new_workspace)
end
"Return whether the `method` was defined inside this notebook, and not in external code."
isfromcell(method::Method, cell_id::UUID) = endswith(String(method.file), string(cell_id))
"""
delete_method_doc(m::Method)
Tries to delete the documentation for this method, this is used when methods are removed.
"""
function delete_method_doc(m::Method)
binding = Docs.Binding(m.module, m.name)
meta = Docs.meta(m.module)
if haskey(meta, binding)
method_sig = Tuple{m.sig.parameters[2:end]...}
multidoc = meta[binding]
filter!(multidoc.order) do msig
if method_sig == msig
pop!(multidoc.docs, msig)
false
else
true
end
end
end
end
"""
Delete all methods of `f` that were defined in this notebook, and leave the ones defined in other packages, base, etc. β
Return whether the function has any methods left after deletion.
"""
function delete_toplevel_methods(f::Function, cell_id::UUID)::Bool
# we can delete methods of functions!
# instead of deleting all methods, we only delete methods that were defined in this notebook. This is necessary when the notebook code extends a function from remote code
methods_table = typeof(f).name.mt
deleted_sigs = Set{Type}()
Base.visit(methods_table) do method # iterates through all methods of `f`, including overridden ones
if isfromcell(method, cell_id) && getfield(method, deleted_world) == alive_world_val
Base.delete_method(method)
delete_method_doc(method)
push!(deleted_sigs, method.sig)
end
end
# if `f` is an extension to an external function, and we defined a method that overrides a method, for example,
# we define `Base.isodd(n::Integer) = rand(Bool)`, which overrides the existing method `Base.isodd(n::Integer)`
# calling `Base.delete_method` on this method won't bring back the old method, because our new method still exists in the method table, and it has a world age which is newer than the original. (our method has a deleted_world value set, which disables it)
#
# To solve this, we iterate again, and _re-enable any methods that were hidden in this way_, by adding them again to the method table with an even newer`primary_world`.
if !isempty(deleted_sigs)
to_insert = Method[]
Base.visit(methods_table) do method
if !isfromcell(method, cell_id) && method.sig β deleted_sigs
push!(to_insert, method)
end
end
# separate loop to avoid visiting the recently added method
for method in Iterators.reverse(to_insert)
setfield!(method, primary_world, one(typeof(alive_world_val))) # `1` will tell Julia to increment the world counter and set it as this function's world
setfield!(method, deleted_world, alive_world_val) # set the `deleted_world` property back to the 'alive' value (for Julia v1.6 and up)
ccall(:jl_method_table_insert, Cvoid, (Any, Any, Ptr{Cvoid}), methods_table, method, C_NULL) # i dont like doing this either!
end
end
return !isempty(methods(f).ms)
end
# function try_delete_toplevel_methods(workspace::Module, name::Symbol)
# try_delete_toplevel_methods(workspace, [name])
# end
function try_delete_toplevel_methods(workspace::Module, (cell_id, name_parts)::Tuple{UUID,Vector{Symbol}})::Bool
try
val = workspace
for name in name_parts
val = getfield(val, name)
end
try
(val isa Function) && delete_toplevel_methods(val, cell_id)
catch ex
@warn "Failed to delete methods for $(name_parts)"
showerror(original_stderr, ex, stacktrace(catch_backtrace()))
false
end
catch
false
end
end
# these deal with some inconsistencies in Julia's internal (undocumented!) variable names
const primary_world = filter(in(fieldnames(Method)), [:primary_world, :min_world]) |> first # Julia v1.3 and v1.0 resp.
const deleted_world = filter(in(fieldnames(Method)), [:deleted_world, :max_world]) |> first # Julia v1.3 and v1.0 resp.
const alive_world_val = getfield(methods(Base.sqrt).ms[1], deleted_world) # typemax(UInt) in Julia v1.3, Int(-1) in Julia 1.0
###
# FORMATTING
###
# TODO: clear key when a cell is deleted furever
const cell_results = Dict{UUID,Any}()
const cell_runtimes = Dict{UUID,Union{Nothing,UInt64}}()
const cell_published_objects = Dict{UUID,Dict{String,Any}}()
const cell_registered_bond_names = Dict{UUID,Set{Symbol}}()
const tree_display_limit = 30
const tree_display_limit_increase = 40
const table_row_display_limit = 10
const table_row_display_limit_increase = 60
const table_column_display_limit = 8
const table_column_display_limit_increase = 30
const tree_display_extra_items = Dict{UUID,Dict{ObjectDimPair,Int64}}()
# This is not a struct to make it easier to pass these objects between distributed processes.
const FormattedCellResult = NamedTuple{(:output_formatted, :errored, :interrupted, :process_exited, :runtime, :published_objects, :has_pluto_hook_features),Tuple{PlutoRunner.MimedOutput,Bool,Bool,Bool,Union{UInt64,Nothing},Dict{String,Any},Bool}}
function formatted_result_of(
notebook_id::UUID,
cell_id::UUID,
ends_with_semicolon::Bool,
known_published_objects::Vector{String}=String[],
showmore::Union{ObjectDimPair,Nothing}=nothing,
workspace::Module=Main;
capture_stdout::Bool=true,
)::FormattedCellResult
load_integrations_if_needed()
currently_running_cell_id[] = cell_id
extra_items = if showmore === nothing
tree_display_extra_items[cell_id] = Dict{ObjectDimPair,Int64}()
else
old = get!(() -> Dict{ObjectDimPair,Int64}(), tree_display_extra_items, cell_id)
old[showmore] = get(old, showmore, 0) + 1
old
end
has_pluto_hook_features = haskey(cell_expanded_exprs, cell_id) && cell_expanded_exprs[cell_id].has_pluto_hook_features
ans = cell_results[cell_id]
errored = ans isa CapturedException
output_formatted = if (!ends_with_semicolon || errored)
logger = get!(() -> PlutoCellLogger(notebook_id, cell_id), pluto_cell_loggers, cell_id)
with_logger_and_io_to_logs(logger; capture_stdout, stdio_loglevel=stdout_log_level) do
format_output(ans; context=IOContext(default_iocontext, :extra_items=>extra_items, :module => workspace))
end
else
("", MIME"text/plain"())
end
published_objects = get(cell_published_objects, cell_id, Dict{String,Any}())
for k in known_published_objects
if haskey(published_objects, k)
published_objects[k] = nothing
end
end
return (;
output_formatted,
errored,
interrupted = false,
process_exited = false,
runtime = get(cell_runtimes, cell_id, nothing),
published_objects,
has_pluto_hook_features,
)
end
"Because even showerror can error... π"
function try_showerror(io::IO, e, args...)
try
showerror(io, e, args...)
catch show_ex
print(io, "\nFailed to show error:\n\n")
try_showerror(io, show_ex, stacktrace(catch_backtrace()))
end
end
# We add a method for the Markdown -> HTML conversion that takes a LaTeX chunk from the Markdown tree and adds our custom span
function htmlinline(io::IO, x::LaTeX)
withtag(io, :span, :class => "tex") do
print(io, '$')
htmlesc(io, x.formula)
print(io, '$')
end
end
# this one for block equations: (double $$)
function html(io::IO, x::LaTeX)
withtag(io, :p, :class => "tex") do
print(io, '$', '$')
htmlesc(io, x.formula)
print(io, '$', '$')
end
end
# because i like that
Base.IOContext(io::IOContext, ::Nothing) = io
"The `IOContext` used for converting arbitrary objects to pretty strings."
const default_iocontext = IOContext(devnull,
:color => false,
:limit => true,
:displaysize => (18, 88),
:is_pluto => true,
:pluto_supported_integration_features => supported_integration_features,
)
const default_stdout_iocontext = IOContext(devnull,
:color => true,
:limit => true,
:displaysize => (18, 75),
:is_pluto => false,
)
const imagemimes = MIME[MIME"image/svg+xml"(), MIME"image/png"(), MIME"image/jpg"(), MIME"image/jpeg"(), MIME"image/bmp"(), MIME"image/gif"()]
# in descending order of coolness
# text/plain always matches - almost always
"""
The MIMEs that Pluto supports, in order of how much I like them.
`text/plain` should always match - the difference between `show(::IO, ::MIME"text/plain", x)` and `show(::IO, x)` is an unsolved mystery.
"""
const allmimes = MIME[MIME"application/vnd.pluto.table+object"(); MIME"application/vnd.pluto.divelement+object"(); MIME"text/html"(); imagemimes; MIME"application/vnd.pluto.tree+object"(); MIME"text/latex"(); MIME"text/plain"()]
"""
Format `val` using the richest possible output, return formatted string and used MIME type.
See [`allmimes`](@ref) for the ordered list of supported MIME types.
"""
function format_output_default(@nospecialize(val), @nospecialize(context=default_iocontext))::MimedOutput