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[Char]
27 # The program being interpreted
30 # Contains the set of valid instructions, used in next
31 var valid_instr
: Set[Char] is noinit
33 # Create an interpreter for `program`.
35 valid_instr
= new HashSet[Char]
36 valid_instr
.add_all
"><[].,+-".chars
40 # Create an interpreter for the file located at `path`.
41 init from_file
(path
: String) do
42 var ifs
= new FileReader.open
(path
)
46 # Starts the interpretation of the loaded program
49 if ip
>= program
.length
then break
55 # Go to the next executable instruction
58 while ip
< program
.length
and not valid_instr
.has
(program
[ip
]) do
63 # Evaluates the current instruction
65 var instr
= program
[ip
]
66 if instr
== '.' then printn dr
[dp
]
68 if dr
[dp
] == 0.ascii
then
69 ip
= find_matching_rbra
74 if dr
[dp
] != 0.ascii
then
75 ip
= find_matching_lbra
81 if dp
>= dr
.length
then dr
.add
(0.ascii
)
88 dr
[dp
] = (dr
[dp
].ascii
+ 1).ascii
91 dr
[dp
] = (dr
[dp
].ascii
- 1).ascii
98 # Seeks for the position of the matching `]` for the `[` located at `ip`
99 fun find_matching_rbra
: Int do
103 if pos
> program
.length
then abort
104 if program
[pos
] == ']' then
111 if program
[pos
] == '[' then lbracnt
+= 1
117 # Seeks for the position of the matching `[` for the `]` located at `ip`
118 fun find_matching_lbra
: Int do
122 if pos
< 0 then abort
123 if program
[pos
] == '[' then
130 if program
[pos
] == ']' then rbracnt
+= 1
137 new BFInterpreter.from_file
(args
[0]).start