From c241ea241e8e9c152f6eb14f163b2ae39749f7bf Mon Sep 17 00:00:00 2001 From: Li Jin Date: Fri, 7 Feb 2020 17:29:34 +0800 Subject: releasing moonplus as a lib. --- .gitignore | 1 + CMakeLists.txt | 36 +++ LICENSE | 2 +- makefile | 3 + moonplus-0.1-1.rockspec | 27 +++ spec/inputs/plus.moon | 6 +- spec/inputs/syntax.moon | 8 + src/MoonP/moon_compiler.cpp | 33 +-- src/MoonPlus.h | 125 ++++++++++ src/StackTracePlus.h | 550 ++++++++++++++++++++++++++++++++++++++++++++ src/moonc.cpp | 179 -------------- src/moonp.cpp | 293 +++++++++++++++++++++++ 12 files changed, 1068 insertions(+), 195 deletions(-) create mode 100644 CMakeLists.txt create mode 100644 moonplus-0.1-1.rockspec create mode 100644 src/MoonPlus.h create mode 100644 src/StackTracePlus.h delete mode 100644 src/moonc.cpp create mode 100644 src/moonp.cpp diff --git a/.gitignore b/.gitignore index 5f6a200..d3acf45 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ moonp build +build.luarocks spec/outputs diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..195895c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,36 @@ +project ( moonp CXX ) +cmake_minimum_required ( VERSION 3.1 ) + +MESSAGE(STATUS "Lua: using information from luarocks") + +MESSAGE(STATUS "LUA_LIBDIR: " ${LUA_INCDIR}/../../lib) +MESSAGE(STATUS "LUA_INCDIR: " ${LUA_INCDIR}) +MESSAGE(STATUS "LUA: " ${LUA}) + +SET(LUA_EXECUTABLE "${LUA}") +SET(LUA_INCLUDE_DIR "${LUA_INCDIR}") + +GET_FILENAME_COMPONENT(LUA_EXEC_NAME ${LUA} NAME_WE) +IF(LUA_EXEC_NAME STREQUAL "luajit") + FIND_LIBRARY(LUA_LIBRARIES + NAMES luajit libluajit + PATHS ${LUA_INCDIR}/../../lib + NO_DEFAULT_PATH) +ELSEIF(LUA_EXEC_NAME MATCHES "lua.*") + FIND_LIBRARY(LUA_LIBRARIES + NAMES lua lua53 lua52 lua51 liblua liblua53 liblua52 liblua51 + PATHS ${LUA_INCDIR}/../../lib + NO_DEFAULT_PATH) +ENDIF() +MESSAGE(STATUS "Lua library: ${LUA_LIBRARIES}") + +enable_language( CXX ) +find_package( Lua REQUIRED ) +include_directories( src ${LUA_INCLUDE_DIR} ) +add_definitions( -std=c++17 -O3 -DLIBMOONP ) + +add_library( moonp MODULE src/MoonP/ast.cpp src/MoonP/parser.cpp src/MoonP/moon_parser.cpp src/MoonP/moon_compiler.cpp src/moonp.cpp) +set_target_properties( moonp PROPERTIES PREFIX "") +target_link_libraries( moonp ${LUA_LIBRARIES} ) + +install(CODE "") diff --git a/LICENSE b/LICENSE index 5b87539..6c2fbc6 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2017 Li Jin +Copyright (c) 2020 Li Jin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/makefile b/makefile index fd2d718..14a7752 100644 --- a/makefile +++ b/makefile @@ -206,7 +206,10 @@ clean: .PHONY: test test: release @echo "Compiling Moonscript codes..." + @$(START_TIME) @./$(BIN_NAME) $(TEST_INPUT)/*.moon -t $(TEST_OUTPUT) + @echo -en "Compile time: " + @$(END_TIME) # Main rule, checks the executable and symlinks to the output all: $(BIN_PATH)/$(BIN_NAME) diff --git a/moonplus-0.1-1.rockspec b/moonplus-0.1-1.rockspec new file mode 100644 index 0000000..aeebe69 --- /dev/null +++ b/moonplus-0.1-1.rockspec @@ -0,0 +1,27 @@ +package = "MoonPlus" +version = "0.1-1" +source = { + url = "git+https://github.com/pigpigyyy/MoonPlus" +} +description = { + summary = "MoonPlus is a compiler for Moonscript written in C++.", + detailed = [[ + MoonPlus is a compiler with features from Moonscript language 0.5.0 and more advanced features. could be faster than the original Moonscript compiler. ]], + homepage = "https://github.com/pigpigyyy/MoonPlus", + license = "MIT" +} +dependencies = { + "lua >= 5.1", +} +build = { + type = "cmake", + variables = { + LUA_INCDIR="$(LUA_INCDIR)", + LUA="$(LUA)", + }, + install = { + lib = { + "build.luarocks/moonp.so" + } + } +} diff --git a/spec/inputs/plus.moon b/spec/inputs/plus.moon index 8a91c93..f455845 100644 --- a/spec/inputs/plus.moon +++ b/spec/inputs/plus.moon @@ -11,5 +11,9 @@ if fcolor = message\match "<%w*>" then message = message\gsub "<%->", fcolor message = message\gsub "<%->", fcolor if fcolor = message\match "<%w*>" -func val if val = getvalue! +valA = func! if func = getfunc! + +valB = do + func = getfunc! + func?! diff --git a/spec/inputs/syntax.moon b/spec/inputs/syntax.moon index ae3fc0c..5442b61 100644 --- a/spec/inputs/syntax.moon +++ b/spec/inputs/syntax.moon @@ -242,7 +242,15 @@ hello "comma", another hello, one, two, three, four, yeah: man okay: yeah + fine: alright +another hello, one, two, three, four, + yeah: man + okay: yeah + +another hello, one, two, three, four, yeah: man + okay: yeah + -- a += 3 - 5 a *= 3 + 5 diff --git a/src/MoonP/moon_compiler.cpp b/src/MoonP/moon_compiler.cpp index d3427d3..30adbae 100644 --- a/src/MoonP/moon_compiler.cpp +++ b/src/MoonP/moon_compiler.cpp @@ -690,7 +690,7 @@ private: break; } } - throw std::logic_error(_info.errorMessage("Expression list must appear at the end of body block."sv, expList)); + throw std::logic_error(_info.errorMessage("Expression list must appear at the end of body or block."sv, expList)); } break; } @@ -1252,26 +1252,31 @@ private: bool oneLined = defs.size() == expList->exprs.objects().size() && traversal::Stop != action->traverse([&](ast_node* n) { switch (n->getId()) { - case "Callable"_id: { - auto callable = static_cast(n); - switch (callable->item->getId()) { - case "Variable"_id: - for (const auto& def : defs) { + case "ChainValue"_id: { + auto chainValue = static_cast(n); + const auto& items = chainValue->items.objects(); + BLOCK_START + auto callable = ast_cast(*items.begin()); + BREAK_IF(!callable); + auto next = items.begin(); ++next; + BREAK_IF(next == items.end()); + BREAK_IF((!ast_is(*next))); + for (const auto& def : defs) { + switch (callable->item->getId()) { + case "Variable"_id: if (def == _parser.toString(callable->item)) { return traversal::Stop; } - } - return traversal::Return; - case "SelfName"_id: - for (const auto& def : defs) { + return traversal::Return; + case "SelfName"_id: if (def == "self"sv) { return traversal::Stop; } - } - return traversal::Return; - default: - return traversal::Continue; + return traversal::Return; + } } + BLOCK_END + return traversal::Continue; } default: return traversal::Continue; diff --git a/src/MoonPlus.h b/src/MoonPlus.h new file mode 100644 index 0000000..da5f3ac --- /dev/null +++ b/src/MoonPlus.h @@ -0,0 +1,125 @@ +R"moonscript_codes( +import "moonp" +import concat, insert, remove from table +unpack = unpack or table.unpack +lua = :loadstring, :load + +local * + +dirsep = "/" + +moonp.moon_compiled = {} + +split = (str, delim) -> + return {} if str == "" + str ..= delim + [m for m in str\gmatch("(.-)"..delim)] + +get_options = (...) -> + count = select "#", ... + opts = select count, ... + if type(opts) == "table" + opts, unpack {...}, nil, count - 1 + else + {}, ... + +-- create moon path package from lua package path +create_moonpath = (package_path) -> + moonpaths = for path in *split package_path, ";" + prefix = path\match "^(.-)%.lua$" + continue unless prefix + prefix .. ".moon" + concat moonpaths, ";" + +moon_loader = (name) -> + name_path = name\gsub "%.", dirsep + + local file, file_path + for path in package.moonpath\gmatch "[^;]+" + file_path = path\gsub "?", name_path + file = io.open file_path + break if file + + if file + text = file\read "*a" + file\close! + res, err = loadstring text, "@#{file_path}" + if not res + error file_path .. ": " .. err + + return res + + return nil, "Could not find moon file" + + +loadstring = (...) -> + options, str, chunk_name, mode, env = get_options ... + chunk_name or= "=(moonscript.loadstring)" + + code, err = moonp.to_lua str, options + unless code + return nil, err + + moonp.moon_compiled[chunk_name] = code if chunk_name + -- the unpack prevents us from passing nil + (lua.loadstring or lua.load) code, chunk_name, unpack { mode, env } + +loadfile = (fname, ...) -> + file, err = io.open fname + return nil, err unless file + text = assert file\read "*a" + file\close! + loadstring text, "@#{fname}", ... + +-- throws errros +dofile = (...) -> + f = assert loadfile ... + f! + +insert_loader = (pos=2) -> + if not package.moonpath + package.moonpath = create_moonpath package.path + + loaders = package.loaders or package.searchers + for loader in *loaders + return false if loader == moon_loader + + insert loaders, pos, moon_loader + true + +remove_loader = -> + loaders = package.loaders or package.searchers + + for i, loader in ipairs loaders + if loader == moon_loader + remove loaders, i + return true + + false + +moon_require = (name)-> + insert_loader! + xpcall (-> require name), (err)-> + msg = moonp.stp.stacktrace err, 2 + print msg + +setmetatable moonp, { + __index: (key)=> + return nil unless key == "stp" + stp = rawget moonp,"stp" + unless stp + stp = with moonp.load_stacktraceplus! + .dump_locals = false + .simplified = true + rawset moonp,"stp",stp + rawset moonp,"load_stacktraceplus",nil + stp + __call: (name)=> @.require name +} + +moonp[k] = v for k,v in pairs { + :insert_loader, :remove_loader, :moon_loader, :dirsep, + :dofile, :loadfile, :loadstring, :create_moonpath, + require:moon_require +} +)moonscript_codes"; diff --git a/src/StackTracePlus.h b/src/StackTracePlus.h new file mode 100644 index 0000000..1a909fd --- /dev/null +++ b/src/StackTracePlus.h @@ -0,0 +1,550 @@ +R"lua_codes( +--[[ +The MIT License + +Copyright (c) 2010 Ignacio BurgueƱo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE.]] + +-- tables +local _G = _G +local string, io, debug, coroutine = string, io, debug, coroutine + +-- functions +local tostring, require = tostring, require +local next, assert = next, assert +local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs +local error = error + +assert(debug, "debug table must be available at this point") + +local string_gmatch = string.gmatch +local string_sub = string.sub +local table_concat = table.concat + +local _M = { + max_tb_output_len = 70, -- controls the maximum length of the 'stringified' table before cutting with ' (more...)' + dump_locals = true, + simplified = false +} + +-- this tables should be weak so the elements in them won't become uncollectable +local m_known_tables = { [_G] = "_G (global table)" } +local function add_known_module(name, desc) + local ok, mod = pcall(require, name) + if ok then + m_known_tables[mod] = desc + end +end + +add_known_module("string", "string module") +add_known_module("io", "io module") +add_known_module("os", "os module") +add_known_module("table", "table module") +add_known_module("math", "math module") +add_known_module("package", "package module") +add_known_module("debug", "debug module") +add_known_module("coroutine", "coroutine module") + +-- lua5.2 +add_known_module("bit32", "bit32 module") +-- luajit +add_known_module("bit", "bit module") +add_known_module("jit", "jit module") +-- lua5.3 +if _VERSION >= "Lua 5.3" then + add_known_module("utf8", "utf8 module") +end + + +local m_user_known_tables = {} + +local m_known_functions = {} +for _, name in ipairs{ + -- Lua 5.2, 5.1 + "assert", + "collectgarbage", + "dofile", + "error", + "getmetatable", + "ipairs", + "load", + "loadfile", + "next", + "pairs", + "pcall", + "print", + "rawequal", + "rawget", + "rawlen", + "rawset", + "require", + "select", + "setmetatable", + "tonumber", + "tostring", + "type", + "xpcall", + + -- Lua 5.1 + "gcinfo", + "getfenv", + "loadstring", + "module", + "newproxy", + "setfenv", + "unpack", + -- TODO: add table.* etc functions +} do + if _G[name] then + m_known_functions[_G[name]] = name + end +end + +local m_user_known_functions = {} + +local function safe_tostring (value) + local ok, err = pcall(tostring, value) + if ok then return err else return (": '%s'"):format(err) end +end + +-- Private: +-- Parses a line, looking for possible function definitions (in a very naive way) +-- Returns '(anonymous)' if no function name was found in the line +local function ParseLine(line) + assert(type(line) == "string") + local match = line:match("^%s*function%s+(%w+)") + if match then + --print("+++++++++++++function", match) + return match + end + match = line:match("^%s*local%s+function%s+(%w+)") + if match then + --print("++++++++++++local", match) + return match + end + match = line:match("^%s*local%s+(%w+)%s+=%s+function") + if match then + --print("++++++++++++local func", match) + return match + end + match = line:match("%s*function%s*%(") -- this is an anonymous function + if match then + --print("+++++++++++++function2", match) + return "(anonymous)" + end + return "(anonymous)" +end + +-- Private: +-- Tries to guess a function's name when the debug info structure does not have it. +-- It parses either the file or the string where the function is defined. +-- Returns '?' if the line where the function is defined is not found +local function GuessFunctionName(info) + -- print("guessing function name") + if type(info.source) == "string" and info.source:sub(1,1) == "@" then + local file = io.open(info.source:sub(2)) + local text + if file then + text = file:read("*a") + file:close() + end + if not text then + -- print("file not found: "..tostring(err)) -- whoops! + return "?" + end + local line + local count = 0 + for lineText in (text.."\n"):gmatch("(.-)\n") do + line = lineText + count = count + 1 + if count == info.linedefined then + break + end + end + if not line then + --print("line not found") -- whoops! + return "?" + end + return ParseLine(line) + else + local line + local lineNumber = 0 + for l in string_gmatch(info.source, "([^\n]+)\n-") do + lineNumber = lineNumber + 1 + if lineNumber == info.linedefined then + line = l + break + end + end + if not line then + -- print("line not found") -- whoops! + return "?" + end + return ParseLine(line) + end +end + +--- +-- Dumper instances are used to analyze stacks and collect its information. +-- +local Dumper = {} + +Dumper.new = function(thread) + local t = { lines = {} } + for k,v in pairs(Dumper) do t[k] = v end + + t.dumping_same_thread = (thread == coroutine.running()) + + -- if a thread was supplied, bind it to debug.info and debug.get + -- we also need to skip this additional level we are introducing in the callstack (only if we are running + -- in the same thread we're inspecting) + if type(thread) == "thread" then + t.getinfo = function(level, what) + if t.dumping_same_thread and type(level) == "number" then + level = level + 1 + end + return debug.getinfo(thread, level, what) + end + t.getlocal = function(level, loc) + if t.dumping_same_thread then + level = level + 1 + end + return debug.getlocal(thread, level, loc) + end + else + t.getinfo = debug.getinfo + t.getlocal = debug.getlocal + end + + return t +end + +-- helpers for collecting strings to be used when assembling the final trace +function Dumper:add (text) + self.lines[#self.lines + 1] = text +end +function Dumper:add_f (fmt, ...) + self:add(fmt:format(...)) +end +function Dumper:concat_lines () + return table_concat(self.lines) +end + +--- +-- Private: +-- Iterates over the local variables of a given function. +-- +-- @param level The stack level where the function is. +-- +function Dumper:DumpLocals (level) + if not _M.dump_locals then return end + + local prefix = "\t " + local i = 1 + + if self.dumping_same_thread then + level = level + 1 + end + + local name, value = self.getlocal(level, i) + if not name then + return + end + self:add("\tLocal variables:\r\n") + while name do + if type(value) == "number" then + self:add_f("%s%s = number: %g\r\n", prefix, name, value) + elseif type(value) == "boolean" then + self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value)) + elseif type(value) == "string" then + self:add_f("%s%s = string: %q\r\n", prefix, name, value) + elseif type(value) == "userdata" then + self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value)) + elseif type(value) == "nil" then + self:add_f("%s%s = nil\r\n", prefix, name) + elseif type(value) == "table" then + if m_known_tables[value] then + self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value]) + elseif m_user_known_tables[value] then + self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value]) + else + local txt = "{" + for k,v in pairs(value) do + txt = txt..safe_tostring(k)..":"..safe_tostring(v) + if #txt > _M.max_tb_output_len then + txt = txt.." (more...)" + break + end + if next(value, k) then txt = txt..", " end + end + self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}") + end + elseif type(value) == "function" then + local info = self.getinfo(value, "nS") + local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value] + if info.what == "C" then + self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value))) + else + local source = info.short_src + if source:sub(2,7) == "string" then + source = source:sub(9) + end + --for k,v in pairs(info) do print(k,v) end + fun_name = fun_name or GuessFunctionName(info) + self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source) + end + elseif type(value) == "thread" then + self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value)) + end + i = i + 1 + name, value = self.getlocal(level, i) + end +end + +local function getMoonLineNumber(fname, line) + local moonCompiled = require("moonp").moon_compiled + local source = moonCompiled["@"..fname] + local file = io.open(fname) + if not source and file then + local codes = file:read("*a") + file:close() + local moonFile = codes:match("^%s*--%s*%[moon%]:%s*([^\n]*)") + if moonFile then + fname = moonFile:gsub("^%s*(.-)%s*$", "%1") + source = codes + end + end + if source then + local i, target = 1, tonumber(line) + for lineCode in source:gmatch("([^\n]*)\n") do + if i == target then + local num = lineCode:match("--%s*(%d*)%s*$") + if num then + return fname, num + end + break + end + i = i + 1 + end + end + return fname, line +end + +--- +-- Public: +-- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc. +-- This function is suitable to be used as an error handler with pcall or xpcall +-- +-- @param thread An optional thread whose stack is to be inspected (defaul is the current thread) +-- @param message An optional error string or object. +-- @param level An optional number telling at which level to start the traceback (default is 1) +-- +-- Returns a string with the stack trace and a string with the original error. +-- +function _M.stacktrace(thread, message, level) + if type(thread) ~= "thread" then + -- shift parameters left + thread, message, level = nil, thread, message + end + + thread = thread or coroutine.running() + + level = level or 1 + + local dumper = Dumper.new(thread) + + local original_error + + if type(message) == "table" then + dumper:add("an error object {\r\n") + local first = true + for k,v in pairs(message) do + if first then + dumper:add(" ") + first = false + else + dumper:add(",\r\n ") + end + dumper:add(safe_tostring(k)) + dumper:add(": ") + dumper:add(safe_tostring(v)) + end + dumper:add("\r\n}") + original_error = dumper:concat_lines() + elseif type(message) == "string" then + original_error = message + local fname, line, msg = message:match('(.+):(%d+): (.*)$') + local nfname, nline, nmsg = fname:match('(.+):(%d+): (.*)$') + if nfname then + fname = nmsg + end + if fname then + fname = fname:gsub("%[string \"", "") + fname = fname:gsub("\"%]", "") + fname = fname:gsub("^%s*(.-)%s*$", "%1") + local extension = fname:match("%.([^%.\\/]*)$") + if not extension then + local fext = fname .. ".lua" + local file = io.open(fext) + if file then + file:close() + fname = fext + else + fext = fname .. ".moon" + file = io.open(fext) + if file then + file:close() + fname = fext + end + end + end + fname, line = getMoonLineNumber(fname, line) + if _M.simplified then + message = table.concat({ + "'", fname, "':", + line, ": ", msg}) + else + message = table.concat({ + "[string \"", fname, "\"]:", + line, ": ", msg}) + end + end + dumper:add(message) + end + + dumper:add("\r\n") + dumper:add[[ +Stack Traceback +=============== +]] + --print(error_message) + + local level_to_show = 1 + if dumper.dumping_same_thread then level = level + 1 end + + local info = dumper.getinfo(level, "nSlf") + while info do + if info.source and info.source:sub(1,1) == "@" then + info.source = info.source:sub(2) + elseif info.what == "main" or info.what == "Lua" then + info.source = info.source + end + local fname = info.source + local extension = fname:match("%.([^%.\\/]*)$") + if not extension then + local fext = fname .. ".lua" + local file = io.open(fext) + if file then + file:close() + fname = fext + else + fext = fname .. ".moon" + file = io.open(fext) + if file then + file:close() + fname = fext + end + end + end + info.source, info.currentline = getMoonLineNumber(fname, info.currentline) + if info.what == "main" then + if _M.simplified then + dumper:add_f("(%d) '%s':%d\r\n", level_to_show, info.source, info.currentline) + else + dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, info.source, info.currentline) + end + elseif info.what == "C" then + --print(info.namewhat, info.name) + --for k,v in pairs(info) do print(k,v, type(v)) end + local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func) + dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name) + --dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value))) + elseif info.what == "tail" then + --print("tail") + --for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name) + dumper:add_f("(%d) tail call\r\n", level_to_show) + dumper:DumpLocals(level) + elseif info.what == "Lua" then + local source = info.source + local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name + if source:sub(2, 7) == "string" then + source = source:sub(10,-3) + end + local was_guessed = false + if not function_name or function_name == "?" then + --for k,v in pairs(info) do print(k,v, type(v)) end + function_name = GuessFunctionName(info) + was_guessed = true + end + -- test if we have a file name + local function_type = (info.namewhat == "") and "function" or info.namewhat + if info.source and info.source:sub(1, 1) == "@" then + if _M.simplified then + dumper:add_f("(%d) '%s':%d%s\r\n", level_to_show, info.source:sub(2), info.currentline, was_guessed and " (guess)" or "") + else + dumper:add_f("(%d) Lua %s '%s' at file '%s':%d%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") + end + elseif info.source and info.source:sub(1,1) == '#' then + if _M.simplified then + dumper:add_f("(%d) '%s':%d%s\r\n", level_to_show, info.source:sub(2), info.currentline, was_guessed and " (guess)" or "") + else + dumper:add_f("(%d) Lua %s '%s' at template '%s':%d%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") + end + else + if _M.simplified then + dumper:add_f("(%d) '%s':%d\r\n", level_to_show, source, info.currentline) + else + dumper:add_f("(%d) Lua %s '%s' at chunk '%s':%d\r\n", level_to_show, function_type, function_name, source, info.currentline) + end + end + dumper:DumpLocals(level) + else + dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what) + end + + level = level + 1 + level_to_show = level_to_show + 1 + info = dumper.getinfo(level, "nSlf") + end + + return dumper:concat_lines(), original_error +end + +-- +-- Adds a table to the list of known tables +function _M.add_known_table(tab, description) + if m_known_tables[tab] then + error("Cannot override an already known table") + end + m_user_known_tables[tab] = description +end + +-- +-- Adds a function to the list of known functions +function _M.add_known_function(fun, description) + if m_known_functions[fun] then + error("Cannot override an already known function") + end + m_user_known_functions[fun] = description +end + +return _M + +)lua_codes"; diff --git a/src/moonc.cpp b/src/moonc.cpp deleted file mode 100644 index d04ce47..0000000 --- a/src/moonc.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* Copyright (c) 2020 Jin Li, http://www.luvfight.me - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#include -#include -#include -#include -#include -#include "MoonP/moon_compiler.h" -#include "MoonP/moon_parser.h" - -int main(int narg, const char** args) { - const char* help = -"Usage: moonc [options|files] ...\n\n" -" -h Print this message\n" -" -t path Specify where to place compiled files\n" -" -o file Write output to file\n" -" -p Write output to standard out\n" -" -b Dump compile time (doesn't write output)\n" -" -l Write line numbers from source codes\n" -" -v Print version\n"; - if (narg == 0) { - std::cout << help; - return 0; - } - MoonP::MoonConfig config; - config.reserveLineNumber = false; - bool writeToFile = true; - bool dumpCompileTime = false; - std::string targetPath; - std::string resultFile; - std::list files; - for (int i = 1; i < narg; ++i) { - switch (hash(args[i])) { - case "-l"_id: - config.reserveLineNumber = true; - break; - case "-p"_id: - writeToFile = false; - break; - case "-t"_id: - ++i; - if (i < narg) { - targetPath = args[i]; - } else { - std::cout << help; - return 1; - } - break; - case "-b"_id: - dumpCompileTime = true; - break; - case "-h"_id: - std::cout << help; - return 0; - case "-v"_id: - std::cout << "Moonscript version: " << MoonP::moonScriptVersion() << '\n'; - return 0; - case "-o"_id: - ++i; - if (i < narg) { - resultFile = args[i]; - } else { - std::cout << help; - return 1; - } - break; - default: - files.push_back(args[i]); - break; - } - } - if (files.empty()) { - std::cout << help; - return 0; - } - if (!resultFile.empty() && files.size() > 1) { - std::cout << "Error: -o can not be used with multiple input files.\n"; - std::cout << help; - } - if (targetPath.back() != '/' && targetPath.back() != '\\') { - targetPath.append("/"); - } - std::list()>>> results; - for (const auto& file : files) { - auto task = std::async(std::launch::async, [=]() { - std::ifstream input(file, input.in); - if (input) { - std::string s( - (std::istreambuf_iterator(input)), - std::istreambuf_iterator()); - if (dumpCompileTime) { - auto start = std::chrono::high_resolution_clock::now(); - auto result = MoonP::moonCompile(s, config); - auto end = std::chrono::high_resolution_clock::now(); - if (!std::get<0>(result).empty()) { - std::chrono::duration diff = end - start; - start = std::chrono::high_resolution_clock::now(); - MoonP::MoonParser{}.parse(s); - end = std::chrono::high_resolution_clock::now(); - std::chrono::duration parseDiff = end - start; - std::cout << file << " \n"; - std::cout << "Parse time: " << std::setprecision(5) << parseDiff.count() * 1000 << " ms\n"; - std::cout << "Compile time: " << std::setprecision(5) << (diff.count() - parseDiff.count()) * 1000 << " ms\n\n"; - return 0; - } else { - std::cout << "Fail to compile: " << file << ".\n"; - std::cout << std::get<1>(result) << '\n'; - return 1; - } - } - auto result = MoonP::moonCompile(s, config); - if (!std::get<0>(result).empty()) { - if (!writeToFile) { - std::cout << std::get<0>(result) << '\n'; - return 1; - } else { - std::string targetFile; - if (resultFile.empty()) { - std::string ext; - targetFile = file; - size_t pos = file.rfind('.'); - if (pos != std::string::npos) { - ext = file.substr(pos + 1); - for (size_t i = 0; i < ext.length(); i++) { - ext[i] = static_cast(tolower(ext[i])); - } - targetFile = file.substr(0, pos) + ".lua"; - } - if (!targetPath.empty()) { - std::string name; - pos = targetFile.find_last_of("/\\"); - if (pos == std::string::npos) { - name = targetFile; - } else { - name = targetFile.substr(pos + 1); - } - targetFile = targetPath + name; - } - } else { - targetFile = resultFile; - } - std::ofstream output(targetFile, output.trunc | output.out); - if (output) { - const auto& codes = std::get<0>(result); - output.write(codes.c_str(), codes.size()); - std::cout << "Built " << file << '\n'; - return 0; - } else { - std::cout << "Fail to write file: " << targetFile << ".\n"; - return 1; - } - } - } else { - std::cout << "Fail to compile: " << file << ".\n"; - std::cout << std::get<1>(result) << '\n'; - return 1; - } - } else { - std::cout << "Fail to read file: " << file << ".\n"; - return 1; - } - }); - results.push_back(std::move(task)); - } - int ret = 0; - for (auto& result : results) { - int val = result.get(); - if (val != 0) { - ret = val; - } - } - return ret; -} - diff --git a/src/moonp.cpp b/src/moonp.cpp new file mode 100644 index 0000000..a6c99df --- /dev/null +++ b/src/moonp.cpp @@ -0,0 +1,293 @@ +/* Copyright (c) 2020 Jin Li, http://www.luvfight.me + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +#include +#include +#include +#include +#include +#include "MoonP/moon_compiler.h" +#include "MoonP/moon_parser.h" + +#ifndef LIBMOONP + +int main(int narg, const char** args) { + const char* help = +"Usage: moonp [options|files] ...\n\n" +" -h Print this message\n" +" -t path Specify where to place compiled files\n" +" -o file Write output to file\n" +" -p Write output to standard out\n" +" -b Dump compile time (doesn't write output)\n" +" -l Write line numbers from source codes\n" +" -v Print version\n"; + if (narg == 0) { + std::cout << help; + return 0; + } + MoonP::MoonConfig config; + config.reserveLineNumber = false; + bool writeToFile = true; + bool dumpCompileTime = false; + std::string targetPath; + std::string resultFile; + std::list files; + for (int i = 1; i < narg; ++i) { + switch (hash(args[i])) { + case "-l"_id: + config.reserveLineNumber = true; + break; + case "-p"_id: + writeToFile = false; + break; + case "-t"_id: + ++i; + if (i < narg) { + targetPath = args[i]; + } else { + std::cout << help; + return 1; + } + break; + case "-b"_id: + dumpCompileTime = true; + break; + case "-h"_id: + std::cout << help; + return 0; + case "-v"_id: + std::cout << "Moonscript version: " << MoonP::moonScriptVersion() << '\n'; + return 0; + case "-o"_id: + ++i; + if (i < narg) { + resultFile = args[i]; + } else { + std::cout << help; + return 1; + } + break; + default: + files.push_back(args[i]); + break; + } + } + if (files.empty()) { + std::cout << help; + return 0; + } + if (!resultFile.empty() && files.size() > 1) { + std::cout << "Error: -o can not be used with multiple input files.\n"; + std::cout << help; + } + if (!targetPath.empty() && targetPath.back() != '/' && targetPath.back() != '\\') { + targetPath.append("/"); + } + std::list()>>> results; + for (const auto& file : files) { + auto task = std::async(std::launch::async, [=]() { + std::ifstream input(file, input.in); + if (input) { + std::string s( + (std::istreambuf_iterator(input)), + std::istreambuf_iterator()); + if (dumpCompileTime) { + auto start = std::chrono::high_resolution_clock::now(); + auto result = MoonP::moonCompile(s, config); + auto end = std::chrono::high_resolution_clock::now(); + if (!std::get<0>(result).empty()) { + std::chrono::duration diff = end - start; + start = std::chrono::high_resolution_clock::now(); + MoonP::MoonParser{}.parse(s); + end = std::chrono::high_resolution_clock::now(); + std::chrono::duration parseDiff = end - start; + std::cout << file << " \n"; + std::cout << "Parse time: " << std::setprecision(5) << parseDiff.count() * 1000 << " ms\n"; + std::cout << "Compile time: " << std::setprecision(5) << (diff.count() - parseDiff.count()) * 1000 << " ms\n\n"; + return 0; + } else { + std::cout << "Fail to compile: " << file << ".\n"; + std::cout << std::get<1>(result) << '\n'; + return 1; + } + } + auto result = MoonP::moonCompile(s, config); + if (!std::get<0>(result).empty()) { + if (!writeToFile) { + std::cout << std::get<0>(result) << '\n'; + return 1; + } else { + std::string targetFile; + if (resultFile.empty()) { + targetFile = file; + size_t pos = file.rfind('.'); + if (pos != std::string::npos) { + targetFile = file.substr(0, pos) + ".lua"; + } + if (!targetPath.empty()) { + std::string name; + pos = targetFile.find_last_of("/\\"); + if (pos == std::string::npos) { + name = targetFile; + } else { + name = targetFile.substr(pos + 1); + } + targetFile = targetPath + name; + } + } else { + targetFile = resultFile; + } + std::ofstream output(targetFile, output.trunc | output.out); + if (output) { + const auto& codes = std::get<0>(result); + output.write(codes.c_str(), codes.size()); + std::cout << "Built " << file << '\n'; + return 0; + } else { + std::cout << "Fail to write file: " << targetFile << ".\n"; + return 1; + } + } + } else { + std::cout << "Fail to compile: " << file << ".\n"; + std::cout << std::get<1>(result) << '\n'; + return 1; + } + } else { + std::cout << "Fail to read file: " << file << ".\n"; + return 1; + } + }); + results.push_back(std::move(task)); + } + int ret = 0; + for (auto& result : results) { + int val = result.get(); + if (val != 0) { + ret = val; + } + } + return ret; +} + +#else + +extern "C" { + +#include "lua.h" +#include "lauxlib.h" + +static const char moonplusCodes[] = +#include "MoonPlus.h" + +static int init_moonplus(lua_State* L) { + MoonP::MoonConfig config; + std::string s(moonplusCodes, sizeof(moonplusCodes) / sizeof(moonplusCodes[0]) - 1); + std::string codes, err; + MoonP::GlobalVars globals; + std::tie(codes, err, globals) = MoonP::moonCompile(s, config); + if (codes.empty()) { + luaL_error(L, "fail to compile moonplus init codes.\n%s", err.c_str()); + } + int top = lua_gettop(L); + if (luaL_loadbuffer(L, codes.c_str(), codes.size(), "=(moonplus)") != 0) { + luaL_error(L, "fail to init moonplus module."); + } else { + lua_call(L, 0, 0); + } + lua_settop(L, top); + return 0; +} + +static const char stpCodes[] = +#include "StackTracePlus.h" + +static int init_stacktraceplus(lua_State* L) { + if (luaL_loadbuffer(L, stpCodes, sizeof(stpCodes) / sizeof(stpCodes[0]) - 1, "=(stacktraceplus)") != 0) { + luaL_error(L, "fail to init stacktraceplus module."); + } else { + lua_call(L, 0, 1); + } + return 1; +} + +static int moontolua(lua_State* L) { + size_t size = 0; + const char* input = luaL_checklstring(L, 1, &size); + MoonP::MoonConfig config; + if (lua_gettop(L) == 2) { + lua_pushstring(L, "lint_global"); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + config.lintGlobalVariable = lua_toboolean(L, -1) != 0; + } + lua_pop(L, 1); + lua_pushstring(L, "implicit_return_root"); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + config.implicitReturnRoot = lua_toboolean(L, -1) != 0; + } + lua_pop(L, 1); + lua_pushstring(L, "reserve_line_number"); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + config.reserveLineNumber = lua_toboolean(L, -1) != 0; + } + lua_pop(L, 1); + } + std::string s(input, size); + std::string codes, err; + MoonP::GlobalVars globals; + std::tie(codes, err, globals) = MoonP::moonCompile(s, config); + if (codes.empty()) { + lua_pushnil(L); + } else { + lua_pushlstring(L, codes.c_str(), codes.size()); + } + if (err.empty()) { + lua_pushnil(L); + } else { + lua_pushlstring(L, err.c_str(), err.size()); + } + if (globals && !globals->empty()) { + lua_createtable(L, static_cast(globals->size()), 0); + int i = 1; + for (const auto& var : *globals) { + lua_createtable(L, 3, 0); + lua_pushlstring(L, var.name.c_str(), var.name.size()); + lua_rawseti(L, -2, 1); + lua_pushinteger(L, var.line); + lua_rawseti(L, -2, 2); + lua_pushinteger(L, var.col); + lua_rawseti(L, -2, 3); + lua_rawseti(L, -2, i); + i++; + } + } else { + lua_pushnil(L); + } + return 3; +} + +int luaopen_moonp(lua_State* L) { + lua_getglobal(L, "package"); + lua_getfield(L, -1, "loaded"); + lua_createtable(L, 0, 0); + lua_pushcfunction(L, moontolua); + lua_setfield(L, -2, "to_lua"); + lua_pushcfunction(L, init_stacktraceplus); + lua_setfield(L, -2, "load_stacktraceplus"); + lua_setfield(L, -2, "moonp"); + lua_pop(L, 2); + init_moonplus(L); + return 0; +} + +} // extern "C" + +#endif // LIBMOONP + -- cgit v1.2.3-55-g6feb