-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathbf.nim
More file actions
88 lines (72 loc) · 1.84 KB
/
bf.nim
File metadata and controls
88 lines (72 loc) · 1.84 KB
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
import net
import strformat
import posix
type
OpType = enum Inc, Move, Loop, Print
Ops = seq[Op]
Op = object
case op: OpType
of Inc, Move: val: int
of Loop: loop: Ops
else: discard
StringIterator = iterator(): char
Tape = object
pos: int
tape: seq[int]
Program = distinct Ops
func initTape(): Tape =
result.pos = 0
result.tape = newSeq[int](1)
proc get(t: Tape): int {.inline.} = t.tape[t.pos]
proc inc(t: var Tape, x: int) {.inline.} = t.tape[t.pos] += x
proc move(t: var Tape, x: int) {.inline.} =
t.pos += x
while t.pos >= t.tape.len:
t.tape.setLen 2 * t.tape.len
func newStringIterator(s: string): StringIterator =
result = iterator(): char =
for i in s:
yield i
func parse(iter: StringIterator): Ops =
for i in iter():
case i
of '+': result.add Op(op: Inc, val: 1)
of '-': result.add Op(op: Inc, val: -1)
of '>': result.add Op(op: Move, val: 1)
of '<': result.add Op(op: Move, val: -1)
of '.': result.add Op(op: Print)
of '[': result.add Op(op: Loop, loop: parse iter)
of ']': break
else: discard
func parse(code: string): Program =
let iter = newStringIterator code
result = Program parse iter
proc run(ops: Ops, t: var Tape) =
for op in ops:
case op.op
of Inc: t.inc op.val
of Move: t.move op.val
of Loop:
while t.get() > 0: run(op.loop, t)
of Print:
stdout.write t.get().chr()
stdout.flushFile()
proc run(ops: Program) =
var tape = initTape()
run Ops ops, tape
proc notify(msg: string) =
try:
var socket = newSocket()
defer: socket.close()
socket.connect("localhost", Port(9001))
socket.send(msg)
except:
discard
import os
var text = paramStr(1).readFile()
var compiler = "Nim Clang"
when defined(gcc):
compiler = "Nim GCC"
notify(&"{compiler}\t{getpid()}")
text.parse().run()
notify("stop")