aboutsummaryrefslogtreecommitdiff
path: root/l/bf.lang
blob: 0ce638911ef82fb0394bf83e3a6444ff01447e2f (plain)
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
type byte := char;

func putstr(char[] str) {
	int i := 0;
	while (str[i] != '\0') {
		putc(str[i]);
		i = i + 1;
	}
}

func int[] makejumpmap(char[] src, int srclen) {
	int[] jm := new int[srclen];
	int[] stack := new int[srclen];
	int stkp := 0;
	int i := 0;
	while (i < srclen) {
		// putint(i); putc(' '); putint(stkp); putc(' '); putc(src[i]); putc('\n');
		if (src[i] == '[') {
			stack[stkp] = i;
			stkp = stkp + 1;
		}
		if (src[i] == ']') {
			stkp = stkp - 1;
			int j := stack[stkp];
			jm[i] = j;
			jm[j] = i;
		}
		i = i + 1;
	}
	if (stkp != 0) {
		putstr("Unmatched opening brackets in BF source\n");
		exit(1);
	}
	/*i = 0;
	while (i < srclen) {
		putint(jm[i]);
		putc(' ');
		i = i + 1;
	}
	putc('\n');*/
	return jm;
}

func interpret(char[] src, int srclen) {
	int[] jm := makejumpmap(src, srclen);
	byte[] mem := new char[4088];
	int ip := 0;
	int memp := 0;
	while (src[ip] != '\0') {
		// putint(ip); putc('\n');
		char c := src[ip];
		if (c == '+') {mem[memp] = mem[memp] + byte(1);}
		if (c == '-') {mem[memp] = mem[memp] - byte(1);}
		if (c == '>') {memp = memp + 1;}
		if (c == '<') {memp = memp - 1;}
		if (c == '.') {putc(mem[memp]);}
		if (c == ',') {mem[memp] = byte(getc());}
		if (c == '[') {
			if (mem[memp] == '\0') {
				ip = jm[ip];
			}
		}
		if (c == ']') {
			if (mem[memp] != '\0') {
				ip = jm[ip];
			}
		}
		ip = ip + 1;
	}

	// debugger;

	putc('\n');
	memp = 0;
	while (memp < 10) {
		putint(int(mem[memp]) & 0xff); putc(' ');
		memp = memp + 1;
	}
	putc('\n');
}

func int main() {
	int bufsize := 12280;
	char[] source := new char[12280];

	int sourcelen := 0;
	while (1) {
		int c := getc();
		// putc(char(c));
		if (c < 0) {
			break;
		} else {
			source[sourcelen] = char(c);
			sourcelen = sourcelen + 1;
			if (sourcelen >= bufsize - 1) {
				break;
			}
		}
	}
	source[sourcelen] = '\0';

	interpret(source, sourcelen);
	return 0;
}