-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbaz5.cr
More file actions
1453 lines (1209 loc) · 45.1 KB
/
baz5.cr
File metadata and controls
1453 lines (1209 loc) · 45.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# TODO: This file is a temporary historical crappy implementation of the rewriters
# framework. Rewriters are a bit like parser combinators except for patterns: think
# "pattern combinators". Here they're implemented as Crystal functions but in fact
# they shouldn't be! They should be term-parsing, too, e.g. (dfsR x) so that we can
# use/construct them at runtime. A proper rewriter framework remains future work.
require "./src/wirewright"
require "./baz5_common"
module ::Ww::Backpath
end
class ::Ww::Backpath::Appender
# :nodoc:
def initialize(@preds : Term::Dict, @tip : Word::None | Word::Terminal | Word::Nonterminal)
end
# :nodoc:
EMPTY = Appender.new(preds: Term[], tip: Word::None.new)
# Constructs an empty backpath appender.
def self.new : Appender
EMPTY
end
private def push(tip1 : Word::Some) : Appender
Appender.new(backpath, tip1)
end
private def replace(tip1 : Word::Some) : Appender
Appender.new(@preds, tip1)
end
# The returned appender will update the key *term* of an existing entry. Its value
# is preserved. If the updated key collides with some existing key, the updated
# key's value wins.
def update_key(term) : Appender
case @tip
in Word::None, Word::Nonterminal
push Word::UpdateKey.new(Term.of(term))
in Word::Terminal
raise KeypathError.new
end
end
# The returned appender will update the value of an existing entry with the given *key*.
def update_value(key) : Appender
case @tip
in Word::None, Word::Nonterminal
push Word::UpdateValue.new(Term.of(key))
in Word::Terminal
raise KeypathError.new
end
end
# The returned appender will modify entries left after removing keys from *ee*. Each
# element of *ee* is converted to a Term using the block.
def delete_keys(ee : Enumerable(T), & : T -> Term) : Appender forall T
case @tip
in Word::None, Word::Nonterminal
keys = Term[].transaction do |commit|
ee.each { |object| commit << yield object }
end
push Word::Delete.new(keys)
in Word::Terminal
raise KeypathError.new
end
end
# Block-less variant of `delete_keys`.
def delete_keys(keys : Enumerable(Term)) : Appender
delete_keys(keys, &.itself)
end
# Block-less variant of `delete_keys`.
def delete_keys(keys : Term::Dict) : Appender
delete_keys(keys.items)
end
# Converts an `update` targeting one item into an update targeting a range of items.
# The size of the range is set by *size*. The returned appender is a **terminal** one:
# appending anything to it will fail.
def span(size, *, ord = 0u32) : Appender
case tip = @tip
when Word::UpdateValue
b = tip.key.to(Int32)
e = b + size
replace Word::Range.new(b, e, ord)
else
raise KeypathError.new
end
end
# Creates a pair with the given *key*. The returned appender is a **terminal** one:
# there is nothing to modify with it, since the value to be modified in fact does
# not exist.
def create_pair(key) : Appender
case @tip
in Word::None, Word::Nonterminal
push Word::CreateLeaf.new(Term.of(key))
in Word::Terminal
raise KeypathError.new
end
end
# Creates a pair with the given *key* and *value*. The returned appender will
# be modifying *value*.
def create_pair(key, *, value) : Appender
case @tip
in Word::None, Word::Nonterminal
push Word::Create.new(Term.of(key), Term.of(value), Term.of(value))
in Word::Terminal
raise KeypathError.new
end
end
# Converts an `update_value` of a single item into an insert of *value* before
# that item. The returned appender will be modifying *value*.
def insert_item(value, *, ord = 0) : Appender
case tip = @tip
when Word::UpdateValue
replace Word::Insert.new(tip.key.as_n, ord, Term.of(value))
else
raise KeypathError.new
end
end
# Shifts a numeric `update_value` *n* items forward.
def forward(n = 1) : Appender
case tip = @tip
when Word::UpdateValue
replace Word::UpdateValue.new(Term.of(tip.key + n))
else
raise KeypathError.new
end
end
# Shifts a numeric `update_value` *n* items backward.
def backward(n = 1) : Appender
forward(-n)
end
# Returns the backpath dict that this appender constructed so far.
def backpath : Term::Dict
case tip = @tip
in Word::None then @preds
in Word::Some then @preds.transaction &.concat(Word.terms(tip))
end
end
end
module ::Ww::Backpath::Word
extend self
alias Any = None | Some
alias Some = Atomic | Compound
# "Atomic" or "indivisible" words that actually exist in the trie.
alias Atomic = Create | CreateLeaf | Delete | Insert | Range | Pair
# "Compound words" are broken down into atomic words.
alias Compound = UpdateKey | UpdateValue
# Backpath words that do not have neighbors/successors in the trie (must stand at
# the end of a "sentence").
alias Terminal = CreateLeaf | Range
# Words that have neighbors/successors in the trie.
alias Nonterminal = Compound | Create | Delete | Insert
record UpdateKey, key : Term
record UpdateValue, key : Term
record None
record Create, key : Term, initial : Term, value : Term
record CreateLeaf, key : Term
record Insert, index : Term::Num, ord : UInt32, initial : Term
record Pair, key : Term
record Range, b : Int32, e : Int32, ord : UInt32
record Delete, keys : Term::Dict
record Key
record Value
# :nodoc:
SYM_PAIR = Term.of(:pair)
# :nodoc:
SYM_RESIDUE = Term.of(:residue)
# :nodoc:
SYM_RANGE = Term.of(:range)
# :nodoc:
SYM_CREATE_LEAF = Term.of(:"create-leaf")
# :nodoc:
SYM_CREATE = Term.of(:create)
# :nodoc:
SYM_INSERT = Term.of(:insert)
# Parses a subject term *subject* into an `Atomic` backpath word.
#
# Raises `KeypathError` if that cannot be done.
def atomic(subject : Term) : Atomic
raise KeypathError.new unless dict = subject.as_itemsonly_d?
raise KeypathError.new if dict.empty?
case {dict[0], dict.size - 1}
when {SYM_PAIR, 1}
_, key = dict
Pair.new(key)
when {SYM_RESIDUE, 1}
_, keys = dict
raise KeypathError.new unless keys = keys.as_d?
Delete.new(keys)
when {SYM_RANGE, 3}
_, b, e, ord = dict
raise KeypathError.new unless (b = b.as_n?) && (e = e.as_n?) && (ord = ord.as_n?)
Range.new(b.to(Int32), e.to(Int32), ord.to(UInt32))
when {SYM_CREATE_LEAF, 1}
_, key = dict
CreateLeaf.new(key)
when {SYM_CREATE, 2}
_, key, initial = dict
Create.new(key, initial, value: initial)
when {SYM_INSERT, 3}
_, index, ord, initial = dict
raise KeypathError.new unless (index = index.as_n?) && (ord = ord.as_n?)
Insert.new(index, ord.to(UInt32), initial)
else
raise KeypathError.new
end
end
# Yields substructure of *word* and/or *matchee* for the block to check out.
def checkout(word : Create, matchee : Term, &) : Nil
yield word.value
end
# :ditto:
def checkout(word : CreateLeaf, matchee : Term, &) : Nil
end
# :ditto:
def checkout(word : Insert, matchee : Term, &) : Nil
yield word.initial
end
# :ditto:
def checkout(word : Range, matchee : Term, &) : Nil
end
# :ditto:
def checkout(word : Delete, matchee : Term, &) : Nil
yield Term.exclude(matchee, word.keys.items)
end
def terms(word : Create) : Enumerable(Term)
{Term.of(:create, word.key, word.value)}
end
def terms(word : CreateLeaf) : Enumerable(Term)
{Term.of(:"create-leaf", word.key)}
end
def terms(word : Insert) : Enumerable(Term)
{Term.of(:insert, word.index, word.ord, word.initial)}
end
def terms(word : UpdateKey) : Enumerable(Term)
{Term.of(:pair, word.key), Term.of(:key)}
end
def terms(word : UpdateValue) : Enumerable(Term)
{Term.of(:pair, word.key), Term.of(:value)}
end
def terms(word : Range) : Enumerable(Term)
{Term.of(:range, word.b, word.e, word.ord)}
end
def terms(word : Delete) : Enumerable(Term)
{Term.of(:residue, word.keys)}
end
end
class ::Ww::KeypathError < Exception
end
alias Rewriter = RewriterContext, Rewrite::Any -> Rewrite::Any
alias Observer = Backpath::Appender, String, Rewrite::Some ->
alias Tick = ->
record RewriterContext, rng : Random, backpath : Backpath::Appender?, envs = Term[], observer : Observer | Tick = (Tick.new { }), options = Term[] do
def backpath(& : Backpath::Appender -> Backpath::Appender)
return self unless kp0 = @backpath
copy_with(backpath: yield kp0)
end
# Passthrough that notifies the observer (if any) of a *leaf rewrite*: rewrite that
# does not have a successor.
#
# "The observer" here means some kind of function that reacts to rewrites at backpaths.
# See `observer`.
def observable(leaf : Rewrite::Any, &explanation : -> String) : Rewrite::Any
if leaf.is_a?(Rewrite::Some)
case observer = @observer
in Observer
@backpath.try { |backpath| observer.call(backpath, yield, leaf) }
in Tick
observer.call
end
end
leaf
end
end
# A rewriter that does not rewrite. The "zero" of rewriters.
#
# NOTE: noRs should be handled by the caller. noR itself does not know whether
# what you give it is a rewrite or not vs. the original term (whatever it is).
# The caller must keep track of its rewriting progress; if a rewriter like noR
# refuses to rewrite, the caller must keep its rewriting progress unchanged. If
# a rewriter agrees to rewrite, the caller must update its progress.
def noR : Rewriter
Rewriter.new { Rewrite.none }
end
# A rewriter that unconditionally replaces anything with one *term*.
def oneR(term term1 : Term) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce do |term0|
# Since this is a Rewrite introduction point we must fortify it with
# a diff(). Otherwise we risk rewriters to short-circuit if they cannot
# determine when to stop due to a sneaky One(T) -> Many([T]) or something
# like that.
ctx.observable(Rewrite.one(term1).diff(term0)) { "unconditional replace with one" }
end
end
end
# A rewriter that unconditionally replaces anything with many terms specified
# in *list*.
def manyR(list : Term::Dict) : Rewriter
Rewriter.new do |ctx, staging|
# Just as above, we're defensive here.
staging.reduce do |term0|
ctx.observable(Rewrite.many(list).diff(term0)) { "unconditional replace with many" }
end
end
end
# :nodoc:
def envR(ctx, prefix, term term0)
ctx.envs.items.reverse_each do |env|
next unless pterm = env.follow?(prefix)
next unless pdict = pterm.as_d?
next unless term1 = pdict[term0]?
return ctx.observable(Rewrite.one(term1).diff(term0)) { "replace with value from the environment" }
end
Rewrite.none
end
# Rewrites a term by replacing it with a corresponding value from the environment.
#
# Follows keypath *prefix* into the environment, replaces the rewritten term with
# its corresponding value from the dictionary thus reached. Noop if *prefix* cannot
# be followed or there is no corresponding value there.
#
# The environment acts as a lookup table that certain rewriters (like `envR`) consult
# to determine how a term should be transformed; in case of `envR`, what it should be
# replaced with.
#
# The environment is mainly managed by `rulesetR`.
def envR(prefix : Enumerable(Term)) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce { |term| envR(ctx, prefix, term) }
end
end
# See `envR(prefix : Enumerable(Term))`.
def envR(*prefix : Term) : Rewriter
envR(prefix)
end
# :nodoc:
EMPTY_PREFIX = [] of Term
# Same as `envR(prefix : Enumerable(Term))`, but with an empty prefix.
def envR : Rewriter
envR(EMPTY_PREFIX)
end
# TODO: we should be able to implement this more efficiently in the future!
private def splice(dict : Term::Dict, splices : Array({Term::Num, Term::Dict}))
splices.each do |start, splice|
next unless index = start.index32?
dict = dict.replace(index, Term.rep(splice.items))
end
dict
end
# :nodoc:
def itemsR(ctx0, term, successor, start : Int32) : Rewrite::Any
unless dict0 = term.as_d?
return Rewrite.none
end
# Fast path
if dict0.pairsonly?
return Rewrite.none
end
splices = nil
dict1 = dict0.transaction do |commit|
# We **must** call successor in proper order due to observers which are only
# capable of doing one backpath-insert at a time.
(start...dict0.itemsize).reverse_each do |index|
item = dict0[index]
ctx1 = ctx0.backpath &.update_value(index)
case rewrite = successor.call(ctx1, Rewrite.one(item))
in Rewrite::None
in Rewrite::One
commit.with(index, rewrite.term)
in Rewrite::Many
splices ||= [] of {Term::Num, Term::Dict}
splices << {Term[index], rewrite.list}
end
end
end
unless splices
# Dict transactions only modify the underlying dict upon the first with()/
# without()/etc. call. Since we only call with() on a Rewrite.one of the successor,
# and since we trust the successor in that its Rewrite.one signals change unconditionally,
# we thus consider a `same?` check sufficient to determine whether the dictionary
# was modified.
return dict0.same?(dict1) ? Rewrite.none : Rewrite.one(dict1)
end
dict1 = splice(dict1, splices)
Rewrite.one(dict1)
end
# Rewrites the itemspart of a dictionary using *successor*.
#
# *start* specifies which item should be considered the first. If the
# dictionary contains less items than that, it won't be rewritten.
def itemsR(successor : Rewriter, *, start : Int32 = 0) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce { |term| itemsR(ctx, term, successor, start) }
end
end
# :nodoc:
def pairsR(ctx0, term, successor) : Rewrite::Any
unless dict0 = term.as_d?
return Rewrite.none
end
dict1 = dict0.transaction do |commit|
dict0.pairspart.each_entry do |key, value0|
ctx1 = ctx0.backpath &.update_value(key)
case rewrite = successor.call(ctx1, Rewrite.one(value0))
in Rewrite::None
in Rewrite::One then commit.with(key, rewrite.term)
in Rewrite::Many then commit.with(key, rewrite.list)
end
end
end
# See `itemsR` to learn why `same?` is sufficient here.
dict0.same?(dict1) ? Rewrite.none : Rewrite.one(dict1)
end
# Rewrites the pairspart of a dictionary using *successor*.
def pairsR(successor : Rewriter) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce { |term| pairsR(ctx, term, successor) }
end
end
# :nodoc:
def callR(ctx, term, callable)
# We do not trust *callable*, and perform an explicit diff to make sure the
# Rewrite *callable* returns reflects whether or not there actually was
# a rewrite.
rewrite = callable.call(term).diff(term)
ctx.observable(rewrite) { "rewrite" }
end
# Rewrites a term using *callable*.
#
# *callable* must respond to `call(term : Term) : Rewrite::Any`
def callR(callable) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce { |term| callR(ctx, term, callable) }
end
end
# See `callR(callable)`.
def callR(&callable : Term -> Rewrite::Any) : Rewriter
callR(callable)
end
# :nodoc:
def chainR(ctx : RewriterContext, term : Term, a : Rewriter, b : Rewriter)
lhs = a.call(ctx, Rewrite.one(term))
rhs = b.call(ctx, lhs.as?(Rewrite::Some) || Rewrite.one(term))
{lhs, rhs}.rightmost?(Rewrite::Some) || Rewrite.none
end
# Rewrites a term first using *a*, then the result of that using *b*, and so on.
def chainR(a : Rewriter, b : Rewriter) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce { |term| chainR(ctx, term, a, b) }
end
end
# :ditto:
def chainR(a : Rewriter, b : Rewriter, *cs : Rewriter) : Rewriter
chainR(chainR(a, b), *cs)
end
# :nodoc:
def allR(ctx : RewriterContext, term : Term, a : Rewriter, b : Rewriter)
unless lhs = a.call(ctx, Rewrite.one(term)).as?(Rewrite::Some)
return Rewrite.none
end
b.call(ctx, lhs)
end
# Similar to `chainR`, but rewrites to the last successful rewrite
# (i.e. skipping all rewriters past the one that failed, if any).
def allR(a : Rewriter, b : Rewriter) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce { |term| allR(ctx, term, a, b) }
end
end
# :ditto:
def allR(a : Rewriter, b : Rewriter, *cs : Rewriter) : Rewriter
allR(allR(a, b), *cs)
end
# :nodoc:
def choiceR(ctx : RewriterContext, term : Term, a : Rewriter, b : Rewriter)
lhs = a.call(ctx, Rewrite.one(term))
lhs.as?(Rewrite::Some) || b.call(ctx, Rewrite.one(term))
end
# Picks the leftmost successful rewriter among *a*, *b*, etc.
def choiceR(a : Rewriter, b : Rewriter) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce { |term| choiceR(ctx, term, a, b) }
end
end
# :ditto:
def choiceR(a : Rewriter, b : Rewriter, *cs) : Rewriter
choiceR(choiceR(a, b), *cs)
end
# :ditto:
def choiceR(a : Rewriter) : Rewriter
a
end
# Rewrites entries of a dictionary (items and pairs) using *successor*.
def entriesR(successor : Rewriter) : Rewriter
chainR(itemsR(successor), pairsR(successor))
end
# :nodoc:
def entryR1(ctx0, dict, key, value, successor)
ctx1 = ctx0.backpath &.update_value(key)
case rewrite = successor.call(ctx1, Rewrite.one(value))
in Rewrite::None
Rewrite.none
in Rewrite::One
Rewrite.one(dict.with(key, rewrite.term))
in Rewrite::Many
if index = dict.index32?(key)
Rewrite.one(dict.replace(index, Term.rep(rewrite.list.items)))
else
Rewrite.one(dict.with(key, rewrite.list))
end
end
end
# :nodoc:
def entryR(ctx, term, successor)
unless dict = term.as_d?
return Rewrite.none
end
case dict.size
when 0 # Empty dict, nothing to randomize
Rewrite.none
when 1 # One entry, nothing to randomize
key, value = dict.nth(0)
entryR1(ctx, dict, key, value, successor)
when 2 # Two elements, randomize A,B s. B,A
indices = { {0, 1}, {1, 0} }[(0..1).sample(ctx.rng)]
indices.each do |index|
key, value = dict.nth(index)
case rewrite = entryR1(ctx, dict, key, value, successor)
in Rewrite::None
in Rewrite::Some then return rewrite
end
end
# No rewritable entries
Rewrite.none
else # More than two elements, visit in disorder
n = dict.size.to_u32
state, prime = Disorder.state(n, ctx.rng)
n.times do
state = index = Disorder.next(n, state, prime)
key, value = dict.nth(index.to_i)
case rewrite = entryR1(ctx, dict, key, value, successor)
in Rewrite::None
in Rewrite::Some then return rewrite
end
end
# No rewritable entries
Rewrite.none
end
end
# Rewrites one random entry of a dictionary using *successor*.
def entryR(successor : Rewriter) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce { |term| entryR(ctx, term, successor) }
end
end
{% for row in { {:item, :pair}, {:pair, :item} } %}
{% lpart, rpart = row %}
# Rewrites one random {{lpart.id}} of a dictionary using *successor*.
def {{lpart.id}}R(successor : Rewriter) : Rewriter
slave = entryR(successor)
Rewriter.new do |ctx, staging|
staging.reduce do |term|
unless dict = term.as_d?
next Rewrite.none
end
case rewrite = slave.call(ctx, Rewrite.one(dict.{{lpart.id}}spart))
in Rewrite::None
Rewrite.none
in Rewrite::One
# entryR always returns a dictionary, but we're a little too loose
# on the types so we have to error-cast. Whatever.
Rewrite.one(rewrite.term.as_d | dict.{{rpart.id}}spart)
in Rewrite::Many
raise "BUG: entryR returned Rewrite::Many"
end
end
end
end
{% end %}
# Allows you to set up a rewriter that can reference itself. Returns a pair
# of procs: the first one is for setting the rewriter that will be used for
# recursion, and the second one represents the recursive rewriter itself.
#
# Here is an example dfsR definition:
#
# ```
# # successor = <successor of dfsR>
#
# set, rec = recR
# set.call choiceR(successor, entriesR(rec))
#
# # You can use `rec` or the rewriter returned by `set` now. They're not identical
# # (`rec` introduces one level of indirection); but their result will be the same.
# ```
def recR : {(Rewriter -> Rewriter), Rewriter}
slot = nil
set = ->(rewriter : Rewriter) { slot = rewriter }
rec = Rewriter.new do |ctx, staging|
next Rewrite.none unless slot_ = slot
slot_.call(ctx, staging)
end
{set, rec}
end
# :nodoc:
def selR(ctx, term, selector, successor)
if env = M1::Operator.match?(Term[], selector, term)
if rewritee = env[:rewritee]?
return successor.call(ctx, Rewrite.one(rewritee)).as?(Rewrite::Some) || Rewrite.one(rewritee)
end
end
Rewrite.none
end
# :nodoc:
def selR(selector, successor)
Rewriter.new do |ctx, staging|
staging.reduce { |term| selR(ctx, term, selector, successor) }
end
end
def rejR(ctx, term, selector, successor)
if M1.probe?(Term[], selector, term)
return Rewrite.none
end
successor.call(ctx, Rewrite.one(term))
end
# :nodoc:
def rejR(selector, successor)
Rewriter.new do |ctx, staging|
staging.reduce { |term| rejR(ctx, term, selector, successor) }
end
end
# Selective rewriter.
#
# *selector* pattern is used to match a term, and if a match is found, the capture
# `rewritee` is passed to the *successor* rewriter.
def selR(selector : Term, successor : Rewriter) : Rewriter
selR(M1.operator(selector), successor)
end
def rejR(selector : Term, successor : Rewriter) : Rewriter
rejR(M1.operator(selector), successor)
end
SELR_SELECTOR_CACHE = SyncLRU(String, Term).new(1024, by_ref: true)
# See the main overload (`Term`) for more info.
def selR(selector : String, successor : Rewriter) : Rewriter
selR(SELR_SELECTOR_CACHE.put_if_absent(selector) { ML.term(selector) }, successor)
end
def rejR(selector : String, successor : Rewriter) : Rewriter
rejR(SELR_SELECTOR_CACHE.put_if_absent(selector) { ML.term(selector) }, successor)
end
# Generates a `choiceR` with more than two branches for you to reduce typing.
def switchR(branches : Enumerable({String, Rewriter}) | Enumerable({Term, Rewriter}) | Enumerable({M1::Operator::Any, Rewriter})) : Rewriter
choice = nil
branches.each do |selector, successor|
rewriter = selR(selector, successor)
choice = choice ? choiceR(choice, rewriter) : rewriter
end
choice || noR
end
# :ditto:
def switchR(*branches : {String, Rewriter} | {Term, Rewriter} | {M1::Operator::Any, Rewriter})
switchR(branches)
end
# Rewrites a term using *successor*; if that produces no change and the term is
# a dictionary term, recurses on its items and pair values (`entriesR`).
def dfsR(successor : Rewriter) : Rewriter
set, rec = recR
set.call choiceR(successor, entriesR(rec))
end
# Rewrites a term using *successor*; if that produces no change and the term is
# a dictionary term, recurses on its items (`itemsR`).
def itemdfsR(successor : Rewriter) : Rewriter
set, rec = recR
set.call choiceR(successor, itemsR(rec))
end
# :nodoc:
def exhR(ctx, term, successor, limit)
state = Rewrite.one(term)
changed = false
(0...limit).each do
case rewrite = successor.call(ctx, state)
in Rewrite::Some
state = rewrite
changed = true
in Rewrite::None
break
end
end
changed ? state : Rewrite.none
end
# Absolute rewriter. Performs absolute rewriting of a term using *successor*.
#
# *Absolute rewriting* is similar to depth-first search rewriting `dfsR`.
#
# One difference is that `absR` rewrites just one entry and backjumps to the root;
# whereas `dfsR` rewrites all entries at any depth, minus those it already visited.
#
# Another difference is that `absR` performs *randomized* or *disordered rewriting*.
# `absR` tries to rewrite the entries it comes upon in random order, and the first
# successful rewrite causes it to backjump to the root. Therefore, "observing this
# from the outside", we see that `absR` finds a random entry at a random depth
# to rewrite.
#
# Absolute rewriting is useful when we want to prioritize context in rules.
# That is, rules with most context must be tried first. With `absR`, any
# rewrite will subsequently and inevitably be assessed in context.
#
# `absR` is an intrinsically inefficient way to rewrite, especially for very
# deep terms (since for any smallest change `absR` will backjump to the root).
# But it is most thorough and most context-aware. If an opportunity for rule
# application exists, it is guaranteed to be taken, regardless of rewrite depth
# and so on.
#
# Obviously, the above starts to shake whenever there are multiple cross-dependent
# opportunities for rewriting. `absR` can choose at random to take one of those
# opportunities, thus disrupting the second one and so on.
#
# Where possible, we recommend using `absR` in combination with `relR`, which
# allows to set a "ceiling" for `absR` to backjump to based on some pattern
# for the "bottom" and a numeric *ascent* -- the number of depth levels to climb.
#
# TODO: This should use a nonrandom right-to-left entryR()
def absR(successor) : Rewriter
set, rec = recR
set.call choiceR(successor, entryR(rec))
end
# Exhaustive rewriter. Performs exhaustive rewriting of a term using *successor*.
#
# *Exhaustive rewriting* is rewriting that stops only when there are no more rewrites
# to do. The resulting term is an *exhaustively rewritten term*. If *memoize* is set
# to `true` (it is by default), this exhaustively rewritten term is stored so that
# further rewrites with the same exhR instance are a noop.
def exhR(successor : Rewriter, *, limit = nil) : Rewriter
Rewriter.new do |ctx, staging|
staging.reduce { |term| exhR(ctx, term, successor, limit) }
end
end
# :nodoc:
module Relr
record Ready, rewrite : Rewrite::Any
record Ascend, ascent : Int32
record None
# Just like in `itemsR`, here we must iterate in a keypath-friendly
# way so that observers that rely solely on {keypath, rewrite} pairs can
# reconstruct what we're doing here without messing up indices etc.
private def self.each_entry_keypath_friendly(dict : Term::Dict, &)
(0...dict.itemsize).reverse_each do |index|
yield Term.of(index), dict[index]
end
dict.pairspart.each_entry do |key, value|
yield key, value
end
end
def self.relr(ctx0, bottom, term, ascent, env, successor)
if M1::Operator.probe?(env, bottom, term)
return Ascend.new(ascent)
end
unless dict0 = term.as_d?
return None.new
end
splices = nil
dict1 = dict0.transaction do |commit|
each_entry_keypath_friendly(dict0) do |key, value|
ctx1 = ctx0.backpath &.update_value(key)
case response = relr(ctx1, bottom, value, ascent, env, successor)
in None
next
in Ascend
unless response.ascent.zero?
return response.copy_with(ascent: response.ascent - 1)
end
rewrite = successor.call(ctx1, Rewrite.one(value))
in Ready
rewrite = response.rewrite
end
case rewrite
in Rewrite::None
in Rewrite::One
commit.with(key, rewrite.term)
in Rewrite::Many
if index = dict0.index?(key)
splices ||= [] of {Term::Num, Term::Dict}
splices << {index, rewrite.list}
else
commit.with(key, rewrite.list)
end
end
end
end
unless splices
# See `itemsR` to learn why this `same?` check is sufficient here.
return Ready.new(dict0.same?(dict1) ? Rewrite.none : Rewrite.one(dict1))
end
dict1 = splice(dict0, splices)
Ready.new(Rewrite.one(dict1))
end
end
module RelrEnv
extend self
alias Any = Literal | Option
record Literal, dict : Term::Dict
record Option, key : Term
def resolve(ctx, env : Literal) : Term::Dict
env.dict
end
def resolve(ctx, env : Option) : Term::Dict
return Term[] unless candidate = ctx.options[env.key]?
return Term[] unless dict = candidate.as_d?
dict
end
end
# Relative rewriter. Performs relative rewriting of a term using *successor*,
# with a *bottom* pattern that determines a stopping point and an *ascent* that
# controls backjumping.
#
# *Relative rewriting* is rewriting that is *anchored* to a specific subterm
# (the *bottom* match) rather than operating globally. When `relR` finds the
# *bottom* pattern, it begins ascending. Once it has climbed *ascent* levels,
# it rewrites the term thus reached using *successor*.
#
# - If `relR` encounters the bottom pattern, it begins its ascent.
# - Once it ascends *ascent* levels, it applies *successor* at that point.
# - If *ascent* is `0`, `relR` rewrites the bottom directly.
# - If multiple *bottom* matches exist, `relR` processes them independently,
# meaning rewriting order can influence results.
#
# `relR` is useful for localizing rewrites to a structured region of the term
# *based on the content of that term*, allowing precise control over where rewriting
# occurs without hard-coded keypaths etc.
#
# `relR` is often used in combination with `absR` to improve efficiency by
# reducing redundant backjumping - `relR` sets the "ceiling" for a successor
# `absR` to backjump to.
#
# NOTE: partially written by ChatGPT because I'm terrible at explaining things.
def relR(bottom : M1::Operator::Any, successor : Rewriter, *, ascent : Int32 = 0, env : RelrEnv::Any = RelrEnv::Literal.new(Term[])) : Rewriter
if ascent.negative?
raise ArgumentError.new("ascent must be positive or 0")
end