-
Notifications
You must be signed in to change notification settings - Fork 30
/
peephole.rs
2665 lines (2454 loc) · 83.6 KB
/
peephole.rs
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
//! Optimisations that replace parts of the BF AST with faster
//! equivalents.
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::num::Wrapping;
use itertools::Itertools;
use crate::diagnostics::Warning;
use crate::bfir::AstNode::*;
use crate::bfir::{get_position, AstNode, BfValue, Combine, Position};
const MAX_OPT_ITERATIONS: u64 = 40;
/// Given a sequence of BF instructions, apply peephole optimisations
/// (repeatedly if necessary).
pub fn optimize(
instrs: Vec<AstNode>,
pass_specification: &Option<String>,
) -> (Vec<AstNode>, Vec<Warning>) {
// Many of our individual peephole optimisations remove
// instructions, creating new opportunities to combine. We run
// until we've found a fixed-point where no further optimisations
// can be made.
let mut prev = instrs.clone();
let mut warnings = vec![];
let (mut result, warning) = optimize_once(instrs, pass_specification);
if let Some(warning) = warning {
warnings.push(warning);
}
for _ in 0..MAX_OPT_ITERATIONS {
if prev == result {
return (result, warnings);
} else {
prev = result.clone();
let (new_result, new_warning) = optimize_once(result, pass_specification);
if let Some(warning) = new_warning {
warnings.push(warning);
}
result = new_result;
}
}
// TODO: use proper Info here.
eprintln!(
"Warning: ran peephole optimisations {} times but did not reach a fixed point!",
MAX_OPT_ITERATIONS
);
(result, warnings)
}
/// Apply all our peephole optimisations once and return the result.
fn optimize_once(
instrs: Vec<AstNode>,
pass_specification: &Option<String>,
) -> (Vec<AstNode>, Option<Warning>) {
let pass_specification = pass_specification.clone().unwrap_or_else(|| {
"combine_inc,combine_ptr,known_zero,\
multiply,zeroing_loop,combine_set,\
dead_loop,redundant_set,read_clobber,\
pure_removal,offset_sort"
.to_owned()
});
let passes: Vec<_> = pass_specification.split(',').collect();
let mut instrs = instrs;
if passes.contains(&"combine_inc") {
instrs = combine_increments(instrs);
}
if passes.contains(&"combine_ptr") {
instrs = combine_ptr_increments(instrs);
}
if passes.contains(&"known_zero") {
instrs = annotate_known_zero(instrs);
}
if passes.contains(&"multiply") {
instrs = extract_multiply(instrs);
}
if passes.contains(&"zeroing_loop") {
instrs = zeroing_loops(instrs);
}
if passes.contains(&"combine_set") {
instrs = combine_set_and_increments(instrs);
}
if passes.contains(&"dead_loop") {
instrs = remove_dead_loops(instrs);
}
if passes.contains(&"redundant_set") {
instrs = remove_redundant_sets(instrs);
}
if passes.contains(&"read_clobber") {
instrs = remove_read_clobber(instrs);
}
let warning = if passes.contains(&"pure_removal") {
let (removed, pure_warning) = remove_pure_code(instrs);
instrs = removed;
pure_warning
} else {
None
};
if passes.contains(&"offset_sort") {
instrs = sort_by_offset(instrs);
}
(instrs, warning)
}
/// Defines a method on iterators to map a function over all loop bodies.
trait MapLoopsExt: Iterator<Item = AstNode> {
fn map_loops<F>(&mut self, f: F) -> Vec<AstNode>
where
F: Fn(Vec<AstNode>) -> Vec<AstNode>,
{
self.map(|instr| match instr {
Loop { body, position } => Loop {
body: f(body),
position,
},
other => other,
})
.collect()
}
}
impl<I> MapLoopsExt for I where I: Iterator<Item = AstNode> {}
/// Given an index into a vector of instructions, find the index of
/// the previous instruction that modified the current cell. If we're
/// unsure, or there isn't one, return None.
///
/// Note this totally ignores the instruction at the index given, even
/// if it has an offset. E.g. if the instruction is
/// Set {amount:100, offset: 1}, we're still considering previous instructions that
/// modify the current cell, not the (cell_index + 1)th cell.
fn previous_cell_change(instrs: &[AstNode], index: usize) -> Option<usize> {
assert!(index < instrs.len());
let mut needed_offset = 0;
for i in (0..index).rev() {
match instrs[i] {
Increment { offset, .. } | Set { offset, .. } => {
if offset == needed_offset {
return Some(i);
}
}
PointerIncrement { amount, .. } => {
needed_offset += amount;
}
MultiplyMove { ref changes, .. } => {
// These cells are written to.
let mut offsets: Vec<isize> = changes.keys().cloned().collect();
// This cell is zeroed.
offsets.push(0);
if offsets.contains(&needed_offset) {
return Some(i);
}
}
// No cells changed, so just keep working backwards.
Write { .. } => {}
// These instructions may have modified the cell, so
// we return None for "I don't know".
Read { .. } | Loop { .. } => return None,
}
}
None
}
/// Inverse of `previous_cell_change`.
///
/// This is very similar to `previous_cell_change` and previous
/// implementations called `previous_cell_change` on the reversed
/// vector. This proved extremely hard to reason about. Instead, we
/// have copied the body of `previous_cell_change` and highlighted the
/// differences.
fn next_cell_change(instrs: &[AstNode], index: usize) -> Option<usize> {
assert!(index < instrs.len());
let mut needed_offset = 0;
// Unlike previous_cell_change, we iterate forward.
for (i, instr) in instrs.iter().enumerate().skip(index + 1) {
match *instr {
Increment { offset, .. } | Set { offset, .. } => {
if offset == needed_offset {
return Some(i);
}
}
PointerIncrement { amount, .. } => {
// Unlike previous_cell_change we must subtract the desired amount.
needed_offset -= amount;
}
MultiplyMove { ref changes, .. } => {
// These cells are written to.
let mut offsets: Vec<isize> = changes.keys().cloned().collect();
// This cell is zeroed.
offsets.push(0);
if offsets.contains(&needed_offset) {
return Some(i);
}
}
// No cells changed, so just keep working backwards.
Write { .. } => {}
// These instructions may have modified the cell, so
// we return None for "I don't know".
Read { .. } | Loop { .. } => return None,
}
}
None
}
/// Combine consecutive increments into a single increment
/// instruction.
fn combine_increments(instrs: Vec<AstNode>) -> Vec<AstNode> {
instrs
.into_iter()
.coalesce(|prev_instr, instr| {
// Collapse consecutive increments.
if let Increment {
amount: prev_amount,
offset: prev_offset,
position: prev_pos,
} = prev_instr
{
if let Increment {
amount,
offset,
position,
} = instr
{
if prev_offset == offset {
return Ok(Increment {
amount: amount + prev_amount,
offset,
position: prev_pos.combine(position),
});
}
}
}
Err((prev_instr, instr))
})
.filter(|instr| {
// Remove any increments of 0.
if let Increment {
amount: Wrapping(0),
..
} = *instr
{
return false;
}
true
})
.map_loops(combine_increments)
}
fn combine_ptr_increments(instrs: Vec<AstNode>) -> Vec<AstNode> {
instrs
.into_iter()
.coalesce(|prev_instr, instr| {
// Collapse consecutive increments.
if let PointerIncrement {
amount: prev_amount,
position: prev_pos,
} = prev_instr
{
if let PointerIncrement { amount, position } = instr {
return Ok(PointerIncrement {
amount: amount + prev_amount,
position: prev_pos.combine(position),
});
}
}
Err((prev_instr, instr))
})
.filter(|instr| {
// Remove any pointer increments of 0.
if let PointerIncrement { amount: 0, .. } = *instr {
return false;
}
true
})
.map_loops(combine_ptr_increments)
}
/// Don't bother updating cells if they're immediately overwritten
/// by a value from stdin.
// TODO: this should generate a warning too.
fn remove_read_clobber(instrs: Vec<AstNode>) -> Vec<AstNode> {
let mut redundant_instr_positions = HashSet::new();
let mut last_write_index = None;
for (index, instr) in instrs.iter().enumerate() {
match *instr {
Read { .. } => {
// If we can find the time this cell was modified:
if let Some(prev_modify_index) = previous_cell_change(&instrs, index) {
// This modify instruction is not redundant if we
// wrote anything afterwards.
if let Some(write_index) = last_write_index {
if write_index > prev_modify_index {
continue;
}
}
// MultiplyMove instructions are not redundant,
// because they affect other cells too.
if matches!(instrs[prev_modify_index], MultiplyMove { .. }) {
continue;
}
redundant_instr_positions.insert(prev_modify_index);
}
}
Write { .. } => {
last_write_index = Some(index);
}
_ => {}
}
}
instrs
.into_iter()
.enumerate()
.filter(|&(index, _)| !redundant_instr_positions.contains(&index))
.map(|(_, instr)| instr)
.map_loops(remove_read_clobber)
}
/// Convert [-] to Set 0.
fn zeroing_loops(instrs: Vec<AstNode>) -> Vec<AstNode> {
instrs
.into_iter()
.map(|instr| {
if let Loop { ref body, position } = instr {
// If the loop is [-]
if body.len() == 1 {
if let Increment {
amount: Wrapping(-1),
offset: 0,
..
} = body[0]
{
return Set {
amount: Wrapping(0),
offset: 0,
position,
};
}
}
}
instr
})
.map_loops(zeroing_loops)
}
/// Remove any loops where we know the current cell is zero.
fn remove_dead_loops(instrs: Vec<AstNode>) -> Vec<AstNode> {
instrs
.clone()
.into_iter()
.enumerate()
.filter(|&(index, ref instr)| {
if !matches!(instr, Loop { .. }) {
// Keep all instructions that aren't loops.
return true;
}
// Find the previous change instruction:
if let Some(prev_change_index) = previous_cell_change(&instrs, index) {
let prev_instr = &instrs[prev_change_index];
// If the previous instruction set to zero, our loop is dead.
// TODO: MultiplyMove also zeroes the current cell.
// TODO: define an is_set_zero() helper.
if matches!(
prev_instr,
Set {
amount: Wrapping(0),
offset: 0,
..
}
) {
return false;
}
}
true
})
.map(|(_, instr)| instr)
.map_loops(remove_dead_loops)
}
/// Reorder flat sequences of instructions so we use offsets and only
/// have one pointer increment at the end. For example, given "+>+>+<"
/// we return:
/// Increment { amount: 1, offset: 0 }
/// Increment { amount: 1, offset: 1 }
/// Increment { amount: 2, offset: 2 }
/// PointerIncrement(1)
fn sort_by_offset(instrs: Vec<AstNode>) -> Vec<AstNode> {
let mut sequence = vec![];
let mut result = vec![];
for instr in instrs {
if matches!(
instr,
Increment { .. } | Set { .. } | PointerIncrement { .. }
) {
sequence.push(instr);
} else {
if !sequence.is_empty() {
result.extend(sort_sequence_by_offset(sequence));
sequence = vec![];
}
if let Loop { body, position } = instr {
result.push(Loop {
body: sort_by_offset(body),
position,
});
} else {
result.push(instr);
}
}
}
if !sequence.is_empty() {
result.extend(sort_sequence_by_offset(sequence));
}
result
}
/// Given a `HashMap` with orderable keys, return the values according to
/// the key order.
/// {2: 'foo': 1: 'bar'} => vec!['bar', 'foo']
fn ordered_values<K: Ord + Hash + Eq, V>(map: HashMap<K, V>) -> Vec<V> {
let mut items: Vec<_> = map.into_iter().collect();
items.sort_by(|a, b| a.0.cmp(&b.0));
items.into_iter().map(|(_, v)| v).collect()
}
/// Given a BF program, combine sets/increments using offsets so we
/// have single `PointerIncrement` at the end.
fn sort_sequence_by_offset(instrs: Vec<AstNode>) -> Vec<AstNode> {
let mut instrs_by_offset: HashMap<isize, Vec<AstNode>> = HashMap::new();
let mut current_offset = 0;
let mut last_ptr_inc_pos = None;
for instr in instrs {
match instr {
Increment {
amount,
offset,
position,
} => {
let new_offset = offset + current_offset;
let same_offset_instrs = instrs_by_offset.entry(new_offset).or_default();
same_offset_instrs.push(Increment {
amount,
offset: new_offset,
position,
});
}
Set {
amount,
offset,
position,
} => {
let new_offset = offset + current_offset;
let same_offset_instrs = instrs_by_offset.entry(new_offset).or_default();
same_offset_instrs.push(Set {
amount,
offset: new_offset,
position,
});
}
PointerIncrement { amount, position } => {
current_offset += amount;
last_ptr_inc_pos = Some(position);
}
// We assume that we were only given a Vec of
// Increment/Set/PointerIncrement instructions. It's
// the job of this function to create instructions with
// offset.
_ => unreachable!(),
}
}
// Append the increment/set instructions, in offset order.
let mut results: Vec<AstNode> = vec![];
for same_offset_instrs in ordered_values(instrs_by_offset) {
results.extend(same_offset_instrs.into_iter());
}
// Add a single PointerIncrement at the end, reflecting the net
// pointer movement in this instruction sequence.
if current_offset != 0 {
results.push(PointerIncrement {
amount: current_offset,
position: last_ptr_inc_pos.unwrap(),
});
}
results
}
/// Combine set instructions with other set instructions or
/// increments.
fn combine_set_and_increments(instrs: Vec<AstNode>) -> Vec<AstNode> {
// It's sufficient to consider immediately adjacent instructions
// as sort_sequence_by_offset ensures that if the offset is the
// same, the instruction is adjacent.
instrs
.into_iter()
.coalesce(|prev_instr, instr| {
// TODO: Set, Write, Increment -> Set, Write, Set
// Inc x, Set y -> Set y
if let (
&Increment {
offset: inc_offset,
position: inc_pos,
..
},
&Set {
amount: set_amount,
offset: set_offset,
position: set_pos,
},
) = (&prev_instr, &instr)
{
if inc_offset == set_offset {
return Ok(Set {
amount: set_amount,
offset: set_offset,
// Whilst the Inc is dead here, by including
// it in the position tracking we can show better warnings.
position: set_pos.combine(inc_pos),
});
}
}
Err((prev_instr, instr))
})
.coalesce(|prev_instr, instr| {
// Set x, Inc y -> Set x+y
if let Set {
amount: set_amount,
offset: set_offset,
position: set_pos,
} = prev_instr
{
if let Increment {
amount: inc_amount,
offset: inc_offset,
position: inc_pos,
} = instr
{
if inc_offset == set_offset {
return Ok(Set {
amount: set_amount + inc_amount,
offset: set_offset,
position: set_pos.combine(inc_pos),
});
}
}
}
Err((prev_instr, instr))
})
.coalesce(|prev_instr, instr| {
// Set x, Set y -> Set y
if let (
&Set {
offset: offset1,
position: position1,
..
},
&Set {
amount,
offset: offset2,
position: position2,
},
) = (&prev_instr, &instr)
{
if offset1 == offset2 {
return Ok(Set {
amount,
offset: offset1,
// Whilst the first Set is dead here, by including
// it in the position tracking we can show better warnings.
position: position1.combine(position2),
});
}
}
Err((prev_instr, instr))
})
.map_loops(combine_set_and_increments)
}
fn remove_redundant_sets(instrs: Vec<AstNode>) -> Vec<AstNode> {
let mut reduced = remove_redundant_sets_inner(instrs);
// Remove a set zero at the beginning of the program, since cells
// are initialised to zero anyway.
if matches!(
reduced.first(),
Some(Set {
amount: Wrapping(0),
offset: 0,
..
})
) {
reduced.remove(0);
}
reduced
}
fn remove_redundant_sets_inner(instrs: Vec<AstNode>) -> Vec<AstNode> {
let mut redundant_instr_positions = HashSet::new();
for (index, instr) in instrs.iter().enumerate() {
if matches!(instr, Loop { .. } | MultiplyMove { .. }) {
// There's no point setting to zero after a loop, as
// the cell is already zero.
if let Some(next_index) = next_cell_change(&instrs, index) {
if let Set {
amount: Wrapping(0),
offset: 0,
..
} = instrs[next_index]
{
redundant_instr_positions.insert(next_index);
}
}
}
}
instrs
.into_iter()
.enumerate()
.filter(|&(index, _)| !redundant_instr_positions.contains(&index))
.map(|(_, instr)| instr)
.map_loops(remove_redundant_sets_inner)
}
fn annotate_known_zero(instrs: Vec<AstNode>) -> Vec<AstNode> {
let mut result = vec![];
let position = if instrs.is_empty() {
None
} else {
get_position(&instrs[0]).map(|first_instr_pos| Position {
start: first_instr_pos.start,
end: first_instr_pos.start,
})
};
// Cells in BF are initialised to zero, so we know the current
// cell is zero at the start of execution.
let set_instr = Set {
amount: Wrapping(0),
offset: 0,
position,
};
// Insert the set instruction unless there is one already present.
if instrs.first() != Some(&set_instr) {
result.push(set_instr);
}
result.extend(annotate_known_zero_inner(&instrs));
result
}
fn annotate_known_zero_inner(instrs: &[AstNode]) -> Vec<AstNode> {
let mut result = Vec::with_capacity(instrs.len());
for (i, instr) in instrs.iter().enumerate() {
let instr = instr.clone();
match instr {
// After a loop, we know the cell is currently zero.
Loop { body, position } => {
result.push(Loop {
body: annotate_known_zero_inner(&body),
position,
});
// Treat this set as positioned at the ].
let set_pos = position.map(|loop_pos| Position {
start: loop_pos.end,
end: loop_pos.end,
});
let set_instr = Set {
amount: Wrapping(0),
offset: 0,
position: set_pos,
};
if instrs.get(i + 1) != Some(&set_instr) {
result.push(set_instr.clone());
}
}
_ => {
result.push(instr);
}
}
}
result
}
/// Remove code at the end of the program that has no side
/// effects. This means we have no write commands afterwards, nor
/// loops (which may not terminate so we should not remove).
fn remove_pure_code(mut instrs: Vec<AstNode>) -> (Vec<AstNode>, Option<Warning>) {
let mut pure_instrs = vec![];
while let Some(last_instr) = instrs.pop() {
match last_instr {
Read { .. } | Write { .. } | Loop { .. } => {
instrs.push(last_instr);
break;
}
_ => {
pure_instrs.push(last_instr);
}
}
}
let warning = if pure_instrs.is_empty() {
None
} else {
let position = pure_instrs
.into_iter()
.map(|instr| get_position(&instr))
.filter(|pos| pos.is_some())
.reduce(|pos1, pos2| pos1.combine(pos2))
.map(|pos| pos.unwrap());
Some(Warning {
message: "These instructions have no effect.".to_owned(),
position,
})
};
(instrs, warning)
}
/// Does this loop body represent a multiplication operation?
/// E.g. "[->>>++<<<]" sets cell #3 to 2*cell #0.
fn is_multiply_loop_body(body: &[AstNode]) -> bool {
// A multiply loop may only contain increments and pointer increments.
for body_instr in body {
match *body_instr {
Increment { .. } | PointerIncrement { .. } => {}
_ => return false,
}
}
// A multiply loop must have a net pointer movement of
// zero.
let mut net_movement = 0;
for body_instr in body {
if let PointerIncrement { amount, .. } = *body_instr {
net_movement += amount;
}
}
if net_movement != 0 {
return false;
}
let changes = cell_changes(body);
// A multiply loop must decrement cell #0.
if let Some(&Wrapping(-1)) = changes.get(&0) {
} else {
return false;
}
changes.len() >= 2
}
/// Return a hashmap of all the cells that are affected by this
/// sequence of instructions, and how much they change.
/// E.g. "->>+++>+" -> {0: -1, 2: 3, 3: 1}
fn cell_changes(instrs: &[AstNode]) -> HashMap<isize, BfValue> {
let mut changes = HashMap::new();
let mut cell_index: isize = 0;
for instr in instrs {
match *instr {
Increment { amount, offset, .. } => {
let current_amount = *changes.get(&(cell_index + offset)).unwrap_or(&Wrapping(0));
changes.insert(cell_index, current_amount + amount);
}
PointerIncrement { amount, .. } => {
cell_index += amount;
}
// We assume this is only called from is_multiply_loop.
_ => unreachable!(),
}
}
changes
}
fn extract_multiply(instrs: Vec<AstNode>) -> Vec<AstNode> {
instrs
.into_iter()
.map(|instr| {
match instr {
Loop { body, position } => {
if is_multiply_loop_body(&body) {
let mut changes = cell_changes(&body);
// MultiplyMove is for where we move to, so ignore
// the cell we're moving from.
changes.remove(&0);
MultiplyMove { changes, position }
} else {
Loop {
body: extract_multiply(body),
position,
}
}
}
i => i,
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
use std::num::Wrapping;
use pretty_assertions::assert_eq;
use quickcheck::quickcheck;
use quickcheck::{Arbitrary, Gen, TestResult};
use crate::bfir::parse;
use crate::bfir::{AstNode, Position};
use crate::diagnostics::Warning;
impl Arbitrary for AstNode {
fn arbitrary<G: Gen>(g: &mut G) -> AstNode {
arbitrary_instr(g, 5)
}
}
// We define a separate function so we can recurse on max_depth.
// See https://github.com/BurntSushi/quickcheck/issues/23
fn arbitrary_instr<G: Gen>(g: &mut G, max_depth: usize) -> AstNode {
let modulus = if max_depth == 0 { 8 } else { 9 };
// If max_depth is zero, don't create loops.
match g.next_u32() % modulus {
// TODO: use arbitrary offsets.
0 => Increment {
amount: Wrapping(Arbitrary::arbitrary(g)),
offset: 0,
position: Some(Position { start: 0, end: 0 }),
},
1 => PointerIncrement {
amount: Arbitrary::arbitrary(g),
position: Some(Position { start: 0, end: 0 }),
},
// TODO: use arbitrary offsets.
2 => Set {
amount: Wrapping(Arbitrary::arbitrary(g)),
offset: 0,
position: Some(Position { start: 0, end: 0 }),
},
3 => Read {
position: Some(Position { start: 0, end: 0 }),
},
4 => Write {
position: Some(Position { start: 0, end: 0 }),
},
5 => {
let mut changes = HashMap::new();
changes.insert(1, Wrapping(-1));
MultiplyMove {
changes,
position: Some(Position { start: 0, end: 0 }),
}
}
6 => {
let mut changes = HashMap::new();
changes.insert(1, Wrapping(2));
changes.insert(4, Wrapping(10));
MultiplyMove {
changes,
position: Some(Position { start: 0, end: 0 }),
}
}
7 => {
// A multiply by 2 loop that accesses a previous
// cell. Quickcheck doesn't seem to generate these by
// chance, but they often expose interesting bugs.
let body = vec![
Increment {
amount: Wrapping(-1),
offset: 0,
position: None,
},
PointerIncrement {
amount: -1,
position: None,
},
Increment {
amount: Wrapping(2),
offset: 0,
position: None,
},
PointerIncrement {
amount: 1,
position: None,
},
];
Loop {
body,
position: None,
}
}
8 => {
assert!(max_depth > 0);
let loop_length = g.next_u32() % 10;
let mut body: Vec<_> = vec![];
for _ in 0..loop_length {
body.push(arbitrary_instr(g, max_depth - 1));
}
Loop {
body,
position: Some(Position { start: 0, end: 0 }),
}
}
_ => unreachable!(),
}
}
#[test]
fn combine_increments_flat() {
let initial = parse("++").unwrap();
let expected = vec![Increment {
amount: Wrapping(2),
offset: 0,
position: Some(Position { start: 0, end: 1 }),
}];
assert_eq!(combine_increments(initial), expected);
}
#[test]
fn combine_increments_unrelated() {
let initial = parse("+>+.").unwrap();
let expected = initial.clone();
assert_eq!(combine_increments(initial), expected);
}
#[test]
fn combine_increments_nested() {
let initial = parse("[++]").unwrap();
let expected = vec![Loop {
body: vec![Increment {
amount: Wrapping(2),
offset: 0,
position: Some(Position { start: 1, end: 2 }),
}],
position: Some(Position { start: 0, end: 3 }),
}];
assert_eq!(combine_increments(initial), expected);
}
#[test]
fn combine_increments_remove_redundant() {
let initial = parse("+-").unwrap();
assert_eq!(combine_increments(initial), vec![]);
}
#[test]
fn quickcheck_combine_increments_remove_zero_any_offset() {
fn combine_increments_remove_zero_any_offset(offset: isize) -> bool {
let initial = vec![Increment {
amount: Wrapping(0),
offset,
position: Some(Position { start: 0, end: 0 }),
}];
combine_increments(initial) == vec![]
}
quickcheck(combine_increments_remove_zero_any_offset as fn(isize) -> bool);
}
#[test]
fn combine_increment_sum_to_zero() {