simplification
Download
784 lines 24.8 KiBLuaModified 2026-11-10 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
local lpeg = require('lpeg')
local re = require('re')
local NomsuCode, LuaCode, Source
do
  local _obj_0 = require("code_obj")
  NomsuCode, LuaCode, Source = _obj_0.NomsuCode, _obj_0.LuaCode, _obj_0.Source
end
local as_text, fields_as_text, deep_equal
do
  local _obj_0 = require('values')
  as_text, fields_as_text, deep_equal = _obj_0.as_text, _obj_0.fields_as_text, _obj_0.deep_equal
end
local Text = require('text')
local SyntaxTree = require("syntax_tree")
local Files = require("files")
local Errhand = require("error_handling")
local C = require("colors")
local make_parser = require("parser")
local NOMSU_VERSION = require("nomsu_version")
local Limits = require("nomsu_limits")
local make_generator
make_generator = require("nomsu_random").make_generator
local make_tree
make_tree = function(tree, userdata)
  tree.source = Source(userdata.filename, tree.start, tree.stop)
  tree.start, tree.stop = nil, nil
  tree = SyntaxTree(tree)
  return tree
end
local older_version
older_version = function(a, b)
  for i = 1, #a do
    if a[i] ~= b[i] then
      return a[i] < b[i]
    end
  end
  return false
end
local OLDEST_SUPPORTED_VERSION = 7
local NOMSU_DIRECTORY = debug.getinfo(1, 'S').source:match("^@(.*)/[^/]*$") or "."
local Parsers = { }
local get_parser
get_parser = function(version)
  if not (Parsers[version]) then
    local path = tostring(NOMSU_DIRECTORY) .. "/nomsu." .. tostring(version) .. ".peg"
    local peg_file = io.open(path)
    assert(peg_file, "No PEG file found for Nomsu version " .. tostring(version) .. " (expected: " .. tostring(path) .. ")")
    local peg_contents = peg_file:read('*a')
    peg_file:close()
    Parsers[version] = make_parser(peg_contents, make_tree)
  end
  return Parsers[version]
end
local tree_to_nomsu, tree_to_inline_nomsu
do
  local _obj_0 = require("nomsu_decompiler")
  tree_to_nomsu, tree_to_inline_nomsu = _obj_0.tree_to_nomsu, _obj_0.tree_to_inline_nomsu
end
local compile, fail_at
do
  local _obj_0 = require('nomsu_compiler')
  compile, fail_at = _obj_0.compile, _obj_0.fail_at
end
local Importer
Importer = function(t, imports)
  imports = imports or { }
  t._IMPORTS = imports
  return setmetatable(t, {
    __index = imports
  })
end
local coroutine_values
coroutine_values = function(co)
  local i = 0
  return function()
    local ok, value = Limits.resume(co)
    if not (ok) then
      error(value, 0)
    end
    if coroutine.status(co) == 'dead' then
      return nil
    end
    i = i + 1
    return i, value
  end
end
local 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
}
local each_compile_time_statement
each_compile_time_statement = function(statement, fn, compiling_tests)
  if not (statement.type == "Action") then
    return 
  end
  if compile_time_stubs[statement.stub] then
    return fn(statement)
  elseif statement.stub == "public" or statement.stub == "local" or (statement.stub == "test" and compiling_tests) then
    local _list_0 = (statement[2].type == "Block" and statement[2] or {
      statement[2]
    })
    for _index_0 = 1, #_list_0 do
      local s = _list_0[_index_0]
      each_compile_time_statement(s, fn, compiling_tests)
    end
  end
end
local runtime_definitions
runtime_definitions = function(statements)
  local vars, actions = { }, { }
  local visit
  visit = function(statement)
    if not (statement.type == "Action") then
      return 
    end
    local _exp_0 = statement.stub
    if "1 =" == _exp_0 then
      local targets = statement[1].type == "Table" and statement[1] or {
        statement[1]
      }
      for _index_0 = 1, #targets do
        local t = targets[_index_0]
        if t.type == "Var" then
          vars[t:as_var()] = true
        end
      end
    elseif "1 means" == _exp_0 then
      if statement[1].type == "Action" then
        actions[statement[1].stub] = true
      end
    elseif "1 all mean" == _exp_0 then
      local _list_0 = statement[1]
      for _index_0 = 1, #_list_0 do
        local a = _list_0[_index_0]
        if a.type == "Action" then
          actions[a.stub] = true
        end
      end
    elseif "public" == _exp_0 or "local" == _exp_0 then
      if statement[2].type == "Block" then
        local _list_0 = statement[2]
        for _index_0 = 1, #_list_0 do
          local s = _list_0[_index_0]
          visit(s)
        end
      else
        return visit(statement[2])
      end
    elseif "public 1 =" == _exp_0 or "local 1 =" == _exp_0 then
      if statement[2].type == "Var" then
        vars[statement[2]:as_var()] = true
      end
    end
  end
  for _index_0 = 1, #statements do
    local s = statements[_index_0]
    visit(s)
  end
  return vars, actions
end
local check_compile_time_uses
check_compile_time_uses = function(statement, vars, actions)
  local _exp_0 = statement.stub
  if "1 compiles to" == _exp_0 or "1 all compile to" == _exp_0 or "at compile time" == _exp_0 then
    local _scrap_0 = nil
  else
    return 
  end
  local body = statement[#statement]
  local shadowed = { }
  local shadow
  shadow = function(t)
    if not (SyntaxTree:is_instance(t)) then
      return 
    end
    if t.type == "Var" then
      shadowed[t:as_var()] = true
    else
      local _list_0 = t
      for _index_0 = 1, #_list_0 do
        local child = _list_0[_index_0]
        shadow(child)
      end
    end
  end
  if statement.stub ~= "at compile time" then
    shadow(statement[1])
  end
  local find_own_vars
  find_own_vars = function(t)
    if not (SyntaxTree:is_instance(t)) then
      return 
    end
    if t.type == "Action" then
      local _exp_1 = t.stub
      if "local" == _exp_1 or "local 1 =" == _exp_1 then
        local _list_0 = (t[2].type == "Block" and t[2] or {
          t[2]
        })
        for _index_0 = 1, #_list_0 do
          local v = _list_0[_index_0]
          shadow((v.type == "Action" and v.stub == "1 =") and v[1] or v)
        end
      elseif "1 =" == _exp_1 or "1 ->" == _exp_1 then
        shadow(t[1])
      end
      if t[1] == "for" then
        for _index_0 = 1, #t do
          local child = t[_index_0]
          if child == "in" then
            break
          end
          shadow(child)
        end
      end
    end
    local _list_0 = t
    for _index_0 = 1, #_list_0 do
      local child = _list_0[_index_0]
      find_own_vars(child)
    end
  end
  find_own_vars(body)
  local hint = "Hint: Define it inside an (at compile time:) block, so it exists while the file is compiling."
  local visit
  visit = function(t)
    if not (SyntaxTree:is_instance(t)) then
      return 
    end
    if t.type == "Action" and t.stub == "\\" then
      return 
    end
    if t.type == "Var" and vars[t:as_var()] and not shadowed[t:as_var()] then
      fail_at(t, (("Compile error: This compile-time code uses $" .. tostring(t:as_var()) .. ", which won't ") .. "have a value until the file runs. " .. tostring(hint)))
    end
    if t.type == "Action" and actions[t.stub] then
      fail_at(t, (("Compile error: This compile-time code uses (" .. tostring(t.stub) .. "), which isn't ") .. "defined until the file runs. " .. tostring(hint)))
    end
    local _list_0 = t
    for _index_0 = 1, #_list_0 do
      local child = _list_0[_index_0]
      visit(child)
    end
  end
  return visit(body)
end
local base_environment = {
  next = next,
  unpack = unpack or table.unpack,
  setmetatable = setmetatable,
  rawequal = rawequal,
  getmetatable = 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 = error,
  package = package,
  os = os,
  require = require,
  tonumber = tonumber,
  tostring = tostring,
  string = string,
  print = print,
  loadfile = loadfile,
  rawset = rawset,
  collectgarbage = collectgarbage,
  rawget = rawget,
  rawlen = rawlen,
  table = table,
  assert = assert,
  dofile = dofile,
  loadstring = loadstring,
  lua_type_of = type,
  select = select,
  math = math,
  io = io,
  load = load,
  pairs = pairs,
  ipairs = ipairs,
  coroutine_values = coroutine_values,
  jit = jit,
  _VERSION = _VERSION,
  LUA_VERSION = (jit and jit.version or _VERSION),
  LUA_API = _VERSION,
  Text = Text,
  lpeg = lpeg,
  re = re,
  Files = Files,
  SyntaxTree = SyntaxTree,
  LuaCode = LuaCode,
  NomsuCode = NomsuCode,
  Source = Source,
  LuaCode_from = (function(src, ...)
    return LuaCode:from(src, ...)
  end),
  NomsuCode_from = (function(src, ...)
    return NomsuCode:from(src, ...)
  end),
  enhance_error = Errhand.enhance_error,
  getfenv = getfenv,
  _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,
  _1_parsed_as_Nomsu = function(nomsu_code, syntax_version)
    local source = nomsu_code.source
    nomsu_code = tostring(nomsu_code)
    local version = nomsu_code:match("^#![^\n]*nomsu[ ]+-V[ ]*([0-9.]+)")
    if syntax_version then
      syntax_version = tonumber(syntax_version:match("^[0-9]+"))
    end
    syntax_version = syntax_version or (version and tonumber(version:match("^[0-9]+")) or NOMSU_VERSION[1])
    if syntax_version < OLDEST_SUPPORTED_VERSION then
      local shebang = Source(source.filename, source.start, source.start + #nomsu_code:match("^[^\n]*"))
      fail_at(shebang, ("Compile error: This file uses Nomsu " .. tostring(syntax_version) .. ", which isn't ") .. ("supported anymore. Hint: Upgrade it to Nomsu " .. tostring(OLDEST_SUPPORTED_VERSION) .. " first, ") .. "with: nomsu -V" .. tostring(OLDEST_SUPPORTED_VERSION) .. " -t upgrade -i " .. tostring(source.filename))
    end
    assert(syntax_version <= NOMSU_VERSION[1], "No parser found for Nomsu syntax version " .. tostring(syntax_version))
    local parse = get_parser(syntax_version)
    local tree = parse(nomsu_code, source.filename)
    if tree.shebang then
      local shebang_version = tree.shebang:match("nomsu %-V[ ]*([%d.]+)")
      if shebang_version and shebang_version ~= "" then
        tree.version = tree.version or (function()
          local _accum_0 = { }
          local _len_0 = 1
          for v in shebang_version:gmatch("%d+") do
            _accum_0[_len_0] = tonumber(v)
            _len_0 = _len_0 + 1
          end
          return _accum_0
        end)()
      end
    end
    return tree
  end,
  Module = function(self, package_name)
    local path
    do
      local ret = self.LOADED_MODULES[package_name]
      if ret then
        return ret
      end
    end
    local load_module = self.MODULE_LOADER
    local code
    code, path = load_module(package_name)
    if not (code) then
      error(path or "Couldn't find the module '" .. tostring(package_name) .. "'", 0)
    end
    do
      local ret = self.LOADED_MODULES[path]
      if ret then
        self.LOADED_MODULES[package_name] = ret
        return ret
      end
    end
    local currently_running = { }
    for i = 2, 999 do
      local info = debug.getinfo(i, 'f')
      if not (info and info.func) then
        break
      end
      if info.func == self.Module then
        local n, upper_path = debug.getlocal(i, 3)
        table.insert(currently_running, upper_path)
        assert(n == "path")
        if upper_path == path then
          local circle = table.concat(currently_running, "', which imports '")
          local err_i = 2
          info = debug.getinfo(err_i)
          while info and (info.func == self.Module or info.func == self.use or info.func == self.export) do
            err_i = err_i + 1
            info = debug.getinfo(err_i)
          end
          fail_at((info or debug.getinfo(2)), ("Circular import: File '" .. tostring(path) .. "' imports '") .. circle .. "'")
        end
      end
    end
    local mod = self:new_environment()
    mod.MODULE_NAME = package_name
    local filename = path
    do
      local other_code = Files.find_source(filename)
      if other_code then
        if other_code ~= code then
          local n = 2
          while Files.find_source(tostring(path) .. " (" .. tostring(n) .. ")") do
            n = n + 1
          end
          filename = tostring(path) .. " (" .. tostring(n) .. ")"
        end
      end
    end
    self.SOURCES[filename] = code
    if path:match("%.lua$") then
      code = LuaCode:from(Source(filename, 1, #code), code)
    else
      code = NomsuCode:from(Source(filename, 1, #code), code)
    end
    local ret = mod:run(code)
    if ret ~= nil then
      mod = ret
    end
    self.LOADED_MODULES[package_name] = mod
    self.LOADED_MODULES[path] = mod
    return mod
  end,
  use = function(self, package_name)
    local mod = self:Module(package_name)
    local imports = assert(rawget(self, "_IMPORTS"))
    for k, v in pairs(mod) do
      imports[k] = v
    end
    local cr_imports = assert(rawget(self.COMPILE_RULES, "_IMPORTS"))
    do
      local public_rules = rawget(mod, "PUBLIC_COMPILE_RULES")
      if public_rules then
        for k, v in pairs(public_rules) do
          cr_imports[k] = v
        end
      end
    end
    return mod
  end,
  export = function(self, package_name)
    local mod = self:Module(package_name)
    local imports = assert(rawget(self, "_IMPORTS"))
    for k, v in pairs(rawget(mod, "_IMPORTS")) do
      if rawget(imports, k) == nil then
        imports[k] = v
      end
    end
    for k, v in pairs(mod) do
      if rawget(self, k) == nil then
        self[k] = v
      end
    end
    do
      local public_rules = rawget(mod, "PUBLIC_COMPILE_RULES")
      if public_rules then
        for k, v in pairs(public_rules) do
          if rawget(self.COMPILE_RULES, k) == nil then
            self.COMPILE_RULES[k] = v
          end
          self.PUBLIC_COMPILE_RULES[k] = v
        end
      end
    end
    return mod
  end,
  begin_public_rules = function(self)
    self._rules_before_public = self._rules_before_public or { }
    return table.insert(self._rules_before_public, (function()
      local _tbl_0 = { }
      for k, v in pairs(self.COMPILE_RULES) do
        _tbl_0[k] = v
      end
      return _tbl_0
    end)())
  end,
  end_public_rules = function(self)
    local before = table.remove(self._rules_before_public)
    for k, v in pairs(self.COMPILE_RULES) do
      if not (before[k] == v) then
        self.PUBLIC_COMPILE_RULES[k] = v
      end
    end
  end,
  run = function(self, to_run)
    if not to_run then
      error("Need both something to run and an environment")
    end
    if type(to_run) == 'string' then
      local filename = Files.anonymous_filename()
      self.SOURCES[filename] = to_run
      to_run = NomsuCode:from(Source(filename, 1, #to_run), to_run)
      return self:run(to_run)
    elseif NomsuCode:is_instance(to_run) then
      local tree = self._1_parsed(to_run)
      if tree == nil then
        return nil
      end
      return self:run(tree)
    elseif SyntaxTree:is_instance(to_run) then
      local filename = to_run.source.filename:gsub("\n.*", "...")
      local lua = self:compile_file(to_run)
      lua:declare_locals()
      lua:prepend("-- File: " .. tostring(filename) .. "\n")
      return self:run(lua)
    elseif LuaCode:is_instance(to_run) then
      local source = to_run.source
      local lua_string = to_run:text()
      lua_string = lua_string:gsub("^#![^\n]*\n", "")
      local chunk_name = tostring(source)
      if self.COMPILING_TESTS then
        chunk_name = chunk_name .. " (tests)"
      end
      local run_lua_fn, err = load(lua_string, chunk_name, "t", rawget(self, "RUNTIME_ENV") or self)
      if not run_lua_fn then
        local err_line = tonumber(tostring(err):match("^.-:(%d+): "))
        if err_line then
          local full_text = to_run:text()
          if full_text ~= lua_string then
            err_line = err_line + 1
          end
          local line_start = 1
          for _ = 2, err_line do
            line_start = (full_text:find("\n", line_start, true) or #full_text) + 1
          end
          local bad_line = full_text:match("[^\n]*", line_start)
          local target = line_start + #bad_line:match("^%s*")
          local culprit
          local find_culprit
          find_culprit = function(code, pos)
            if code.source and code.source ~= to_run.source then
              culprit = code.source
            end
            local _list_0 = code.bits
            for _index_0 = 1, #_list_0 do
              local b = _list_0[_index_0]
              local len = #tostring(b)
              if type(b) ~= 'string' and pos <= target and target < pos + len then
                return find_culprit(b, pos)
              end
              pos = pos + len
            end
          end
          find_culprit(to_run, 1)
          if culprit then
            local message = tostring(err):match("^.-:%d+: (.*)")
            fail_at(culprit, ("Compile error: This code compiled to Lua that won't load:\n\n" .. ("    " .. tostring(bad_line:match("^%s*(.-)%s*$")) .. "\n\nLua says: " .. tostring(message) .. "\n") .. "Hint: This is a bug in Nomsu, or in a compile rule that this code uses."))
          end
        end
        local lines
        do
          local _accum_0 = { }
          local _len_0 = 1
          for i, line in ipairs(lua_string:lines()) do
            _accum_0[_len_0] = ("%3d|%s"):format(i, line)
            _len_0 = _len_0 + 1
          end
          lines = _accum_0
        end
        local line_numbered_lua = table.concat(lines, "\n")
        error("Failed to compile generated code:\n" .. tostring(C("bright blue", line_numbered_lua)) .. "\n\n" .. tostring(err), 0)
      end
      local source_key = chunk_name
      local file
      if not (self.SOURCE_MAP[source_key] or self.OPTIMIZATION >= 2) then
        file = Files.read(source.filename)
        if not file and self.NOMSU_PREFIX then
          file = Files.read(tostring(self.NOMSU_PREFIX) .. "/share/nomsu/" .. tostring(table.concat(NOMSU_VERSION, ".")) .. "/" .. tostring(source.filename))
        end
      end
      if file then
        local map = { }
        local lua_line = 1
        local nomsu_line = Files.get_line_number(file, source.start)
        local map_sources
        map_sources = function(s)
          if type(s) == 'string' then
            for nl in s:gmatch("\n") do
              local _update_0 = lua_line
              map[_update_0] = map[_update_0] or nomsu_line
              lua_line = lua_line + 1
            end
          else
            if s.source and s.source.filename == source.filename then
              nomsu_line = Files.get_line_number(file, s.source.start)
            end
            local _list_0 = s.bits
            for _index_0 = 1, #_list_0 do
              local b = _list_0[_index_0]
              map_sources(b)
            end
          end
        end
        map_sources(to_run)
        local _update_0 = lua_line
        map[_update_0] = map[_update_0] or nomsu_line
        map[0] = 0
        self.SOURCE_MAP[source_key] = map
      end
      return run_lua_fn()
    else
      return error("Attempt to run unknown thing: " .. as_text(to_run))
    end
  end,
  compile_file = function(self, tree)
    local outer_tests = self._tests_to_compile
    self._tests_to_compile = { }
    local statements = { }
    local _list_0 = ((tree.type == "Block" or tree.type == "File") and tree or {
      tree
    })
    for _index_0 = 1, #_list_0 do
      local statement = _list_0[_index_0]
      statement.version = tree.version
      if statement.type == "Error" then
        self:compile(statement)
      end
      table.insert(statements, statement)
    end
    local _, runtime_actions = runtime_definitions(statements)
    local runtime_vars = { }
    local lua = LuaCode:from(tree.source)
    local has_lines = false
    local add_line
    add_line = function(line_lua)
      if has_lines then
        lua:add("\n")
      end
      has_lines = true
      return lua:add(line_lua)
    end
    local last = statements[#statements]
    local 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) do
      local _continue_0 = false
      repeat
        local statement_lua
        local run_compile_time
        run_compile_time = function(s)
          check_compile_time_uses(s, runtime_vars, runtime_actions)
          local s_lua = self:compile(s)
          if s == statement then
            statement_lua = s_lua
          end
          s_lua:declare_locals()
          return self:run(s_lua)
        end
        each_compile_time_statement(statement, run_compile_time, self.COMPILING_TESTS)
        statement_lua = statement_lua or self:compile(statement)
        for v in pairs(runtime_definitions({
          statement
        })) do
          runtime_vars[v] = true
        end
        if statement == final_return then
          final_return_lua = statement_lua
          _continue_0 = true
          break
        end
        if statement_lua:text() == "" then
          lua:add(statement_lua)
          _continue_0 = true
          break
        end
        add_line(statement_lua)
        if not (statement_lua:last(1) == ";" or statement_lua:last(4):match("[^_a-zA-Z0-9]end$")) then
          lua:add(";")
        end
        _continue_0 = true
      until true
      if not _continue_0 then
        break
      end
    end
    local _list_1 = self._tests_to_compile
    for _index_0 = 1, #_list_1 do
      local body = _list_1[_index_0]
      local body_lua = self:compile(body)
      body_lua.is_scope = true
      add_line(LuaCode("TESTS[" .. tostring(tostring(body.source):as_lua()) .. "] = function()\n    ", body_lua, "\nend"))
    end
    if final_return_lua then
      add_line(final_return_lua)
    end
    self._tests_to_compile = outer_tests
    return lua
  end
}
local new_instance
new_instance = function(config)
  if config == nil then
    config = { }
  end
  local nomsu_environment
  nomsu_environment = Importer((function()
    local _tbl_0 = { }
    for k, v in pairs(base_environment) do
      _tbl_0[k] = v
    end
    return _tbl_0
  end)())
  nomsu_environment._ENV = nomsu_environment
  nomsu_environment._G = nomsu_environment
  nomsu_environment.COMPILE_RULES = Importer((function()
    local _tbl_0 = { }
    for k, v in pairs(require('bootstrap')) do
      _tbl_0[k] = v
    end
    return _tbl_0
  end)(), nil)
  nomsu_environment.PUBLIC_COMPILE_RULES = { }
  nomsu_environment.TESTS = { }
  nomsu_environment.globals = { }
  nomsu_environment.MODULE_NAME = "nomsu"
  nomsu_environment.NOMSU_VERSION = NOMSU_VERSION
  nomsu_environment.RANDOM = make_generator()
  nomsu_environment.math = setmetatable((function()
    local _tbl_0 = { }
    for k, v in pairs(math) do
      _tbl_0[k] = v
    end
    return _tbl_0
  end)(), 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 function(text)
    io.write(text)
    return io.flush()
  end
  nomsu_environment.READ_INPUT = config.input or function()
    return io.read()
  end
  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)
  nomsu_environment.SOURCES = { }
  Files.add_sources(nomsu_environment.SOURCES)
  local parse_as_nomsu = nomsu_environment._1_parsed_as_Nomsu
  nomsu_environment._1_parsed_as_Nomsu = function(nomsu_code, syntax_version)
    if type(nomsu_code) == 'string' then
      local filename = Files.anonymous_filename()
      nomsu_environment.SOURCES[filename] = nomsu_code
      nomsu_code = NomsuCode:from(Source(filename, 1, #nomsu_code), nomsu_code)
    end
    return parse_as_nomsu(nomsu_code, syntax_version)
  end
  nomsu_environment._1_parsed = function(nomsu_code)
    local tree = nomsu_environment._1_parsed_as_Nomsu(nomsu_code)
    if tree and tree.version and older_version(tree.version, NOMSU_VERSION) then
      local compatibility = nomsu_environment:Module("compatibility")
      tree = compatibility._1_upgraded_from_2_to(tree, tree.version, NOMSU_VERSION)
    end
    return tree
  end
  nomsu_environment.new_environment = function()
    local env = Importer({ }, (function()
      local _tbl_0 = { }
      for k, v in pairs(nomsu_environment) do
        _tbl_0[k] = v
      end
      return _tbl_0
    end)())
    env._ENV = env
    env._G = env
    env.TESTS = { }
    env.COMPILE_RULES = Importer({ }, (function()
      local _tbl_0 = { }
      for k, v in pairs(nomsu_environment.COMPILE_RULES) do
        _tbl_0[k] = v
      end
      return _tbl_0
    end)())
    env.PUBLIC_COMPILE_RULES = { }
    return env
  end
  return nomsu_environment
end
return {
  new_instance = new_instance,
  NOMSU_VERSION = NOMSU_VERSION,
  NOMSU_DIRECTORY = NOMSU_DIRECTORY
}