~mikelma/oktac

oktac/examples/brain-fuck/main.ok -rw-r--r-- 1.9 KiB
79afb735 — mikelma basic lambda function support 7 months ago
                                                                                
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
extern fun printf(&u8, ...)

fun main(): i8 {
    let program = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.";
    let input = "";

    let program_idx = 0u64;
    let tape_idx    = 0u64;
    let input_idx   = 0u64;

    let tape: [u8; 20] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

    while true {
        let cmd = program[program_idx];

        # check if final of string is reached
        if cmd == 0 { 
            break;

        } elif cmd == 62 { # '>' command
            tape_idx = tape_idx + 1;

        } elif cmd == 60 { # '<' command
            tape_idx = tape_idx - 1;

        } elif cmd == 43 { # '+' command
            tape[tape_idx] = tape[tape_idx] + 1;

        } elif cmd == 45 { # '-' command
            tape[tape_idx] = tape[tape_idx] - 1;

        } elif cmd == 46 { # '.' command
            printf(@cstr("%c"), tape[tape_idx]);

        } elif cmd == 44 { # ',' command
            tape[tape_idx] = input[input_idx];
            input_idx = input_idx + 1;

        } elif cmd == 91 && tape[tape_idx] == 0 { # '[' command
            let cont = 1;

            while cont > 0 {
                program_idx = program_idx + 1;
                cmd = program[program_idx];

                if cmd == 91 { # '['
                    cont = cont + 1;

                } elif cmd == 93 { # ']'
                    cont = cont - 1;
                } 
            }

        } elif cmd == 93 && tape[tape_idx] != 0 { # ']' command
            let cont = 1;

            while cont > 0 {
                program_idx = program_idx - 1;
                cmd = program[program_idx];

                if cmd == 91 { # '['
                    cont = cont - 1;

                } elif cmd == 93 { # ']'
                    cont = cont + 1;
                } 
            }

            program_idx = program_idx - 1;
        }  

        program_idx = program_idx + 1;
    }

    ret 0;
}