-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbrainfuck.nim
209 lines (178 loc) · 6.08 KB
/
brainfuck.nim
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
## :Author: Dennis Felsing
##
## This module implements an interpreter for the brainfuck programming language
## as well as a compiler of brainfuck into efficient Nim code.
##
## Example:
##
## .. code:: nim
## import brainfuck, streams
##
## interpret("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.")
## # Prints "Hello World!"
##
## proc mandelbrot = compileFile("examples/mandelbrot.b")
## mandelbrot() # Draws a mandelbrot set
import streams
when not defined(nimnode):
type NimNode = PNimrodNode
proc readCharEOF*(input: Stream): char =
## Read a character from an `input` stream and return a Unix EOF (-1). This
## is necessary because brainfuck assumes Unix EOF while streams use \0 for
## EOF.
result = input.readChar
if result == '\0': # Streams return 0 for EOF
result = '\255' # BF assumes EOF to be -1
{.push overflowchecks: off.}
proc xinc*(c: var char) {.inline.} =
## Increment a character with wrapping instead of overflow checks.
inc c
proc xdec*(c: var char) {.inline.} =
## Decrement a character with wrapping instead of underflow checks.
dec c
{.pop.}
proc interpret*(code: string; input, output: Stream) =
## Interprets the brainfuck `code` string, reading from `input` and writing
## to `output`.
##
## Example:
##
## .. code:: nim
## var inpStream = newStringStream("Hello World!\n")
## var outStream = newFileStream(stdout)
## interpret(readFile("examples/rot13.b"), inpStream, outStream)
var
tape = newSeq[char]()
codePos = 0
tapePos = 0
proc run(skip = false): bool =
while tapePos >= 0 and codePos < code.len:
if tapePos >= tape.len:
tape.add '\0'
if code[codePos] == '[':
inc codePos
let oldPos = codePos
while run(tape[tapePos] == '\0'):
codePos = oldPos
elif code[codePos] == ']':
return tape[tapePos] != '\0'
elif not skip:
case code[codePos]
of '+': xinc tape[tapePos]
of '-': xdec tape[tapePos]
of '>': inc tapePos
of '<': dec tapePos
of '.': output.write tape[tapePos]
of ',': tape[tapePos] = input.readCharEOF
else: discard
inc codePos
discard run()
proc interpret*(code, input: string): string =
## Interprets the brainfuck `code` string, reading from `input` and returning
## the result directly.
##
## Example:
##
## .. code:: nim
## echo interpret(readFile("examples/rot13.b"), "Hello World!\n")
var outStream = newStringStream()
interpret(code, input.newStringStream, outStream)
result = outStream.data
proc interpret*(code: string) =
## Interprets the brainfuck `code` string, reading from stdin and writing to
## stdout.
##
## Example:
##
## .. code:: nim
## interpret(readFile("examples/rot13.b"))
interpret(code, stdin.newFileStream, stdout.newFileStream)
import macros
proc compile(code, input, output: string): NimNode {.compiletime.} =
var stmts = @[newStmtList()]
template addStmt(text): typed =
stmts[stmts.high].add parseStmt(text)
addStmt """
when not compiles(newStringStream()):
static:
quit("Error: Import the streams module to compile brainfuck code", 1)
"""
addStmt "var tape: array[1_000_000, char]"
addStmt "var inpStream = " & input
addStmt "var outStream = " & output
addStmt "var tapePos = 0"
for c in code:
case c
of '+': addStmt "xinc tape[tapePos]"
of '-': addStmt "xdec tape[tapePos]"
of '>': addStmt "inc tapePos"
of '<': addStmt "dec tapePos"
of '.': addStmt "outStream.write tape[tapePos]"
of ',': addStmt "tape[tapePos] = inpStream.readCharEOF"
of '[': stmts.add newStmtList()
of ']':
var loop = newNimNode(nnkWhileStmt)
loop.add parseExpr("tape[tapePos] != '\\0'")
loop.add stmts.pop
stmts[stmts.high].add loop
else: discard
result = stmts[0]
#echo result.repr
macro compileString*(code: string; input, output: untyped): typed =
## Compiles the brainfuck code read from `filename` at compile time into Nim
## code that reads from the `input` variable and writes to the `output`
## variable, both of which have to be strings.
result = compile($code,
"newStringStream(" & $input & ")", "newStringStream()")
result.add parseStmt($output & " = outStream.data")
macro compileString*(code: string): typed =
## Compiles the brainfuck `code` string into Nim code that reads from stdin
## and writes to stdout.
echo code
compile($code, "stdin.newFileStream", "stdout.newFileStream")
macro compileFile*(filename: string; input, output: untyped): typed =
## Compiles the brainfuck code read from `filename` at compile time into Nim
## code that reads from the `input` variable and writes to the `output`
## variable, both of which have to be strings.
##
## Example:
##
## .. code-block:: nim
## proc rot13(input: string): string =
## compileFile("examples/rot13.b", input, result)
## echo rot13("Hello World!\n")
result = compile(staticRead(filename.strval),
"newStringStream(" & $input & ")", "newStringStream()")
result.add parseStmt($output & " = outStream.data")
macro compileFile*(filename: string): typed =
## Compiles the brainfuck code read from `filename` at compile time into Nim
## code that reads from stdin and writes to stdout.
##
## Example:
##
## .. code-block:: nim
## proc mandelbrot = compileFile("examples/mandelbrot.b")
## mandelbrot()
compile(staticRead(filename.strval),
"stdin.newFileStream", "stdout.newFileStream")
when isMainModule:
import docopt, tables, strutils
proc mandelbrot = compileFile("../examples/mandelbrot.b")
let doc = """
brainfuck
Usage:
brainfuck mandelbrot
brainfuck interpret [<file.b>]
brainfuck (-h | --help)
brainfuck (-v | --version)
Options:
-h --help Show this screen.
-v --version Show version.
"""
let args = docopt(doc, version = "brainfuck 1.0")
if args["mandelbrot"]:
mandelbrot()
elif args["interpret"]:
let code = if args["<file.b>"]: readFile($args["<file.b>"])
else: readAll stdin
interpret(code)