forth-stuff/ForthInterpreter.tl

40 lines
1.1 KiB
Plaintext

local CoreWords = require("CoreWords")
local ds = require("DataStructures")
local istream = require("InputStream")
local Stack, Dictionary, WordInfo, State = ds.Stack, ds.Dictionary, ds.WordInfo, ds.State
local helpers = require("CoreHelpers")
local isNumber, skipWhitespace, parseToken = helpers.isNumber, helpers.skipWhitespace, helpers.parseToken
local machineState = State:new()
function standardInputRefill(): string
local input = io.read().."\n"
return input
end
local standardInputStream = istream:new(standardInputRefill)
machineState.activeInputStream = standardInputStream
machineState.activeDataStack = Stack:new()
table.insert(machineState.dictionaries, CoreWords)
while(true) do
skipWhitespace(machineState)
local token: string = parseToken(machineState)
if isNumber(token) then
machineState.activeDataStack:push(tonumber(token))
else
for i, dictionary in ipairs(machineState.dictionaries) do
local wordinfo = dictionary:lookup(token)
if wordinfo then
(wordinfo as WordInfo).func(machineState)
goto continue
end
end
print(string.format('%q ?', token))
::continue::
end
end