123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524 | -- This file defines the environment in which Nomsu code runs, including some
-- basic bootstrapping functionality.
lpeg = require 'lpeg'
re = require 're'
{:NomsuCode, :LuaCode, :Source} = require "code_obj"
{:as_text, :fields_as_text, :deep_equal} = require 'values'
Text = require 'text'
SyntaxTree = require "syntax_tree"
Files = require "files"
Errhand = require "error_handling"
C = require "colors"
make_parser = require("parser")
NOMSU_VERSION = require "nomsu_version"
Limits = require "nomsu_limits"
{:make_generator} = require "nomsu_random"
make_tree = (tree, userdata)->
tree.source = Source(userdata.filename, tree.start, tree.stop)
tree.start, tree.stop = nil, nil
tree = SyntaxTree(tree)
return tree
-- Whether version `a` (e.g. {7} or {8,0,0}) is older than the same-length prefix of
-- version `b`
older_version = (a, b)->
for i=1,#a
return a[i] < b[i] if a[i] != b[i]
return false
-- The oldest version of Nomsu whose code can be parsed and upgraded
OLDEST_SUPPORTED_VERSION = 7
-- The grammar files (nomsu.<version>.peg) are next to this file
NOMSU_DIRECTORY = debug.getinfo(1, 'S').source\match("^@(.*)/[^/]*$") or "."
-- Parsers are made the first time they're needed, and shared by every Nomsu instance
Parsers = {}
get_parser = (version)->
unless Parsers[version]
path = "#{NOMSU_DIRECTORY}/nomsu.#{version}.peg"
peg_file = io.open(path)
assert peg_file, "No PEG file found for Nomsu version #{version} (expected: #{path})"
peg_contents = peg_file\read('*a')
peg_file\close!
Parsers[version] = make_parser(peg_contents, make_tree)
return Parsers[version]
{:tree_to_nomsu, :tree_to_inline_nomsu} = require "nomsu_decompiler"
{:compile, :fail_at} = require('nomsu_compiler')
-- Each environment looks up anything it doesn't define in the table of its imports
-- (stored in the environment itself, since a weak table from environments to imports
-- would keep environments alive on LuaJIT, which doesn't support ephemeron tables)
Importer = (t, imports)->
imports or= {}
t._IMPORTS = imports
return setmetatable(t, {__index: imports})
-- Iterate over the values a coroutine yields, as (index, value) pairs. Unlike
-- coroutine.wrap(), this keeps going when the coroutine yields nil.
coroutine_values = (co)->
i = 0
return ->
ok, value = Limits.resume(co)
error(value, 0) unless ok
return nil if coroutine.status(co) == 'dead'
i += 1
return i, value
-- Statements that run as soon as they're compiled, so that the rest of the file can
-- use the compile rules and modules they define.
compile_time_stubs = {
"use": true, "export": true, "at compile time": true,
"1 compiles to": true, "1 all compile to": true, "1 parses as": true, "1 all parse as": true,
}
-- When tests are being compiled, these statements in tests run as soon as they're
-- compiled too, so later tests can use the compile rules that earlier tests define.
each_compile_time_statement = (statement, fn, compiling_tests)->
return unless statement.type == "Action"
if compile_time_stubs[statement.stub]
fn(statement)
elseif statement.stub == "public" or statement.stub == "local" or
(statement.stub == "test" and compiling_tests)
for s in *(statement[2].type == "Block" and statement[2] or {statement[2]})
each_compile_time_statement(s, fn, compiling_tests)
-- Names of variables and actions that a file defines when it runs (not in an
-- (at compile time) block). Compile rules can't use these, since they run before the
-- file does.
runtime_definitions = (statements)->
vars, actions = {}, {}
visit = (statement)->
return unless statement.type == "Action"
switch statement.stub
when "1 ="
targets = statement[1].type == "Table" and statement[1] or {statement[1]}
for t in *targets
vars[t\as_var!] = true if t.type == "Var"
when "1 means"
actions[statement[1].stub] = true if statement[1].type == "Action"
when "1 all mean"
for a in *statement[1]
actions[a.stub] = true if a.type == "Action"
when "public", "local"
if statement[2].type == "Block"
visit(s) for s in *statement[2]
else
visit(statement[2])
when "public 1 =", "local 1 ="
vars[statement[2]\as_var!] = true if statement[2].type == "Var"
visit(s) for s in *statements
return vars, actions
-- Fail if a compile-time statement uses something that won't exist until the file runs
check_compile_time_uses = (statement, vars, actions)->
switch statement.stub
when "1 compiles to", "1 all compile to", "at compile time" then nil
else return
body = statement[#statement]
-- Variables that the compile-time code makes itself (its arguments, and variables it
-- assigns or loops over) are its own, since it's compiled separately from the file
shadowed = {}
shadow = (t)->
return unless SyntaxTree\is_instance(t)
if t.type == "Var" then shadowed[t\as_var!] = true
else shadow(child) for child in *t
shadow(statement[1]) if statement.stub != "at compile time"
find_own_vars = (t)->
return unless SyntaxTree\is_instance(t)
if t.type == "Action"
switch t.stub
when "local", "local 1 ="
for v in *(t[2].type == "Block" and t[2] or {t[2]})
shadow((v.type == "Action" and v.stub == "1 =") and v[1] or v)
when "1 =", "1 ->"
shadow(t[1])
if t[1] == "for"
for child in *t
break if child == "in"
shadow(child)
find_own_vars(child) for child in *t
find_own_vars(body)
hint = "Hint: Define it inside an (at compile time:) block, so it exists while the file is compiling."
visit = (t)->
return unless SyntaxTree\is_instance(t)
-- \(...) is a template for code, which doesn't run while compiling
return if t.type == "Action" and t.stub == "\\"
if t.type == "Var" and vars[t\as_var!] and not shadowed[t\as_var!]
fail_at t, ("Compile error: This compile-time code uses $#{t\as_var!}, which won't "..
"have a value until the file runs. #{hint}")
if t.type == "Action" and actions[t.stub]
fail_at t, ("Compile error: This compile-time code uses (#{t.stub}), which isn't "..
"defined until the file runs. #{hint}")
visit(child) for child in *t
visit(body)
-- The contents that every Nomsu instance starts with
base_environment = {
-- Lua stuff:
-- (Functions that catch errors don't catch running out of resource limits)
:next, unpack: unpack or table.unpack, :setmetatable, :rawequal, :getmetatable,
pcall: Limits.pcall, xpcall: Limits.xpcall,
yield:coroutine.yield, resume:Limits.resume, coroutine_status_of:coroutine.status,
coroutine_wrap:Limits.wrap, coroutine_from: coroutine.create,
:error, :package, :os, :require, :tonumber, :tostring, :string,
:print, :loadfile, :rawset, :collectgarbage, :rawget, :rawlen,
:table, :assert, :dofile, :loadstring, lua_type_of:type, :select, :math, :io, :load,
:pairs, :ipairs, :coroutine_values, :jit,
:_VERSION, LUA_VERSION: (jit and jit.version or _VERSION),
LUA_API: _VERSION
-- Nomsu types:
Text:Text,
-- Utilities and misc.
lpeg:lpeg, re:re, Files:Files,
:SyntaxTree,
:LuaCode, :NomsuCode, :Source
LuaCode_from: ((src, ...)-> LuaCode\from(src, ...)),
NomsuCode_from: ((src, ...)-> NomsuCode\from(src, ...)),
enhance_error: Errhand.enhance_error
getfenv:getfenv,
-- Nomsu functions:
_1_as_nomsu:tree_to_nomsu, _1_as_inline_nomsu:tree_to_inline_nomsu,
compile: compile, at_1_fail:fail_at, _1_as_text:as_text,
_1_deeply_equals:deep_equal, _1_fields_as_text:fields_as_text,
IS_EXIT_SIGNAL: Errhand.is_exit_signal,
-- Parse code as the given version of Nomsu (by default, the version in its shebang),
-- without upgrading it
_1_parsed_as_Nomsu: (nomsu_code, syntax_version)->
source = nomsu_code.source
nomsu_code = tostring(nomsu_code)
version = nomsu_code\match("^#![^\n]*nomsu[ ]+-V[ ]*([0-9.]+)")
if syntax_version
syntax_version = tonumber(syntax_version\match("^[0-9]+"))
syntax_version or= version and tonumber(version\match("^[0-9]+")) or NOMSU_VERSION[1]
if syntax_version < OLDEST_SUPPORTED_VERSION
shebang = Source(source.filename, source.start, source.start + #nomsu_code\match("^[^\n]*"))
fail_at shebang, "Compile error: This file uses Nomsu #{syntax_version}, which isn't "..
"supported anymore. Hint: Upgrade it to Nomsu #{OLDEST_SUPPORTED_VERSION} first, "..
"with: nomsu -V#{OLDEST_SUPPORTED_VERSION} -t upgrade -i #{source.filename}"
assert syntax_version <= NOMSU_VERSION[1], "No parser found for Nomsu syntax version #{syntax_version}"
parse = get_parser(syntax_version)
tree = parse(nomsu_code, source.filename)
if tree.shebang
shebang_version = tree.shebang\match("nomsu %-V[ ]*([%d.]+)")
if shebang_version and shebang_version != ""
tree.version or= [tonumber(v) for v in shebang_version\gmatch("%d+")]
return tree
Module: (package_name)=>
-- This *must* be the first local
local path
if ret = @LOADED_MODULES[package_name]
return ret
-- The instance's loader finds the module's code, and the filename it came from
load_module = @MODULE_LOADER
code, path = load_module(package_name)
error(path or "Couldn't find the module '#{package_name}'", 0) unless code
if ret = @LOADED_MODULES[path]
@LOADED_MODULES[package_name] = ret
return ret
-- Traverse up the callstack to look for import loops
-- This is more reliable than keeping a list of running files, since
-- that gets messed up when errors occur.
currently_running = {}
for i=2,999
info = debug.getinfo(i, 'f')
break unless info and info.func
if info.func == @Module
n, upper_path = debug.getlocal(i, 3) -- 3 means "path"
table.insert(currently_running, upper_path)
assert(n == "path")
if upper_path == path
--circle = "\n "..table.concat(currently_running, "\n..imports ")
circle = table.concat(currently_running, "', which imports '")
err_i = 2
info = debug.getinfo(err_i)
while info and (info.func == @Module or info.func == @use or info.func == @export)
err_i += 1
info = debug.getinfo(err_i)
fail_at (info or debug.getinfo(2)), "Circular import: File '#{path}' imports '"..circle.."'"
mod = @new_environment!
mod.MODULE_NAME = package_name
-- Another instance may have different code with the same filename, so give this
-- code a filename of its own, so error messages show the right code
filename = path
if other_code = Files.find_source(filename)
if other_code != code
n = 2
while Files.find_source("#{path} (#{n})")
n += 1
filename = "#{path} (#{n})"
@SOURCES[filename] = code
if path\match("%.lua$")
code = LuaCode\from(Source(filename, 1, #code), code)
else
code = NomsuCode\from(Source(filename, 1, #code), code)
ret = mod\run(code)
if ret != nil
mod = ret
@LOADED_MODULES[package_name] = mod
@LOADED_MODULES[path] = mod
return mod
use: (package_name)=>
mod = @Module(package_name)
imports = assert rawget(@, "_IMPORTS")
for k,v in pairs(mod)
imports[k] = v
cr_imports = assert rawget(@COMPILE_RULES, "_IMPORTS")
if public_rules = rawget(mod, "PUBLIC_COMPILE_RULES")
for k,v in pairs(public_rules)
cr_imports[k] = v
return mod
export: (package_name)=>
mod = @Module(package_name)
imports = assert rawget(@, "_IMPORTS")
for k,v in pairs(rawget(mod, "_IMPORTS"))
if rawget(imports, k) == nil
imports[k] = v
for k,v in pairs(mod)
if rawget(@, k) == nil
@[k] = v
if public_rules = rawget(mod, "PUBLIC_COMPILE_RULES")
for k,v in pairs(public_rules)
if rawget(@COMPILE_RULES, k) == nil
@COMPILE_RULES[k] = v
@PUBLIC_COMPILE_RULES[k] = v
return mod
-- (public:) blocks that define compile rules are wrapped in these, so that the
-- rules the block defines are added to PUBLIC_COMPILE_RULES
begin_public_rules: =>
@_rules_before_public or= {}
table.insert @_rules_before_public, {k,v for k,v in pairs(@COMPILE_RULES)}
end_public_rules: =>
before = table.remove @_rules_before_public
for k,v in pairs(@COMPILE_RULES)
@PUBLIC_COMPILE_RULES[k] = v unless before[k] == v
run: (to_run)=>
if not to_run
error("Need both something to run and an environment")
if type(to_run) == 'string'
filename = Files.anonymous_filename!
@SOURCES[filename] = to_run
to_run = NomsuCode\from(Source(filename, 1, #to_run), to_run)
return @run(to_run)
elseif NomsuCode\is_instance(to_run)
tree = @._1_parsed(to_run)
return nil if tree == nil
return @run(tree)
elseif SyntaxTree\is_instance(to_run)
filename = to_run.source.filename\gsub("\n.*", "...")
lua = @compile_file(to_run)
lua\declare_locals!
lua\prepend "-- File: #{filename}\n"
return @run(lua)
elseif LuaCode\is_instance(to_run)
source = to_run.source
lua_string = to_run\text!
-- For some reason, Lua doesn't strip shebangs from Lua files
lua_string = lua_string\gsub("^#![^\n]*\n","")
-- Code compiled for tests is different from the same file's normal code, which
-- may be loaded too, so it needs its own name (and source map)
chunk_name = tostring(source)
chunk_name ..= " (tests)" if @COMPILING_TESTS
-- If you replace chunk_name with "nil", source mapping won't happen
-- A sandbox's code runs in its runtime environment, which only has what the
-- sandboxed code is allowed to use, instead of in the compile context
run_lua_fn, err = load(lua_string, chunk_name, "t", rawget(@, "RUNTIME_ENV") or @)
if not run_lua_fn
err_line = tonumber(tostring(err)\match("^.-:(%d+): "))
if err_line
full_text = to_run\text!
-- A shebang line was stripped from lua_string, so line numbers are off by one
err_line += 1 if full_text != lua_string
line_start = 1
for _=2,err_line
line_start = (full_text\find("\n", line_start, true) or #full_text) + 1
bad_line = full_text\match("[^\n]*", line_start)
target = line_start + #bad_line\match("^%s*")
-- Find the innermost piece of code with its own source that produced the bad line
local culprit
find_culprit = (code, pos)->
if code.source and code.source != to_run.source
culprit = code.source
for b in *code.bits
len = #tostring(b)
if type(b) != 'string' and pos <= target and target < pos + len
return find_culprit(b, pos)
pos += len
find_culprit(to_run, 1)
if culprit
message = tostring(err)\match("^.-:%d+: (.*)")
fail_at culprit, ("Compile error: This code compiled to Lua that won't load:\n\n"..
" #{bad_line\match("^%s*(.-)%s*$")}\n\nLua says: #{message}\n"..
"Hint: This is a bug in Nomsu, or in a compile rule that this code uses.")
lines =[("%3d|%s")\format(i,line) for i, line in ipairs lua_string\lines!]
line_numbered_lua = table.concat(lines, "\n")
error("Failed to compile generated code:\n#{C("bright blue", line_numbered_lua)}\n\n#{err}", 0)
source_key = chunk_name
local file
unless @SOURCE_MAP[source_key] or @OPTIMIZATION >= 2
file = Files.read(source.filename)
if not file and @NOMSU_PREFIX
file = Files.read("#{@NOMSU_PREFIX}/share/nomsu/#{table.concat NOMSU_VERSION, "."}/#{source.filename}")
-- Without the source file, errors just show Lua line numbers
if file
map = {}
lua_line = 1
nomsu_line = Files.get_line_number(file, source.start)
map_sources = (s)->
if type(s) == 'string'
for nl in s\gmatch("\n")
map[lua_line] or= nomsu_line
lua_line += 1
else
if s.source and s.source.filename == source.filename
nomsu_line = Files.get_line_number(file, s.source.start)
for b in *s.bits do map_sources(b)
map_sources(to_run)
map[lua_line] or= nomsu_line
map[0] = 0
-- Mapping from lua line number to nomsu line numbers
@SOURCE_MAP[source_key] = map
return run_lua_fn!
else
error("Attempt to run unknown thing: "..as_text(to_run))
-- Compile a whole file into a single chunk of Lua code. Definitions of compile rules
-- (and imports and (at compile time) blocks) run as soon as they're compiled, so
-- later parts of the file can use them, while everything else only runs when the
-- whole file runs.
compile_file: (tree)=>
outer_tests = @_tests_to_compile
@_tests_to_compile = {}
statements = {}
for statement in *((tree.type == "Block" or tree.type == "File") and tree or {tree})
statement.version = tree.version
if statement.type == "Error"
@compile(statement)
table.insert statements, statement
-- Compile-time code can't use variables from earlier in the file, or actions
-- from anywhere in the file, since actions are declared at the top of the file.
_, runtime_actions = runtime_definitions(statements)
runtime_vars = {}
lua = LuaCode\from(tree.source)
has_lines = false
add_line = (line_lua)->
lua\add "\n" if has_lines
has_lines = true
lua\add line_lua
-- Nothing after a top-level (return) runs, so tests go before one at the end
last = statements[#statements]
final_return = last and last.type == "Action" and last\get_stub!\match("^return") and last
local final_return_lua
for i, statement in ipairs statements
-- Compile-time code inside a statement (like compile rules in a (public:)
-- block) runs in order before the rest of the statement is compiled
local statement_lua
run_compile_time = (s)->
check_compile_time_uses(s, runtime_vars, runtime_actions)
s_lua = @compile(s)
statement_lua = s_lua if s == statement
s_lua\declare_locals!
@run(s_lua)
each_compile_time_statement statement, run_compile_time, @COMPILING_TESTS
statement_lua or= @compile(statement)
for v in pairs(runtime_definitions({statement}))
runtime_vars[v] = true
if statement == final_return
final_return_lua = statement_lua
continue
if statement_lua\text! == ""
-- Declarations (like (local $x)) don't have any code
lua\add statement_lua
continue
add_line statement_lua
unless statement_lua\last(1) == ";" or statement_lua\last(4)\match("[^_a-zA-Z0-9]end$")
lua\add ";"
-- Tests only run after the whole file has, so they're compiled last, when every
-- compile rule in the file is defined
for body in *@_tests_to_compile
body_lua = @compile(body)
body_lua.is_scope = true
add_line LuaCode("TESTS[#{tostring(body.source)\as_lua!}] = function()\n ", body_lua, "\nend")
add_line final_return_lua if final_return_lua
@_tests_to_compile = outer_tests
return lua
}
-- Make a new Nomsu instance, with its own root environment, compile rules, and loaded
-- modules, and return its root environment. Every module the instance loads gets its
-- own environment, which starts with the contents of the root environment.
-- Config options:
-- loader: a function that takes a module name and returns the module's code and the
-- filename it came from, or nil and an error message
-- optimization: the optimization level (default: 1)
-- print: a function that (say) and (ask) use to write text (default: write to stdout)
-- input: a function that (ask) uses to read a line of text (default: read from stdin)
-- exit: the function that (exit) calls (default: os.exit)
new_instance = (config={})->
local nomsu_environment
nomsu_environment = Importer{k,v for k,v in pairs(base_environment)}
nomsu_environment._ENV = nomsu_environment
nomsu_environment._G = nomsu_environment
nomsu_environment.COMPILE_RULES = Importer({k,v for k,v in pairs(require('bootstrap'))}, nil)
nomsu_environment.PUBLIC_COMPILE_RULES = {}
nomsu_environment.TESTS = {}
nomsu_environment.globals = {}
nomsu_environment.MODULE_NAME = "nomsu"
nomsu_environment.NOMSU_VERSION = NOMSU_VERSION
-- Each instance has its own random number generator, so its random numbers don't
-- affect any other instance's (or the program running Nomsu's)
nomsu_environment.RANDOM = make_generator!
nomsu_environment.math = setmetatable({k,v for k,v in pairs(math)}, nil)
nomsu_environment.math.random = nomsu_environment.RANDOM.random
nomsu_environment.math.randomseed = nomsu_environment.RANDOM.seed
nomsu_environment.MODULE_LOADER = assert(config.loader, "A Nomsu instance needs a module loader")
nomsu_environment.OPTIMIZATION = config.optimization or 1
nomsu_environment.WRITE_OUTPUT = config.print or (text)->
io.write(text)
io.flush!
nomsu_environment.READ_INPUT = config.input or -> io.read!
nomsu_environment.exit = config.exit or os.exit
nomsu_environment.quit = nomsu_environment.exit
nomsu_environment.LOADED_MODULES = {}
nomsu_environment.SOURCE_MAP = {}
Errhand.register_source_map(nomsu_environment.SOURCE_MAP)
-- The code of the files and text that this instance has run, by filename
nomsu_environment.SOURCES = {}
Files.add_sources(nomsu_environment.SOURCES)
parse_as_nomsu = nomsu_environment._1_parsed_as_Nomsu
nomsu_environment._1_parsed_as_Nomsu = (nomsu_code, syntax_version)->
if type(nomsu_code) == 'string'
filename = Files.anonymous_filename!
nomsu_environment.SOURCES[filename] = nomsu_code
nomsu_code = NomsuCode\from(Source(filename, 1, #nomsu_code), nomsu_code)
return parse_as_nomsu(nomsu_code, syntax_version)
-- Parse code, and upgrade it if it's from an older version of Nomsu
nomsu_environment._1_parsed = (nomsu_code)->
tree = nomsu_environment._1_parsed_as_Nomsu(nomsu_code)
if tree and tree.version and older_version(tree.version, NOMSU_VERSION)
compatibility = nomsu_environment\Module("compatibility")
tree = compatibility._1_upgraded_from_2_to(tree, tree.version, NOMSU_VERSION)
return tree
nomsu_environment.new_environment = ->
env = Importer({}, {k,v for k,v in pairs(nomsu_environment)})
env._ENV = env
env._G = env
env.TESTS = {}
env.COMPILE_RULES = Importer({}, {k,v for k,v in pairs(nomsu_environment.COMPILE_RULES)})
env.PUBLIC_COMPILE_RULES = {}
return env
return nomsu_environment
return {:new_instance, :NOMSU_VERSION, :NOMSU_DIRECTORY}
|