2021-05-19 03:43:19 +00:00
|
|
|
local ds = require("DataStructures")
|
|
|
|
local Stack, Dictionary, WordInfo, Environment = ds.Stack, ds.Dictionary, ds.WordInfo, ds.Environment
|
|
|
|
local helpers = require("CoreHelpers")
|
|
|
|
local isNumber, skipWhitespace, parseToken = helpers.isNumber, helpers.skipWhitespace, helpers.parseToken
|
2021-05-20 03:04:04 +00:00
|
|
|
local istream = require("InputStream")
|
|
|
|
local CoreWords = require("CoreWords")
|
|
|
|
local Pointer = ds.Pointer
|
2021-05-19 03:43:19 +00:00
|
|
|
local type Interpreters = record
|
|
|
|
inner: function(Environment)
|
|
|
|
outer: function(Environment)
|
|
|
|
end
|
|
|
|
|
2021-05-23 11:59:36 +00:00
|
|
|
function Interpreters.start(env: Environment)
|
|
|
|
table.insert(env.dictionaries, CoreWords)
|
2021-05-20 03:04:04 +00:00
|
|
|
local interpreterInstructions = {}
|
|
|
|
table.insert(interpreterInstructions, Interpreters.outer)
|
|
|
|
table.insert(interpreterInstructions, helpers.reset)
|
|
|
|
local startPointer = Pointer:new()
|
|
|
|
startPointer.referant = interpreterInstructions
|
2021-05-23 11:59:36 +00:00
|
|
|
env.instructionPointer = startPointer
|
|
|
|
Interpreters.inner(env)
|
2021-05-20 03:04:04 +00:00
|
|
|
end
|
|
|
|
|
2021-05-19 03:43:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
function Interpreters.outer(env: Environment)
|
|
|
|
skipWhitespace(env)
|
2021-05-23 11:59:36 +00:00
|
|
|
local token: string | nil = parseToken(env)
|
|
|
|
if not token then
|
|
|
|
env.running = false
|
|
|
|
return
|
|
|
|
end
|
2021-05-19 03:43:19 +00:00
|
|
|
if isNumber(token) then
|
|
|
|
env.activeDataStack:push(tonumber(token))
|
|
|
|
else
|
|
|
|
for _, dictionary in ipairs(env.dictionaries) do
|
|
|
|
local wordinfo = dictionary:lookup(token)
|
|
|
|
if wordinfo then
|
|
|
|
(wordinfo as WordInfo).func(env)
|
|
|
|
goto continue
|
|
|
|
end
|
|
|
|
end
|
|
|
|
print(string.format('%q ?', token))
|
|
|
|
::continue::
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
function Interpreters.inner(env: Environment)
|
2021-05-23 11:59:36 +00:00
|
|
|
while(env.running) do
|
2021-05-19 03:43:19 +00:00
|
|
|
env.instructionPointer:deref() as function(Environment)(env)
|
|
|
|
env.instructionPointer:inc()
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
return Interpreters
|