-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainfuck.bbl
88 lines (80 loc) · 3.02 KB
/
brainfuck.bbl
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
struct Tape contents index size.
impl Tape {
static func new: size {
Tape contents: (Array newOf: 0 length: size)
index: 0
size: size
}
func read {
self contents get: self index
}
func write: value {
self contents set: self index
value: value
}
func next {
self index = self index + 1.
self index greaterThanOrEquals: self size $ ifTrue: [
Program error: "tape out of range".
].
}
func prev {
self index = self index - 1.
self index lessThan: 0 $ ifTrue: [
Program error: "tape out of range".
].
}
}
struct Interpreter instructions index tape.
impl Interpreter {
static func new: instructions {
Interpreter instructions: instructions chars
index: 0
tape: (Tape new: 1000)
}
func step {
// Exit if the instruction pointer has gone off the end of the tape
(self index greaterThanOrEquals: self instructions length) ifTrue: [ Program exit. ].
// Otherwise, execute the current instruction
ins = self currentInstruction.
ins match toOneOf: #{
?[ |"+"| self tape write: (self tape read + 1) ]
?[ |"-"| self tape write: (self tape read - 1) ]
?[ |">"| self tape next ]
?[ |"<"| self tape prev ]
?[ |"["|
self tape read equals: 0 $ ifTrue: [
// Seek the matching ] and jump past it
bracketDepth = 1
[ bracketDepth greaterThan: 0 ] whileTrue: [
self index = self index + 1.
self currentInstruction equals: "[" $ ifTrue: [ bracketDepth = bracketDepth + 1 ].
self currentInstruction equals: "]" $ ifTrue: [ bracketDepth = bracketDepth - 1 ].
]
]
]
?[ |"]"|
self tape read notEquals: 0 $ ifTrue: [
// Seek the matching [ and jump to it
bracketDepth = 1
[ bracketDepth greaterThan: 0 ] whileTrue: [
self index = self index - 1.
self currentInstruction equals: "[" $ ifTrue: [ bracketDepth = bracketDepth - 1 ].
self currentInstruction equals: "]" $ ifTrue: [ bracketDepth = bracketDepth + 1 ].
]
]
]
?[ |"."| Console print: (String charFromAsciiCode: self tape read) ]
}
// TODO: , command
// Move onto the next instruction
self index = self index + 1.
}
func currentInstruction {
self instructions get: self index
}
}
// Program from: https://esolangs.org/wiki/Brainfuck
helloWorld = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.".
interpreter = Interpreter new: helloWorld.
[ true ] whileTrue: [ interpreter step ].