-
Notifications
You must be signed in to change notification settings - Fork 7
/
notebook.jl
1923 lines (1595 loc) · 53.2 KB
/
notebook.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.18.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 iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ ab02837b-79ec-40d7-bff1-c1d2dd7362ef
md"""
# PlutoTest.jl
_Visual, reactive testing library for Julia_
A macro `@test` that you can use to verify your code's correctness.
**But instead of just saying _"Pass"_ or _"Fail"_, let's try to show you _why_ a test failed.**
- ✨ _time travel_ ✨ to replay the execution step-by-step
- ⭐️ _multimedia display_ ⭐️ to make results easy to read
"""
# ╔═╡ 56347b7e-5007-45f8-8f6d-8ac8cc719637
md"""
Tests have _time-travel_ functionality built in! **Click on the test results above.**
"""
# ╔═╡ 191f1f04-18d4-485b-af8b-a2f073b7043b
md"""
## Installation and more info
> [github.com/JuliaPluto/PlutoTest.jl](https://github.com/JuliaPluto/PlutoTest.jl)
"""
# ╔═╡ ec1fd70a-d92a-4688-98b2-135879f07141
md"""
### (You need `Pluto ≥ 0.14.5` to run this notebook)
"""
# ╔═╡ 78704300-0531-4f8e-8aa5-3f588fbdd190
import Test: Test, @test_warn, @test_nowarn, @test_logs, @test_skip, @test_broken, @test_throws, @test_deprecated
# ╔═╡ 9129342b-f560-4901-81a2-56e3f8641521
export @test_nowarn, @test_warn, @test_logs, @test_skip, @test_broken, @test_throws, @test_deprecated
# ╔═╡ 0d70962a-3880-4dee-a439-35068d019f5a
md"""
# Type definitions
"""
# ╔═╡ 113cc425-e224-4f77-bfbd-ef4eb1d1ed70
abstract type TestResult end
# ╔═╡ 6188f559-bcab-4da6-84b2-a3fe522a5c3c
abstract type Fail <: TestResult end
# ╔═╡ c24b46ce-bcbb-4dc9-8a59-b5b1bd2cd617
abstract type Pass <: TestResult end
# ╔═╡ 5041085e-a406-4ed4-ab82-84d8f126cf0f
const Code = Any
# ╔═╡ 03ccd498-83c3-41bb-84d7-625adabd7aee
struct CorrectCall <: Pass
expr::Code
steps::Vector
end
# ╔═╡ 1bcf8bd1-c8a3-49a1-9791-d813aa856399
Base.@kwdef struct ErrorCall <: Fail
expr::Code
steps::Vector
error::CapturedException
end
# ╔═╡ 14c525a1-eca1-466b-8e63-3a90d7d7111c
struct WrongCall <: Fail
expr::Code
steps::Vector
end
# ╔═╡ a2efc968-246c-40c2-b285-2ec94b185a44
md"""
# Test macro
"""
# ╔═╡ dbfbcc16-c740-436c-bbf0-fee16b0a20c5
md"""
# $(html"<img src='https://cdn.jsdelivr.net/gh/ionic-team/ionicons@5.5.1/src/svg/time-outline.svg' style='height: .75em; margin-bottom: -.1em'>") _Time travel_ evaluation
In Julia, expressions are objects! This means that, before evaluation, code is expressed as a Julia object:
"""
# ╔═╡ 7c2bab29-8609-4575-b2ca-7feb34915645
md"""
You can use `Core.eval` to evaluate expressions at runtime:
"""
# ╔═╡ 838b5904-1de2-4d9f-8f3c-a93ec224d40e
md"""
But _did you know_ that you can also **partially evaluate** expressions?
"""
# ╔═╡ b056a99d-5b13-47ba-a199-d788410e3c99
md"""
Here, `ex2` is not a raw `Expr` — it _contains_ an evaluated array!
"""
# ╔═╡ 5b093e83-78c1-4187-b406-56e79800e1be
md"""
## `Computed` struct
Our time travel mechanism will be based on the partial evaluation principle introduced above. To differentiate between computed results and the original expression, we will wrap all computed results in a `struct`.
"""
# ╔═╡ a461f1fd-b5a5-4ae3-a47c-067a6081fb24
struct Computed
x
end
# ╔═╡ f9c81ab1-556c-4d81-bee8-2897c20e324d
md"""
We also add a function to recursively _unwrap_ an expression with `Computed` entries:
"""
# ╔═╡ a392d2d6-5a16-4383-b0ef-5003aa2de9fa
unwrap_computed(x) = x
# ╔═╡ ae95b691-f54b-4bf5-b17b-3e5bd1edf75e
unwrap_computed(c::Computed) = c.x
# ╔═╡ 12119016-fa61-4d38-8c58-821ea435df7d
unwrap_computed(e::Expr) = Expr(e.head, unwrap_computed.(e.args)...)
# ╔═╡ 74929fa6-d1f7-41cd-ab55-48f35d5fbf28
md"""
## `code_loweredish_with_lenses`
"""
# ╔═╡ f1ede628-d158-4296-befd-3eaa87cdad27
md"""
`ERROR_ON_UNKNOWN_EXPRESSION_TYPE` is set so when you view this notebook, you get explicit errors whenever we reach things we can't parse now but can work around.
Examples like this are `try ... catch ... end`, which we can't parse yet (control flow stuff is complex >_>) but we can still just evaluate that whole thing and call it a day.
"""
# ╔═╡ 5e66e59b-fdb8-4373-b231-097b0227dc5c
begin
struct ExprWithLens
expr
lens
expr_to_show
end
ExprWithLens(; expr, lens=[], expr_to_show=expr) = ExprWithLens(expr, lens, expr_to_show)
end
# ╔═╡ 17dea9e5-84ea-4476-a318-cc475043c83b
Frames = Vector{ExprWithLens}
# ╔═╡ c47252b9-8869-4878-b9bf-7eeb7ed17c9a
struct CantStepifyThisYetException <: Exception
expr
end
# ╔═╡ 0a3f5c6c-6e1b-458c-bf91-523a0b639b41
md"""
### `code_loweredish_with_lenses` for all non-Expr types
"""
# ╔═╡ 43fe89d7-f33e-4dfa-853e-327e981feb1e
function code_loweredish_with_lenses(x::Symbol)
# Should we replace variables with their value as a step?
[ExprWithLens(expr=x, lens=[])]
# For now I'm assuming people know what their variables are...
# return ExprWithLens[]
end
# ╔═╡ fc000550-3053-483e-bc41-6aed22c3999c
code_loweredish_with_lenses(x::QuoteNode) = ExprWithLens[]
# ╔═╡ 3f11ca4c-dd06-47c9-92e2-cb97c18a06db
code_loweredish_with_lenses(x::Number) = ExprWithLens[]
# ╔═╡ b155d336-f746-4c82-8206-ab1a49cedea8
code_loweredish_with_lenses(x::String) = ExprWithLens[]
# ╔═╡ f9b2a11d-8c4e-47a5-9d93-38025fae9a95
code_loweredish_with_lenses(::Char) = ExprWithLens[]
# ╔═╡ 221aa13b-aa25-4145-8076-da77432364bb
code_loweredish_with_lenses(x::LineNumberNode) = ExprWithLens[]
# ╔═╡ 2a514f2f-79c8-4b0d-be8a-170f3386d5d5
code_loweredish_with_lenses(x) = error("Type of expression not supported ($(typeof(x)))")
# code_loweredish_with-lenses(x) = [ExprWithLens(expr=x, lens=[])]
# ╔═╡ 9fb4d52d-77f2-4032-a769-6d5e60be43bf
md"""
### `expr_lenses_for_quoted`
Which will ignore everything except `:$` expressions, and then call `code_loweredish_with_lenses` for those.
"""
# ╔═╡ cade56ad-312e-40cf-bcda-11480ce27852
expr_lenses_for_quoted(x, _) = ExprWithLens[]
# ╔═╡ 810470b8-0a6c-48b8-aba2-a2058b8d9f59
md"## `build_step_by_step_blocks`"
# ╔═╡ a29d5277-e97a-4cca-8e31-8037f9cfdd80
"""
build_check_for_computed(lens::Expr, default::Expr)
Ideally, this function doesn't exist.
It will wrap a normal expression into an expression that first checks if the `lens` refers to a `Computed` value, if so use the value it contains, if not, use the original expression.
This is fine for now, but it isn't beautiful, and I didn't want to make this output even bigger expressions (as these are put inline into existing expressions, making them already quite unreadable), so there isn't any error handling. (If executing `lens` gives an error, you're out).
Ideally we don't have to check for `Computed`, because we know very well which references will be `Computed` and which won't. But that's for later 🙃
"""
function build_check_for_computed(lens::Expr, default::Expr)
if Meta.isexpr(default, :..., 1) && Meta.isexpr(default.args[1], :call)
# Can't have `x...` as a standalone expression, so need to
# dive in to replace the `x` instead of the whole thing
# e.g. `(x[1] isa Computed ? x[1].x : (1:7))...` (fine)
# instead of `(x isa Computed ? x.x : (1:7)...)` (not fine)
# Subtle, but important difference.
:((
$(lens).args[1] isa Computed ?
$(lens).args[1].x :
$(esc(default.args[1]))
)...)
elseif Meta.isexpr(default, :call)
# We can assume that a `call` will be done before
:($(lens) isa Computed ? $(lens).x : $(esc(default)))
else
esc(default)
end
end
# ╔═╡ 4f7aac13-9e49-4b2b-8d78-53f583f6130a
function build_check_for_computed(lens::Expr, default::Any)
esc(default)
end
# ╔═╡ cc7102e1-6af0-43bb-8cf0-43e2cec210e3
Base.@kwdef struct PartialEvaluatedException <: Exception
expr_with_lens::ExprWithLens
steps::Vector
error::CapturedException
end
# ╔═╡ ec6f1b07-d026-45ca-996d-be7693664cd7
deepcopy_expr(e::Expr) = Expr(e.head, (deepcopy_expr(sub_e) for sub_e in e.args)...)
# ╔═╡ dadf1c50-6588-4345-a240-69a72336c7cd
deepcopy_expr(e) = e
# ╔═╡ d384e3fc-b207-48ce-bc7b-1b47a14b1581
function apply_lens_to_frames(lens, frames)
map(frames) do frame
ExprWithLens(
expr=frame.expr,
lens=[lens..., frame.lens...]
)
end
end
# ╔═╡ a6e8c835-f209-445a-9f43-cdf2ecfd1b57
md"""
# Tests for all expression types
"""
# ╔═╡ 5759b2cc-1e96-4069-ae42-bc159c7cf5fb
md"## Basic"
# ╔═╡ 716d9ddc-18dc-4973-924e-e5ebf9161ff6
md"## Edge cases"
# ╔═╡ bc08755d-721f-403e-af95-36494b8fb7bc
md"## Things we can't parse yet"
# ╔═╡ de94f2b5-96ae-4936-870f-7639a39fd40d
md"""
> TODO
>
> Functions that aren't just coming from simple references (so say, Higher-order functions and such) should actually get a mention in the time travel. Right now it is still as this odd `#X#123` thingy (which is even worse when it is anonymous..), but this we could make prettier later.
"""
# ╔═╡ 21d4560e-721f-4ed4-9db7-86a8151ab22c
md"""
# UI
"""
# ╔═╡ 99afc7f4-727c-4277-8311-f2ffa94830ae
md"""
#### Slotting
We walk through the expression tree. Whenever we find a `Computed` object, we generate a random key (e.g. `iosjddfo`), we add it to our dictionary (`found`). In the expression, we replace the `Computed` object with a placeholder symbol `__slotiosjddfo__`. We will later be able to match the object to this slot.
"""
# ╔═╡ 4956526a-daf9-43c9-bff3-ff2446016e2e
slot!(found, c::Computed) = let
k = Symbol("__slot", join(rand('a':'z', 16)), "__")
found[k] = c
k
end
# ╔═╡ 84ff6a23-c134-4910-b630-a7ad45f3bf29
slot!(found, x) = x
# ╔═╡ 318363d0-6d9e-4144-b478-b775f437edaf
slot!(found, e::Expr) = Expr(e.head, slot!.([found], e.args)...)
# ╔═╡ 67fd07b7-340b-4e24-bc06-e4c85b186872
slot(e) = let
d = Dict{Symbol,Any}()
new_e = slot!(d, e)
d, new_e
end
# ╔═╡ c6d5597c-d505-4125-88c4-10415934d2a4
md"""
## SlottedDisplay
We use `print` to turn the expression into source code.
For each line, we regex-search for slot variables, and we split the line around those. The code segments around slots are rendered inside `<pre-ish>` tags (like `<pre>` but inline), and the slots are replaced by [embedded displays](https://github.com/fonsp/Pluto.jl/pull/1126) of the objects.
"""
# ╔═╡ c877c109-db16-468c-8f3c-8294db859d6d
begin
struct SlottedDisplay
d
e
end
SlottedDisplay(expr) = SlottedDisplay(slot(expr)...)
end
# ╔═╡ b5763c10-e11c-4389-b6fc-421d2c9682f1
md"""
## Frame viewer
A widget that takes a series of elements and displays them as 'video frames' with a timeline scrubber.
"""
# ╔═╡ 3d5abd58-02ab-4b91-a7a3-d9068d4df017
md"""
## @visual_debug (awesome)
"""
# ╔═╡ f9ed2487-a7f6-4ce9-b673-f8a298cd5fc3
md"""
# Appendix
"""
# ╔═╡ 20166ec9-7084-4d58-8b19-3aa51cc8f2c6
md"""
## Macro Lenses
I need stuff like Accessors.jl, but I didn't feel like another dependency and also *felt* like I should be macro-ish. So that's that this is...
"""
# ╔═╡ 1633fe05-cb51-4032-b6b6-f23db72bbd49
struct FieldLens property::Symbol end
# ╔═╡ 7c312943-c48b-40e7-a499-227f7ff8aa59
struct PropertyLens property end
# ╔═╡ a0207e25-0398-4104-8c0f-a8fbd9fe1d53
struct EmptyPropertyLens end
# ╔═╡ 7d14b79c-74e5-4986-80b7-de7cd7d48670
quote_if_needed(x::Union{Expr, Symbol, QuoteNode, LineNumberNode}) = QuoteNode(x)
# ╔═╡ 5950488e-2008-48d8-9095-7f9421df191e
quote_if_needed(x) = x
# ╔═╡ 77cc33a3-c2bc-4f2d-ba88-e3693ec79b0c
function lens_to_setter(subject, lens::Vector, value)
if length(lens) === 0
throw(ArgumentError("lens needs at least one element in path"))
elseif length(lens) === 1
property = lens[1]
if property isa FieldLens
:($subject.$(property.property) = $value)
elseif property isa PropertyLens
:($subject[$(quote_if_needed(property.property))] = $value)
elseif property isa EmptyPropertyLens
:($subject[] = $value)
else
error("Unknown lens type")
end
else
property, path... = lens
next_subject = if property isa FieldLens
:($subject.$(property.property))
elseif property isa PropertyLens
:($subject[$(quote_if_needed(property.property))])
elseif property isa EmptyPropertyLens
:($subject[])
else
error("Unknown lens type")
end
lens_to_setter(next_subject, path, value)
end
end
# ╔═╡ 5a3a0f63-dcce-49c9-84fd-a6317184820f
function lens_to_getter(subject, lens::Vector)
if length(lens) == 0
return subject
end
property, path... = lens
next_subject = if property isa FieldLens
:($subject.$(property.property))
elseif property isa PropertyLens
:($subject[$(quote_if_needed(property.property))])
elseif property isa EmptyPropertyLens
:($subject[])
else
error("Unknown lens type")
end
lens_to_getter(next_subject, path)
end
# ╔═╡ f5d9a4c5-300f-4dae-8507-346ec0b74632
"""
function build_step_by_step_blocks(lowered::Vector{ExprWithLens};
expr_ref_lens,
steps_lens,
)::Vector{Expr}
Transforms an `ExprWithLens`-list (created by `code_loweredish_with_lenses`), into a list of expressions that will mutate whatever `expr_ref_lens` points to.
- `expr_ref_lens` needs to point to a `Ref{Expr}`
- `steps_lens` needs to point to a `Vector{Expr}`
"""
function build_step_by_step_blocks(
lowered::Vector{ExprWithLens};
expr_ref_lens=:EXPR_REF_LENS_DEFAULT,
steps_lens=:STEPS_LENS_DEFAULT,
)::Vector{Expr}
map(lowered) do frame
# This whoooooole thing is to not execute parts of the code multiple times.
# It replaces, when possible, the arguments in the expression with a reference
# to the argument in the latest version of the expression
# (where some nodes are Computed, which we will use)
frame_lens = lens_to_getter(expr_ref_lens, [
EmptyPropertyLens(),
frame.lens...,
])
# TODO Use the same check here as we use in `code_loweredish_with_lenses`..
# .... Right now it only de-dupes inside calls, but not inside blocks
# .... (which we do split up in code_loweredish_with_lenses)
expr_with_arguments_as_references = if Meta.isexpr(frame.expr, :call)
Expr(
frame.expr.head,
map(enumerate(frame.expr.args)) do (i, arg)
arg_lens = :($(frame_lens).args[$(i)])
build_check_for_computed(arg_lens, arg)
end...
)
else
esc(frame.expr)
end
# If you feel like "I don't need that optimised shit",
# and want to see an easier to digest result, uncomment this line
#expr_with_arguments_as_references = esc(frame.expr)
quote
try
$(expr_ref_lens == :EXPR_REF_LENS_DEFAULT ? :(error("expr_ref_lens wasn't assigned, so this code will not work, but you can see and inspect it")) : nothing)
$(steps_lens == :STEPS_LENS_DEFAULT ? :(error("steps_lens wasn't assigned, so this code will not work, but you can see and inspect it")) : nothing)
val = $(expr_with_arguments_as_references)
# Could use Accessors.jl to make this a lot less expensive... 🤷♀️
$expr_ref_lens[] = $(deepcopy_expr)($expr_ref_lens[])
$(lens_to_setter(
expr_ref_lens,
[EmptyPropertyLens(), frame.lens...],
:(Computed(val))
))
# TODO Ideally we even render the step here directly,
# .... so any side-effects on mutable objects will
# .... show up in time-travel.
push!($steps_lens, $expr_ref_lens[])
catch error
captured_error = CapturedException(
error,
stacktrace(catch_backtrace())
)
$expr_ref_lens[] = $(deepcopy_expr)($expr_ref_lens[])
$(lens_to_setter(
expr_ref_lens,
[EmptyPropertyLens(), frame.lens...],
:(:(throw($(Computed(error)))))
))
push!($steps_lens, $expr_ref_lens[])
push!($steps_lens, :(throw($(Computed(error)))))
throw(PartialEvaluatedException(
expr_with_lens=$(frame),
steps=$steps_lens,
error=captured_error,
))
end
end
end
end
# ╔═╡ 35f63c4e-3583-4ea8-a057-31f18f8a09d6
md"""
## `@skip_as_script`
"""
# ╔═╡ ef59d0f0-0f02-4089-a49d-53fb0427c3a0
embed_display(x) = if isdefined(Main, :PlutoRunner) && isdefined(Main.PlutoRunner, :embed_display)
# if this package is used inside Pluto, and Pluto is new enough
Main.PlutoRunner.embed_display(x)
else
identity(x)
end
# ╔═╡ 35b2770e-1db6-4327-bf86-c27a4b61dbd3
function is_inside_pluto(m::Module)::Bool
if isdefined(m, :PlutoForceDisplay)
return m.PlutoForceDisplay
else
isdefined(m, :PlutoRunner) && parentmodule(m) === Main
end
end
# ╔═╡ cf314b21-3f4f-4637-b1ce-ec1d5d5af966
begin
if is_inside_pluto(@__MODULE__)
import Pkg
Pkg.activate("..")
Pkg.instantiate()
end
import HypertextLiteral: @htl
end
# ╔═╡ 872b4877-30dd-4a92-a3c8-69eb50675dcb
preish(x) = @htl("<pre-ish>$(x)</pre-ish>")
# ╔═╡ 2f6e353d-2cdc-46d6-9727-01b0a6167ca0
ERROR_ON_UNKNOWN_EXPRESSION_TYPE = is_inside_pluto(@__MODULE__)
# ╔═╡ 22640a2f-ea38-4517-a4f3-7a65e60ffebe
"""
@displayonly expression
Marks a expression as Pluto-only, which means that it won't be executed when running outside Pluto. Do not use this for your own projects.
"""
macro skip_as_script(ex) is_inside_pluto(__module__) ? esc(ex) : nothing end
# ╔═╡ fd8428a3-9fa3-471a-8b2d-5bbb8fdb3137
@skip_as_script begin
is_good_boy(x) = true
is_bad_boy(x) = false
end
# ╔═╡ d97987a0-bdc0-46ed-a6a5-f35c1ce961dc
ex1 = @skip_as_script :(first([56,sqrt(9)]))
# ╔═╡ 69bfb438-7ecf-4f9b-8bc4-51e07aa46ef1
@skip_as_script Core.eval(Module(), ex1)
# ╔═╡ a3c41025-2f4a-4f9c-8577-72e4b7abbb98
ex2_inner = @skip_as_script ex1.args[2]
# ╔═╡ 3e79ff61-6532-4879-9402-86473aa7d960
ex2_inner_result = @skip_as_script Core.eval(Module(), ex2_inner)
# ╔═╡ 38e54516-cdf4-4c1d-815b-68e1e7a7f6f7
ex3 = Expr(:call, :first, Computed(ex2_inner_result))
# ╔═╡ 9bed78b6-5a8f-44ce-ab66-cab685daf264
unwrap_computed(ex3)
# ╔═╡ 275c5f57-623d-439f-b09d-f7c745e0bed6
ex2 = @skip_as_script Expr(:call, :first, ex2_inner_result)
# ╔═╡ 94ebb761-21fb-4015-acb3-26310b19b0dc
@skip_as_script macro return_one()
return 1
end
# ╔═╡ 586826a5-d667-4035-9796-bd2db61498d6
@skip_as_script macro expand_at_runtime(expr)
quote
macroexpand($(__module__), $(QuoteNode(expr)))
end
end
# ╔═╡ a8fd09d1-c5ca-47f3-8fb3-32d8aeef3e59
@skip_as_script macro return_error(expr)
quote
try
$(esc(expr))
error("Expected an error")
catch error
error
end
end
end
# ╔═╡ d414f840-4952-4de5-a565-7fdc81a94817
"The opposite of `@skip_as_script`"
macro only_as_script(ex) is_inside_pluto(__module__) ? nothing : esc(ex) end
# ╔═╡ 64bf02a4-4fe3-424d-ae6e-5906c3395278
md"""
## PlutoUI favourites
"""
# ╔═╡ f3916810-1911-48bd-936b-776206fcad54
const toc_css = """
@media screen and (min-width: 1081px) {
.plutoui-toc.aside {
position:fixed;
right: 1rem;
top: 5rem;
width:25%;
padding: 10px;
border: 3px solid rgba(0, 0, 0, 0.15);
border-radius: 10px;
box-shadow: 0 0 11px 0px #00000010;
/* That is, viewport minus top minus Live Docs */
max-height: calc(100vh - 5rem - 56px);
overflow: auto;
z-index: 50;
background: white;
}
}
.plutoui-toc header {
display: block;
font-size: 1.5em;
margin-top: 0.67em;
margin-bottom: 0.67em;
margin-left: 0;
margin-right: 0;
font-weight: bold;
border-bottom: 2px solid rgba(0, 0, 0, 0.15);
}
.plutoui-toc section .toc-row {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding-bottom: 2px;
}
.highlight-pluto-cell-shoulder {
background: rgba(0, 0, 0, 0.05);
background-clip: padding-box;
}
.plutoui-toc section a {
text-decoration: none;
font-weight: normal;
color: gray;
}
.plutoui-toc section a:hover {
color: black;
}
.plutoui-toc.indent section a.H1 {
font-weight: 700;
line-height: 1em;
}
.plutoui-toc.indent section a.H1 {
padding-left: 0px;
}
.plutoui-toc.indent section a.H2 {
padding-left: 10px;
}
.plutoui-toc.indent section a.H3 {
padding-left: 20px;
}
.plutoui-toc.indent section a.H4 {
padding-left: 30px;
}
.plutoui-toc.indent section a.H5 {
padding-left: 40px;
}
.plutoui-toc.indent section a.H6 {
padding-left: 50px;
}
"""
# ╔═╡ 122c27a5-a6e8-45ef-a968-b9b4b3f9ad09
const toc_js = toc -> """
const getParentCell = el => el.closest("pluto-cell")
const getHeaders = () => {
const depth = Math.max(1, Math.min(6, $(toc.depth))) // should be in range 1:6
const range = Array.from({length: depth}, (x, i) => i+1) // [1, ..., depth]
const selector = range.map(i => `pluto-notebook pluto-cell h\${i}`).join(",")
return Array.from(document.querySelectorAll(selector))
}
const indent = $(repr(toc.indent))
const aside = $(repr(toc.aside))
const render = (el) => html`\${el.map(h => {
const parent_cell = getParentCell(h)
const a = html`<a
class="\${h.nodeName}"
href="#\${parent_cell.id}"
>\${h.innerText}</a>`
/* a.onmouseover=()=>{
parent_cell.firstElementChild.classList.add(
'highlight-pluto-cell-shoulder'
)
}
a.onmouseout=() => {
parent_cell.firstElementChild.classList.remove(
'highlight-pluto-cell-shoulder'
)
} */
a.onclick=(e) => {
e.preventDefault();
h.scrollIntoView({
behavior: 'smooth',
block: 'center'
})
}
return html`<div class="toc-row">\${a}</div>`
})}`
const tocNode = html`<nav class="plutoui-toc">
<header>$(toc.title)</header>
<section></section>
</nav>`
tocNode.classList.toggle("aside", aside)
tocNode.classList.toggle("indent", aside)
const updateCallback = () => {
tocNode.querySelector("section").replaceWith(
html`<section>\${render(getHeaders())}</section>`
)
}
updateCallback()
const notebook = document.querySelector("pluto-notebook")
// We have a mutationobserver for each cell:
const observers = {
current: [],
}
const createCellObservers = () => {
observers.current.forEach((o) => o.disconnect())
observers.current = Array.from(notebook.querySelectorAll("pluto-cell")).map(el => {
const o = new MutationObserver(updateCallback)
o.observe(el, {attributeFilter: ["class"]})
return o
})
}
createCellObservers()
// And one for the notebook's child list, which updates our cell observers:
const notebookObserver = new MutationObserver(() => {
updateCallback()
createCellObservers()
})
notebookObserver.observe(notebook, {childList: true})
// And finally, an observer for the document.body classList, to make sure that the toc also works when if is loaded during notebook initialization
const bodyClassObserver = new MutationObserver(updateCallback)
bodyClassObserver.observe(document.body, {attributeFilter: ["class"]})
invalidation.then(() => {
notebookObserver.disconnect()
bodyClassObserver.disconnect()
observers.current.forEach((o) => o.disconnect())
})
return tocNode
"""
# ╔═╡ 9126f47d-cbc7-411f-93bd-8684ba06c9e9
toc() = HTML("""
<script>
$(toc_js((;title="Table of Contents", indent=true, depth=3, aside=true)))
</script>
<style>
$(toc_css)
</style>
""")
# ╔═╡ c763ed72-82c9-445c-a8f7-a0c40982e4d9
@skip_as_script toc()
# ╔═╡ 955705f9-c90d-495d-86b4-5f3b5bc9fc8e
begin
struct Slider
xs
end
Base.get(s::Slider) = first(s.xs)
Base.show(io::IO, m::MIME"text/html", s::Slider) = show(io, m, @htl("<input type=range min=$(minimum(s.xs)) max=$(maximum(s.xs)) value=$(first(s.xs))>"))
Slider
end
# ╔═╡ 187c3005-cd43-45a0-8cbd-bc96b9cb39da
Dump(x; maxdepth=8) = sprint(io -> dump(io, x; maxdepth=maxdepth)) |> Text
# ╔═╡ a6709e08-964d-46ea-9813-2c70a834824b
@skip_as_script Dump(ex1)
# ╔═╡ 10803c0d-d0a5-45c5-b7ef-9659e441df69
@skip_as_script Dump(ex2)
# ╔═╡ 411271a6-4236-45e2-ab34-f26410108821
Dump(ex3)
# ╔═╡ 6c0156a9-7281-4326-9e1f-989efa73bb7b
begin
struct Show{M <: MIME}
mime::M
data
end
Base.show(io::IO, ::M, x::Show{M}) where M <: MIME = write(io, x.data)
Show
end
# ╔═╡ e46cf3e0-aa15-4c17-a925-3e9fc5109d54
@skip_as_script Hannes = let
url = "https://user-images.githubusercontent.com/6933510/116753174-fa40ab80-aa06-11eb-94d7-88f4171970b2.jpeg"
data = read(download(url))
Show(MIME"image/jpg"(), data)
end;
# ╔═╡ 6f5ba692-4b6a-405a-8cd3-1a8f9cc06611
plot(args...; kwargs...) = Hannes
# ╔═╡ 5b70aaf1-9623-4f55-b055-4263ed8be31d
@skip_as_script Floep = let
url = "https://user-images.githubusercontent.com/6933510/116753861-142ebe00-aa08-11eb-8ce8-684af1098935.jpeg"
data = read(download(url))
Show(MIME"image/jpg"(), data)
end;
# ╔═╡ bf2abe01-6ae0-4066-8704-12f64e04511b
@skip_as_script friends = Any[Hannes, Floep];
# ╔═╡ 8d3df0c0-eb48-4dae-97a8-8c01f0b0a34b
md"## Pretty printing code"
# ╔═╡ dbd41240-9fc4-4e25-8b25-2b68afa679f2
begin
struct EscapeExpr
expr
end
function Base.show(io::IO, val::EscapeExpr)
print(io, "\$(esc(")
print(io, val.expr)
print(io, "))")
end
EscapeExpr
end
# ╔═╡ 7cc07d1b-7757-4428-8028-dc892bf05f2f
move_escape_calls_up(e::Expr) = begin
args = move_escape_calls_up.(e.args)
if all(x -> Meta.isexpr(x, :escape, 1), args)
Expr(:escape, Expr(e.head, (arg.args[1] for arg in args)...))
else
Expr(e.head, args...)
end
end
# ╔═╡ e0837338-e657-4bdc-ae91-1de9224da78d
move_escape_calls_up(x) = x
# ╔═╡ 64df4678-0721-4911-8289-fb18f55e6657
escape_syntax_to_esc_call(e::Expr) = if e.head === :escape
EscapeExpr(e.args[1])
else
Expr(e.head, (escape_syntax_to_esc_call(x) for x in e.args)...)
end
# ╔═╡ 58845ff9-821b-45d4-b5ec-96e1949bb277
escape_syntax_to_esc_call(x) = x
# ╔═╡ 4d5f44e4-85e9-4985-9b76-73be5e097186
remove_linenums(e::Expr) = if e.head === :macrocall
Expr(
e.head,
(
x isa LineNumberNode ?
LineNumberNode(0, nothing) :
remove_linenums(x)
for x
in e.args
)...,
)
else
Expr(e.head, (remove_linenums(x) for x in e.args if !(x isa LineNumberNode))...)
end
# ╔═╡ dd495e00-d74d-47d4-a5d5-422fb147ec3b
remove_linenums(x) = x
# ╔═╡ e414c28a-8111-4821-ab25-21aff8289d26
function remove_singleline_blocks(e::Expr)
if Meta.isexpr(e, :quote) || Meta.isexpr(e, :macrocall)
e
elseif Meta.isexpr(e, :block, 1)
remove_singleline_blocks(e.args[1])
else
Expr(
e.head,
(remove_singleline_blocks(a) for a in e.args)...
)
end
end
# ╔═╡ c13e0f00-d3c4-4f1d-9531-84ed480c81f3
remove_singleline_blocks(x) = x
# ╔═╡ b765dbfe-4e58-4bb9-b1d6-aa4378d4e9c9
expr_to_str(e; mod=@__MODULE__(), context::IO=devnull) = let
Computed;
printed = sprint() do io
Base.print(
IOContext(IOContext(io, :module => mod), context),
remove_singleline_blocks(escape_syntax_to_esc_call(move_escape_calls_up(remove_linenums(e))))
)
end
replace(printed, r"#= line 0 =# ?" => "")
end
# ╔═╡ 227129bc-4415-4240-ad55-815bde65a5a1
function Base.showerror(io::IO, error::CantStepifyThisYetException)
print(io, "CantStepifyThisYetException: Can't make `$(expr_to_str(error.expr))` into separate steps yet")
end
# ╔═╡ ab0a19b8-cf7c-4c4f-802a-f85eef81fc02
function Base.show(io::IO, m::MIME"text/html", sd::SlottedDisplay)
d, e = sd.d, sd.e
s = expr_to_str(e; context=io)
lines = split(replace(s, r"#= line 0 =# ?" => ""), "\n")
r = r"\_\_slot[a-z]{16}\_\_"
embed_display
h = @htl("""<slotted-code>
$(
map(lines) do l
keys = [Symbol(m.match) for m in eachmatch(r, l)]
rest = split(l, r; keepempty=true)
result = vcat((
[(isempty(r) ? @htl("") : preish(r)), embed_display(d[k].x)]
for (r,k) in zip(rest, keys)
)...)
push!(result, preish(last(rest)))
@htl("<line-like>$(result)</line-like>")
end
)
</slotted-code>""")
show(io, m, h)
end