simplification
Download
174 lines 6.6 KiBMoonScriptModified 2026-11-08 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
-- This file contains a set of compile actions needed for bootstrapping
{:match, :sub, :gsub, :format, :byte, :find} = string
{:LuaCode, :Source} = require "code_obj"
SyntaxTree = require "syntax_tree"
Files = require "files"

{:fail_at} = require('nomsu_compiler')
unpack or= table.unpack

MAX_LINE = 80 -- For beautification purposes, try not to make lines much longer than this value

-- Compile the body of a (local:) or (public:) block and return the names it defines
-- (outside of any functions in it). A variable by itself, like $x or {$x, $y}, declares
-- that name without giving it a value.
compile_definitions = (body)=>
    statements = body.type == "Block" and body or {body}
    names, seen, rest = {}, {}, {}
    add_name = (name)->
        unless seen[name]
            names[#names+1] = name
            seen[name] = true
    for statement in *statements
        if statement.type == "Var"
            add_name @compile(statement)\text!
        elseif statement.type == "Table" and #statement > 0 and
                #[v for v in *statement when v.type == "Var"] == #statement
            add_name(@compile(v)\text!) for v in *statement
        else
            rest[#rest+1] = statement
    lua = LuaCode\from(body.source)
    if #rest > 0
        rest_lua = @compile(SyntaxTree{type:"Block", source:body.source, unpack(rest)})
        add_name(v) for v in *rest_lua\get_free_vars!
        rest_lua\remove_free_vars!
        lua\add rest_lua
    return lua, names

-- ($fn 1 2) and (call $fn 1 2) both call a function. Arguments at the end of an action
-- aren't part of its stub, so (call $fn) takes any number of them.
compile_call = (_t, fn, ...)=>
    lua = LuaCode!
    fn_lua = @compile(fn)
    lua\add fn_lua
    unless fn_lua\text!\match("^%(.*%)$") or fn_lua\text!\match("^[_a-zA-Z][_a-zA-Z0-9.]*$")
        lua\parenthesize!
    lua\add "("
    for i=1,select('#',...)
        lua\add(", ") if i > 1
        lua\add @compile((select(i, ...)))
    lua\add ")"
    return lua

compile_actions = {
    [""]: compile_call
    ["call"]: compile_call

    ["Lua"]: (_t, code)=>
        if not code
            return LuaCode("LuaCode()")
        if code.type != "Text"
            return LuaCode("LuaCode:from(", tostring(code.source)\as_lua!, ", ", @compile(code), ")")

        operate_on_text = (text)->
            lua = LuaCode\from(text.source, "LuaCode:from(", tostring(text.source)\as_lua!)
            for bit in *text
                local bit_lua
                if type(bit) == "string"
                    bit_lua = bit\as_lua!
                elseif bit.type == "Text"
                    bit_lua = operate_on_text(bit)
                elseif bit.type == "Block"
                    bit_lua = LuaCode\from bit.source, "(function()",
                        "\n    local _lua = LuaCode:from(", tostring(bit.source)\as_lua!, ")",
                        "\n    local function add(...) _lua:add(...) end",
                        "\n    local function join_with(glue)",
                        "\n        local old_bits = _lua.bits",
                        "\n        _lua = LuaCode:from(_lua.source)",
                        "\n        _lua:concat_add(old_bits, glue)",
                        "\n    end",
                        "\n    ", @compile(bit),
                        "\n    return _lua",
                        "\nend)()"
                else
                    bit_lua = @compile(bit)

                bit_leading_len = #(bit_lua\match("^[^\n]*"))
                lua\add(lua\trailing_line_len! + bit_leading_len > MAX_LINE and ",\n    " or ", ")
                lua\add(bit_lua)
            lua\add ")"
            return lua

        return operate_on_text code

    ["lua >"]: (_t, code)=>
        if code.type != "Text"
            return code
        operate_on_text = (text)->
            lua = LuaCode\from(text.source)
            for bit in *text
                if type(bit) == "string"
                    lua\add bit
                elseif bit.type == "Text"
                    lua\add(operate_on_text(bit))
                else
                    lua\add @compile(bit)
            return lua
        return operate_on_text code

    ["= lua"]: (_t, code)=>
        @compile(SyntaxTree{type:"Action", "lua", ">", code})

    ["1 as lua"]: (_t, code)=>
        LuaCode("_ENV:compile(", @compile(code), ")")

    ["use"]: (_t, path)=>
        LuaCode("_ENV:use(#{@compile(path)})")

    ["export"]: (_t, path)=>
        LuaCode("_ENV:export(#{@compile(path)})")

    -- Code that the rest of the file needs while it's being compiled, like helpers for
    -- compile rules. It runs during compilation and also when the file runs, and what it
    -- defines is module-level (not local), so it's visible in both cases.
    ["at compile time"]: (_t, body)=>
        lua = @compile(body)
        lua\remove_free_vars!
        return lua

    -- Variables defined in a (local:) block are always new local variables, even if a
    -- variable with the same name exists outside of the block.
    ["local"]: (_t, body)=>
        lua, names = compile_definitions(@, body)
        lua.forced_locals = names
        return lua

    ["local 1 ="]: (t, var, value)=>
        @compile SyntaxTree{type:"Action", source:t.source, "local",
            SyntaxTree{type:"Action", source:var.source, var, "=", value}}

    -- Variables, actions, and compile rules defined in a (public:) block are visible to
    -- files that (use) this file.
    ["public"]: (_t, body)=>
        lua, names = compile_definitions(@, body)
        lua.public_vars = names
        if lua\text!\match("COMPILE_RULES")
            lua\prepend "_ENV:begin_public_rules();\n"
            lua\add "\n_ENV:end_public_rules();"
        return lua

    ["public 1 ="]: (t, var, value)=>
        @compile SyntaxTree{type:"Action", source:t.source, "public",
            SyntaxTree{type:"Action", source:var.source, var, "=", value}}

    ["run"]: (_t, path)=>
        LuaCode("_ENV:run(#{@compile(path)})")

    -- Tests are only compiled when the test tool sets COMPILING_TESTS. compile_file()
    -- compiles them at the end of the file, so they can use anything in it.
    ["test"]: (_t, body)=>
        unless body.type == 'Block'
            fail_at(body, "Compile error: This should be a Block")
        if @COMPILING_TESTS
            table.insert @_tests_to_compile, body
        return LuaCode("")

    ["is jit"]: (_t, code)=> LuaCode("jit")
    ["nomsu environment"]: (_t)=> LuaCode("_ENV")
    ["nomsu environment name"]: (_t)=> LuaCode('"_ENV"')
    ["Lua version"]: (_t)=> LuaCode("LUA_API")
    ["this file was run directly"]: (_t)=> LuaCode('WAS_RUN_DIRECTLY')
    ["the command line arguments"]: (_t)=> LuaCode('COMMAND_LINE_ARGS')
}

return compile_actions