simplification
Download
97 lines 4.7 KiBMoonScriptModified 2026-11-09 raw
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
-- This file lets Lua programs use Nomsu as a library:
--     nomsu = require "nomsu"
--     runtime = nomsu.Runtime{modules: {"./my_nomsu_lib"}}
--     ok, err = runtime\run [[say "Hello"]]
-- Each runtime has its own environment and loaded modules, so runtimes don't
-- affect each other.
{:new_instance, :NOMSU_DIRECTORY} = require "nomsu_environment"
Errhand = require "error_handling"
{:file_loader, :table_loader, :chain_loaders} = require "nomsu_loaders"
{:make_sandbox} = require "nomsu_sandbox"
{:run_limited} = require "nomsu_limits"

-- The most nodes a plain copy may have, so copying can't run away or exhaust memory
MAX_COPY_NODES = 1000000

-- Make a deep copy of a Lua value, but error on functions, coroutines, or
-- tables that have metatables. We don't want shared data or user code escaping
-- the sandbox.
plain_copy = (value, _seen={}, _count={n: 0})->
    t = type(value)
    switch t
        when "string", "number", "boolean", "nil"
            return value
        when "table"
            unless getmetatable(value) == nil
                error("A sandbox value can only be a plain table (one with no metatable).", 0)
            error("A sandbox value can't contain a cycle.", 0) if _seen[value]
            _seen[value] = true
            result = {}
            for k, v in pairs value
                _count.n += 1
                if _count.n > MAX_COPY_NODES
                    error("Sandbox value is too big to copy.", 0)
                result[plain_copy(k, _seen, _count)] = plain_copy(v, _seen, _count)
            _seen[value] = nil
            return result
        else
            error("A sandbox value can only be plain data, not a #{t}.", 0)

-- A Nomsu runtime, with its own environment and loaded modules
class Runtime
    -- Config options:
    --   modules: where to find modules, besides Nomsu's own library: a list of directories,
    --     and/or module names mapped to their code (default: the current directory)
    --   print: a function that writes text, which (say) uses (default: write to stdout)
    --   input: a function that reads a line of text, which (ask) uses (default: read stdin)
    --   limits: limits for each run(), as a table with any of: instructions (the number of
    --     Lua instructions), seconds (of CPU time), and memory (in kilobytes, approximately).
    --     These can be changed later with runtime.limits.
    --   environment: a table of extra values for the runtime's environment, which are
    --     added before the core library loads
    new: (config={})=>
        modules = config.modules or {"."}
        directories = {"#{NOMSU_DIRECTORY}/lib"}
        for dir in *modules
            table.insert directories, dir
        loader = chain_loaders(
            table_loader({k,v for k,v in pairs(modules) when type(k) == "string"}),
            file_loader(directories))
        @root = new_instance{
            :loader, print: config.print, input: config.input, exit: Errhand.exit_signal
        }
        for k,v in pairs(config.environment or {})
            @root[k] = v
        @root\export("core")
        @environment = @root.new_environment!
        @environment.MODULE_NAME = "main"
        @host_names = {k, true for k in pairs(config.environment or {})}
        @limits = config.limits

    -- Run some Nomsu code (text, NomsuCode, or a syntax tree). Returns true and the code's
    -- return value, or false and an error message. If the code calls (exit), this returns
    -- false and an exit signal, which has the exit code in its .exit field. If the code runs
    -- out of one of the runtime's limits, this returns false and a limit signal, which
    -- has the limit ("instructions", "time", or "memory") in its .limit field.
    run: (code)=>
        run = ->
            ok, value = xpcall((-> @environment\run(code)), Errhand.enhance_error)
            -- A sealed runtime copies its result to plain data, so the program running
            -- Nomsu can't be made to run sandboxed code by using the result.
            if ok and @sealed
                ok, value = pcall(plain_copy, value)
            return ok, value
        return run_limited(@limits, run)

    -- Seal the runtime, which can't be undone. Code that runs afterwards is sandboxed: it
    -- can only use the core language and what the program running Nomsu added to the
    -- environment (with the environment config option). With (use), it can bring in the
    -- safe exports of a module that was loaded before sealing, but it can't load new
    -- modules from disk. It can't use inline Lua, define compile rules, or use Lua's
    -- libraries for files, the OS, and so on.
    seal: =>
        return if @sealed
        @sealed = true
        @environment = make_sandbox(@environment, @host_names)

return {:Runtime, :plain_copy}