simplification
Download
349 lines 14.2 KiBMoonScriptModified 2026-11-10 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
-- 
-- This file contains the source code of the Nomsu compiler.
--
unpack or= table.unpack
{:match, :sub, :gsub, :format, :byte, :find} = string
{:LuaCode, :Source} = require "code_obj"
require "text"
SyntaxTree = require "syntax_tree"
Files = require "files"
NOMSU_VERSION = require "nomsu_version"

pretty_error = require("pretty_errors")
{:find_suggestions} = require "error_handling"
{:try_with_budget, :remaining_instructions} = require "nomsu_limits"
fail_at = (source, msg)->
    local file
    if SyntaxTree\is_instance(source)
        file = source\get_source_file!
        source = source.source
    elseif type(source) == 'string'
        source = Source\from_string(source)
    elseif not Source\is_instance(source)
        -- debug.getinfo() output:
        assert(source.short_src and source.currentline)
        file = Files.read(source.short_src)
        assert file, "Could not find #{source.short_src}"
        lines = file\lines!
        start = 1
        for i=1,source.currentline-1
            start += #lines[i]
        stop = start + #lines[source.currentline]
        source = Source(source.short_src, start, stop)

    if source and not file
        file = Files.read(source.filename)
    if not file
        if NOMSU_PREFIX
            path = "#{NOMSU_PREFIX}/share/nomsu/#{table.concat NOMSU_VERSION, "."}/#{source.filename}"
            file = Files.read(path)
    if not file
        error("Can't find file: "..tostring(source.filename))

    title, err_msg, hint = msg\match("([^:]*):[ \n]+(.*)[ \n]+Hint: (.*)")
    if not err_msg
        err_msg, hint = msg\match("(.*)[ \n]+Hint:[ \n]+(.*)")
        title = "Failure"
    if not err_msg
        title, err_msg = msg\match("([^:]*):[ \n]+(.*)")
    if not err_msg
        err_msg = msg
        title = "Failure"

    err_str = pretty_error{
        title: title,
        error: err_msg, hint: hint, source: file,
        start:source.start, stop:source.stop, filename:source.filename,
    }
    error(err_str, 0)

-- This function is used by regular function/method calls and produces a
-- compiler error if a Block is passed as an argument, since those should only
-- be used by compile-time actions. This kind of mistake can happen if the user
-- mistypes a compile-time action and it's being compiled as a regular function.
fail_if_block_arg = (tree, stub)=>
    found, suggestions = try_with_budget(remaining_instructions!/2, find_suggestions, stub, {},
        {COMPILE_RULES: @COMPILE_RULES})
    hint = if found and #suggestions > 0
        " Hint: Maybe you meant (#{table.concat suggestions, ") or ("})?"
    else nil
    fail_at tree, "Compile error: (#{stub}) isn't a compile rule, so it can't take a block of code as an argument.#{hint}"

-- Chains of Lua's binary operators, like (2 * $x + 3 ^ 2) or ($a and $b or $c), compile
-- directly to the same Lua expression (with Lua's precedence rules), so there's no
-- need to define an action for every combination of operators.
chainable_operators = {"+": true, "-": true, "*": true, "/": true, "^": true, "%": true,
    "and": true, "or": true}
is_operator_chain = (tree)->
    return false unless #tree >= 3 and #tree % 2 == 1
    for i, tok in ipairs tree
        is_operator = type(tok) == 'string'
        return false if is_operator != (i % 2 == 0)
        return false if is_operator and not chainable_operators[tok]
    return true

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

-- Compile a `.key = value` entry of a table literal into a Lua table field, like
-- `key=value` or `[key]=value`. A missing value means `true`.
compile_table_entry = (key, value)=>
    if key.type != "Index"
        key = SyntaxTree{type:"Index", source:key.source, key}
    key_lua = @compile(key)
    if key_lua\match("^%.")
        key_lua = key_lua\text!\sub(2)
    return LuaCode\from key.source, key_lua, "=", (value and @compile(value) or "true")

compile = (tree)=>
    if tree == nil
        error("No tree was passed in.")

    switch tree.type
        when "Action"
            stub = tree.stub
            compile_action = @COMPILE_RULES[stub]
            if not compile_action and is_operator_chain(tree)
                lua = LuaCode\from(tree.source)
                for i,tok in ipairs tree
                    if type(tok) == 'string'
                        lua\add tok
                    else
                        tok_lua = @compile(tok)
                        -- TODO: this is overly eager, should be less aggressive
                        tok_lua\parenthesize! if tok.type == "Action"
                        lua\add tok_lua
                    lua\add " " if i < #tree
                lua\parenthesize!
                return lua

            if not compile_action
                seen_words = {}
                words = {}
                for word in stub\gmatch("[^0-9 ][^ ]*")
                    unless seen_words[word]
                        seen_words[word] = true
                        table.insert words, word
                table.sort(words)
                stub2 = table.concat(words, " ")
                compile_action = @COMPILE_RULES[stub2]
                if compile_action
                    if debug.getinfo(compile_action, 'u').isvararg
                        stub = stub2
                    else compile_action = nil

            if compile_action
                args = [arg for arg in *tree when type(arg) != "string"]
                ret = compile_action(@, tree, unpack(args))
                if ret == nil
                    info = debug.getinfo(compile_action, "S")
                    filename = Source\from_string(info.source).filename
                    fail_at tree,
                        ("Compile error: The compile-time action here (#{stub}) failed to return any value. "..
                        "Hint: Look at the implementation of (#{stub}) in #{filename}:#{info.linedefined} and make sure it's returning something.")
                unless SyntaxTree\is_instance(ret)
                    ret.source or= tree.source
                    return ret
                if ret != tree
                    return @compile(ret)

            lua = LuaCode\from(tree.source)
            lua\add((stub)\as_lua_id!,"(")
            for argnum, arg in ipairs tree\get_args!
                fail_if_block_arg(@, tree, stub) if arg.type == "Block"
                arg_lua = @compile(arg)
                if lua\trailing_line_len! + #tostring(arg_lua) > MAX_LINE
                    lua\add(argnum > 1 and ",\n    " or "\n    ")
                elseif argnum > 1
                    lua\add ", "
                lua\add arg_lua
            lua\add ")"
            return lua

        when "MethodCall"
            stub = tree\get_stub!
            compile_action = @COMPILE_RULES[stub]
            if compile_action
                args = tree\get_args!
                ret = compile_action(@, tree, unpack(args))
                if ret == nil
                    info = debug.getinfo(compile_action, "S")
                    filename = Source\from_string(info.source).filename
                    fail_at tree,
                        ("Compile error: The compile-time method here (#{stub}) failed to return any value. "..
                        "Hint: Look at the implementation of (#{stub}) in #{filename}:#{info.linedefined} "..
                        "and make sure it's returning something.")
                unless SyntaxTree\is_instance(ret)
                    ret.source or= tree.source
                    return ret
                if ret != tree
                    return @compile(ret)

            lua = LuaCode\from tree.source
            target_lua = @compile tree[1]
            target_text = target_lua\text!
            -- TODO: this parenthesizing is maybe overly conservative
            if not (target_text\match("^%(.*%)$") or target_text\match("^[_a-zA-Z][_a-zA-Z0-9.]*$") or
                tree[1].type == "IndexChain")
                target_lua\parenthesize!

            lua\add target_lua, ":"
            lua\add((tree[2].stub)\as_lua_id!,"(")
            for argnum, arg in ipairs tree[2]\get_args!
                fail_if_block_arg(@, tree, stub) if arg.type == "Block"
                arg_lua = @compile(arg)
                if lua\trailing_line_len! + #tostring(arg_lua) > MAX_LINE
                    lua\add(argnum > 1 and ",\n    " or "\n    ")
                elseif argnum > 1
                    lua\add ", "
                lua\add arg_lua
            lua\add ")"
            return lua

        when "Block"
            lua = LuaCode\from(tree.source)
            for i, line in ipairs tree
                if line.type == "Error"
                    return @compile(line)
            has_lines = false
            for i, line in ipairs tree
                line_lua = @compile(line)
                -- Declarations (like (local $x)) don't have any code, but still need to
                -- be part of the block
                if line_lua\text! == ""
                    lua\add line_lua
                    continue
                lua\add "\n" if has_lines
                has_lines = true
                lua\add line_lua
                unless line_lua\last(1) == ";" or line_lua\last(4)\match("[^_a-zA-Z0-9]end$")
                    lua\add ";"
            return lua

        when "Text"
            if #tree == 0
                return LuaCode\from(tree.source, '""')
            if #tree == 1 and type(tree[1]) == 'string'
                return LuaCode\from(tree.source, tree[1]\as_lua!)
            lua = LuaCode\from(tree.source, "Text(")
            added = 0
            string_buffer = ""
            add_bit = (bit)->
                if added > 0
                    if lua\trailing_line_len! + #tostring(bit) > MAX_LINE
                        lua\add ",\n  "
                    else
                        lua\add ", "
                lua\add bit
                added += 1

            for i, bit in ipairs tree
                if type(bit) == "string"
                    string_buffer ..= bit
                    continue
                if string_buffer != ""
                    for i=1,#string_buffer,MAX_LINE
                        add_bit string_buffer\sub(i, i+MAX_LINE-1)\as_lua!
                    string_buffer = ""

                if bit.type == "Block"
                    fail_at bit, ("Compile error: Text can't contain blocks. "..
                        "Hint: Use a comprehension instead, like \\(($x for $x in $list) joined)")
                add_bit @compile(bit)

            if string_buffer != ""
                for i=1,#string_buffer,MAX_LINE
                    add_bit string_buffer\sub(i, i+MAX_LINE-1)\as_lua!
                string_buffer = ""

            if added == 0
                return LuaCode\from(tree.source, '""')
            lua\add ")"
            return lua

        when "Table"
            lua = LuaCode\from tree.source, "{"
            sep = ''
            for i, item in ipairs tree
                if item.type == "Block"
                    fail_at item, ("Compile error: Table literals can't contain blocks. "..
                        "Hint: Use a comprehension instead, like ($x for $x in $list) or "..
                        "($k = $v for ($k = $v) in $table)")
                item_lua = switch item.type
                    when "Index" -- {.x} is shorthand for {.x = (yes)}
                        compile_table_entry(@, item, nil)
                    when "Action"
                        -- Nomsu 7 parsed {.x = 1} as an assignment action
                        if item.stub == "1 =" and item[1].type == "Index"
                            compile_table_entry(@, item[1], item[3])
                        else @compile(item)
                    else @compile(item)
                lua\add sep, item_lua
                if item.type == "Comment"
                    lua\add "\n"
                    sep = ''
                elseif lua\trailing_line_len! > MAX_LINE
                    sep = ",\n    "
                else
                    sep = ", "
            lua\add "}"
            return lua

        when "Index"
            key_lua = @compile(tree[1])
            key_str = key_lua\match('^"([a-zA-Z_][a-zA-Z0-9_]*)"$')
            return if key_str and key_str\is_lua_id!
                LuaCode\from tree.source, ".", key_str
            elseif key_lua\first(1) == "["
                -- NOTE: this *must* use a space after the [ to avoid freaking out
                -- Lua's parser if the inner expression is a long string. Lua
                -- parses x[[[y]]] as x("[y]"), not as x["y"]
                LuaCode\from tree.source, "[ ",key_lua,"]"
            else
                LuaCode\from tree.source, "[",key_lua,"]"

        when "TableEntry"
            return compile_table_entry(@, tree[1], tree[2])
        
        when "IndexChain"
            lua = @compile(tree[1])
            if lua\match("['\"}]$") or lua\match("]=*]$")
                lua\parenthesize!
            if lua\text! == "..."
                return LuaCode\from(tree.source, "select(", @compile(tree[2][1]), ", ...)")
            for i=2,#tree
                key = tree[i]
                -- TODO: remove this shim
                if key.type != "Index"
                    key = SyntaxTree{type:"Index", source:key.source, key}
                lua\add @compile(key)
            return lua

        when "Number"
            number = tostring(tree[1])\gsub("_", "")
            return LuaCode\from(tree.source, number)

        when "Var"
            if tree[1].type == "MethodCall"
                return LuaCode\from(tree.source, @compile(tree[1][1]), ".", tree[1][2]\get_stub!\as_lua_id!)
            return LuaCode\from(tree.source, tree\as_var!\as_lua_id!)

        when "File"
            error("Whole files are compiled with compile_file(), which runs compile-time code "..
                "as it goes")
        
        when "Comment"
            return LuaCode\from(tree.source, "-- ", (tree[1]\gsub('\n', '\n-- ')))
        
        when "Error"
            err_msg = pretty_error{
                title:"Parse error"
                error:tree.error, hint:tree.hint, source:tree\get_source_file!
                start:tree.source.start, stop:tree.source.stop, filename:tree.source.filename
            }
            -- Coroutine yield here?
            error(err_msg)

        else
            error("Unknown type: #{tree.type}")

return {:compile, :fail_at}