simplification
Download
317 lines 14.3 KiBMoonScriptModified 2026-11-10 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
-- This file contains the logic for making nicer error messages
debug_getinfo = debug.getinfo
Files = require "files"
C = require "colors"
pretty_error = require("pretty_errors")

-- Each Nomsu instance has a source map (mapping a chunk's Lua line numbers to Nomsu line
-- numbers for each chunk it runs), which it registers here. The keys are weak, so a
-- source map is freed along with its instance.
source_maps = setmetatable({}, {__mode:'k'})
register_source_map = (map)-> source_maps[map] = true
source_map_for = (chunk_name)->
    return nil unless chunk_name
    for map in pairs(source_maps)
        if chunk_map = map[chunk_name]
            return chunk_map

ok, to_lua = pcall -> require('moonscript.base').to_lua
if not ok then to_lua = -> nil
MOON_SOURCE_MAP = setmetatable {},
    __index: (file)=>
        _, line_table = to_lua(file)
        self[file] = line_table or false
        return line_table or false

-- Make a better version of debug.getinfo that provides info about the original source
-- where the error came from, even if that's in another language.
debug.getinfo = (thread,f,what)->
    if what == nil
        f,what,thread = thread,f,nil
    if type(f) == 'number' then f += 1 -- Account for this wrapper function
    info = if thread == nil
        debug_getinfo(f,what)
    else debug_getinfo(thread,f,what)
    if not info or not info.func then return info
    if info.short_src or info.source or info.linedefine or info.currentline
        -- TODO: reduce duplicate code
        if map = source_map_for(info.source)
            if info.currentline
                info.currentline = assert(map[info.currentline])
            if info.linedefined
                info.linedefined = assert(map[info.linedefined])
            if info.lastlinedefined
                info.lastlinedefined = assert(map[info.lastlinedefined])
            info.short_src = info.source\match('@([^[]*)') or info.short_src
            info.name = if info.name
                "action '#{info.name\from_lua_id!}'"
            else "main chunk"
    return info

-- Raising an exit signal stops the Nomsu code that's running, without exiting the whole
-- program. Nomsu's (try) doesn't catch exit signals. Code that runs out of a resource
-- limit is stopped the same way, with a signal that has the limit's name in .limit
ExitSignal = {__tostring: => @limit and "ran out of #{@limit}" or "exit(#{@exit})"}
exit_signal = (code=0)-> error(setmetatable({exit: code}, ExitSignal), 0)
is_exit_signal = (x)-> getmetatable(x) == ExitSignal

-- This uses a slightly modified Damerau-Levenshtein distance:
strdist = (a,b,max_dist,cache={})->
    if a == b then return 0
    if max_dist <= 0 or math.abs(#a-#b) > max_dist then return math.huge
    if #a < #b then a,b = b,a
    if b == "" then return #a
    -- The result depends on max_dist, since a call with a smaller budget may give up early
    k = a..'\003'..b..'\003'..max_dist
    unless cache[k]
        -- Insert, delete, substitute (given weight 1.125 as a heuristic, which unlike 1.1 has no floating point rounding)
        sub_weight = (a\sub(-1) ~= b\sub(-1) and 1.125 or 0)
        cache[k] = math.min(
            strdist(a\sub(1,-2),b,max_dist-1,cache) + 1,
            strdist(a,b\sub(1,-2),max_dist-1,cache) + 1,
            strdist(a\sub(1,-2),b\sub(1,-2),max_dist-sub_weight,cache) + sub_weight
        )
        -- Transposition:
        if #a >= 2 and #b >= 2 and a\sub(-1,-1) == b\sub(-2,-2) and a\sub(-2,-2) == b\sub(-1,-1)
            cache[k] = math.min(cache[k], strdist(a\sub(1,-3),b\sub(1,-3),max_dist-1,cache) + 1)
    return cache[k]

-- Find the closest matches for a misspelled action among the given local names and the
-- names in the environment
find_suggestions = (action_name, names, env)->
    THRESHOLD = math.min(4.5, .9*#action_name) -- Ignore matches with strdist > THRESHOLD
    candidates = {}
    cache = {}
    consider = (name)->
        if strdist(name, action_name, THRESHOLD, cache) <= THRESHOLD and name != ""
            table.insert candidates, name

    for name in *names do consider name\from_lua_id!

    -- Globals and global compile rules:
    scan = (t, is_lua_id)->
        return unless t
        for k,v in pairs(t)
            if type(k) == 'string' and type(v) == 'function'
                consider(is_lua_id and k or k\from_lua_id!)
    scan env.COMPILE_RULES, true
    scan env.COMPILE_RULES and env.COMPILE_RULES._IMPORTS, true
    scan env
    scan env._IMPORTS

    for c in *candidates do THRESHOLD = math.min(THRESHOLD, strdist(c, action_name, THRESHOLD, cache))
    return [c for c in *candidates when strdist(c, action_name, THRESHOLD, cache) <= THRESHOLD]

-- This is called by enhance_error, using try_with_budget. The code that raised the error is
-- at stack level 5: 1 is this function, 2 is pcall, 3 is try_with_budget, 4 is enhance_error.
ERROR_STACK_LEVEL = 5

add_error_details = (error_message)->
    -- Hacky: detect the line numbering
    unless error_message and error_message\match("%d|")
        error_message or= ""
        -- When calling 'nil' actions, make a better error message
        if fn_name = error_message\match("attempt to call a nil value %(method '(.*)'%)")
            action_name = fn_name\from_lua_id!
            error_message = "This object does not have the method '#{action_name}'."
        elseif fn_name = (error_message\match("attempt to call a nil value %(global '(.*)'%)") or
            error_message\match("attempt to call global '(.*)' %(a nil value%)"))

            action_name = fn_name\from_lua_id!
            error_message = "The action '#{action_name}' is not defined."

            -- Look for simple misspellings:

            -- This check is necessary for handling both top-level code and code inside a fn
            func = debug.getinfo(ERROR_STACK_LEVEL,'f').func
            local env
            if _VERSION == "Lua 5.1"
                env = getfenv(func)
            else
                -- _ENV isn't always the first upvalue, so search for it
                find_env = (f)->
                    for i=1,debug.getinfo(f, 'u').nups
                        ename,e = debug.getupvalue(f, i)
                        return e if ename == "_ENV" or ename == "_G"
                env = find_env(func)
                unless env
                    func = debug.getinfo(ERROR_STACK_LEVEL+1,'f').func
                    env = find_env(func) or _G

            -- Locals and upvalues are collected here, because the stack levels are different
            -- inside try_with_budget:
            names = {}
            
            -- Locals:
            for i=1,99
                k, v = debug.getlocal(ERROR_STACK_LEVEL, i)
                break if k == nil
                unless k\sub(1,1) == "(" or type(v) != 'function'
                    table.insert names, k

            -- Upvalues:
            for i=1,debug.getinfo(func, 'u').nups
                k, v = debug.getupvalue(func, i)
                unless k\sub(1,1) == "(" or type(v) != 'function'
                    table.insert names, k

            -- nomsu_limits requires this file, so it can't be required at the top of this one
            -- Suggestions are optional, so leave room for the rest of the error message.
            -- If there isn't enough budget, the error just won't have any suggestions.
            {:try_with_budget, :remaining_instructions} = require "nomsu_limits"
            found, suggestions = try_with_budget(remaining_instructions!/2, find_suggestions, action_name, names, env)
            if found
                if #suggestions == 1
                    error_message ..= "\n"..C('italic', "Suggestion: Maybe you meant '#{suggestions[1]}'? ")
                elseif #suggestions > 0
                    last = table.remove(suggestions)
                    error_message ..= "\n"..C('italic', "Suggestion: Maybe you meant '#{table.concat suggestions, "', '"}'#{#suggestions > 1 and ',' or ''} or '#{last}'? ")

        level = ERROR_STACK_LEVEL
        while true
            -- TODO: reduce duplicate code
            calling_fn = debug_getinfo(level)
            if not calling_fn then break
            level += 1
            local filename, file, line_num
            if map = source_map_for(calling_fn.source)
                if calling_fn.currentline
                    line_num = assert(map[calling_fn.currentline])
                filename,start,stop = calling_fn.source\match('@([^[]*)%[([0-9]+):([0-9]+)]')
                if not filename
                    filename,start = calling_fn.source\match('@([^[]*)%[([0-9]+)]')
                assert(filename)
                file = Files.read(filename)
            else
                filename = calling_fn.short_src
                file = Files.read(filename)
                if calling_fn.short_src\match("%.moon$") and type(MOON_SOURCE_MAP[file]) == 'table'
                    char = MOON_SOURCE_MAP[file][calling_fn.currentline]
                    line_num = file\line_number_at(char)
                else
                    line_num = calling_fn.currentline

            if file and filename and line_num
                start = 1
                lines = file\lines!
                for i=1,line_num-1 do start += #lines[i] + 1
                stop = start + #lines[line_num]
                start += #lines[line_num]\match("^ *")
                error_message = pretty_error{
                    title:"Error"
                    error:error_message, source:file
                    start:start, stop:stop, filename:filename
                }
                break
            if calling_fn.func == xpcall then break


    ret = {
        C('bold red', error_message or "Error")
        "stack traceback:"
    }

    level = ERROR_STACK_LEVEL
    while true
        -- TODO: reduce duplicate code
        calling_fn = debug_getinfo(level)
        if not calling_fn then break
        if calling_fn.func == xpcall then break
        level += 1
        name = calling_fn.name and "function '#{calling_fn.name}'" or nil
        if calling_fn.linedefined == 0 then name = "main chunk"
        if name == "function 'run_lua_fn'" then continue
        line = nil
        if map = source_map_for(calling_fn.source)
            if calling_fn.currentline
                calling_fn.currentline = assert(map[calling_fn.currentline])
            if calling_fn.linedefined
                calling_fn.linedefined = assert(map[calling_fn.linedefined])
            if calling_fn.lastlinedefined
                calling_fn.lastlinedefined = assert(map[calling_fn.lastlinedefined])
            --calling_fn.short_src = calling_fn.source\match('"([^[]*)')
            filename,start,stop = calling_fn.source\match('@([^[]*)%[([0-9]+):([0-9]+)]')
            if not filename
                filename,start = calling_fn.source\match('@([^[]*)%[([0-9]+)]')
            assert(filename)
            name = if calling_fn.name
                "action '#{calling_fn.name\from_lua_id!}'"
            else "main chunk"

            file = Files.read(filename)
            lines = file and file\lines! or {}
            if err_line = lines[calling_fn.currentline]
                offending_statement = C('bright red', err_line\match("^[ ]*(.*)"))
                line = C('yellow', "#{filename}:#{calling_fn.currentline} in #{name}\n        #{offending_statement}")
            else
                line = C('yellow', "#{filename}:#{calling_fn.currentline} in #{name}")
        else
            local line_num
            if name == nil
                search_level = level
                _info = debug.getinfo(search_level)
                while true
                    search_level += 1
                    _info = debug.getinfo(search_level)
                    break unless _info
                    for i=1,999
                        varname, val = debug.getlocal(search_level, i)
                        if not varname then break
                        if val == calling_fn.func
                            name = "local '#{varname}'"
                            if not varname\match("%(")
                                break
                    unless name
                        for i=1,_info.nups
                            varname, val = debug.getupvalue(_info.func, i)
                            if not varname then break
                            if val == calling_fn.func
                                name = "upvalue '#{varname}'"
                                if not varname\match("%(")
                                    break

            local file, lines
            if file = Files.read(calling_fn.short_src)
                lines = file\lines!
            
            if file and (calling_fn.short_src\match("%.moon$") or file\match("^#![^\n]*moon\n")) and type(MOON_SOURCE_MAP[file]) == 'table'
                char = MOON_SOURCE_MAP[file][calling_fn.currentline]
                line_num = file\line_number_at(char)
                line = C('cyan', "#{calling_fn.short_src}:#{line_num} in #{name or '?'}")
            else
                line_num = calling_fn.currentline
                if calling_fn.short_src == '[C]'
                    line = C('green', "#{calling_fn.short_src} in #{name or '?'}")
                else
                    line = C('blue', "#{calling_fn.short_src}:#{calling_fn.currentline} in #{name or '?'}")

            if file
                if err_line = lines[line_num]
                    offending_statement = C('bright red', "#{err_line\match("^[ ]*(.*)$")}")
                    line ..= "\n        "..offending_statement
        table.insert ret, line
        if calling_fn.istailcall
            table.insert ret, C('dim', "      (...tail calls...)")

    return table.concat(ret, "\n")

-- Error details are optional, so if there aren't enough instructions left to work them
-- out, this gives back the original error instead of running out of instructions.
enhance_error = (error_message)->
    return error_message if getmetatable(error_message) == ExitSignal
    -- Lazy loaded to prevent import issues:
    {:try_with_budget, :remaining_instructions} = require "nomsu_limits"
    finished, enhanced = try_with_budget(remaining_instructions!, add_error_details, error_message)
    return finished and enhanced or error_message or "Error"

guard = (fn)->
    ok, err = xpcall(fn, enhance_error)
    if not ok
        io.stderr\write err
        io.stderr\flush!
        os.exit 1

return {
    :guard, :enhance_error, :register_source_map, :ExitSignal, :exit_signal,
    :is_exit_signal, :find_suggestions,
}