Last active
September 7, 2024 19:54
-
-
Save drguildo/212d14b724e85c833efd6e524290276d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import streams | |
import system | |
import tables | |
var data: array[30_000, byte] | |
var dataPointer: int = 0 | |
var instructions: seq[char] | |
var instructionPointer: int = 0 | |
proc panic(message: string) = | |
stderr.writeLine("ERROR: " & message) | |
system.quit(-1) | |
proc incrementByte() = | |
inc(data[dataPointer]) | |
proc decrementByte() = | |
dec(data[dataPointer]) | |
proc outputByte() = | |
stdout.write(data[dataPointer]) | |
proc incrementDataPointer() = | |
inc(dataPointer) | |
proc decrementDataPointer() = | |
dec(dataPointer) | |
proc conditionalJumpForward() = | |
if data[dataPointer] == 0: | |
var nestedPairs = 1 | |
while instructions[instructionPointer] != ']' and nestedPairs != 0: | |
inc(instructionPointer) | |
if instructions[instructionPointer] == '[': | |
inc(nestedPairs) | |
elif instructions[instructionPointer] == ']': | |
dec(nestedPairs) | |
proc conditionalJumpBackwards() = | |
if data[dataPointer] != 0: | |
var nestedPairs = 1 | |
while instructions[instructionPointer] != '[' and nestedPairs != 0: | |
dec(instructionPointer) | |
if instructions[instructionPointer] == ']': | |
inc(nestedPairs) | |
elif instructions[instructionPointer] == '[': | |
dec(nestedPairs) | |
proc readByte() = | |
var buf: array[1, byte] | |
let numBytesRead = stdin.readBytes(buf, 0, 1) | |
if numBytesRead != 1: | |
panic("Failed to read byte from stdin.") | |
data[dataPointer] = buf[0] | |
var instructionToProc = { | |
'+': incrementByte, | |
'-': decrementByte, | |
'>': incrementDataPointer, | |
'<': decrementDataPointer, | |
'[': conditionalJumpForward, | |
']': conditionalJumpBackwards, | |
',': readByte, | |
'.': outputByte | |
}.newTable | |
proc loadCode(filename: string): seq[char] = | |
var strm = newFileStream(filename, fmRead) | |
var sourceCode = strm.readAll() | |
strm.close() | |
for ch in sourceCode: | |
if instructionToProc.hasKey(ch): | |
result.add(ch) | |
when isMainModule: | |
instructions = loadCode(paramStr(1)) | |
while true: | |
instructionToProc[instructions[instructionPointer]]() | |
inc(instructionPointer) | |
if instructionPointer >= len(instructions): | |
system.quit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bf.nim(63, 6) Error: type mismatch: got '(char, proc ())' for '('[', conditionalJumpForward)' but expected '(char, proc (){.gcsafe.})'