b614776ab72782170ee6930edb02d7b214ed5556
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]
33 # Starts interpretation of file `filename`
34 init(filename
: String) do
35 var ifs
= new IFStream.open
(filename
.simplify_path
)
36 valid_instr
= new HashSet[Char]
37 valid_instr
.add_all
"><[].,+-".chars
39 program
= ifs
.read_all
43 # Starts the interpretation of the loaded program
46 if ip
>= program
.length
then break
52 # Go to the next executable instruction
55 while ip
< program
.length
and not valid_instr
.has
(program
[ip
]) do
60 # Evaluates the current instruction
62 var instr
= program
[ip
]
63 if instr
== '.' then printn dr
[dp
]
65 if dr
[dp
] == 0.ascii
then
66 ip
= find_matching_rbra
71 if dr
[dp
] != 0.ascii
then
72 ip
= find_matching_lbra
78 if dp
>= dr
.length
then dr
.add
(0.ascii
)
85 dr
[dp
] = (dr
[dp
].ascii
+ 1).ascii
88 dr
[dp
] = (dr
[dp
].ascii
- 1).ascii
95 # Seeks for the position of the matching `]` for the `[` located at `ip`
96 fun find_matching_rbra
: Int do
100 if pos
> program
.length
then abort
101 if program
[pos
] == ']' then
108 if program
[pos
] == '[' then lbracnt
+= 1
114 # Seeks for the position of the matching `[` for the `]` located at `ip`
115 fun find_matching_lbra
: Int do
119 if pos
< 0 then abort
120 if program
[pos
] == '[' then
127 if program
[pos
] == ']' then rbracnt
+= 1
134 var i
= new BFInterpret(args
[0])