Skip to content

Commit e7335a3

Browse files
committed
Add interpreter implementation
1 parent b8526a2 commit e7335a3

File tree

1 file changed

+57
-2
lines changed

1 file changed

+57
-2
lines changed

src/luasm.lua

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,14 @@ function instruction:parse(elements, luasm)
185185
args[i - 1] = arg
186186
end
187187

188-
return { op = opcode, args = args, line = luasm.current_line }
188+
return {
189+
op = opcode,
190+
args = args,
191+
line = luasm.current_line,
192+
run = function(instr, interpreter)
193+
self.settings.executor(instr, interpreter)
194+
end
195+
}
189196
end
190197

191198
--[[
@@ -373,14 +380,62 @@ function LuASM.stack()
373380
end
374381

375382
local interpreter = {}
376-
function LuASM:interpreter()
383+
384+
-- TODO position_exists
385+
386+
function interpreter:jump(index)
387+
if type(index) == "string" then -- Jump to label
388+
index = self.data.labels[index]
389+
390+
if index == nil then
391+
return "This label does not exist"
392+
end
393+
end
394+
395+
if type(index) ~= "number" then
396+
error("The index must be a number or a string", 2)
397+
end
398+
399+
if index < 0 or index > self.data.parsed_lines then
400+
error("This position does not exist.")
401+
end
402+
403+
self.ic = index
404+
return nil
405+
end
406+
407+
function interpreter:next_instruction()
408+
::start::
409+
410+
if self.data.parsed_lines < self.ip then
411+
return nil
412+
end
413+
414+
local line = self.data.instructions[self.ip]
415+
if line == nil then
416+
self.ip = self.ip + 1
417+
goto start
418+
end
419+
420+
line:run(self)
421+
end
422+
423+
function LuASM:interpreter(data, memory)
377424
local obj = {}
378425

379426
setmetatable(obj, interpreter)
380427
interpreter.__index = interpreter
381428

382429
obj.luasm = self
383430

431+
obj.ip = 1
432+
obj.data = data
433+
434+
obj.memory = memory or {
435+
stack = LuASM.stack(),
436+
heap = {}
437+
}
438+
384439
return obj
385440
end
386441

0 commit comments

Comments
 (0)