-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
311 lines (255 loc) · 7.09 KB
/
main.go
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
package main
import (
"fmt"
"os"
"flag"
"io/ioutil"
"strings"
"github.com/eiannone/keyboard"
)
const BRAINFUCK_VERSION = "v1.0"
// error status
const (
KErrorNone = 0
KErrorUnableToOpenFile = 1
KErrorMemoryBlockSizeToSmall = 2
KErrorProblemParsingFile = 3
KErrorSyntaxError = 4
KErrorBracketsNotPaired = 5
KErrorUnexpectedClosingBracketFound = 6
KErrorInvalidCharacterFound = 7
)
const (
DEFAULT_MEMORY_SIZE = 30000 // bytes
DEFAULT_CODE_SIZE = 10000 // bytes
DEFAULT_SOURCE_FILE = "A.BF" // to be changed
MINIMUM_MMEORY_BLOCK_SIZE = 1000 // min menory size
)
var (
sourceFileName string = DEFAULT_SOURCE_FILE
memorySizePtr *int
)
var (
memoryPtr int // Pointer to current location in memory
instructionPtr int // Pointer to current instruction
memory []uint8
instructions []uint8
// useful limits and sizes
codeSize int = DEFAULT_CODE_SIZE
sourceFileSize int
fileSize int
nestingLevel int // count of the bracket nesting level from the root
)
func main () {
displayBanner ()
// read command line arguments, 'MEMORY' & 'FILE'
flag.StringVar (&sourceFileName, "file", DEFAULT_SOURCE_FILE,"Name of default code file")
memorySizePtr = flag.Int ("memory", DEFAULT_MEMORY_SIZE, "Working memory size in bytes")
flag.Parse ()
fmt.Printf ("Reading from source file '%s' ...\n", strings.ToUpper (sourceFileName))
fmt.Printf ("Initialising memory block : %d bytes\n", *memorySizePtr)
if *memorySizePtr <= MINIMUM_MMEORY_BLOCK_SIZE {
showStatus (KErrorMemoryBlockSizeToSmall, "", *memorySizePtr)
}
// init memory block
memory = make ([]uint8, *memorySizePtr, *memorySizePtr)
fmt.Println ("Reading File ....")
if data, err := readFileToMemory (sourceFileName); err == nil {
codeSize = len(data)
instructions = make ([]uint8, codeSize, codeSize)
instructionPtr = 0
fmt.Println ("Parsing file ...")
if status := parseFile (data); status != KErrorNone {
showStatus (status, sourceFileName,0)
} else {
fmt.Println ("Executing file ...")
if status := executeFile (); status != KErrorNone {
showStatus (KErrorSyntaxError, sourceFileName,0)
}
}
} else {
showStatus (KErrorUnableToOpenFile, sourceFileName,0)
}
}
// private methods
func displayBanner () {
fmt.Printf ("BrainFuck Interpreter %s\n\n", BRAINFUCK_VERSION)
}
func readFileToMemory (filename string) ([]uint8, error) {
file, err := os.Open (sourceFileName)
defer file.Close ()
if err == nil {
data, err := ioutil.ReadAll (file)
if err == nil {
return data, nil
}
}
return nil, err
}
func parseFile (data []uint8) int {
var sourceIndex int
var targetIndex int
var bracketCount int
for sourceIndex < len(data) {
if validChar (data[sourceIndex]) {
instructions[targetIndex] = data[sourceIndex]
// check bracket paring matches up
if instructions[targetIndex] == '[' {
bracketCount++
} else {
if instructions[targetIndex] == ']' {
bracketCount--
}
}
if bracketCount < 0 {
showStatus (KErrorUnexpectedClosingBracketFound,"",0)
}
targetIndex++
}
sourceIndex++
}
if bracketCount != 0 {
showStatus (KErrorBracketsNotPaired,"",0)
}
fileSize = targetIndex
return KErrorNone
}
func executeFile () int {
resetPtrs ()
for instructionPtr < fileSize {
switch instructions[instructionPtr] {
case '+': incrementValueAtDataPtr ()
case '-': decrementValueAtDataPtr ()
case '<': decrementDataPtr ()
case '>': incrementDataPtr ()
case '.': outputByte ()
case ',': inputByte ()
case '[': skipForwardIfZero ()
case ']': skipBackwardIfNotZero ()
default:
return KErrorInvalidCharacterFound
}
}
return KErrorNone
}
func resetPtrs () {
instructionPtr = 0
memoryPtr = 0
nestingLevel = 0
}
// '>' command
func incrementDataPtr () {
if memoryPtr < *memorySizePtr - 1 {
memoryPtr++
}
instructionPtr++
}
// '<' command
func decrementDataPtr () {
if memoryPtr > 0 {
memoryPtr--
}
instructionPtr++
}
// '+' command
func incrementValueAtDataPtr () {
memory[memoryPtr]++
instructionPtr++
}
// '-'
func decrementValueAtDataPtr () {
memory[memoryPtr]--
instructionPtr++
}
// '.'
func outputByte () {
fmt.Printf("%c", memory[memoryPtr])
instructionPtr++
}
// ',' command
func inputByte () {
char, _, err := keyboard.GetSingleKey ()
if err == nil {
memory[memoryPtr] = uint8(char)
}
instructionPtr++
}
// '[' command
func skipForwardIfZero () {
if memory[memoryPtr] == 0 {
// skip to byte after matching closing bracket
var openBracketCount, closingBracketCount int
var foundMatchingBracket bool = false
for !foundMatchingBracket && (instructionPtr < fileSize){
if instructions[instructionPtr] == '[' {
openBracketCount++
} else if instructions[instructionPtr] == ']' {
closingBracketCount++
}
instructionPtr++
if (openBracketCount == closingBracketCount) {
foundMatchingBracket = true;
}
}
} else {
// move to next byte
instructionPtr++
}
}
// ']' command
func skipBackwardIfNotZero () {
if instructions[instructionPtr] != 0 {
var foundMatchingBracket bool = false
var nestingLevel int = 0
for instructionPtr >= 0 && !foundMatchingBracket {
if instructions[instructionPtr] == '[' {
nestingLevel++
} else if instructions[instructionPtr] == ']' {
nestingLevel--
}
if (nestingLevel == 0) {
foundMatchingBracket = true
} else {
instructionPtr--
}
}
} else {
instructionPtr++
}
}
func validChar (ch uint8) bool {
return strings.IndexByte ("+-.,[]<>", ch) != -1
}
func dump (){
fmt.Printf ("%d:", instructionPtr)
for i:=0; i <5; i++{
fmt.Printf ("%02d ", memory[i])
}
fmt.Println ()
}
func showStatus (status int, extraInfoString string, extraInfoValue int) {
var message string = "\nError: "
if status != KErrorNone {
switch (status) {
case KErrorUnableToOpenFile:
message += fmt.Sprintf ("Unable to open file '%s'\n", strings.ToUpper(extraInfoString))
case KErrorMemoryBlockSizeToSmall:
message += fmt.Sprintf ("Specified memory size is too small (Minimum is %d bytes)\n", extraInfoValue)
case KErrorProblemParsingFile:
message += fmt.Sprintf ("Problem parsing file '%s'\n", strings.ToUpper(extraInfoString))
case KErrorSyntaxError:
message += fmt.Sprintf ("Syntax error in file\n")
case KErrorBracketsNotPaired:
message += fmt.Sprintf ("Mismatched opening and closing brackets\n")
case KErrorUnexpectedClosingBracketFound:
message += fmt.Sprintf ("Closing backet found before any opening bracket\n")
case KErrorInvalidCharacterFound:
message += fmt.Sprintf ("Invalid character found whilst executing code : '%s'\n", extraInfoString)
default:
// shouldnt get here but catch it anyway
fmt.Println ("Unknown Error Detected (%d)\n", status)
}
fmt.Println (message)
os.Exit(status)
}
}