cranefack 0.4.2

An optimizing brainfuck compiler
Documentation
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
use crate::ir::opt_info::BlockInfo;
use std::ops::Range;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Op {
    pub op_type: OpType,
    pub span: Range<usize>,
}

impl Op {
    pub fn start() -> Op {
        Op {
            op_type: OpType::Start,
            span: 0..1,
        }
    }

    pub fn inc_ptr(span: Range<usize>, count: usize) -> Op {
        Op {
            op_type: OpType::IncPtr(count),
            span,
        }
    }

    pub fn dec_ptr(span: Range<usize>, count: usize) -> Op {
        Op {
            op_type: OpType::DecPtr(count),
            span,
        }
    }

    pub fn ptr_offset(span: Range<usize>, offset: isize) -> Op {
        Op {
            op_type: OpType::new_ptr_offset(offset),
            span,
        }
    }

    pub fn inc(span: Range<usize>, count: u8) -> Op {
        Op {
            op_type: OpType::Inc(0, count),
            span,
        }
    }

    pub fn inc_with_offset(span: Range<usize>, offset: isize, count: u8) -> Op {
        Op {
            op_type: OpType::Inc(offset, count),
            span,
        }
    }

    pub fn dec(span: Range<usize>, count: u8) -> Op {
        Op {
            op_type: OpType::Dec(0, count),
            span,
        }
    }

    pub fn dec_with_offset(span: Range<usize>, offset: isize, count: u8) -> Op {
        Op {
            op_type: OpType::Dec(offset, count),
            span,
        }
    }

    pub fn copy(span: Range<usize>, src_offset: isize, dest_offset: isize) -> Op {
        Op {
            op_type: OpType::Copy(src_offset, dest_offset),
            span,
        }
    }

    pub fn _move(span: Range<usize>, src_offset: isize, dest_offset: isize) -> Op {
        Op {
            op_type: OpType::Move(src_offset, dest_offset),
            span,
        }
    }

    pub fn put_char(span: Range<usize>) -> Op {
        Op {
            op_type: OpType::PutChar(0),
            span,
        }
    }

    pub fn put_char_with_offset(span: Range<usize>, offset: isize) -> Op {
        Op {
            op_type: OpType::PutChar(offset),
            span,
        }
    }

    pub fn get_char(span: Range<usize>) -> Op {
        Op {
            op_type: OpType::GetChar(0),
            span,
        }
    }

    pub fn d_loop(span: Range<usize>, ops: Vec<Op>, info: BlockInfo) -> Op {
        Op {
            op_type: OpType::DLoop(ops, info),
            span,
        }
    }

    pub fn l_loop(span: Range<usize>, ops: Vec<Op>, info: BlockInfo) -> Op {
        Op {
            op_type: OpType::LLoop(ops, info),
            span,
        }
    }

    pub fn i_loop(span: Range<usize>, ops: Vec<Op>, step: u8, info: BlockInfo) -> Op {
        Op {
            op_type: OpType::ILoop(ops, step, LoopDecrement::Auto, info),
            span,
        }
    }

    pub fn i_loop_with_decrement(
        span: Range<usize>,
        ops: Vec<Op>,
        step: u8,
        decrement: LoopDecrement,
        info: BlockInfo,
    ) -> Op {
        Op {
            op_type: OpType::ILoop(ops, step, decrement, info),
            span,
        }
    }

    pub fn c_loop(span: Range<usize>, ops: Vec<Op>, iterations: u8, info: BlockInfo) -> Op {
        Op {
            op_type: OpType::CLoop(ops, iterations, LoopDecrement::Auto, info),
            span,
        }
    }

    pub fn c_loop_with_decrement(
        span: Range<usize>,
        ops: Vec<Op>,
        iterations: u8,
        decrement: LoopDecrement,
        info: BlockInfo,
    ) -> Op {
        Op {
            op_type: OpType::CLoop(ops, iterations, decrement, info),
            span,
        }
    }

    pub fn set(span: Range<usize>, value: u8) -> Op {
        Op {
            op_type: OpType::Set(0, value),
            span,
        }
    }

    pub fn set_with_offset(span: Range<usize>, offset: isize, value: u8) -> Op {
        Op {
            op_type: OpType::Set(offset, value),
            span,
        }
    }

    pub fn add(span: Range<usize>, dest_offset: isize, multi: u8) -> Op {
        Op {
            op_type: OpType::Add(0, dest_offset, multi),
            span,
        }
    }

    pub fn add_with_offset(
        span: Range<usize>,
        src_offset: isize,
        dest_offset: isize,
        multi: u8,
    ) -> Op {
        Op {
            op_type: OpType::Add(src_offset, dest_offset, multi),
            span,
        }
    }

    pub fn nz_add(span: Range<usize>, dest_offset: isize, multi: u8) -> Op {
        Op {
            op_type: OpType::NzAdd(0, dest_offset, multi),
            span,
        }
    }

    pub fn c_add(span: Range<usize>, dest_offset: isize, value: u8) -> Op {
        Op {
            op_type: OpType::CAdd(0, dest_offset, value),
            span,
        }
    }

    pub fn nz_c_add(span: Range<usize>, dest_offset: isize, value: u8) -> Op {
        Op {
            op_type: OpType::NzCAdd(0, dest_offset, value),
            span,
        }
    }

    pub fn c_add_with_offset(
        span: Range<usize>,
        src_offset: isize,
        dest_offset: isize,
        value: u8,
    ) -> Op {
        Op {
            op_type: OpType::CAdd(src_offset, dest_offset, value),
            span,
        }
    }

    pub fn sub(span: Range<usize>, dest_offset: isize, multi: u8) -> Op {
        Op {
            op_type: OpType::Sub(0, dest_offset, multi),
            span,
        }
    }

    pub fn c_sub(span: Range<usize>, dest_offset: isize, value: u8) -> Op {
        Op {
            op_type: OpType::CSub(0, dest_offset, value),
            span,
        }
    }

    pub fn nz_sub(span: Range<usize>, dest_offset: isize, multi: u8) -> Op {
        Op {
            op_type: OpType::NzSub(0, dest_offset, multi),
            span,
        }
    }

    pub fn nz_sub_with_offset(
        span: Range<usize>,
        src_offset: isize,
        dest_offset: isize,
        multi: u8,
    ) -> Op {
        Op {
            op_type: OpType::NzSub(src_offset, dest_offset, multi),
            span,
        }
    }

    pub fn nz_c_sub(span: Range<usize>, dest_offset: isize, value: u8) -> Op {
        Op {
            op_type: OpType::NzCSub(0, dest_offset, value),
            span,
        }
    }

    pub fn mul(span: Range<usize>, dest_offset: isize, multi: u8) -> Op {
        Op {
            op_type: OpType::Mul(0, dest_offset, multi),
            span,
        }
    }

    pub fn nz_mul(span: Range<usize>, dest_offset: isize, multi: u8) -> Op {
        Op {
            op_type: OpType::NzMul(0, dest_offset, multi),
            span,
        }
    }

    pub fn t_nz(span: Range<usize>, ops: Vec<Op>, info: BlockInfo) -> Op {
        Op {
            op_type: OpType::TNz(ops, info),
            span,
        }
    }

    pub fn d_t_nz(
        span: Range<usize>,
        ops: Vec<Op>,
        end_offset: Option<isize>,
        info: BlockInfo,
    ) -> Op {
        Op {
            op_type: OpType::DTNz(ops, end_offset, info),
            span,
        }
    }

    pub fn search_zero(span: Range<usize>, step: isize) -> Op {
        Op {
            op_type: OpType::SearchZero(step, false),
            span,
        }
    }
}

/// Information about when to decrement a loop counter
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum LoopDecrement {
    /// Decrement before body invocation
    Pre,

    /// Decrement after body invocation
    Post,

    /// Doesn't matter.
    /// The counter isn't accessed during loop invocation
    Auto,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OpType {
    /// Start of application
    /// This is a nop op but helps optimization passes to detect if a cell is zero
    Start,

    /// Increment heap pointer by offset
    IncPtr(usize),

    /// Decrement heap pointer by offset
    DecPtr(usize),

    /// Increment cell at offset
    Inc(isize, u8),

    /// Decrement cell at offset
    Dec(isize, u8),

    /// Set cell at offset
    Set(isize, u8),

    /// Add current value to value at offset and reset current value to 0
    Add(isize, isize, u8),

    /// Add current value to value at offset without setting current value to 0
    NzAdd(isize, isize, u8),

    /// Add constant value to value at offset and reset current value to 0
    CAdd(isize, isize, u8),

    /// Add constant value to value at offset without setting current value to 0
    NzCAdd(isize, isize, u8),

    /// Subtract current value to value at offset and reset current value to 0
    Sub(isize, isize, u8),

    /// Subtract current value to value at offset without setting current value to 0
    NzSub(isize, isize, u8),

    /// Subtract constant value to value at offset and reset current value to 0
    CSub(isize, isize, u8),

    /// Subtract constant value to value at offset without setting current value to 0
    NzCSub(isize, isize, u8),

    /// Multiply current value to value at offset and reset current value to 0
    Mul(isize, isize, u8),

    /// Multiply current value to value at offset without setting current value to 0
    NzMul(isize, isize, u8),

    /// Move value to value at offset and reset current value to 0
    Move(isize, isize),

    /// Copy value to value at offset without setting current value to 0
    Copy(isize, isize),

    /// Output current cell
    PutChar(isize),

    ///  Outputs a constant string/array
    PutString(Vec<u8>),

    /// Read from stdin into current cell
    GetChar(isize),

    /// Dynamic loop as defined in raw brainfuck source
    DLoop(Vec<Op>, BlockInfo),

    /// Loop using the same iterator cell for each iteration
    LLoop(Vec<Op>, BlockInfo),

    /// Loop with an iterator variable and know steps per iteration
    ILoop(Vec<Op>, u8, LoopDecrement, BlockInfo),

    /// Loop with compile time known iteration count
    CLoop(Vec<Op>, u8, LoopDecrement, BlockInfo),

    /// Test if not zero.
    ///
    /// Executes block if current value is not zero. Similar to `if true { ops }`
    TNz(Vec<Op>, BlockInfo),

    /// Test if not zero dynamic.
    ///
    /// Executes block if current value is not zero. Similar to `if true { ops }`
    /// In contrast to TNz the end position of the heap pointer differs from the entry point
    DTNz(Vec<Op>, Option<isize>, BlockInfo),

    /// Move heap pointer to first cell containing zero based on step
    SearchZero(isize, bool),
}

impl OpType {
    /// Get IncPtr or DecPtr according to offset
    pub fn new_ptr_offset(offset: isize) -> OpType {
        if offset < 0 {
            OpType::DecPtr((-offset) as usize)
        } else {
            OpType::IncPtr(offset as usize)
        }
    }

    pub fn is_ptr_inc_or_dec(&self) -> bool {
        matches!(self, OpType::DecPtr(_) | OpType::IncPtr(_))
    }

    /// Return offset of pointer increments and decrements
    pub fn get_ptr_offset(&self) -> Option<isize> {
        match self {
            OpType::IncPtr(count) => Some(*count as isize),
            OpType::DecPtr(count) => Some(-(*count as isize)),
            _ => None,
        }
    }

    /// Test for arithmetic ops without offsets
    pub fn is_simple_arithmetic(&self) -> bool {
        matches!(
            self,
            OpType::Set(_, _)
                | OpType::Inc(_, _)
                | OpType::Dec(_, _)
                | OpType::IncPtr(_)
                | OpType::DecPtr(_)
        )
    }

    /// Test for arithmetic ops
    pub fn is_arithmetic(&self) -> bool {
        matches!(self, OpType::Set(..) | OpType::Inc(..) | OpType::Dec(..))
    }

    /// Test if op zeros the src offset
    pub fn is_zeroing(&self, test_offset: isize) -> bool {
        match self {
            OpType::Add(offset, ..)
            | OpType::CAdd(offset, ..)
            | OpType::Sub(offset, ..)
            | OpType::CSub(offset, ..)
            | OpType::Move(offset, ..)
            | OpType::Set(offset, 0) => test_offset == *offset,
            OpType::DLoop(..)
            | OpType::LLoop(..)
            | OpType::ILoop(..)
            | OpType::CLoop(..)
            | OpType::TNz(..)
            | OpType::DTNz(..)
            | OpType::SearchZero(..) => test_offset == 0,
            OpType::Start => true,
            _ => false,
        }
    }

    /// Test if op zeros the src offset without reading/using the value
    pub fn is_zeroing_unread(&self, test_offset: isize) -> bool {
        match self {
            OpType::CAdd(offset, ..) | OpType::CSub(offset, ..) | OpType::Set(offset, 0) => {
                test_offset == *offset
            }
            OpType::CLoop(..) => test_offset == 0,
            _ => false,
        }
    }

    /// Returns the destination offset for ops that overwrites a cell
    pub fn get_overwriting_dest_offset(&self) -> Option<isize> {
        match self {
            OpType::Move(_, dest_offset)
            | OpType::Copy(_, dest_offset)
            | OpType::Set(dest_offset, _)
            | OpType::GetChar(dest_offset) => Some(*dest_offset),

            _ => None,
        }
    }

    /// Returns the source offset for ops that set it to zero without reading the value
    pub fn get_unread_zeroing_src_offset(&self) -> Option<isize> {
        match self {
            OpType::CAdd(offset, ..)
            | OpType::CSub(offset, ..)
            | OpType::Set(offset, 0)
            | OpType::GetChar(offset) => Some(*offset),
            OpType::CLoop(..) => Some(0),
            _ => None,
        }
    }

    pub fn get_children(&self) -> Option<&Vec<Op>> {
        match self {
            OpType::DLoop(children, ..)
            | OpType::LLoop(children, ..)
            | OpType::ILoop(children, ..)
            | OpType::CLoop(children, ..)
            | OpType::TNz(children, ..)
            | OpType::DTNz(children, ..) => Some(children),
            _ => None,
        }
    }

    pub fn get_children_mut(&mut self) -> Option<&mut Vec<Op>> {
        match self {
            OpType::DLoop(children, ..)
            | OpType::LLoop(children, ..)
            | OpType::ILoop(children, ..)
            | OpType::CLoop(children, ..)
            | OpType::TNz(children, ..)
            | OpType::DTNz(children, ..) => Some(children),
            _ => None,
        }
    }

    pub fn get_block_info(&self) -> Option<&BlockInfo> {
        match self {
            OpType::DLoop(_, info)
            | OpType::LLoop(_, info)
            | OpType::ILoop(_, _, _, info)
            | OpType::CLoop(_, _, _, info)
            | OpType::TNz(_, info)
            | OpType::DTNz(_, _, info) => Some(info),
            _ => None,
        }
    }

    pub fn get_block_info_mut(&mut self) -> Option<&mut BlockInfo> {
        match self {
            OpType::DLoop(_, info)
            | OpType::LLoop(_, info)
            | OpType::ILoop(_, _, _, info)
            | OpType::CLoop(_, _, _, info)
            | OpType::TNz(_, info)
            | OpType::DTNz(_, _, info) => Some(info),
            _ => None,
        }
    }

    pub fn is_possible_write(&self, test_offset: isize) -> bool {
        match self {
            OpType::Inc(offset, _)
            | OpType::Dec(offset, _)
            | OpType::Set(offset, _)
            | OpType::GetChar(offset)
            | OpType::NzAdd(_, offset, _)
            | OpType::NzCAdd(_, offset, _)
            | OpType::NzSub(_, offset, _)
            | OpType::NzCSub(_, offset, _)
            | OpType::NzMul(_, offset, _)
            | OpType::Copy(_, offset) => *offset == test_offset,
            OpType::Add(src_offset, dest_offset, _)
            | OpType::CAdd(src_offset, dest_offset, _)
            | OpType::Sub(src_offset, dest_offset, _)
            | OpType::CSub(src_offset, dest_offset, _)
            | OpType::Mul(src_offset, dest_offset, _)
            | OpType::Move(src_offset, dest_offset) => {
                *src_offset == test_offset || *dest_offset == test_offset
            }
            OpType::PutString(_) | OpType::PutChar(_) | OpType::IncPtr(_) | OpType::DecPtr(_) => {
                false
            }
            OpType::Start | OpType::SearchZero(_, _) | OpType::DLoop(..) | OpType::DTNz(..) => true,
            OpType::LLoop(.., info)
            | OpType::ILoop(.., info)
            | OpType::CLoop(.., info)
            | OpType::TNz(.., info) => test_offset == 0 || info.was_cell_written(test_offset),
        }
    }
}