Improve lua build process + folder structure
This commit is contained in:
7
lua/src/auth.d.tl
Normal file
7
lua/src/auth.d.tl
Normal file
@@ -0,0 +1,7 @@
|
||||
local record Auth
|
||||
id: string
|
||||
token: string
|
||||
server: string
|
||||
end
|
||||
|
||||
return Auth
|
||||
139
lua/src/lib/framebuffer.tl
Normal file
139
lua/src/lib/framebuffer.tl
Normal file
@@ -0,0 +1,139 @@
|
||||
local record ScreenContent
|
||||
x: integer
|
||||
y: integer
|
||||
width: integer
|
||||
height: integer
|
||||
blink: boolean
|
||||
fg: integer
|
||||
text: {string}
|
||||
fg_color: {string}
|
||||
bg_color: {string}
|
||||
palette: {integer}
|
||||
end
|
||||
|
||||
local record Buffer
|
||||
target: term.Redirect
|
||||
serialize: function(): ScreenContent
|
||||
is_dirty: function(): boolean
|
||||
clear_dirty: function()
|
||||
end
|
||||
|
||||
local COLOR_LOOKUP <const> : {number: integer} = {
|
||||
[colors.white] = 0x0,
|
||||
[colors.orange] = 0x1,
|
||||
[colors.magenta] = 0x2,
|
||||
[colors.lightBlue] = 0x3,
|
||||
[colors.yellow] = 0x4,
|
||||
[colors.lime] = 0x5,
|
||||
[colors.pink] = 0x6,
|
||||
[colors.gray] = 0x7,
|
||||
[colors.lightGray] = 0x8,
|
||||
[colors.cyan] = 0x9,
|
||||
[colors.purple] = 0xA,
|
||||
[colors.blue] = 0xB,
|
||||
[colors.brown] = 0xC,
|
||||
[colors.green] = 0xD,
|
||||
[colors.red] = 0xE,
|
||||
[colors.black] = 0xF,
|
||||
}
|
||||
|
||||
local function wrap(parent: term.Redirect): Buffer
|
||||
local x, y = parent.getCursorPos()
|
||||
local width, height = parent.getSize()
|
||||
local blink = parent.getCursorBlink()
|
||||
local fg = COLOR_LOOKUP[parent.getTextColor()]
|
||||
local palette: {number} = {}
|
||||
for c = 0, 15 do
|
||||
palette[c+1] = colors.packRGB(parent.getPaletteColor(2^c))
|
||||
end
|
||||
local dirty: boolean = false
|
||||
|
||||
local win = window.create(parent, 1, 1, width, height)
|
||||
|
||||
local overrides: table = {}
|
||||
|
||||
overrides.setCursorPos = function(new_x: integer, new_y: integer)
|
||||
win.setCursorPos(new_x, new_y)
|
||||
x = new_x
|
||||
y = new_y
|
||||
end
|
||||
|
||||
overrides.setCursorBlink = function(new_blink: boolean)
|
||||
win.setCursorBlink(new_blink)
|
||||
blink = new_blink
|
||||
end
|
||||
|
||||
overrides.setTextColor = function(new_color: number)
|
||||
local r = { pcall(win.setTextColor, new_color) }
|
||||
if not r[1] then
|
||||
error((r[2] as string):sub(8))
|
||||
end
|
||||
fg = COLOR_LOOKUP[new_color]
|
||||
end
|
||||
overrides.setTextColour = overrides.setTextColor
|
||||
|
||||
overrides.setPaletteColor = function(color: number, r_rgb: number, g: number | nil, b: number | nil)
|
||||
local r = { pcall(win.setPaletteColor, color, r_rgb, g, b) }
|
||||
if not r[1] then
|
||||
error((r[2] as string):sub(8))
|
||||
end
|
||||
local index = COLOR_LOOKUP[color]
|
||||
if g == nil then
|
||||
palette[1 + index] = r_rgb
|
||||
else
|
||||
palette[1 + index] = colors.packRGB(r_rgb, g, b)
|
||||
end
|
||||
end
|
||||
overrides.setPaletteColour = overrides.setPaletteColor
|
||||
|
||||
local target = setmetatable(overrides, {
|
||||
__index = function(_: table, k: any): any
|
||||
dirty = true
|
||||
return (win as table)[k]
|
||||
end
|
||||
}) as term.Redirect
|
||||
|
||||
target.setTextColor(colors.white)
|
||||
target.setBackgroundColor(colors.black)
|
||||
target.setCursorPos(1,1)
|
||||
target.clear()
|
||||
|
||||
local buffer: Buffer = {
|
||||
target = target
|
||||
}
|
||||
|
||||
buffer.serialize = function(): ScreenContent
|
||||
local text: {string} = {}
|
||||
local fg_color: {string} = {}
|
||||
local bg_color: {string} = {}
|
||||
for i = 1, height do
|
||||
local t, f, b = win.getLine(i)
|
||||
table.insert(text, t)
|
||||
table.insert(fg_color, f)
|
||||
table.insert(bg_color, b)
|
||||
end
|
||||
return {
|
||||
x = x,
|
||||
y = y,
|
||||
width = width,
|
||||
height = height,
|
||||
blink = blink,
|
||||
fg = fg,
|
||||
text = text,
|
||||
fg_color = fg_color,
|
||||
bg_color = bg_color,
|
||||
palette = palette
|
||||
}
|
||||
end
|
||||
|
||||
buffer.is_dirty = function(): boolean
|
||||
return dirty
|
||||
end
|
||||
|
||||
buffer.clear_dirty = function() dirty = false end
|
||||
|
||||
return buffer
|
||||
|
||||
end
|
||||
|
||||
return { wrap = wrap, Buffer = Buffer, ScreenContent = ScreenContent }
|
||||
42
lua/src/lib/ringbuffer.tl
Normal file
42
lua/src/lib/ringbuffer.tl
Normal file
@@ -0,0 +1,42 @@
|
||||
local record Ringbuffer<T>
|
||||
{T}
|
||||
push: function(self: Ringbuffer<T>, el: T): boolean
|
||||
pop: function(self: Ringbuffer<T>): T | nil
|
||||
is_empty: function(self: Ringbuffer<T>): boolean
|
||||
|
||||
head: integer
|
||||
n: integer
|
||||
size: integer
|
||||
end
|
||||
|
||||
local impl: table = {}
|
||||
|
||||
impl.push = function<T>(self: Ringbuffer<T>, el: T): boolean
|
||||
if self.n == self.size then return false end
|
||||
-- items are at head + 0, head + 1, ..., head + (n-1)
|
||||
local tail = (self.head + self.n) % self.size
|
||||
self[1 + tail] = el
|
||||
self.n = self.n + 1
|
||||
return true
|
||||
end
|
||||
|
||||
impl.pop = function<T>(self: Ringbuffer<T>): T | nil
|
||||
if self.n == 0 then return nil end
|
||||
local res = self[1 + self.head]
|
||||
self.head = (self.head + 1) % self.size
|
||||
self.n = self.n - 1
|
||||
return res
|
||||
end
|
||||
|
||||
impl.is_empty = function<T>(self: Ringbuffer<T>): boolean
|
||||
return self.n == 0
|
||||
end
|
||||
|
||||
local function new<T>(size: integer): Ringbuffer<T>
|
||||
return setmetatable({ head = 0, n = 0, size = size }, { __index = impl })
|
||||
end
|
||||
|
||||
return {
|
||||
new = new,
|
||||
Ringbuffer = Ringbuffer
|
||||
}
|
||||
94
lua/src/lib/socket.tl
Normal file
94
lua/src/lib/socket.tl
Normal file
@@ -0,0 +1,94 @@
|
||||
local enum State
|
||||
"reset"
|
||||
"error"
|
||||
"ok"
|
||||
"viewer_connected"
|
||||
end
|
||||
|
||||
local BAD_STATES <const> : {State: boolean} = {
|
||||
["reset"] = true,
|
||||
["error"] = true,
|
||||
}
|
||||
|
||||
local type StateCallback = function(new_state: State)
|
||||
|
||||
local record Socket
|
||||
state: State
|
||||
is_bad_state: function(self: Socket): boolean
|
||||
_set_state: function(self: Socket, state: State)
|
||||
on_state_change: function(self: Socket, cb: StateCallback)
|
||||
send: function(self: Socket, message: string)
|
||||
reconnect: function(self: Socket)
|
||||
close: function(self: Socket)
|
||||
signal_viewer_connect: function(self: Socket, connected: boolean)
|
||||
_endpoint: string
|
||||
_headers: {string: string}
|
||||
_callback: StateCallback
|
||||
_ws: http.Websocket
|
||||
end
|
||||
|
||||
local impl: table = {}
|
||||
|
||||
impl.is_bad_state = function(self: Socket): boolean
|
||||
return BAD_STATES[self.state] ~= nil
|
||||
end
|
||||
|
||||
impl._set_state = function(self: Socket, state: State)
|
||||
self.state = state
|
||||
self._callback(state)
|
||||
end
|
||||
|
||||
impl.on_state_change = function(self: Socket, cb: StateCallback)
|
||||
self._callback = cb
|
||||
end
|
||||
|
||||
impl.send = function(self: Socket, message: string)
|
||||
-- "message" needs to be valid JSON
|
||||
-- otherwise the server will not accept it
|
||||
|
||||
if self:is_bad_state() then return end
|
||||
|
||||
local r = { pcall(self._ws.send, message) }
|
||||
|
||||
if r[1] == false then
|
||||
if (r[2] as string):sub(-11) == "closed file" then
|
||||
self:_set_state("reset")
|
||||
elseif (r[2] as string):sub(-9) == "too large" then
|
||||
-- TODO handle
|
||||
-- the connection stays open though
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
impl.reconnect = function(self: Socket)
|
||||
local r = http.websocket(self._endpoint, self._headers)
|
||||
if r ~= false then
|
||||
self._ws = r as http.Websocket
|
||||
self:_set_state("ok")
|
||||
else
|
||||
self:_set_state("error")
|
||||
end
|
||||
end
|
||||
|
||||
impl.close = function(self: Socket)
|
||||
if self:is_bad_state() then return end
|
||||
self._ws.close()
|
||||
end
|
||||
|
||||
impl.signal_viewer_connect = function(self: Socket, connected: boolean)
|
||||
if self:is_bad_state() then return end --how?
|
||||
local new_state: State = connected and "viewer_connected" or "ok"
|
||||
self:_set_state(new_state)
|
||||
end
|
||||
|
||||
local function new(endpoint: string, headers: {string: string}): Socket
|
||||
return setmetatable({
|
||||
state = "reset",
|
||||
_endpoint = endpoint,
|
||||
_headers = headers,
|
||||
_callback = function(_: State) end,
|
||||
_ws = nil,
|
||||
}, { __index = impl })
|
||||
end
|
||||
|
||||
return { new = new, State = State, StateCallback = StateCallback, Socket = Socket }
|
||||
165
lua/src/main.tl
Normal file
165
lua/src/main.tl
Normal file
@@ -0,0 +1,165 @@
|
||||
local json = require("vendor/json")
|
||||
local Framebuffer = require("lib/framebuffer")
|
||||
local Ringbuffer = require("lib/ringbuffer")
|
||||
local Socket = require("lib/socket")
|
||||
local auth = require("auth")
|
||||
local ENDPOINT <const> = auth.server:gsub("http", "ws", 1) .. "/ipmi/computer/" .. auth.id .. "/ws"
|
||||
local HEADERS <const> = { ["Authorization"] = "Bearer " .. auth.token }
|
||||
|
||||
print("[MAIN] Init")
|
||||
|
||||
local socket = Socket.new(ENDPOINT, HEADERS)
|
||||
|
||||
-- Set up framebuffer capture and statusline
|
||||
|
||||
print("[MAIN] Setup framebuffer")
|
||||
|
||||
local prev_term = term.current()
|
||||
local orig_native = term.native
|
||||
local buffer = Framebuffer.wrap(orig_native())
|
||||
term.native = function(): term.Redirect
|
||||
return buffer.target
|
||||
end
|
||||
|
||||
local width, height = term.getSize()
|
||||
local top_line = window.create(buffer.target, 1, 1, width, 1)
|
||||
local main_view = window.create(buffer.target, 1, 2, width, height - 1)
|
||||
term.redirect(main_view as term.Redirect)
|
||||
|
||||
local function set_bar(text: string, fg: string | nil, bg: string | nil)
|
||||
fg = fg or ("9"):rep(text:len())
|
||||
bg = bg or ("f"):rep(text:len())
|
||||
top_line.clear()
|
||||
top_line.setCursorPos(1,1)
|
||||
top_line.blit(text, fg, bg)
|
||||
main_view.restoreCursor()
|
||||
end
|
||||
|
||||
-- Create tasks
|
||||
|
||||
local bar_codes: { Socket.State: {string} } = {
|
||||
["reset"] = {"[WS] RST", "78870111"},
|
||||
["error"] = {"[WS] ERR", "78870EEE"},
|
||||
["ok"] = {"[WS] OK\x03", "78870DD5"},
|
||||
["viewer_connected"] = {"[WS] CON", "78870999"},
|
||||
}
|
||||
|
||||
socket:on_state_change(function(new_state: Socket.State)
|
||||
set_bar(table.unpack(bar_codes[new_state]))
|
||||
end)
|
||||
|
||||
local ws_task = coroutine.create(function()
|
||||
while true do
|
||||
if socket:is_bad_state() then
|
||||
socket:reconnect()
|
||||
end
|
||||
sleep(1)
|
||||
end
|
||||
end)
|
||||
|
||||
local report_task = coroutine.create(function()
|
||||
local last_report = -1.0
|
||||
while true do
|
||||
local now = os.clock()
|
||||
local interval = (socket.state == "viewer_connected") and 0.05 or 1
|
||||
if now - last_report >= interval then
|
||||
local message = json.encode({
|
||||
screen = buffer.serialize()
|
||||
})
|
||||
socket:send(message)
|
||||
last_report = now
|
||||
end
|
||||
sleep(0) -- until next gametick
|
||||
end
|
||||
end)
|
||||
|
||||
-- basically parallel.waitForAny
|
||||
|
||||
local record Task
|
||||
coro: thread
|
||||
filter: string | nil
|
||||
end
|
||||
|
||||
local background_tasks: {Task} = {
|
||||
{coro = ws_task},
|
||||
{coro = report_task},
|
||||
}
|
||||
|
||||
local shell_task: Task = {
|
||||
coro = coroutine.create(function() shell.run("shell") end)
|
||||
}
|
||||
|
||||
local function handle_event(e: table, pid: integer)
|
||||
if e[1] == "terminate" then return end
|
||||
|
||||
local task = background_tasks[pid]
|
||||
if task.filter == nil or task.filter == e[1] then
|
||||
local ok, param = coroutine.resume(task.coro, table.unpack(e as {any}))
|
||||
if not ok then
|
||||
term.native = orig_native
|
||||
term.redirect(term.native())
|
||||
term.clear()
|
||||
term.setCursorPos(1,1)
|
||||
print(("OMEGABIG OOF @ PID %d"):format(pid))
|
||||
error(param, 0)
|
||||
else
|
||||
task.filter = param as string
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local event_queue: Ringbuffer.Ringbuffer<table> = Ringbuffer.new(64)
|
||||
event_queue:push({n = 0})
|
||||
|
||||
local shell_deaths: {any} = {}
|
||||
|
||||
local shell_running = true
|
||||
while shell_running do
|
||||
local e: table
|
||||
|
||||
if not event_queue:is_empty() then
|
||||
e = event_queue:pop() as table
|
||||
else
|
||||
e = table.pack(os.pullEventRaw())
|
||||
end
|
||||
|
||||
if e[1] == "websocket_message" and e[2] == ENDPOINT then
|
||||
local payload = json.decode(e[3] as string) as table
|
||||
if payload["type"] == "push_event" then
|
||||
event_queue:push(payload["event"] as table)
|
||||
elseif payload["type"] == "viewer_connect" then
|
||||
socket:signal_viewer_connect(true)
|
||||
elseif payload["type"] == "viewer_disconnect" then
|
||||
socket:signal_viewer_connect(false)
|
||||
end
|
||||
else
|
||||
for pid = 1, #background_tasks do
|
||||
handle_event(e, pid)
|
||||
end
|
||||
|
||||
if shell_task.filter == nil or shell_task.filter == e[1] or e[1] == "terminate" then
|
||||
local ok, param = coroutine.resume(shell_task.coro, table.unpack(e as {any}))
|
||||
if not ok then
|
||||
-- shell died i guess?
|
||||
table.insert(shell_deaths, param)
|
||||
else
|
||||
shell_task.filter = param as string
|
||||
end
|
||||
end
|
||||
|
||||
if coroutine.status(shell_task.coro) == "dead" then
|
||||
shell_running = false
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
socket:close()
|
||||
|
||||
term.native = orig_native
|
||||
term.redirect(prev_term)
|
||||
term.clear()
|
||||
term.setCursorPos(1,1)
|
||||
|
||||
for i = 1, #shell_deaths do
|
||||
print(shell_deaths[i])
|
||||
end
|
||||
6
lua/src/vendor/json.d.tl
vendored
Normal file
6
lua/src/vendor/json.d.tl
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
local record Json
|
||||
encode: function(value: any): string
|
||||
decode: function(str: string): any
|
||||
end
|
||||
|
||||
return Json
|
||||
388
lua/src/vendor/json.lua
vendored
Normal file
388
lua/src/vendor/json.lua
vendored
Normal file
@@ -0,0 +1,388 @@
|
||||
--
|
||||
-- json.lua
|
||||
--
|
||||
-- Copyright (c) 2020 rxi
|
||||
--
|
||||
-- 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.
|
||||
--
|
||||
|
||||
local json = { _version = "0.1.2" }
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
-- Encode
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
local encode
|
||||
|
||||
local escape_char_map = {
|
||||
[ "\\" ] = "\\",
|
||||
[ "\"" ] = "\"",
|
||||
[ "\b" ] = "b",
|
||||
[ "\f" ] = "f",
|
||||
[ "\n" ] = "n",
|
||||
[ "\r" ] = "r",
|
||||
[ "\t" ] = "t",
|
||||
}
|
||||
|
||||
local escape_char_map_inv = { [ "/" ] = "/" }
|
||||
for k, v in pairs(escape_char_map) do
|
||||
escape_char_map_inv[v] = k
|
||||
end
|
||||
|
||||
|
||||
local function escape_char(c)
|
||||
return "\\" .. (escape_char_map[c] or string.format("u%04x", c:byte()))
|
||||
end
|
||||
|
||||
|
||||
local function encode_nil(val)
|
||||
return "null"
|
||||
end
|
||||
|
||||
|
||||
local function encode_table(val, stack)
|
||||
local res = {}
|
||||
stack = stack or {}
|
||||
|
||||
-- Circular reference?
|
||||
if stack[val] then error("circular reference") end
|
||||
|
||||
stack[val] = true
|
||||
|
||||
if rawget(val, 1) ~= nil or next(val) == nil then
|
||||
-- Treat as array -- check keys are valid and it is not sparse
|
||||
local n = 0
|
||||
for k in pairs(val) do
|
||||
if type(k) ~= "number" then
|
||||
error("invalid table: mixed or invalid key types")
|
||||
end
|
||||
n = n + 1
|
||||
end
|
||||
if n ~= #val then
|
||||
error("invalid table: sparse array")
|
||||
end
|
||||
-- Encode
|
||||
for i, v in ipairs(val) do
|
||||
table.insert(res, encode(v, stack))
|
||||
end
|
||||
stack[val] = nil
|
||||
return "[" .. table.concat(res, ",") .. "]"
|
||||
|
||||
else
|
||||
-- Treat as an object
|
||||
for k, v in pairs(val) do
|
||||
if type(k) ~= "string" then
|
||||
error("invalid table: mixed or invalid key types")
|
||||
end
|
||||
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
|
||||
end
|
||||
stack[val] = nil
|
||||
return "{" .. table.concat(res, ",") .. "}"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
local function encode_string(val)
|
||||
return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
|
||||
end
|
||||
|
||||
|
||||
local function encode_number(val)
|
||||
-- Check for NaN, -inf and inf
|
||||
if val ~= val or val <= -math.huge or val >= math.huge then
|
||||
error("unexpected number value '" .. tostring(val) .. "'")
|
||||
end
|
||||
return string.format("%.14g", val)
|
||||
end
|
||||
|
||||
|
||||
local type_func_map = {
|
||||
[ "nil" ] = encode_nil,
|
||||
[ "table" ] = encode_table,
|
||||
[ "string" ] = encode_string,
|
||||
[ "number" ] = encode_number,
|
||||
[ "boolean" ] = tostring,
|
||||
}
|
||||
|
||||
|
||||
encode = function(val, stack)
|
||||
local t = type(val)
|
||||
local f = type_func_map[t]
|
||||
if f then
|
||||
return f(val, stack)
|
||||
end
|
||||
error("unexpected type '" .. t .. "'")
|
||||
end
|
||||
|
||||
|
||||
function json.encode(val)
|
||||
return ( encode(val) )
|
||||
end
|
||||
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
-- Decode
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
local parse
|
||||
|
||||
local function create_set(...)
|
||||
local res = {}
|
||||
for i = 1, select("#", ...) do
|
||||
res[ select(i, ...) ] = true
|
||||
end
|
||||
return res
|
||||
end
|
||||
|
||||
local space_chars = create_set(" ", "\t", "\r", "\n")
|
||||
local delim_chars = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
|
||||
local escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
|
||||
local literals = create_set("true", "false", "null")
|
||||
|
||||
local literal_map = {
|
||||
[ "true" ] = true,
|
||||
[ "false" ] = false,
|
||||
[ "null" ] = nil,
|
||||
}
|
||||
|
||||
|
||||
local function next_char(str, idx, set, negate)
|
||||
for i = idx, #str do
|
||||
if set[str:sub(i, i)] ~= negate then
|
||||
return i
|
||||
end
|
||||
end
|
||||
return #str + 1
|
||||
end
|
||||
|
||||
|
||||
local function decode_error(str, idx, msg)
|
||||
local line_count = 1
|
||||
local col_count = 1
|
||||
for i = 1, idx - 1 do
|
||||
col_count = col_count + 1
|
||||
if str:sub(i, i) == "\n" then
|
||||
line_count = line_count + 1
|
||||
col_count = 1
|
||||
end
|
||||
end
|
||||
error( string.format("%s at line %d col %d", msg, line_count, col_count) )
|
||||
end
|
||||
|
||||
|
||||
local function codepoint_to_utf8(n)
|
||||
-- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
|
||||
local f = math.floor
|
||||
if n <= 0x7f then
|
||||
return string.char(n)
|
||||
elseif n <= 0x7ff then
|
||||
return string.char(f(n / 64) + 192, n % 64 + 128)
|
||||
elseif n <= 0xffff then
|
||||
return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)
|
||||
elseif n <= 0x10ffff then
|
||||
return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,
|
||||
f(n % 4096 / 64) + 128, n % 64 + 128)
|
||||
end
|
||||
error( string.format("invalid unicode codepoint '%x'", n) )
|
||||
end
|
||||
|
||||
|
||||
local function parse_unicode_escape(s)
|
||||
local n1 = tonumber( s:sub(1, 4), 16 )
|
||||
local n2 = tonumber( s:sub(7, 10), 16 )
|
||||
-- Surrogate pair?
|
||||
if n2 then
|
||||
return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)
|
||||
else
|
||||
return codepoint_to_utf8(n1)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
local function parse_string(str, i)
|
||||
local res = ""
|
||||
local j = i + 1
|
||||
local k = j
|
||||
|
||||
while j <= #str do
|
||||
local x = str:byte(j)
|
||||
|
||||
if x < 32 then
|
||||
decode_error(str, j, "control character in string")
|
||||
|
||||
elseif x == 92 then -- `\`: Escape
|
||||
res = res .. str:sub(k, j - 1)
|
||||
j = j + 1
|
||||
local c = str:sub(j, j)
|
||||
if c == "u" then
|
||||
local hex = str:match("^[dD][89aAbB]%x%x\\u%x%x%x%x", j + 1)
|
||||
or str:match("^%x%x%x%x", j + 1)
|
||||
or decode_error(str, j - 1, "invalid unicode escape in string")
|
||||
res = res .. parse_unicode_escape(hex)
|
||||
j = j + #hex
|
||||
else
|
||||
if not escape_chars[c] then
|
||||
decode_error(str, j - 1, "invalid escape char '" .. c .. "' in string")
|
||||
end
|
||||
res = res .. escape_char_map_inv[c]
|
||||
end
|
||||
k = j + 1
|
||||
|
||||
elseif x == 34 then -- `"`: End of string
|
||||
res = res .. str:sub(k, j - 1)
|
||||
return res, j + 1
|
||||
end
|
||||
|
||||
j = j + 1
|
||||
end
|
||||
|
||||
decode_error(str, i, "expected closing quote for string")
|
||||
end
|
||||
|
||||
|
||||
local function parse_number(str, i)
|
||||
local x = next_char(str, i, delim_chars)
|
||||
local s = str:sub(i, x - 1)
|
||||
local n = tonumber(s)
|
||||
if not n then
|
||||
decode_error(str, i, "invalid number '" .. s .. "'")
|
||||
end
|
||||
return n, x
|
||||
end
|
||||
|
||||
|
||||
local function parse_literal(str, i)
|
||||
local x = next_char(str, i, delim_chars)
|
||||
local word = str:sub(i, x - 1)
|
||||
if not literals[word] then
|
||||
decode_error(str, i, "invalid literal '" .. word .. "'")
|
||||
end
|
||||
return literal_map[word], x
|
||||
end
|
||||
|
||||
|
||||
local function parse_array(str, i)
|
||||
local res = {}
|
||||
local n = 1
|
||||
i = i + 1
|
||||
while 1 do
|
||||
local x
|
||||
i = next_char(str, i, space_chars, true)
|
||||
-- Empty / end of array?
|
||||
if str:sub(i, i) == "]" then
|
||||
i = i + 1
|
||||
break
|
||||
end
|
||||
-- Read token
|
||||
x, i = parse(str, i)
|
||||
res[n] = x
|
||||
n = n + 1
|
||||
-- Next token
|
||||
i = next_char(str, i, space_chars, true)
|
||||
local chr = str:sub(i, i)
|
||||
i = i + 1
|
||||
if chr == "]" then break end
|
||||
if chr ~= "," then decode_error(str, i, "expected ']' or ','") end
|
||||
end
|
||||
return res, i
|
||||
end
|
||||
|
||||
|
||||
local function parse_object(str, i)
|
||||
local res = {}
|
||||
i = i + 1
|
||||
while 1 do
|
||||
local key, val
|
||||
i = next_char(str, i, space_chars, true)
|
||||
-- Empty / end of object?
|
||||
if str:sub(i, i) == "}" then
|
||||
i = i + 1
|
||||
break
|
||||
end
|
||||
-- Read key
|
||||
if str:sub(i, i) ~= '"' then
|
||||
decode_error(str, i, "expected string for key")
|
||||
end
|
||||
key, i = parse(str, i)
|
||||
-- Read ':' delimiter
|
||||
i = next_char(str, i, space_chars, true)
|
||||
if str:sub(i, i) ~= ":" then
|
||||
decode_error(str, i, "expected ':' after key")
|
||||
end
|
||||
i = next_char(str, i + 1, space_chars, true)
|
||||
-- Read value
|
||||
val, i = parse(str, i)
|
||||
-- Set
|
||||
res[key] = val
|
||||
-- Next token
|
||||
i = next_char(str, i, space_chars, true)
|
||||
local chr = str:sub(i, i)
|
||||
i = i + 1
|
||||
if chr == "}" then break end
|
||||
if chr ~= "," then decode_error(str, i, "expected '}' or ','") end
|
||||
end
|
||||
return res, i
|
||||
end
|
||||
|
||||
|
||||
local char_func_map = {
|
||||
[ '"' ] = parse_string,
|
||||
[ "0" ] = parse_number,
|
||||
[ "1" ] = parse_number,
|
||||
[ "2" ] = parse_number,
|
||||
[ "3" ] = parse_number,
|
||||
[ "4" ] = parse_number,
|
||||
[ "5" ] = parse_number,
|
||||
[ "6" ] = parse_number,
|
||||
[ "7" ] = parse_number,
|
||||
[ "8" ] = parse_number,
|
||||
[ "9" ] = parse_number,
|
||||
[ "-" ] = parse_number,
|
||||
[ "t" ] = parse_literal,
|
||||
[ "f" ] = parse_literal,
|
||||
[ "n" ] = parse_literal,
|
||||
[ "[" ] = parse_array,
|
||||
[ "{" ] = parse_object,
|
||||
}
|
||||
|
||||
|
||||
parse = function(str, idx)
|
||||
local chr = str:sub(idx, idx)
|
||||
local f = char_func_map[chr]
|
||||
if f then
|
||||
return f(str, idx)
|
||||
end
|
||||
decode_error(str, idx, "unexpected character '" .. chr .. "'")
|
||||
end
|
||||
|
||||
|
||||
function json.decode(str)
|
||||
if type(str) ~= "string" then
|
||||
error("expected argument of type string, got " .. type(str))
|
||||
end
|
||||
local res, idx = parse(str, next_char(str, 1, space_chars, true))
|
||||
idx = next_char(str, idx, space_chars, true)
|
||||
if idx <= #str then
|
||||
decode_error(str, idx, "trailing garbage")
|
||||
end
|
||||
return res
|
||||
end
|
||||
|
||||
|
||||
return json
|
||||
Reference in New Issue
Block a user