simplification
Download
360 lines 8.3 KiBLuaModified 2026-11-09 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
local Errhand = require("error_handling")
local Text = require("text")
local unpack = unpack or table.unpack
local CHECK_INTERVAL = 1000
local active
local OVER_BUDGET = { }
local stop
stop = function(reason)
  active.signal = setmetatable({
    limit = reason
  }, Errhand.ExitSignal)
  return error(active.signal, 0)
end
local check_memory
check_memory = function(extra_bytes)
  if extra_bytes == nil then
    extra_bytes = 0
  end
  if not (active and active.limits.memory) then
    return 
  end
  if active.signal then
    error(active.signal, 0)
  end
  local used
  used = function()
    return collectgarbage("count") + extra_bytes / 1024 - active.start_memory
  end
  if used() > active.limits.memory then
    collectgarbage()
    if used() > active.limits.memory then
      return stop("memory")
    end
  end
end
local check
check = function()
  if not (active) then
    return 
  end
  if coroutine.running() == active.host then
    return 
  end
  if active.signal then
    error(active.signal, 0)
  end
  active.instructions = active.instructions + CHECK_INTERVAL
  if active.soft_limit and active.instructions > active.soft_limit then
    error(OVER_BUDGET, 0)
  end
  local instructions, seconds
  do
    local _obj_0 = active.limits
    instructions, seconds = _obj_0.instructions, _obj_0.seconds
  end
  if instructions and active.instructions > instructions then
    stop("instructions")
  end
  if seconds and os.clock() - active.start_time > seconds then
    stop("time")
  end
  return check_memory()
end
local hook_coroutine
hook_coroutine = function(co)
  if active and not jit and type(co) == 'thread' then
    return debug.sethook(co, check, "", CHECK_INTERVAL)
  end
end
local keep_stopping
keep_stopping = function(...)
  if active and active.signal then
    error(active.signal, 0)
  end
  return ...
end
local limited_pcall
limited_pcall = function(...)
  return keep_stopping(pcall(...))
end
local limited_xpcall
limited_xpcall = function(...)
  return keep_stopping(xpcall(...))
end
local limited_resume
limited_resume = function(co, ...)
  hook_coroutine(co)
  return keep_stopping(coroutine.resume(co, ...))
end
local limited_wrap
limited_wrap = function(fn)
  local co = coroutine.create(fn)
  local finish
  finish = function(ok, ...)
    if not (ok) then
      error((...), 0)
    end
    return ...
  end
  return function(...)
    return finish(limited_resume(co, ...))
  end
end
local string_rep = string.rep
local limited_rep
limited_rep = function(s, n, sep)
  if active and type(n) == 'number' then
    check_memory(#tostring(s) * n + (sep and #tostring(sep) * n or 0))
  end
  return string_rep(s, n, sep)
end
local buffer_strings_are_counted
do
  local before = collectgarbage("count")
  local s = string_rep("x", 100000)
  buffer_strings_are_counted = collectgarbage("count") - before > 50
end
local PATTERN_BUDGET = 1e8
local log = math.log
local count_quantifiers
count_quantifiers = function(patt)
  local n = 0
  local i, len = 1, #patt
  local in_class = false
  while i <= len do
    local _continue_0 = false
    repeat
      local c = string.sub(patt, i, i)
      if c == '%' then
        i = i + 2
        _continue_0 = true
        break
      end
      if in_class then
        if c == ']' then
          in_class = false
        end
      elseif c == '[' then
        in_class = true
      elseif c == '*' or c == '+' or c == '-' then
        n = n + 1
      end
      i = i + 1
      _continue_0 = true
    until true
    if not _continue_0 then
      break
    end
  end
  return n
end
local check_pattern
check_pattern = function(subject, patt, plain)
  if not (active) then
    return 
  end
  if plain then
    return 
  end
  local q = count_quantifiers(tostring(patt))
  if q < 2 then
    return 
  end
  local subject_length = #tostring(subject)
  if subject_length < 2 then
    return 
  end
  if q * log(subject_length) > log(PATTERN_BUDGET) then
    return stop("instructions")
  end
end
local checking_memory_after
checking_memory_after = function(fn)
  local after
  after = function(...)
    if active and active.limits.memory then
      local extra_bytes = 0
      if not (buffer_strings_are_counted) then
        for i = 1, select("#", ...) do
          local value = select(i, ...)
          if type(value) == 'string' then
            extra_bytes = extra_bytes + #value
          end
        end
      end
      check_memory(extra_bytes)
    end
    return ...
  end
  return function(...)
    return after(fn(...))
  end
end
local checking_pattern
checking_pattern = function(fn)
  return function(s, patt, ...)
    check_pattern(s, patt)
    return fn(s, patt, ...)
  end
end
local checking_find_pattern
checking_find_pattern = function(fn)
  return function(s, patt, init, plain, ...)
    check_pattern(s, patt, plain)
    return fn(s, patt, init, plain, ...)
  end
end
local _list_0 = {
  "matches",
  "matching",
  "matching_groups",
  "all_matches_of",
  "split",
  "isplit"
}
for _index_0 = 1, #_list_0 do
  local name = _list_0[_index_0]
  Text[name] = checking_pattern(Text[name])
end
local _list_1 = {
  "position_of",
  "position_of_1_after"
}
for _index_0 = 1, #_list_1 do
  local name = _list_1[_index_0]
  Text[name] = checking_find_pattern(Text[name])
end
local with_replacement = Text.as_lua_id("with 1 ->")
Text[with_replacement] = checking_memory_after(checking_pattern(Text[with_replacement]))
Text.rep = limited_rep
Text.gsub = checking_memory_after(Text.gsub)
Text.format = checking_memory_after(Text.format)
local limited_string_library
limited_string_library = function()
  local lib
  do
    local _tbl_0 = { }
    for k, v in pairs(string) do
      if k ~= "dump" then
        _tbl_0[k] = v
      end
    end
    lib = _tbl_0
  end
  lib.match, lib.gmatch = checking_pattern(string.match), checking_pattern(string.gmatch)
  lib.find = checking_find_pattern(string.find)
  lib.gsub = checking_memory_after(checking_pattern(string.gsub))
  lib.rep, lib.format = limited_rep, Text.format
  return lib
end
local run_limited
run_limited = function(limits, fn, ...)
  if active or not limits then
    return fn(...)
  end
  active = {
    limits = limits,
    instructions = 0,
    start_time = os.clock(),
    start_memory = collectgarbage("count"),
    host = coroutine.running()
  }
  local co = coroutine.create(fn)
  local jit_was_on, old_hook
  if jit then
    jit_was_on = jit.status()
    jit.off()
    old_hook = {
      debug.gethook()
    }
    debug.sethook(check, "", CHECK_INTERVAL)
  else
    debug.sethook(co, check, "", CHECK_INTERVAL)
  end
  local results = {
    n = 0
  }
  local collect
  collect = function(...)
    results = {
      n = select("#", ...),
      ...
    }
  end
  collect(coroutine.resume(co, ...))
  local signal = active.signal
  active = nil
  if jit then
    if old_hook[1] then
      debug.sethook(unpack(old_hook))
    else
      debug.sethook()
    end
    if jit_was_on then
      jit.on()
    end
  end
  if signal then
    return false, signal
  end
  if not (results[1]) then
    error(results[2], 0)
  end
  if coroutine.status(co) ~= "dead" then
    error("Code can't yield outside of a coroutine.", 0)
  end
  return unpack(results, 2, results.n)
end
local run_unlimited
run_unlimited = function(fn, ...)
  local outer = active
  active = nil
  local finish
  finish = function(ok, ...)
    active = outer
    if not (ok) then
      error((...), 0)
    end
    return ...
  end
  return finish(pcall(fn, ...))
end
local remaining_instructions
remaining_instructions = function()
  local limit = active and active.limits.instructions
  return limit and limit - active.instructions or math.huge
end
local try_with_budget
try_with_budget = function(budget, fn, ...)
  local outer = active and active.soft_limit
  if active then
    active.soft_limit = math.min(outer or math.huge, active.instructions + budget)
  end
  local finish
  finish = function(ok, ...)
    if active then
      active.soft_limit = outer
    end
    if not ok and (...) == OVER_BUDGET then
      return false
    end
    if not (ok) then
      error((...), 0)
    end
    return true, ...
  end
  return finish(pcall(fn, ...))
end
return {
  run_limited = run_limited,
  run_unlimited = run_unlimited,
  try_with_budget = try_with_budget,
  remaining_instructions = remaining_instructions,
  checking_memory_after = checking_memory_after,
  limited_string_library = limited_string_library,
  pcall = limited_pcall,
  xpcall = limited_xpcall,
  resume = limited_resume,
  wrap = limited_wrap
}