fr 0.1.1

A programming language with an unusual compiler backend
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
use crate::{Error, Eval, Literal, Lower, Program};
use core::fmt;
use std::sync::Mutex;

lazy_static! {
    static ref COMPILED: Mutex<String> = Mutex::new(String::new());
    static ref CONTROL_REGISTERS: Mutex<Vec<Value>> = Mutex::new(Vec::new());

    /// This variable is responsible for keeping track of each statically allocated variable
    /// For example, if a variable `test` is allocated statically with size 4, the STACK_PTR
    /// will be allocated by 4, and the next variable will be allocated at the STACK_PTR
    pub static ref STACK_PTR: Mutex<u32> = Mutex::new(0);
    pub static ref RETURN: Value = Value::new(1).unwrap();
    pub static ref TEMP0: Value = Value::new(1).unwrap();
    pub static ref TEMP1: Value = Value::new(1).unwrap();
    pub static ref TEMP2: Value = Value::new(1).unwrap();
    pub static ref TEMP3: Value = Value::new(1).unwrap();
    pub static ref TEMP4: Value = Value::new(1).unwrap();
    pub static ref TEMP5: Value = Value::new(1).unwrap();
    pub static ref TEMP6: Value = Value::new(1).unwrap();

    pub static ref STACK_SIZE: Mutex<u32> = Mutex::new(16384);
    pub static ref HEAP_SIZE: Mutex<u32> = Mutex::new(8192);
}

pub fn increment_stack(allocation_size: u32) -> Result<(), Error> {
    let mut stack_ptr = STACK_PTR.lock().unwrap();
    *stack_ptr += allocation_size;
    if *stack_ptr > *STACK_SIZE.lock().unwrap() {
        Err(Error::StackOverflow)
    } else {
        Ok(())
    }
}

pub fn set_stack(stack_size: u32) -> Result<(), Error> {
    let mut stack_ptr = STACK_PTR.lock().unwrap();
    *stack_ptr = stack_size;
    if *stack_ptr > *STACK_SIZE.lock().unwrap() {
        Err(Error::StackOverflow)
    } else {
        Ok(())
    }
}

pub fn add_to_compiled(s: impl ToString) {
    let mut c = COMPILED.lock().unwrap();
    (*c) += &s.to_string();
}

#[allow(unused_must_use)]
pub fn init() {
    let f = |_: &Value| {};
    f(&RETURN);
    f(&TEMP0);
    f(&TEMP1);
    f(&TEMP2);
    f(&TEMP3);
    f(&TEMP4);
    f(&TEMP5);
    f(&TEMP6);

    add_to_compiled(format!(
        "STARTING STACK PTR IS {} ",
        *STACK_PTR.lock().unwrap()
    ));
}

pub fn compile() -> String {
    RETURN.free();
    TEMP0.free();
    TEMP1.free();
    TEMP2.free();
    TEMP3.free();
    TEMP4.free();
    TEMP5.free();
    TEMP6.free();

    add_to_compiled(format!(
        "FINAL STACK PTR IS {} ",
        *STACK_PTR.lock().unwrap()
    ));

    COMPILED.lock().unwrap().clone()
}

pub struct Control;
impl Control {
    pub fn if_begin(var: Value) -> Result<(), Error> {
        add_to_compiled("\nIF BEGIN\n");
        TEMP5.assign(var)?;
        TEMP6.assign(Eval::Literal(Literal::byte_int(1)).lower()?)?;

        // CONTROL_REGISTERS.lock().unwrap().push(var);

        Self::while_begin(*TEMP5);
        add_to_compiled("\nTHEN CODE BEGIN\n");
        Ok(())
    }

    pub fn else_begin() -> Result<(), Error> {
        add_to_compiled("\nTHEN CODE END\n");
        TEMP5.zero();
        TEMP6.zero();
        Self::while_end();
        Self::while_begin(*TEMP6);
        add_to_compiled("\nELSE CODE BEGIN\n");
        // TEMP0.zero();
        // let var = CONTROL_REGISTERS.lock().unwrap().pop().unwrap();
        // TEMP1.assign(var)?;
        // var.zero();
        // add_to_compiled(var.to() + "]" + &var.from());
        // var.assign(*TEMP1)?;
        // TEMP1.zero();
        Ok(())
    }

    pub fn if_end() -> Result<(), Error> {
        add_to_compiled("\nELSE CODE END\n");
        TEMP6.zero();
        Self::while_end();
        // TEMP0.zero();
        // let var = CONTROL_REGISTERS.lock().unwrap().pop().unwrap();
        // TEMP1.assign(var)?;
        // var.zero();
        // add_to_compiled(var.to() + "]" + &var.from());
        // var.assign(*TEMP1)?;
        // TEMP1.zero();
        add_to_compiled("\nIF END\n");
        Ok(())
    }

    pub fn while_begin(var: Value) {
        add_to_compiled("\nWHILE BEGIN\n");
        // TEMP0.zero();
        CONTROL_REGISTERS.lock().unwrap().push(var);
        add_to_compiled(var.to() + "[" + &var.from());
        add_to_compiled("\nCODE BEGIN\n");
    }

    pub fn while_end() {
        add_to_compiled("\nCODE END\n");
        let var = CONTROL_REGISTERS.lock().unwrap().pop().unwrap();
        add_to_compiled(var.to() + "]" + &var.from());
        add_to_compiled("\nWHILE END\n");
    }
}

pub struct Stdin;
impl Stdin {
    pub fn getch(var: Value) {
        let mut result = String::new();

        result += &var.to();
        result += ",";
        result += &var.from();

        add_to_compiled("\nPRINT CELL\n");
        add_to_compiled(&result);
        add_to_compiled("\nDONE\n");
    }
}

pub struct Stdout;
impl Stdout {
    /// This prints a Value according to its size.
    /// Basically, this prints each cell that the Value owns.
    pub fn print(var: Value) {
        let mut result = String::new();

        result += &var.to();
        for _ in 0..var.size() {
            result += ".>";
        }
        for _ in 0..var.size() {
            result += "<";
        }
        result += &var.from();

        add_to_compiled("\nPRINT CELL\n");
        add_to_compiled(&result);
        add_to_compiled("\nDONE\n");
    }


    /// This prints a pointer to a value like a CString
    /// This requires brainfuck compatibility mode to be disabled.
    pub fn print_cstr(var: Value) -> Result<(), Error> {
        let mut result = String::new();

        // Dereference value and print string
        result += &var.to();
        result += "*[.>]&";
        // Refer back to home
        result += &var.from();

        add_to_compiled("\nPRINT CELL\n");
        add_to_compiled(&result);
        add_to_compiled("\nDONE\n");

        if Program::brainfuck_enabled() {
            Err(Error::CannotUsePointersInBrainFuckMode)
        } else {
            Ok(())
        }
    }
}

/// This object represents a value stored on the tape.
/// Objects can be stored indirectly or directly.
/// In brainfuck compatibility mode, dereferencing
/// or referencing an object is illegal.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd)]
pub struct Value {
    pub offset: u32,
    pub reference_depth: u32,
    pub number_cells: u32,
}

/// This is for debugging.
impl fmt::Debug for Value {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(
            f,
            "(to `{}` | from `{}` | {} wide)",
            self.to(),
            self.from(),
            self.size()
        )
    }
}

impl Value {
    pub fn new(size: u32) -> Result<Self, Error> {
        let result = Self {
            offset: *STACK_PTR.lock().unwrap(),
            reference_depth: 0,
            number_cells: size,
        };

        result.zero();

        increment_stack(size)?;
        Ok(result)
    }

    pub fn alloc(size: u32) -> Result<Self, Error> {
        let mut result = Self::new(1)?;
        result.number_cells = size;

        add_to_compiled(format!("\nALLOCATING {} CELLS\n", size));
        add_to_compiled(result.to());
        add_to_compiled("+".repeat(size as usize));
        add_to_compiled("?*");
        add_to_compiled("+>".repeat(size as usize));
        add_to_compiled("&");
        add_to_compiled(result.from());
        add_to_compiled("\nDONE\n");

        if Program::brainfuck_enabled() {
            Err(Error::CannotUsePointersInBrainFuckMode)
        } else {
            Ok(result)
        }
    }

    pub fn variable_alloc(size: Self) -> Result<Self, Error> {
        let result = Self::new(1)?;

        result.assign(size)?;

        add_to_compiled("\nALLOCATING CELLS\n");
        add_to_compiled(&result.to());
        add_to_compiled("?");
        add_to_compiled(&result.from());
        add_to_compiled("\nDONE\n");

        if Program::brainfuck_enabled() {
            Err(Error::CannotUsePointersInBrainFuckMode)
        } else {
            Ok(result)
        }
    }

    pub fn copy(&self) -> Result<Self, Error> {
        let val = Self::new(self.number_cells)?;
        val.assign(*self)?;
        Ok(val)
    }

    pub fn is_ref(&self) -> bool {
        self.reference_depth > 0
    }

    pub fn zero(&self) {
        add_to_compiled(self.to());
        for _ in 0..self.number_cells {
            add_to_compiled("[-]>");
        }
        for _ in 0..self.number_cells {
            add_to_compiled("<");
        }
        add_to_compiled(self.from());
    }

    pub fn free(&self) {
        add_to_compiled(&format!(
            "\nFREEING CELLS {}~{}\n",
            self.offset,
            self.offset + self.size()
        ));
        add_to_compiled(&self.to());

        for _ in 0..self.size() {
            add_to_compiled("[-]>");
        }

        for _ in 0..self.size() {
            add_to_compiled("<");
        }

        add_to_compiled(self.from());

        add_to_compiled("\nDONE\n");
    }

    pub fn set(&self, val: impl Into<usize>) {
        add_to_compiled(&self.to());
        add_to_compiled("[-]");
        add_to_compiled("+".repeat(val.into()));
        add_to_compiled(self.from());
    }

    pub fn assign(&self, val: Self) -> Result<(), Error> {
        if val == *self {
            return Ok(());
        }

        if Program::brainfuck_enabled() && val.size() > self.size() {
            return Err(Error::CannotAssignLargerValueToSmallerValueInBrainFuckMode);
        } else if Program::size_warn_enabled() && val.size() > self.size() {
            eprintln!("Warning: assigning larger value to smaller value");
        }

        TEMP0.zero();

        for cell in 0..val.size() {
            let cell_to = val.to() + &">".repeat(cell as usize);
            let cell_from = "<".repeat(cell as usize) + &val.from();
            let this_to = self.to() + &">".repeat(cell as usize);
            let this_from = "<".repeat(cell as usize) + &self.from();
            add_to_compiled(this_to.clone() + "[-]" + &this_from);
            add_to_compiled(
                cell_to.clone()
                    + "["
                    + &cell_from
                    + &this_to
                    + "+"
                    + &this_from
                    + &TEMP0.to()
                    + "+"
                    + &TEMP0.from()
                    + &cell_to
                    + "-"
                    + &cell_from
                    + &cell_to
                    + "]"
                    + &cell_from,
            );
            add_to_compiled(
                TEMP0.to()
                    + "["
                    + &TEMP0.from()
                    + &cell_to
                    + "+"
                    + &cell_from
                    + &TEMP0.to()
                    + "-"
                    + &TEMP0.from()
                    + &TEMP0.to()
                    + "]"
                    + &TEMP0.from(),
            );
        }
        Ok(())
    }

    pub fn plus_eq(&self, val: Self) {
        TEMP0.zero();

        for cell in 0..val.size() {
            let cell_to = val.to() + &">".repeat(cell as usize);
            let cell_from = "<".repeat(cell as usize) + &val.from();
            let this_to = self.to() + &">".repeat(cell as usize);
            let this_from = "<".repeat(cell as usize) + &self.from();
            add_to_compiled(
                cell_to.clone()
                    + "["
                    + &cell_from
                    + &this_to
                    + "+"
                    + &this_from
                    + &TEMP0.to()
                    + "+"
                    + &TEMP0.from()
                    + &cell_to
                    + "-"
                    + &cell_from
                    + &cell_to
                    + "]"
                    + &cell_from,
            );
            add_to_compiled(
                TEMP0.to()
                    + "["
                    + &TEMP0.from()
                    + &cell_to
                    + "+"
                    + &cell_from
                    + &TEMP0.to()
                    + "-"
                    + &TEMP0.from()
                    + &TEMP0.to()
                    + "]"
                    + &TEMP0.from(),
            );
        }
    }

    pub fn minus_eq(&self, val: Self) {
        TEMP0.zero();

        for cell in 0..val.size() {
            let cell_to = val.to() + &">".repeat(cell as usize);
            let cell_from = "<".repeat(cell as usize) + &val.from();
            let this_to = self.to() + &">".repeat(cell as usize);
            let this_from = "<".repeat(cell as usize) + &self.from();
            add_to_compiled(
                cell_to.clone()
                    + "["
                    + &cell_from
                    + &this_to
                    + "-"
                    + &this_from
                    + &TEMP0.to()
                    + "+"
                    + &TEMP0.from()
                    + &cell_to
                    + "-"
                    + &cell_from
                    + &cell_to
                    + "]"
                    + &cell_from,
            );
            add_to_compiled(
                TEMP0.to()
                    + "["
                    + &TEMP0.from()
                    + &cell_to
                    + "+"
                    + &cell_from
                    + &TEMP0.to()
                    + "-"
                    + &TEMP0.from()
                    + &TEMP0.to()
                    + "]"
                    + &TEMP0.from(),
            );
        }
    }

    pub fn byte_int(value: u8) -> Result<Self, Error> {
        let result = Self::new(1)?;
        add_to_compiled(result.to());
        add_to_compiled("+".repeat(value as usize));
        add_to_compiled(result.from());
        Ok(result)
    }

    pub fn unsigned_short(value: u16) -> Result<Self, Error> {
        let result = Self::new(1)?;
        add_to_compiled(result.to());
        add_to_compiled("+".repeat(value as usize));
        add_to_compiled(result.from());

        if Program::brainfuck_enabled() {
            Err(Error::CannotUseUnsignedShortsInBrainFuckMode)
        } else {
            Ok(result)
        }
    }

    pub fn character(value: char) -> Result<Self, Error> {
        let result = Self::new(1)?;
        add_to_compiled(result.to());
        add_to_compiled("+".repeat(value as usize));
        add_to_compiled(result.from());
        Ok(result)
    }

    pub fn string(value: impl ToString) -> Result<Self, Error> {
        let result = Self::new((value.to_string().len() + 1) as u32)?;

        add_to_compiled(result.to());
        for ch in value.to_string().chars() {
            add_to_compiled("+".repeat(ch as usize) + ">");
        }

        for _ in value.to_string().chars() {
            add_to_compiled("<");
        }
        add_to_compiled(result.from());

        Ok(result)
    }

    pub fn to(&self) -> String {
        ">".repeat(self.offset as usize).to_string() + &"*".repeat(self.reference_depth as usize)
    }

    pub fn from(&self) -> String {
        "&".repeat(self.reference_depth as usize) + &"<".repeat(self.offset as usize).to_string()
    }

    pub fn size(&self) -> u32 {
        self.number_cells
    }

    pub fn deref(&self) -> Result<Self, Error> {
        let mut result = Self::new(1)?;

        result.reference_depth = self.reference_depth + 1;
        result.offset = self.offset;

        if Program::brainfuck_enabled() {
            Err(Error::CannotUsePointersInBrainFuckMode)
        } else {
            Ok(result)
        }
    }

    pub fn refer(&self) -> Result<Self, Error> {
        let result = Self::new(1)?;

        add_to_compiled(result.to());
        add_to_compiled("+".repeat(self.offset as usize));
        add_to_compiled(result.from());

        if Program::brainfuck_enabled() {
            Err(Error::CannotUsePointersInBrainFuckMode)
        } else {
            Ok(result)
        }
    }
}