aboutsummaryrefslogtreecommitdiff
path: root/bf.lang
blob: 71a5d8ad1400a694bca5c7ffbce18296222b9782 (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
105
106
func putstr(char[] str) {
	int i := 0;
	while (str[i] != '\0') {
		putc(str[i]);
		i = i + 1;
	}
}

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

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;
	}
	/*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);
	char[] 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] + char(1);}
		if (c == '-') {mem[memp] = mem[memp] - char(1);}
		if (c == '>') {memp = memp + 1;}
		if (c == '<') {memp = memp - 1;}
		if (c == '.') {putc(mem[memp]);}
		if (c == ',') {mem[memp] = char(getc());}
		if (c == '[') {
			if (mem[memp] == '\0') {
				ip = jm[ip];
			}
		}
		if (c == ']') {
			if (mem[memp] != '\0') {
				ip = jm[ip];
			}
		}
		ip = ip + 1;
	}

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

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

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

	interpret(source, sourcelen);
	return 0;
}