1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Simple brainfuck interpreter
18 # Interpreter for Brainfuck source code.
21 var dr
= new Array[Byte]
27 # The program being interpreted
30 # Create an interpreter for `program`.
35 # Create an interpreter for the file located at `path`.
36 init from_file
(path
: String) do
37 var ifs
= new FileReader.open
(path
)
38 init(ifs
.read_all_bytes
)
41 # Starts the interpretation of the loaded program
44 if ip
>= program
.length
then break
51 # Evaluates the current instruction
53 var instr
= program
[ip
]
54 if instr
== '.'.ascii
then printn dr
[dp
].ascii
55 if instr
== '['.ascii
then
57 ip
= find_matching_rbra
61 if instr
== ']'.ascii
then
63 ip
= find_matching_lbra
67 if instr
== '>'.ascii
then
69 if dp
>= dr
.length
then dr
.add
(0u8
)
71 if instr
== '<'.ascii
then
75 if instr
== '+'.ascii
then
78 if instr
== '-'.ascii
then
81 if instr
== ','.ascii
then
86 # Seeks for the position of the matching `]` for the `[` located at `ip`
87 fun find_matching_rbra
: Int do
91 if pos
> program
.length
then abort
92 if program
[pos
] == ']'.ascii
then
99 if program
[pos
] == '['.ascii
then lbracnt
+= 1
105 # Seeks for the position of the matching `[` for the `]` located at `ip`
106 fun find_matching_lbra
: Int do
110 if pos
< 0 then abort
111 if program
[pos
] == '['.ascii
then
118 if program
[pos
] == ']'.ascii
then rbracnt
+= 1
125 new BFInterpreter.from_file
(args
[0]).start