diff --git a/Src/Hyperion-core/data/lib/http b/Src/Hyperion-core/data/lib/http index e69de29..d313a9a 100644 --- a/Src/Hyperion-core/data/lib/http +++ b/Src/Hyperion-core/data/lib/http @@ -0,0 +1,201 @@ +--:Minify:-- +local http = {} + +local syscall = syscall + +local function parseUrl(url) + local proto, host, path = + url:match( + "^(https?://)([^/]+)(/.*)$" + ) + + if not proto then + proto, host = + url:match( + "^(https?://)([^/]+)$" + ) + + path = "/" + end + + if not proto then + return nil, "EINVAL" + end + + return host, path +end + +local function buildRequest(req) + local host, path = + parseUrl(req.url) + + if not host then + return nil, path + end + + local method = + req.method or "GET" + + local body = + req.body or "" + + local headers = + table.deepcopy( + req.headers or {} + ) + + headers.Host = + headers.Host or host + + headers.Connection = + headers.Connection or "close" + + if body ~= "" then + headers["Content-Length"] = + tostring(#body) + end + + local out = { + method .. + " " .. + path .. + " HTTP/1.1" + } + + for k, v in pairs(headers) do + out[#out + 1] = + tostring(k) .. + ": " .. + tostring(v) + end + + out[#out + 1] = "" + out[#out + 1] = body + + return table.concat(out, "\r\n") +end + +local function parseResponse(raw) + local headerEnd = + raw:find( + "\r\n\r\n", + 1, + true + ) + + if not headerEnd then + return nil, "EBADMSG" + end + + local headerPart = + raw:sub(1, headerEnd - 1) + + local body = + raw:sub(headerEnd + 4) + + local lines = {} + + for line in headerPart:gmatch("[^\r\n]+") do + lines[#lines + 1] = line + end + + local _, code, msg = + lines[1]:match( + "^(HTTP/%S+)%s+(%d+)%s*(.*)$" + ) + + local headers = {} + + for i = 2, #lines do + local k, v = + lines[i]:match( + "^([^:]+):%s*(.*)$" + ) + + if k then + headers[k:lower()] = v + end + end + + return { + code = tonumber(code), + message = msg, + headers = headers, + body = body + } +end + +local function readAll(fd) + local out = "" + + while true do + local chunk = + syscall.read(fd, 4096) + + if not chunk or chunk == "" then + break + end + + out = out .. chunk + end + + return out +end + +function http.request(req) + local raw, err = + buildRequest(req) + + if not raw then + return nil, err + end + + local fd = + syscall.socket(0, 0) + + if not fd then + return nil, "ESOCKET" + end + + local ok, err = + syscall.connect(fd, req.url) + + if not ok then + syscall.close(fd) + return nil, err + end + + local ok2, err2 = + syscall.write(fd, raw) + + if not ok2 then + syscall.close(fd) + return nil, err2 + end + + local resp = + readAll(fd) + + syscall.close(fd) + + return parseResponse(resp) +end + +function http.get(url, headers) + return http.request({ + url = url, + method = "GET", + headers = headers + }) +end + +function http.post(url, body, headers) + return http.request({ + url = url, + method = "POST", + body = body, + headers = headers + }) +end + +return http \ No newline at end of file diff --git a/Src/Hyperion-firmware-cct/data/boot/cct/initdisks b/Src/Hyperion-firmware-cct/data/boot/cct/initdisks index 1480a0b..84d1ffb 100644 --- a/Src/Hyperion-firmware-cct/data/boot/cct/initdisks +++ b/Src/Hyperion-firmware-cct/data/boot/cct/initdisks @@ -258,7 +258,7 @@ local function refresh() end end end - + local function iter() refresh() local combined = {} diff --git a/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/22_http.kmod b/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/22_http.kmod index 2e517bd..f35b515 100644 --- a/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/22_http.kmod +++ b/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/22_http.kmod @@ -1 +1,306 @@ --:Minify:-- +local kernel = ... + +local handler = {} + +local http = kernel.apis.http + +kernel.cct.httpqueue = kernel.cct.httpqueue or {} +kernel.cct.httpresponse = kernel.cct.httpresponse or {} +kernel.cct.httperror = kernel.cct.httperror or {} + +local function parseRawRequest(raw) + local sepLen = 4 + + local headerEnd = + raw:find("\r\n\r\n", 1, true) + + if not headerEnd then + headerEnd = + raw:find("\n\n", 1, true) + + sepLen = 2 + end + + local headerPart + local body = "" + + if headerEnd then + headerPart = raw:sub(1, headerEnd - 1) + body = raw:sub(headerEnd + sepLen) + else + headerPart = raw + end + + local lines = {} + + for line in headerPart:gmatch("[^\r\n]+") do + lines[#lines + 1] = line + end + + if #lines == 0 then + return nil, "EINVAL" + end + + local method, path = + lines[1]:match("^(%S+)%s+(%S+)") + + if not method or not path then + return nil, "EBADMSG" + end + + local headers = {} + + for i = 2, #lines do + local k, v = + lines[i]:match("^([^:]+):%s*(.*)$") + + if k then + headers[k] = v + end + end + + local host = headers.Host or headers.host + + if not host and not path:match("^https?://") then + return nil, "EHOSTUNREACH" + end + + local url + + if path:match("^https?://") then + url = path + else + url = "http://" .. host .. path + end + + local req = { + url = url, + method = method, + headers = headers + } + + if body ~= "" then + req.body = body + end + + return req +end + +local function buildResponse(resp) + if not resp then + return nil, "EINVAL" + end + + local code, msg = resp.getResponseCode() + + local headers = + resp:getResponseHeaders() + + local body = + resp:readAll() or "" + + local out = { + "HTTP/1.1 " .. + tostring(code) .. + " " .. + tostring(msg) + } + + local hasLength = false + + for k, v in pairs(headers or {}) do + if k:lower() == "content-length" then + hasLength = true + end + + out[#out + 1] = + tostring(k) .. + ": " .. + tostring(v) + end + + if not hasLength then + out[#out + 1] = + "Content-Length: " .. + tostring(#body) + end + + out[#out + 1] = "" + out[#out + 1] = body + + return table.concat(out, "\r\n") +end + +function handler.connect(fd, address) + local fdo = kernel.currentTask.fd[fd] + + if not fdo then + return nil, "EBADF" + end + + fdo.socket.rbuf = "" + fdo.socket.closed = false + fdo.socket.httpid = nil + + fdo.handle.write = function(raw) + local req, err = + parseRawRequest(raw) + + if not req then + return nil, err + end + + local id = + tostring(kernel.uuid()) + + fdo.socket.httpid = id + + kernel.cct.httpqueue[id] = true + + local ok, err = + http.request(req, id) + + if not ok then + kernel.cct.httpqueue[id] = nil + return nil, err + end + + return true + end + + fdo.handle.read = function(count) + count = count or 4096 + + local sock = fdo.socket + + if #sock.rbuf > 0 then + local out = + sock.rbuf:sub(1, count) + + sock.rbuf = + sock.rbuf:sub(count + 1) + + return out + end + + local id = sock.httpid + + if not id then + return "" + end + + local function finish(resp) + sock.rbuf = + buildResponse(resp) or "" + + local out = + sock.rbuf:sub(1, count) + + sock.rbuf = + sock.rbuf:sub(count + 1) + + return out + end + + if kernel.cct.httpresponse[id] then + local resp = + kernel.cct.httpresponse[id] + + kernel.cct.httpresponse[id] = nil + kernel.cct.httpqueue[id] = nil + + return finish(resp) + end + + if kernel.cct.httperror[id] then + local err = + kernel.cct.httperror[id] + + kernel.cct.httperror[id] = nil + kernel.cct.httpqueue[id] = nil + + return nil, err + end + + kernel.currentTask.status = "D" + + local coro + + coro = function() + if kernel.cct.httpresponse[id] then + local resp = + kernel.cct.httpresponse[id] + + kernel.cct.httpresponse[id] = nil + kernel.cct.httpqueue[id] = nil + + kernel.asyncReturn( + finish(resp) + ) + + return + end + + if kernel.cct.httperror[id] then + local err = + kernel.cct.httperror[id] + + kernel.cct.httperror[id] = nil + kernel.cct.httpqueue[id] = nil + + kernel.asyncReturn( + nil, + err + ) + + return + end + + coroutine.yield() + end + + kernel.currentTask.ksh = + coroutine.create(function() + local ok, err = + xpcall( + coro, + debug.traceback + ) + + if not ok then + kernel.asyncReturn( + nil, + err + ) + end + end) + end + + fdo.handle.close = function() + fdo.socket.closed = true + + local id = + fdo.socket.httpid + + if id then + kernel.cct.httpqueue[id] = nil + kernel.cct.httpresponse[id] = nil + kernel.cct.httperror[id] = nil + end + + return true + end + + return true +end + +kernel.socket.registerProtocal( + "http://", + handler +) + +kernel.socket.registerProtocal( + "https://", + handler +) \ No newline at end of file diff --git a/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/25_tty.kmod b/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/25_tty.kmod index e690425..f560b6e 100644 --- a/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/25_tty.kmod +++ b/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/25_tty.kmod @@ -223,6 +223,9 @@ local function newtty(obj, id, ev) gctrl=function() return serializeBool(kernel.cct.ctrl)..";"..serializeBool(kernel.cct.alt) end, + isvirt=function() + return false + end, gplt=function() return plt end @@ -243,8 +246,39 @@ end local fifo = kernel.newFifo() kernel.cct.fifo=fifo -newtty(kernel.apis.term, "1", fifo.pop) +newtty(kernel.apis.term, "1", function() end) for i,v in ipairs({peripheral.find("monitor")}) do newtty(v,tostring(i+1),function () end) +end + +kernel.devfs.data["input"]["keyboard1"] = function(op, mode) + if op=="type" then + return "Keyboard" + elseif op=="open" then + local h = { + read=function(amount) + local rv="" + for i=1, amount or 1 do + local event = {fifo.pop()} + if event[1] then + rv=rv..event[1] + end + end + if rv=="" then rv=nil end + return rv + end, + write=function(content) + end + } + if mode=="rw" then + return h + elseif mode=="r" then + h["write"]=nil + return h + elseif mode=="w" then + h["read"]=nil + return h + end + end end \ No newline at end of file diff --git a/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/30_deamon.kmod b/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/30_deamon.kmod index f3d4acc..551a274 100644 --- a/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/30_deamon.kmod +++ b/Src/Hyperion-firmware-cct/data/lib/modules/cc-tweaked/30_deamon.kmod @@ -4,6 +4,7 @@ local keys=kernel.apis.keys kernel.processes.cctdeamon = function() local timeout = false + kernel.log("CCT deamon started") while true do local event = {kernel.EFI:getMachineEvent()} @@ -66,6 +67,12 @@ kernel.processes.cctdeamon = function() elseif eventType == "keyTyped" then if charOrKey then kernel.cct.fifo.push(charOrKey) end + elseif eventType == "mouse_scroll" then + if event[2] == 1 then + kernel.cct.fifo.push("S") + else + kernel.cct.fifo.push("T") + end elseif eventType == "http_success" then kernel.cct.httpqueue[event[2]]=nil kernel.cct.httpresponse[event[2]]=event[3] @@ -83,4 +90,6 @@ kernel.processes.cctdeamon = function() sleep(0.05) end end -end \ No newline at end of file +end + +kernel.log("CCT deamon queued for execution") \ No newline at end of file diff --git a/Src/Hyperion-kernel/data/boot/fstab b/Src/Hyperion-kernel/data/boot/fstab index 0f7573d..cce912b 100644 --- a/Src/Hyperion-kernel/data/boot/fstab +++ b/Src/Hyperion-kernel/data/boot/fstab @@ -1,4 +1,4 @@ U $;/ U devfs0000;/dev/ U tmpfs0000;/tmp/ -U procfs0000;/proc/ \ No newline at end of file +U procfs0000;/proc/ diff --git a/Src/Hyperion-kernel/data/boot/kernel.lua b/Src/Hyperion-kernel/data/boot/kernel.lua index 3286917..d5afe4e 100644 --- a/Src/Hyperion-kernel/data/boot/kernel.lua +++ b/Src/Hyperion-kernel/data/boot/kernel.lua @@ -19,26 +19,34 @@ kernel.status = "start" kernel.key = {} kernel.cache = {} kernel.cache.preload = {} +kernel.unixSockets={} kernel._G=_G kernel.sleep=sleep _G.sleep=nil -local windowsExp = true +local windowsExp = false -function kernel.log(msg, level, c) - c=c or 0x6D6D6D - kernel.LOG_Text = kernel.LOG_Text..tostring(EFI:date()).." "..kernel.users[kernel.uid].." "..kernel.process.."["..tostring(level or "INFO").."]: "..msg.."\n" - if kernel.status == "start" then - screen:setTextColor(c) - screen:print(tostring(EFI:date()).." "..kernel.users[kernel.uid].." "..kernel.process.."["..tostring(level or "INFO").."]: "..msg) - elseif kernel.status == "term" then - kernel.standbyTask=kernel.currentTask - kernel.currentTask=kernel.kernelTask - local file=kernel.vfs.open("/dev/console", "w") - kernel.vfs.devctl(file,"sfgc",c) - kernel.vfs.write(file,tostring(EFI:date()).." "..kernel.users[kernel.uid].." "..kernel.process.."["..tostring(level or "INFO").."]: "..msg.."\n") - kernel.vfs.close(file) - kernel.currentTask=kernel.standbyTask +function kernel.log(msg, level, c, nopanic) + local f=function() + c=c or 0x6D6D6D + kernel.LOG_Text = kernel.LOG_Text..tostring(EFI:date()).." "..kernel.users[kernel.uid].." "..kernel.process.."["..tostring(level or "INFO").."]: "..msg.."\n" + if kernel.status == "start" then + screen:setTextColor(c) + screen:print(tostring(EFI:date()).." "..kernel.users[kernel.uid].." "..kernel.process.."["..tostring(level or "INFO").."]: "..msg) + elseif kernel.status == "term" then + kernel.standbyTask=kernel.currentTask + kernel.currentTask=kernel.kernelTask + local file=kernel.vfs.open("/dev/console", "w") + kernel.vfs.devctl(file,"sfgc",c) + kernel.vfs.write(file,tostring(EFI:date()).." "..kernel.users[kernel.uid].." "..kernel.process.."["..tostring(level or "INFO").."]: "..msg.."\n") + kernel.vfs.close(file) + kernel.currentTask=kernel.standbyTask + end + end + + local ok,err = xpcall(f,debug.traceback) + if not ok and not nopanic then + kernel.panic(err) end end @@ -246,6 +254,15 @@ function kernel.reboot() kernel.status="reboot" end +function kernel.halt() + kernel.exitMain=true + kernel.status="halt" +end + +function kernel.asyncReturn(...) + kernel.currentTask.syscallReturn = {...} +end + kernel.syscalls["time"]=function() return kernel.EFI:getEpochMs() end kernel.syscalls["date"]=function() return kernel.EFI:date() end kernel.syscalls["log"]=kernel.log @@ -264,8 +281,21 @@ kernel.syscalls["sysdump"]=function() end return rv end -kernel.syscalls["reboot"]=kernel.reboot -kernel.syscalls["shutdown"]=kernel.shutdown +kernel.syscalls["reboot"]=function() + if kernel.uid==0 or kernel.groups.wheel then + kernel.reboot() + end +end +kernel.syscalls["shutdown"]=function() + if kernel.uid==0 or kernel.groups.wheel then + kernel.shutdown() + end +end +kernel.syscalls["halt"]=function() + if kernel.uid==0 or kernel.groups.wheel then + kernel.halt() + end +end kernel.log("Running modules") for _,p in ipairs(modules) do @@ -287,11 +317,18 @@ kernel.log("Kernel initialized successfully.") kernel.saveLog() kernel.status="running" screen:disable() -kernel.main() +local ok,err = xpcall(kernel.main, debug.traceback) +if not ok then + kernel.panic(err) +end if kernel.status=="panic" then kernel.panic(kernel.reason) end if kernel.status=="reboot" then EFI.reboot=true return true +elseif kernel.status=="halt" then + kernel.log("System halted.") + kernel.saveLog() + while true do end end \ No newline at end of file diff --git a/Src/Hyperion-kernel/data/boot/safeboot.cfg b/Src/Hyperion-kernel/data/boot/safeboot.cfg index 8005543..b079c61 100644 --- a/Src/Hyperion-kernel/data/boot/safeboot.cfg +++ b/Src/Hyperion-kernel/data/boot/safeboot.cfg @@ -7,5 +7,5 @@ return { initPath = "/sbin/init", maxOpenFiles = 128, maxFilesPerTask = 16, - preempt=true + preempt = true, } \ No newline at end of file diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/01_stdlib.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/01_stdlib.kmod index 0c0420a..b4ec413 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/01_stdlib.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/01_stdlib.kmod @@ -229,6 +229,23 @@ function toHex(num) return string.format("%X", num) end +local st={ + push=function(self,...) table.insert(self.contents,{...}) end, + pop=function(self) return table.unpack(table.remove(self.contents)) end, +} +local q={ + push=function(self,...) table.insert(self.contents,{...}) end, + pop=function(self) return table.unpack(table.remove(self.contents,1)) end, +} + +function stack() + return setmetatable({contents={}}, {__index=st}) +end + +function queue() + return setmetatable({contents={}}, {__index=q}) +end + local function makeSyscallProxy() local backing = {} return setmetatable(backing, { diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/10_vfs.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/10_vfs.kmod index 2aa8be6..800cd89 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/10_vfs.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/10_vfs.kmod @@ -542,6 +542,7 @@ local function allocFD(task) if fd >= kernel.config.maxFilesPerTask then error("ENFILE") end return fd end + local function checkSystemLimit() if total >= kernel.config.maxOpenFiles - 16 then error("ENFILE") end end @@ -555,27 +556,88 @@ function vfs.newfd(fdobj) return fd end -function vfs.mount(target, diskOrId) +function vfs.mount(target, diskOrId, bind) local _euid = (kernel.currentTask and (kernel.currentTask.euid or kernel.currentTask.uid)) or kernel.uid if _euid ~= 0 then error("EPERM") end if not target then error("EINVAL") end target = normalizeMountPoint(target) local drive, path = resolvePath(target) - if not drive:directoryExists(path) then drive:makeDirectory(path) end - if drive:type(target) ~= "directory" then error("EINVAL") end - + if not drive:directoryExists(path) then + drive:makeDirectory(path) + end + if drive:type(path) ~= "directory" then + error("EINVAL") + end local disk, id - if type(diskOrId) == "string" then - disk = kernel.disks[diskOrId] - if not disk then error("ENODEV") end - checkDisk(disk); id = diskOrId - elseif type(diskOrId) == "table" then - checkDisk(diskOrId); disk = diskOrId - id = disk.address; vfs.disks[id] = disk - else error("EINVAL") end - + -- bind mount + if bind then + local src = normalizeMountPoint(diskOrId) + local srcDrive = resolvePath(src) + if not srcDrive then error("ENOENT") end + id = "bind:" .. src + disk = { + address = id, + isBind = true, + source = srcDrive, + exists = function(_, p) + return srcDrive:exists(p) + end, + type = function(_, p) + return srcDrive:type(p) + end, + list = function(_, p) + return srcDrive:list(p) + end, + open = function(_, ...) + return srcDrive:open(...) + end, + remove = function(_, p) + return srcDrive:remove(p) + end, + makeDirectory = function(_, p) + return srcDrive:makeDirectory(p) + end, + rename = function(_, a, b) + return srcDrive:rename(a, b) + end, + size = function(_, p) + return srcDrive:size(p) + end, + lastModified = function(_, p) + return srcDrive:lastModified(p) + end, + isReadOnly = function() + return srcDrive:isReadOnly() + end, + spaceTotal = function() + return srcDrive:spaceTotal() + end, + spaceUsed = function() + return srcDrive:spaceUsed() + end + } + vfs.disks[id] = disk + else + if type(diskOrId) == "string" then + disk = vfs.disks[diskOrId] + if not disk then error("ENODEV") end + checkDisk(disk) + id = diskOrId + elseif type(diskOrId) == "table" then + checkDisk(diskOrId) + disk = diskOrId + id = disk.address + vfs.disks[id] = disk + else + error("EINVAL") + end + end if vfs.mounts[id] then error("EBUSY") end - for _, mp in pairs(vfs.mounts) do if mp == target then error("EBUSY") end end + for _, mp in pairs(vfs.mounts) do + if mp == target then + error("EBUSY") + end + end vfs.mounts[id] = target return true end @@ -588,7 +650,11 @@ function vfs.umount(target) for id, mp in pairs(vfs.mounts) do if mp == target then if id == "$" then error("EBUSY") end - vfs.mounts[id] = nil; return true + vfs.mounts[id] = nil + if vfs.disks[id] and vfs.disks[id].isBind then + vfs.disks[id] = nil + end + return true end end error("EINVAL") diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/11_ld.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/11_ld.kmod new file mode 100644 index 0000000..302edf0 --- /dev/null +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/11_ld.kmod @@ -0,0 +1,63 @@ +--:Minify:-- +local kernel = ... +local cache = {} +kernel.searchpaths = { + "?", "?.lua", "/lib/?", "/lib/?.lua", "/usr/lib/?", "/usr/lib/?.lua", + "/usr/local/lib/?", "/usr/local/lib/?.lua" +} +kernel.reqcache = cache + +local function require(module, ...) + if cache[module] then return cache[module].ret end + kernel.currentTask.status = "D" + local args = {...} + kernel.currentTask.ksh = coroutine.create(function() + local coro = function() + for _, path in ipairs(kernel.searchpaths) do + local filepath = path:gsub("?", module) + if kernel.vfs.exists(filepath) then + if kernel.vfs.type(filepath) == "directory" then + filepath = filepath .. "/init.lua" + if kernel.vfs.type(filepath) == "directory" then + kernel.asyncReturn(false, "Module not found: "..module) + return + end + end + + local fd = kernel.vfs.open(filepath, "r") + local chunks = {} + while true do + local chunk = kernel.vfs.read(fd, 4096) + if not chunk or chunk == "" then break end + chunks[#chunks + 1] = chunk + coroutine.yield() + end + kernel.vfs.close(fd) + local data = table.concat(chunks) + local func, err = load(data, "@"..module, "t", kernel._U) + if not func then + kernel.asyncReturn(false, "Error loading module "..module..": "..tostring(err)) + return + end + local ok, ret = xpcall(func, debug.traceback, table.unpack(args)) + if not ok then + kernel.asyncReturn(false, "Error running module "..module..": "..tostring(ret)) + return + end + cache[module] = {ret = ret, expires = kernel.EFI:getEpochMs() + 120000} + kernel.asyncReturn(true, ret) + return + end + coroutine.yield() + end + kernel.asyncReturn(false, "Module not found: "..module) + end + local status, err = xpcall(coro, debug.traceback) + if not status then + kernel.asyncReturn(false, "Error in require coroutine for module "..module..": "..tostring(err)) + end + end) +end + +kernel.syscalls["require"] = require +_G.require = function(...) return syscall.require(...) end \ No newline at end of file diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/11_require.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/11_require.kmod deleted file mode 100644 index 7068837..0000000 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/11_require.kmod +++ /dev/null @@ -1,40 +0,0 @@ ---:Minify:-- -local kernel = ... -local cache = {} -kernel.searchpaths = { - "/lib/?.lua", "/lib/?", "/usr/lib/?.lua", "/usr/lib/?", - "/usr/local/lib/?.lua", "/usr/local/lib/?", "?.lua", "?" -} - -function require(module, ...) - if cache[module] then return cache[module] end - local modpath = module:gsub("%.", "/") - local failed = {} - for _, path in ipairs(kernel.searchpaths) do - local full_path = string.replace(path, "?", modpath) - if full_path:sub(1, 1) ~= "/" then - full_path = kernel.currentTask.cwd .. full_path - end - - if kernel.vfs.exists(full_path) then - if kernel.vfs.type(full_path) == "directory" then - full_path = full_path .. "/init" - end - - if kernel.vfs.exists(full_path) then - local handle = kernel.vfs.open(full_path, "r") - local file_content = kernel.vfs.read(handle, 1024 * 1024 * 4) - kernel.vfs.close(handle) - - return - assert(load(file_content, full_path, "t", kernel._U))(...) - else - table.insert(failed, full_path) - end - else - table.insert(failed, full_path) - end - end - - error("Module not found: " .. module .. " (searched paths: " .. table.concat(failed, ", ") .. ")") -end diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/12_devfs.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/12_devfs.kmod index be427d5..12121f0 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/12_devfs.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/12_devfs.kmod @@ -140,6 +140,83 @@ function data.zero(op, mode) end end +local function buildMeta(entries, opts) + opts = opts or {} + local uid = opts.uid or 0 + local gid = opts.gid or 0 + local perms = opts.perms or 0x3F -- default read/write for owner/group/world + + local chunks = {} + table.insert(chunks, string.char(0x02)) -- version header + + for path, target in pairs(entries) do + local name = path + local nameLen = #name + if nameLen > 255 then + error("Filename too long (>255 bytes): "..name) + end + + -- Determine entry type: 0x01 = symlink if target ~= nil and target ~= "" + local entryType = 0x00 + local cmeta = "" + if target and target ~= "" then + entryType = 0x01 + cmeta = target + end + local cmetaLen = #cmeta + if cmetaLen > 255 then + error("cmeta too long (>255 bytes) for "..name) + end + + -- Build entry as bytes + table.insert(chunks, string.char(nameLen)) -- name length + table.insert(chunks, name) -- name + table.insert(chunks, string.char(entryType)) -- entry type + table.insert(chunks, string.char(uid % 256, math.floor(uid/256) % 256)) -- uid + table.insert(chunks, string.char(gid % 256, math.floor(gid/256) % 256)) -- gid + table.insert(chunks, string.char(perms % 256, math.floor(perms/256) % 256)) -- perms + table.insert(chunks, string.char(cmetaLen)) -- cmeta length + if cmetaLen > 0 then + table.insert(chunks, cmeta) + end + end + + return table.concat(chunks) +end + +local function simpleFile(r,w) + return function(op, mode) + if op=="type" then + return "file" + elseif op=="open" then + if mode=="r" then + return { + read=r + } + elseif mode=="w" then + return { + write=w + } + end + end + end +end + +local function strFile(str) + local dat=tostring(str) + local pos=1 + return simpleFile(function(amount) + pos=pos+amount + return dat:sub(pos-amount, pos) + end,function() error("EACCES") end) +end + +data[".meta"]=strFile(buildMeta({ + stdin="/proc/self/fd/0", + stdout="/proc/self/fd/1", + log="/var/log/syslog.log" +})) + if kernel.EFI:getEEPROM() then function data.eeprom(op, mode) if op=="type" then @@ -216,7 +293,8 @@ if kernel.EFI:getNvram() then end end -data["disk"]={} +data["disk"]={["by-id"]={}, ["by-path"]={}, ["by-label"]={}} +data["input"]={} kernel.devfs={} kernel.devfs.data=data kernel.devfs.proxy=proxy diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/12_procfs.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/12_procfs.kmod index 028c343..2ead312 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/12_procfs.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/12_procfs.kmod @@ -114,7 +114,8 @@ local function newtaskproxy(task) }, children={ [".meta"]=strFile(buildMeta(children)) - } + }, + pid=strFile(task.pid) } end diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/12_tmpfs.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/12_tmpfs.kmod index eecb14f..96d4517 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/12_tmpfs.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/12_tmpfs.kmod @@ -1,134 +1,141 @@ --:Minify:-- local kernel = ... -local proxy = {} -local data = {} +kernel.vfs.remove("/tmp") +kernel.vfs.mkdir("/tmp") +if not kernel.config.tmpToDisk then + local proxy = {} + local data = {} -proxy.address = "tmpfs0000" -proxy.isvirt = true -proxy.isReadOnly = function() return false end + proxy.address = "tmpfs0000" + proxy.isvirt = true + proxy.isReadOnly = function() return false end -proxy.spaceUsed = function() return 0 end -proxy.spaceTotal = function() return 0 end + proxy.spaceUsed = function() return 0 end + proxy.spaceTotal = function() return 0 end -proxy.makeDirectory = function(_, path) - local steps = kernel.vfs.splitPath(path) - local step = data - for i=1,#steps do - if not step[steps[i]] then - step[steps[i]] = {} - elseif type(step[steps[i]]) ~= "table" then - error("ENOTDIR") + proxy.makeDirectory = function(_, path) + local steps = kernel.vfs.splitPath(path) + local step = data + for i=1,#steps do + if not step[steps[i]] then + step[steps[i]] = {} + elseif type(step[steps[i]]) ~= "table" then + error("ENOTDIR") + end + step = step[steps[i]] end - step = step[steps[i]] end -end -proxy.remove = function(_, path) - local steps = kernel.vfs.splitPath(path) - local step = data - for i=1,#steps-1 do - step = step[steps[i]] - if not step then error("ENOENT") end - end - step[steps[#steps]] = nil -end - -proxy.setLabel = function(_, label) end -proxy.getLabel = function() return "tmpfs" end - -proxy.attributes = function(_, path) - local steps = kernel.vfs.splitPath(path) - local step = data - for i=1,#steps do - step = step[steps[i]] - if not step then error("ENOENT") end - end - return { - size = type(step) == "string" and #step or 0, - modified = 0, - created = 0, - } -end - -function proxy:open(path, mode) - local steps = kernel.vfs.splitPath(path) - local step = data - for i=1,#steps-1 do - if not step[steps[i]] then - if mode == "w" then step[steps[i]] = {} else error("ENOENT") end - elseif type(step[steps[i]]) ~= "table" then - error("ENOTDIR") + proxy.remove = function(_, path) + local steps = kernel.vfs.splitPath(path) + local step = data + for i=1,#steps-1 do + step = step[steps[i]] + if not step then error("ENOENT") end end - step = step[steps[i]] + step[steps[#steps]] = nil end - local filename = steps[#steps] - if mode == "r" then - if type(step[filename]) ~= "string" then error("ENOENT") end - local content = step[filename] - local pos = 1 + proxy.setLabel = function(_, label) end + proxy.getLabel = function() return "tmpfs" end + + proxy.attributes = function(_, path) + local steps = kernel.vfs.splitPath(path) + local step = data + for i=1,#steps do + step = step[steps[i]] + if not step then error("ENOENT") end + end return { - read = function(amount) - amount = amount or #content - local chunk = content:sub(pos, pos+amount-1) - pos = pos + #chunk - return chunk - end, - close = function() end, + size = type(step) == "string" and #step or 0, + modified = 0, + created = 0, } - elseif mode == "w" then - step[filename] = "" - local buf = {} - return { - write = function(str) - buf[#buf + 1] = str - end, - close = function() - step[filename] = table.concat(buf) - end, - } - elseif mode == "a" then - if type(step[filename]) ~= "string" then step[filename] = "" end - return { - write = function(str) - step[filename] = step[filename] .. str - end, - close = function() end, - } - else - error("EACCES") end -end -function proxy:type(path) - local steps = kernel.vfs.splitPath(path) - local step = data - if #steps == 0 then return "directory" end - for i=1,#steps do - step = step[steps[i]] - if not step then return false end + function proxy:open(path, mode) + local steps = kernel.vfs.splitPath(path) + local step = data + for i=1,#steps-1 do + if not step[steps[i]] then + if mode == "w" then step[steps[i]] = {} else error("ENOENT") end + elseif type(step[steps[i]]) ~= "table" then + error("ENOTDIR") + end + step = step[steps[i]] + end + local filename = steps[#steps] + + if mode == "r" then + if type(step[filename]) ~= "string" then error("ENOENT") end + local content = step[filename] + local pos = 1 + return { + read = function(amount) + amount = amount or #content + local chunk = content:sub(pos, pos+amount-1) + pos = pos + #chunk + return chunk + end, + close = function() end, + } + elseif mode == "w" then + step[filename] = "" + local buf = {} + return { + write = function(str) + buf[#buf + 1] = str + end, + close = function() + step[filename] = table.concat(buf) + end, + } + elseif mode == "a" then + if type(step[filename]) ~= "string" then step[filename] = "" end + return { + write = function(str) + step[filename] = step[filename] .. str + end, + close = function() end, + } + else + error("EACCES") + end end - if type(step) == "table" then return "directory" end - if type(step) == "string" then return "file" end -end -function proxy:list(path) - local steps = kernel.vfs.splitPath(path) - local step = data - for i=1,#steps do - step = step[steps[i]] - if not step then error("ENOENT") end + function proxy:type(path) + local steps = kernel.vfs.splitPath(path) + local step = data + if #steps == 0 then return "directory" end + for i=1,#steps do + step = step[steps[i]] + if not step then return false end + end + if type(step) == "table" then return "directory" end + if type(step) == "string" then return "file" end end - if type(step) ~= "table" then error("ENOTDIR") end - local keys = {} - for k,_ in pairs(step) do table.insert(keys, k) end - return keys -end -function proxy:fileExists(path) - local t = self:type(path) - return t == "file" or t == "directory" -end + function proxy:list(path) + local steps = kernel.vfs.splitPath(path) + local step = data + for i=1,#steps do + step = step[steps[i]] + if not step then error("ENOENT") end + end + if type(step) ~= "table" then error("ENOTDIR") end + local keys = {} + for k,_ in pairs(step) do table.insert(keys, k) end + return keys + end -kernel.disks["tmpfs0000"] = proxy \ No newline at end of file + function proxy:fileExists(path) + local t = self:type(path) + return t == "file" or t == "directory" + end + + kernel.disks["tmpfs0000"] = proxy +else + kernel.log("tmpToDisk enabled, skipping tmpfs module") + kernel.log("tmpfs0000 will passthrough to /tmp on the disk") +end \ No newline at end of file diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/19_fstab.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/19_fstab.kmod index 9034cea..50bdc8e 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/19_fstab.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/19_fstab.kmod @@ -25,10 +25,11 @@ for _, line in ipairs(string.split(kernel.fstab, "\n")) do else local id = line:sub(3, semicolon_pos - 1) local path = trim(line:sub(semicolon_pos + 1)) - kernel.log("Mounted "..id.." to "..path) + kernel.log("Mounting '"..id.."' to '"..path.."'") if id ~= "$" then kernel.vfs.mount(path, id) end + kernel.log("Mounted "..id.." to "..path) end end end \ No newline at end of file diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/20_socket.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/20_socket.kmod index 18e280a..cf70b3c 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/20_socket.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/20_socket.kmod @@ -1,67 +1,194 @@ --:Minify:-- --- Supports: --- AF_UNIX - local IPC via /var/run/*.sock paths --- AF_INET - network sockets with three backends: --- Implemented by drivers but expect http:// and https:// --- --- Socket lifecycle: --- fd = syscall.socket(domain, socktype) -- "unix"/"inet", "stream"/"dgram" --- syscall.bind(fd, address) -- server: claim address --- syscall.listen(fd, backlog) -- server: mark as listening --- cfd = syscall.accept(fd) -- server: get connected client fd (blocking poll) --- syscall.connect(fd, address) -- client: connect to server --- syscall.send(fd, data) -- send bytes --- syscall.recv(fd, len) -- receive bytes (blocking poll, returns "" on nothing) --- syscall.sockshutdown(fd) -- half-close send side --- -- normal vfs.close(fd) closes the socket +local kernel = ... -local kernel=... -local socket={} -socket.handlers={} -kernel.socket=socket +local socket = {} -function socket.registerProtocal(protocal, handler) - socket.handlers[protocal] = handler +socket.handlers = {} + +kernel.socket = socket + +local P = kernel.vfs.P +local sys = kernel.syscalls + +function socket.registerProtocal(proto, handler) + socket.handlers[proto] = handler end -function socket.socket() - local P=kernel.vfs.P - local data=kernel.newFifo() - local isClosed=false - return kernel.vfs.newfd({ - handle={ - read=function() if isClosed then error("ECCON") end return data.pop() end, - write=function(data) if isClosed then error("ECCON") end return data.push(data) end, - close=function() isClosed = true end +local function getHandler(address) + for proto, handler in pairs(socket.handlers) do + if string.hasPrefix(address, proto) then + return handler + end + end +end + +function socket.socket(domain, socktype) + local fd = kernel.vfs.newfd({ + handle = {}, + + type = "socket", + + refcount = 1, + + socket = { + connected = false, + protocol = nil, + address = nil }, - type="socket", - refcount=1, - socket={}, - meta={ - owner=kernel.currentTask.uid, - group=kernel.currentTask.uid, - etype=2, - perms=P.OWNER_R+P.OWNER_W+P.GROUP_R+P.GROUP_W + + meta = { + owner = kernel.currentTask.uid, + group = kernel.currentTask.uid, + etype = 2, + + perms = + P.OWNER_R + + P.OWNER_W + + P.GROUP_R + + P.GROUP_W }, - isvirt=true + + isvirt = true }) + + local fdo = kernel.currentTask.fd[fd] + + fdo.handle.read = function() + return "" + end + + fdo.handle.write = function() + return nil, "ENOTCONN" + end + + fdo.handle.close = function() + fdo.socket.connected = false + return true + end + + return fd end function socket.connect(fd, address) - local handler - for k, v in pairs(socket.handlers) do - if string.hasPrefix(address, k) then - handler=v - end + local fdo = kernel.currentTask.fd[fd] + + if not fdo then + return nil, "EBADF" end - handler.connect(kernel.currentTask.fd[fd], address) + + if fdo.type ~= "socket" then + return nil, "ENOTSOCK" + end + + local handler = + getHandler(address) + + if not handler then + return nil, "EPROTONOSUPPORT" + end + + fdo.socket.protocol = handler + fdo.socket.address = address + + local ok, err = + handler.connect(fd, address) + + if not ok then + return nil, err + end + + fdo.socket.connected = true + + return true end function socket.listen(fd, backlog) - error("Not Implemented") + local fdo = + kernel.currentTask.fd[fd] + + if not fdo then + return nil, "EBADF" + end + + if not fdo.handle.listen then + return nil, "EOPNOTSUPP" + end + + return fdo.handle.listen(backlog) end -local sys=kernel.syscalls -sys["socket"]=socket.socket +function socket.send(fd, data) + local fdo = + kernel.currentTask.fd[fd] + + if not fdo then + return nil, "EBADF" + end + + if fdo.type ~= "socket" then + return nil, "ENOTSOCK" + end + + if not fdo.socket.connected then + return nil, "ENOTCONN" + end + + if not fdo.handle.write then + return nil, "EOPNOTSUPP" + end + + return fdo.handle.write(data) +end + +function socket.recv(fd, amount) + local fdo = + kernel.currentTask.fd[fd] + + if not fdo then + return nil, "EBADF" + end + + if fdo.type ~= "socket" then + return nil, "ENOTSOCK" + end + + if not fdo.socket.connected then + return nil, "ENOTCONN" + end + + if not fdo.handle.read then + return nil, "EOPNOTSUPP" + end + + return fdo.handle.read(amount) +end + +function socket.sockshutdown(fd) + local fdo = + kernel.currentTask.fd[fd] + + if not fdo then + return nil, "EBADF" + end + + if fdo.type ~= "socket" then + return nil, "ENOTSOCK" + end + + if fdo.handle.close then + return fdo.handle.close() + end + + fdo.socket.connected = false + + return true +end + +sys.socket = socket.socket +sys.connect = socket.connect +sys.listen = socket.listen +sys.send = socket.send +sys.recv = socket.recv +sys.sockshutdown = socket.sockshutdown kernel.log("Loaded socket module") \ No newline at end of file diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/30_vterm.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/30_vterm.kmod new file mode 100644 index 0000000..1ec91b7 --- /dev/null +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/30_vterm.kmod @@ -0,0 +1,129 @@ +--:Minify:-- +local kernel = ... + +local vterms = {} + +local function createVt(id, width, height) + local vt = { + id = id, + width = width, + height = height, + buffer = {}, + cursorX = 1, + cursorY = 1, + fgColor = 0xFFFFFF, + bgColor = 0x000000, + obj = {} + } + + for y = 1, height do + vt.buffer[y] = {} + for x = 1, width do + vt.buffer[y][x] = {char = " ", fgColor = vt.fgColor, bgColor = vt.bgColor} + end + end + + local function scroll(lines) + for _ = 1, lines do + table.remove(vt.buffer, 1) + vt.buffer[vt.height] = {} + for x = 1, vt.width do + vt.buffer[vt.height][x] = {char = " ", fgColor = vt.fgColor, bgColor = vt.bgColor} + end + end + end + + function vt.obj:write(content) + local x, y = vt.cursorX, vt.cursorY + if x>vt.width then return end + if y>vt.height then return end + for i = 1, #content do + local c = content:sub(i, i) + if c == "\n" then + y = y + 1 + x = 1 + elseif c == "\t" then + local tabSize = 4 + local spaces = tabSize - ((x - 1) % tabSize) + for _ = 1, spaces do + vt.buffer[y][x] = {char = " ", fgColor = vt.fgColor, bgColor = vt.bgColor} + x = x + 1 + if x > vt.width then + x = 1 + y = y + 1 + end + end + elseif c == "\b" then + if x > 1 then + x = x - 1 + vt.buffer[y][x] = {char = " ", fgColor = vt.fgColor, bgColor = vt.bgColor} + end + else + if x <= vt.width and y <= vt.height then + vt.buffer[y][x] = {char = c, fgColor = vt.fgColor, bgColor = vt.bgColor} + x = x + 1 + end + end + + if x > vt.width then + x = 1 + y = y + 1 + end + + if y > vt.height then + scroll(1) + y = vt.height + end + end + + vt.cursorX, vt.cursorY = x, y + end + + function vt.obj:spos(x, y) + vt.cursorX = tonumber(x) + vt.cursorY = tonumber(y) + end + + function vt.obj:gpos() + return tostring(vt.cursorX)..";"..tostring(vt.cursorY) + end + + function vt.obj:sfgc(color) + vt.fgColor = tonumber(color) + end + + function vt.obj:sbgc(color) + vt.bgColor = tonumber(color) + end + + function vt.obj:gfgc() + return vt.fgColor + end + + function vt.obj:gbgc() + return vt.bgColor + end + + function vt.obj:gplt() + return 24 + end + + function vt.obj:clear() + for y = 1, vt.height do + for x = 1, vt.width do + vt.buffer[y][x] = {char = " ", fgColor = vt.fgColor, bgColor = vt.bgColor} + end + end + vt.cursorX, vt.cursorY = 1, 1 + end + + function vt.obj:isvirt() + return true + end + + function vt.obj:gctrl() + return serializeBool(vt.ctrl)..";"..serializeBool(vt.alt) + end + + return vt +end \ No newline at end of file diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/45_hypervisor.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/45_hypervisor.kmod index ad4606e..0985a6d 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/45_hypervisor.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/45_hypervisor.kmod @@ -21,7 +21,7 @@ local function loadExecutable(path) local env = kernel.freshUserEnv() local func, err = load(data, "@" .. path, "t", env) - if not func then error("ENOEXEC: " .. tostring(err)) end + if not func then kernel.log("Failed to load executable: " .. tostring(err).. " : ".. tostring(path)); error("ENOEXEC: " .. tostring(err)) end local meta = kernel.vfs.lstat(path) local suid_set = bit_is_set(meta.perms, 6) @@ -211,6 +211,8 @@ function sys.kill(pid, force) return false, "Task is already dead" elseif task.status == "D" and not force then return false, "Cannot kill task waiting for IO" + elseif task.euid ~= kernel.uid and kernel.uid ~= 0 then + return false, "Different user" end local caller = kernel.currentTask local ceuid = caller and (caller.euid or caller.uid) or kernel.uid @@ -227,6 +229,8 @@ function sys.stop(pid) return false, "Task does not exist" elseif task.status ~= "R" and task.status ~= "S" then return false, "Cannot stop non-running task" + elseif task.euid ~= kernel.uid and kernel.uid ~= 0 then + return false, "Different user" else if task.status == "S" then task.status = "ST" @@ -243,6 +247,8 @@ function sys.continue(pid) return false, "Task does not exist" elseif task.status ~= "T" and task.status ~= "ST" then return false, "Task is not stopped" + elseif task.euid ~= kernel.uid and kernel.uid ~= 0 then + return false, "Different user" else if task.status == "ST" then task.status = "S" @@ -299,20 +305,21 @@ function sys.getuid() return kernel.currentTask.uid end local function reapDeadTasks() for pid, task in pairs(tasks) do if task.status == "Z" and not task.reapTime then - task.coro = nil - task.ivs = nil - task.vs = nil - task.args = nil - task.envars = nil - task.cwd = nil - task.numRuns = nil - task.totalTime = nil - task.lastTime = nil - task.timeSlice = nil + if task.pid == 1 then kernel.panic("Attempted to gc init!") end + task.coro = nil + task.ivs = nil + task.vs = nil + task.args = nil + task.envars = nil + task.cwd = nil + task.numRuns = nil + task.totalTime = nil + task.lastTime = nil + task.timeSlice = nil task.syscallReturn = nil - task.sleep = nil - task.fd = nil - task.reapTime = kernel.EFI:getEpochMs() + 30000 + task.sleep = nil + task.fd = nil + task.reapTime = kernel.EFI:getEpochMs() + 30000 elseif task.reapTime and kernel.EFI:getEpochMs() > task.reapTime and task.status == "Z" then @@ -344,7 +351,23 @@ local k_max = 0.5 local B = 0.01 function kernel.main() + kernel.log("Starting main loop...") + kernel.saveLog() + local stopLog=5 + local logTasks=100 + while not kernel.exitMain do + if kernel.config.logTasks then + if logTasks<0 then + kernel.log("Active Tasks:") + for i,v in pairs(tasks) do + kernel.log(v.name.." : "..v.status.." : "..tostring(v.pid).." : "..tostring(v.exit)) + end + kernel.log("[END BLOCK]") + logTasks=100 + end + logTasks=logTasks-1 + end local N = 0 local Tmin_hit = 0 local Tmax_hit = 0 @@ -352,6 +375,7 @@ function kernel.main() local taskTimes = {} for pid, task in pairs(tasks) do + if kernel.exitMain then break end kernel.currentTask = task kernel.uid = task.euid or task.uid kernel.process = task.name @@ -366,9 +390,29 @@ function kernel.main() task.sleep = 0 end + if task.status == "DS" and kernel.EFI:getEpochMs() >= task.sleep then + task.status = "D" + task.sleep = 0 + end + if task.status == "D" then if task.ksh then coroutine.resume(task.ksh) + if coroutine.status(task.ksh) == "dead" then + task.ksh = nil + if task.status == "D" then + task.status = "R" + end + + if kernel.config.debugSyscalls then + kernel.log("Task " .. task.pid .. " IO wait completed", "DBUG", 0x00FFFF) + local sysret = task.syscallReturn + for i = 2, #sysret do + local v = type(sysret[i]) == "table" and table.serialize(sysret[i]) or tostring(sysret[i]) + kernel.log(" retval[" .. (i-1) .. "] = " .. v, "DBUG", 0x00FFFF) + end + end + end end end @@ -405,7 +449,9 @@ function kernel.main() if task.status == "R" then local startTime = kernel.EFI:getEpochMs() local ret - + if stopLog > 0 then + kernel.log("Running task " .. tostring(task.pid) .. " (" .. task.name .. ") with time slice " .. string.format("%.3f", task.timeSlice) .. "s", "DBUG", 0x00FFFF) + end if kernel.config.preempt then if not task.debugger then ret = { resumeWithTimeout(task.coro, task.timeSlice, table.unpack(task.syscallReturn)) } @@ -491,6 +537,11 @@ function kernel.main() end reapDeadTasks() + if stopLog > 0 then + kernel.log("Executed " .. N .. " tasks, avg time: " .. string.format("%.2f", T_prev_avg) .. "ms, var: " .. string.format("%.2f", T_prev_var) .. ", B: " .. string.format("%.5f", B)) + stopLog = stopLog - 1 + kernel.saveLog() + end end end diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/90_kgc.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/90_kgc.kmod new file mode 100644 index 0000000..9a14d1a --- /dev/null +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/90_kgc.kmod @@ -0,0 +1,11 @@ +local kernel = ... +kernel.processes.kgc = function() + while true do + for i,v in pairs(kernel.reqcache) do + if v.expires and kernel.EFI:getEpochMs() > v.expires then + kernel.reqcache[i] = nil + end + end + kernel.sleep(5000) + end +end \ No newline at end of file diff --git a/Src/hysh/data/bin/login b/Src/coreutils/data/bin/login similarity index 98% rename from Src/hysh/data/bin/login rename to Src/coreutils/data/bin/login index 13659d7..51b9c86 100644 --- a/Src/hysh/data/bin/login +++ b/Src/coreutils/data/bin/login @@ -1,5 +1,5 @@ --:Minify:-- -syscall.open("/dev/tty/1", "r") --stdin (fd 0) +syscall.open("/dev/input/keyboard1", "r") --stdin (fd 0) syscall.open("/dev/tty/1", "w") --stdout (fd 1) syscall.open("/dev/null", "w") --stderr (fd 2) diff --git a/Src/hysh/data/bin/lsusers b/Src/coreutils/data/bin/lsusers similarity index 100% rename from Src/hysh/data/bin/lsusers rename to Src/coreutils/data/bin/lsusers diff --git a/Src/hysh/data/bin/mount b/Src/coreutils/data/bin/mount similarity index 100% rename from Src/hysh/data/bin/mount rename to Src/coreutils/data/bin/mount diff --git a/Src/hysh/data/bin/passwd b/Src/coreutils/data/bin/passwd similarity index 100% rename from Src/hysh/data/bin/passwd rename to Src/coreutils/data/bin/passwd diff --git a/Src/hysh/data/bin/su b/Src/coreutils/data/bin/su similarity index 100% rename from Src/hysh/data/bin/su rename to Src/coreutils/data/bin/su diff --git a/Src/hysh/data/bin/sudo b/Src/coreutils/data/bin/sudo similarity index 100% rename from Src/hysh/data/bin/sudo rename to Src/coreutils/data/bin/sudo diff --git a/Src/hysh/data/bin/umount b/Src/coreutils/data/bin/umount similarity index 100% rename from Src/hysh/data/bin/umount rename to Src/coreutils/data/bin/umount diff --git a/Src/hysh/data/bin/useradd b/Src/coreutils/data/bin/useradd similarity index 100% rename from Src/hysh/data/bin/useradd rename to Src/coreutils/data/bin/useradd diff --git a/Src/hysh/data/bin/userdel b/Src/coreutils/data/bin/userdel similarity index 100% rename from Src/hysh/data/bin/userdel rename to Src/coreutils/data/bin/userdel diff --git a/Src/hysh/data/bin/usermod b/Src/coreutils/data/bin/usermod similarity index 100% rename from Src/hysh/data/bin/usermod rename to Src/coreutils/data/bin/usermod diff --git a/Src/hysh/control/symlinks.json b/Src/hysh/control/symlinks.json new file mode 100644 index 0000000..4a4d945 --- /dev/null +++ b/Src/hysh/control/symlinks.json @@ -0,0 +1,3 @@ +{ + "/bin/sh": "/bin/hysh" +} \ No newline at end of file diff --git a/Src/hysh/data/bin/help b/Src/hysh/data/bin/help index f8938aa..03f40a6 100644 --- a/Src/hysh/data/bin/help +++ b/Src/hysh/data/bin/help @@ -107,6 +107,7 @@ local COMMANDS = { { name="whoami", usage="whoami", desc="Print the current username.", flags={} }, { name="id", usage="id [username]", desc="Print user identity (uid, gid).", flags={} }, { name="ps", usage="ps", desc="List running tasks with pid, user, name, and status.", flags={} }, + { name="hyperctl", usage="hyperctl [service]", desc="Control system services (start, stop, restart, status, list, enable, disable).", flags={} }, { name="hostname", usage="hostname [NAME]", desc="Print or set the system hostname.", flags={} }, { name="uname", usage="uname [-asnrm]", desc="Print system information (OS name, hostname, release, machine).", flags={ {"-a","Print all fields"}, diff --git a/Src/hysh/data/bin/hysh b/Src/hysh/data/bin/hysh index 6bf3655..e18c487 100644 --- a/Src/hysh/data/bin/hysh +++ b/Src/hysh/data/bin/hysh @@ -1,10 +1,10 @@ --:Minify:-- -syscall.open("/dev/tty/1","r") --stdin (Device 0) +local success, errorMsg = xpcall(function() + +syscall.open("/dev/input/keyboard1","r") --stdin (Device 0) syscall.open("/dev/tty/1","w") --stdout (Device 1) syscall.open("/dev/null","w") --stderr (device 2) -local success, errorMsg = xpcall(function() - local fs = require("fs") syscall.devctl(1,"clear") @@ -833,6 +833,14 @@ builtinCmds.ops = function() end end +builtinCmds.reboot = function () + syscall.reboot() +end + +builtinCmds.shutdown = function () + syscall.shutdown() +end + local function listDir(dir, prefix) local ok, entries = pcall(syscall.listdir, dir) if not ok or not entries then return {} end @@ -1203,9 +1211,9 @@ local function runCommand(command) local proc = syscall.spawn(function() -- Open standard fds so programs that don't do it themselves work correctly. - syscall.open("/dev/tty/1", "r") -- fd 0 stdin + syscall.open("/dev/input/keyboard1", "r") -- fd 0 stdin syscall.open("/dev/tty/1", "w") -- fd 1 stdout - syscall.open("/dev/null", "w") -- fd 2 stderr + syscall.open("/dev/null", "w") -- fd 2 stderr -- exec replaces this coroutine's code with a fresh isolated environment -- compiled from disk by the kernel (via loadExecutable -> freshUserEnv), -- so the child cannot share any upvalue or syscall table state with hysh. diff --git a/Src/hysh/data/bin/tree b/Src/hysh/data/bin/tree new file mode 100644 index 0000000..b681c90 --- /dev/null +++ b/Src/hysh/data/bin/tree @@ -0,0 +1,113 @@ +--:Minify:-- +local cloptions = { + a = false, + h = false, + l = false, + help = false, +} +local inpArgs = { ... } +local args = {} +local name = syscall.getTask(syscall.getpid()).name + +for _, v in pairs(inpArgs) do + if v:sub(1, 2) == "--" then + local opt = v:sub(3) + if cloptions[opt] == nil then + print(name .. ": unrecognized option '" .. v .. "'.") + print("try '" .. name .. " --help' for more information.") + return + end + cloptions[opt] = true + elseif v:sub(1, 1) == "-" then + for i = 2, #v do + local opt = v:sub(i, i) + if cloptions[opt] == nil then + print(name .. ": invalid option '-" .. opt .. "'.") + print("try '" .. name .. " --help' for more information.") + return + end + cloptions[opt] = true + end + else + table.insert(args, v) + end +end + +if cloptions.help then + print("Usage: " .. name .. " [OPTION]... [DIR]") + print("List all entries in the specified DIRectory, or cwd if not specified.") + print("Display directory tree structure.") + print("") + print("Options:") + print(" -a do not ignore entries starting with .") + print(" -h with -l, print sizes in human readable format (e.g., 1K 234M 2G)") + print(" -l use a long listing format (show file sizes)") + print(" --help display this help and exit") + return +end + +local fs = require("fs") +local dir = args[1] or "" +if dir:sub(1, 1) ~= "/" then + dir = syscall.getcwd() .. "/" .. dir +end +if dir:sub(-1) ~= "/" then dir = dir .. "/" end + +if not fs.isDir(dir) then + print(name .. ": cannot access '" .. (args[1] or dir) .. "': no such directory") + return +end + +local function format_size(size) + if not cloptions.h then return tostring(size) end + if size < 1024 then return tostring(size) .. "B" + elseif size < 1024*1024 then return string.format("%.1fK", size/1024) + elseif size < 1024*1024*1024 then return string.format("%.1fM", size/1024/1024) + else return string.format("%.1fG", size/1024/1024/1024) end +end + +local function pdir(current_dir, level, prefix) + prefix = prefix or "" + local list = fs.list(current_dir) + if not cloptions.a then + for i = #list, 1, -1 do + if list[i]:sub(1, 1) == "." then table.remove(list, i) end + end + end + table.sort(list) + if current_dir:sub(-1) ~= "/" then current_dir = current_dir .. "/" end + + for i, entry in ipairs(list) do + local full_path = current_dir .. entry + local is_last = (i == #list) + local branch = is_last and "`--" or "|--" + local indent = prefix .. branch + local suffix = "" + local info = "" + + if fs.isDir(full_path) then + suffix = "/" + end + + if cloptions.l then + local stat = fs.stat and fs.stat(full_path) + if stat then + local size = stat.size or 0 + info = " " .. format_size(size) + end + end + + print(indent .. entry .. suffix .. info) + + if fs.isDir(full_path) then + local new_prefix = prefix .. (is_last and " " or "| ") + pcall(pdir, full_path, level + 1, new_prefix) + end + end +end + +-- Print root directory +local root_name = dir:sub(1, -2) -- remove trailing / +if root_name == "" then root_name = "/" end +print(root_name) +pdir(dir, 0, "") \ No newline at end of file diff --git a/Src/installer/data/bin/hyperion-build b/Src/installer/data/bin/hyperion-build new file mode 100644 index 0000000..e69de29 diff --git a/Src/installer/data/bin/install b/Src/installer/data/bin/install new file mode 100644 index 0000000..e69de29 diff --git a/Src/minify/data/bin/minify b/Src/minify/data/bin/minify new file mode 100644 index 0000000..d77a484 --- /dev/null +++ b/Src/minify/data/bin/minify @@ -0,0 +1,29 @@ + +local function usageError() + print( + "\nusage: minify or unminify \n" .. + " The modified code will be printed to the stdout, pipe it to a file,\n" .. + " or something else as desired EG:\n\n" .. + " minify minify input.lua > output.lua\n\n" .. + " * minify will minify the code in the file.\n" .. + " * unminify will beautify the code and replace the variable names with easily\n" .. + " find-replacable ones to aide in reverse engineering minified code.\n") + syscall.exit(0) +end + +local args = {...} + +if #args ~= 2 then + usageError() +end + +local minify = require("minify") +local fs = require("fs") + +if args[1] == 'minify' then + print(minify.minify(fs.readAllText(args[2]))) +elseif args[1] == 'unminify' then + print(minify.beautify(fs.readAllText(args[2]))) +else + usageError() +end diff --git a/Src/minify/data/lib/minify.lua b/Src/minify/data/lib/minify.lua new file mode 100644 index 0000000..1b7d0c6 --- /dev/null +++ b/Src/minify/data/lib/minify.lua @@ -0,0 +1,3106 @@ +--[[ +MIT License + +Copyright (c) 2017 Mark Langen + +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 lib = {} + +local function lookupify(tb) + for _, v in pairs(tb) do + tb[v] = true + end + return tb +end + +local function CountTable(tb) + local c = 0 + for _ in pairs(tb) do c = c + 1 end + return c +end + +local function FormatTableInt(tb, atIndent, ignoreFunc) + if tb.Print then + return tb.Print() + end + atIndent = atIndent or 0 + local useNewlines = (CountTable(tb) > 1) + local baseIndent = string.rep(' ', atIndent + 1) + local out = "{" .. (useNewlines and '\n' or '') + for k, v in pairs(tb) do + if type(v) ~= 'function' and not ignoreFunc(k) then + out = out .. (useNewlines and baseIndent or '') + if type(k) == 'number' then + --nothing to do + elseif type(k) == 'string' and k:match("^[A-Za-z_][A-Za-z0-9_]*$") then + out = out .. k .. " = " + elseif type(k) == 'string' then + out = out .. "[\"" .. k .. "\"] = " + else + out = out .. "[" .. tostring(k) .. "] = " + end + if type(v) == 'string' then + out = out .. "\"" .. v .. "\"" + elseif type(v) == 'number' then + out = out .. v + elseif type(v) == 'table' then + out = out .. FormatTableInt(v, atIndent + (useNewlines and 1 or 0), ignoreFunc) + else + out = out .. tostring(v) + end + if next(tb, k) then + out = out .. "," + end + if useNewlines then + out = out .. '\n' + end + end + end + out = out .. (useNewlines and string.rep(' ', atIndent) or '') .. "}" + return out +end + +local function FormatTable(tb, ignoreFunc) + ignoreFunc = ignoreFunc or function() + return false + end + return FormatTableInt(tb, 0, ignoreFunc) +end + +local WhiteChars = lookupify { ' ', '\n', '\t', '\r' } + +local EscapeForCharacter = { ['\r'] = '\\r', ['\n'] = '\\n', ['\t'] = '\\t', ['"'] = '\\"', ["'"] = "\\'", ['\\'] = '\\' } + +local CharacterForEscape = { ['r'] = '\r', ['n'] = '\n', ['t'] = '\t', ['"'] = '"', ["'"] = "'", ['\\'] = '\\' } + +local AllIdentStartChars = lookupify { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', + 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', + 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', + 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_' } + +local AllIdentChars = lookupify { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', + 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', + 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', + 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' } + +local Digits = lookupify { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' } + +local HexDigits = lookupify { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f' } + +local Symbols = lookupify { '+', '-', '*', '/', '^', '%', ',', '{', '}', '[', ']', '(', ')', ';', '#', '.', ':' } + +local EqualSymbols = lookupify { '~', '=', '>', '<' } + +local Keywords = lookupify { + 'and', 'break', 'do', 'else', 'elseif', + 'end', 'false', 'for', 'function', 'goto', 'if', + 'in', 'local', 'nil', 'not', 'or', 'repeat', + 'return', 'then', 'true', 'until', 'while', +}; + +local BlockFollowKeyword = lookupify { 'else', 'elseif', 'until', 'end' } + +local UnopSet = lookupify { '-', 'not', '#' } + +local BinopSet = lookupify { + '+', '-', '*', '/', '%', '^', '#', + '..', '.', ':', + '>', '<', '<=', '>=', '~=', '==', + 'and', 'or' +} + +local GlobalRenameIgnore = lookupify { + +} + +local BinaryPriority = { + ['+'] = { 6, 6 }, + ['-'] = { 6, 6 }, + ['*'] = { 7, 7 }, + ['/'] = { 7, 7 }, + ['%'] = { 7, 7 }, + ['^'] = { 10, 9 }, + ['..'] = { 5, 4 }, + ['=='] = { 3, 3 }, + ['~='] = { 3, 3 }, + ['>'] = { 3, 3 }, + ['<'] = { 3, 3 }, + ['>='] = { 3, 3 }, + ['<='] = { 3, 3 }, + ['and'] = { 2, 2 }, + ['or'] = { 1, 1 }, +}; +local UnaryPriority = 8 + +-- Eof, Ident, Keyword, Number, String, Symbol + +local function CreateLuaTokenStream(text) + -- Tracking for the current position in the buffer, and + -- the current line / character we are on. + local p = 1 + local length = #text + + -- Output buffer for tokens + local tokenBuffer = {} + + -- Get a character, or '' if at eof + local function look(n) + n = p + (n or 0) + if n <= length then + return text:sub(n, n) + else + return '' + end + end + local function get() + if p <= length then + local c = text:sub(p, p) + p = p + 1 + return c + else + return '' + end + end + + -- Error + local olderr = error + local function error(str) + local q = 1 + local line = 1 + local char = 1 + while q <= p do + if text:sub(q, q) == '\n' then + line = line + 1 + char = 1 + else + char = char + 1 + end + q = q + 1 + end + for _, token in pairs(tokenBuffer) do + print(token.Type .. "<" .. token.Source .. ">") + end + olderr("file<" .. line .. ":" .. char .. ">: " .. str) + end + + -- Consume a long data with equals count of `eqcount' + local function longdata(eqcount) + while true do + local c = get() + if c == '' then + error("Unfinished long string.") + elseif c == ']' then + local done = true -- Until contested + for i = 1, eqcount do + if look() == '=' then + p = p + 1 + else + done = false + break + end + end + if done and get() == ']' then + return + end + end + end + end + + -- Get the opening part for a long data `[` `=`* `[` + -- Precondition: The first `[` has been consumed + -- Return: nil or the equals count + local function getopen() + local startp = p + while look() == '=' do + p = p + 1 + end + if look() == '[' then + p = p + 1 + return p - startp - 1 + else + p = startp + return nil + end + end + + -- Add token + local whiteStart = 1 + local tokenStart = 1 + local function token(type) + local tk = { + Type = type, + LeadingWhite = text:sub(whiteStart, tokenStart - 1), + Source = text:sub(tokenStart, p - 1), + } + table.insert(tokenBuffer, tk) + whiteStart = p + tokenStart = p + return tk + end + + -- Parse tokens loop + while true do + -- Mark the whitespace start + whiteStart = p + + -- Get the leading whitespace + comments + while true do + local c = look() + if c == '' then + break + elseif c == '-' then + if look(1) == '-' then + p = p + 2 + -- Consume comment body + if look() == '[' then + p = p + 1 + local eqcount = getopen() + if eqcount then + -- Long comment body + longdata(eqcount) + else + -- Normal comment body + while true do + local c2 = get() + if c2 == '' or c2 == '\n' then + break + end + end + end + else + -- Normal comment body + while true do + local c2 = get() + if c2 == '' or c2 == '\n' then + break + end + end + end + else + break + end + elseif WhiteChars[c] then + p = p + 1 + else + break + end + end + local leadingWhite = text:sub(whiteStart, p - 1) + + -- Mark the token start + tokenStart = p + + -- Switch on token type + local c1 = get() + if c1 == '' then + -- End of file + token('Eof') + break + elseif c1 == '\'' or c1 == '\"' then + -- String constant + while true do + local c2 = get() + if c2 == '\\' then + local c3 = get() + local esc = CharacterForEscape[c3] + if not esc then + error("Invalid Escape Sequence `" .. c3 .. "`.") + end + elseif c2 == c1 then + break + end + end + token('String') + elseif AllIdentStartChars[c1] then + -- Ident or Keyword + while AllIdentChars[look()] do + p = p + 1 + end + if Keywords[text:sub(tokenStart, p - 1)] then + token('Keyword') + else + token('Ident') + end + elseif Digits[c1] or (c1 == '.' and Digits[look()]) then + -- Number + if c1 == '0' and look() == 'x' then + p = p + 1 + -- Hex number + while HexDigits[look()] do + p = p + 1 + end + else + -- Normal Number + while Digits[look()] do + p = p + 1 + end + if look() == '.' then + -- With decimal point + p = p + 1 + while Digits[look()] do + p = p + 1 + end + end + if look() == 'e' or look() == 'E' then + -- With exponent + p = p + 1 + if look() == '-' then + p = p + 1 + end + while Digits[look()] do + p = p + 1 + end + end + end + token('Number') + elseif c1 == '[' then + -- '[' Symbol or Long String + local eqCount = getopen() + if eqCount then + -- Long string + longdata(eqCount) + token('String') + else + -- Symbol + token('Symbol') + end + elseif c1 == '.' then + -- Greedily consume up to 3 `.` for . / .. / ... tokens + if look() == '.' then + get() + if look() == '.' then + get() + end + end + token('Symbol') + elseif EqualSymbols[c1] then + if look() == '=' then + p = p + 1 + end + token('Symbol') + elseif c1 == ':' then + -- ':' or '::' + if look() == ':' then + get() + end + token('Symbol') + elseif Symbols[c1] then + token('Symbol') + else + error("Bad symbol `" .. c1 .. "` in source.") + end + end + return tokenBuffer +end + +local function CreateLuaParser(text) + -- Token stream and pointer into it + local tokens = CreateLuaTokenStream(text) + -- for _, tok in pairs(tokens) do + -- print(tok.Type..": "..tok.Source) + -- end + local p = 1 + + local function get() + local tok = tokens[p] + if p < #tokens then + p = p + 1 + end + return tok + end + local function peek(n) + n = p + (n or 0) + return tokens[n] or tokens[#tokens] + end + + local function getTokenStartPosition(token) + local line = 1 + local char = 0 + local tkNum = 1 + while true do + local tk = tokens[tkNum] + local text; + if tk == token then + text = tk.LeadingWhite + else + text = tk.LeadingWhite .. tk.Source + end + for i = 1, #text do + local c = text:sub(i, i) + if c == '\n' then + line = line + 1 + char = 0 + else + char = char + 1 + end + end + if tk == token then + break + end + tkNum = tkNum + 1 + end + return line .. ":" .. (char + 1) + end + local function debugMark() + local tk = peek() + return "<" .. tk.Type .. " `" .. tk.Source .. "`> at: " .. getTokenStartPosition(tk) + end + + local function isBlockFollow() + local tok = peek() + return tok.Type == 'Eof' or (tok.Type == 'Keyword' and BlockFollowKeyword[tok.Source]) + end + local function isUnop() + return UnopSet[peek().Source] or false + end + local function isBinop() + return BinopSet[peek().Source] or false + end + local function expect(type, source) + local tk = peek() + if tk.Type == type and (source == nil or tk.Source == source) then + return get() + else + for i = -3, 3 do + print("Tokens[" .. i .. "] = `" .. peek(i).Source .. "`") + end + if source then + error(getTokenStartPosition(tk) .. ": `" .. source .. "` expected.") + else + error(getTokenStartPosition(tk) .. ": " .. type .. " expected.") + end + end + end + + local function MkNode(node) + local getf = node.GetFirstToken + local getl = node.GetLastToken + function node:GetFirstToken() + local t = getf(self) + assert(t) + return t + end + + function node:GetLastToken() + local t = getl(self) + assert(t) + return t + end + + return node + end + + -- Forward decls + local block; + local expr; + + -- Expression list + local function exprlist() + local exprList = {} + local commaList = {} + table.insert(exprList, expr()) + while peek().Source == ',' do + table.insert(commaList, get()) + table.insert(exprList, expr()) + end + return exprList, commaList + end + + local function prefixexpr() + local tk = peek() + if tk.Source == '(' then + local oparenTk = get() + local inner = expr() + local cparenTk = expect('Symbol', ')') + return MkNode { + Type = 'ParenExpr', + Expression = inner, + Token_OpenParen = oparenTk, + Token_CloseParen = cparenTk, + GetFirstToken = function(self) + return self.Token_OpenParen + end, + GetLastToken = function(self) + return self.Token_CloseParen + end, + } + elseif tk.Type == 'Ident' then + return MkNode { + Type = 'VariableExpr', + Token = get(), + GetFirstToken = function(self) + return self.Token + end, + GetLastToken = function(self) + return self.Token + end, + } + else + print(debugMark()) + error(getTokenStartPosition(tk) .. ": Unexpected symbol") + end + end + + local function tableexpr() + local obrace = expect('Symbol', '{') + local entries = {} + local separators = {} + while peek().Source ~= '}' do + if peek().Source == '[' then + -- Index + local obrac = get() + local index = expr() + local cbrac = expect('Symbol', ']') + local eq = expect('Symbol', '=') + local value = expr() + table.insert(entries, { + EntryType = 'Index', + Index = index, + Value = value, + Token_OpenBracket = obrac, + Token_CloseBracket = cbrac, + Token_Equals = eq, + }) + elseif peek().Type == 'Ident' and peek(1).Source == '=' then + -- Field + local field = get() + local eq = get() + local value = expr() + table.insert(entries, { + EntryType = 'Field', + Field = field, + Value = value, + Token_Equals = eq, + }) + else + -- Value + local value = expr() + table.insert(entries, { + EntryType = 'Value', + Value = value, + }) + end + + -- Comma or Semicolon separator + if peek().Source == ',' or peek().Source == ';' then + table.insert(separators, get()) + else + break + end + end + local cbrace = expect('Symbol', '}') + return MkNode { + Type = 'TableLiteral', + EntryList = entries, + Token_SeparatorList = separators, + Token_OpenBrace = obrace, + Token_CloseBrace = cbrace, + GetFirstToken = function(self) + return self.Token_OpenBrace + end, + GetLastToken = function(self) + return self.Token_CloseBrace + end, + } + end + + -- List of identifiers + local function varlist() + local varList = {} + local commaList = {} + local hasVararg = false + + -- first item + if peek().Source == '...' then + table.insert(varList, get()) + hasVararg = true + elseif peek().Type == 'Ident' then + table.insert(varList, get()) + end + + -- remaining items + while peek().Source == ',' do + table.insert(commaList, get()) + + if peek().Source == '...' then + table.insert(varList, get()) + hasVararg = true + break -- vararg must be last + else + table.insert(varList, expect('Ident')) + end + end + + return varList, commaList, hasVararg + end + + -- Body + local function blockbody(terminator) + local body = block() + local after = peek() + if after.Type == 'Keyword' and after.Source == terminator then + get() + return body, after + else + print(after.Type, after.Source) + error(getTokenStartPosition(after) .. ": " .. terminator .. " expected.") + end + end + + -- Function declaration + local function funcdecl(isAnonymous) + local functionKw = get() + -- + local nameChain; + local nameChainSeparator; + -- + if not isAnonymous then + nameChain = {} + nameChainSeparator = {} + -- + table.insert(nameChain, expect('Ident')) + -- + while peek().Source == '.' do + table.insert(nameChainSeparator, get()) + table.insert(nameChain, expect('Ident')) + end + if peek().Source == ':' then + table.insert(nameChainSeparator, get()) + table.insert(nameChain, expect('Ident')) + end + end + -- + local oparenTk = expect('Symbol', '(') + local argList, argCommaList, hasVararg = varlist() + local cparenTk = expect('Symbol', ')') + local fbody, enTk = blockbody('end') + -- + return MkNode { + Type = (isAnonymous and 'FunctionLiteral' or 'FunctionStat'), + NameChain = nameChain, + ArgList = argList, + Body = fbody, + HasVararg = hasVararg, + -- + Token_Function = functionKw, + Token_NameChainSeparator = nameChainSeparator, + Token_OpenParen = oparenTk, + Token_ArgCommaList = argCommaList, + Token_CloseParen = cparenTk, + Token_End = enTk, + GetFirstToken = function(self) + return self.Token_Function + end, + GetLastToken = function(self) + return self.Token_End; + end, + } + end + + -- Argument list passed to a funciton + local function functionargs() + local tk = peek() + if tk.Source == '(' then + local oparenTk = get() + local argList = {} + local argCommaList = {} + while peek().Source ~= ')' do + table.insert(argList, expr()) + if peek().Source == ',' then + table.insert(argCommaList, get()) + else + break + end + end + local cparenTk = expect('Symbol', ')') + return MkNode { + CallType = 'ArgCall', + ArgList = argList, + -- + Token_CommaList = argCommaList, + Token_OpenParen = oparenTk, + Token_CloseParen = cparenTk, + GetFirstToken = function(self) + return self.Token_OpenParen + end, + GetLastToken = function(self) + return self.Token_CloseParen + end, + } + elseif tk.Source == '{' then + return MkNode { + CallType = 'TableCall', + TableExpr = expr(), + GetFirstToken = function(self) + return self.TableExpr:GetFirstToken() + end, + GetLastToken = function(self) + return self.TableExpr:GetLastToken() + end, + } + elseif tk.Type == 'String' then + return MkNode { + CallType = 'StringCall', + Token = get(), + GetFirstToken = function(self) + return self.Token + end, + GetLastToken = function(self) + return self.Token + end, + } + else + error("Function arguments expected.") + end + end + + local function primaryexpr() + local base = prefixexpr() + assert(base, "nil prefixexpr") + while true do + local tk = peek() + if tk.Source == '.' then + local dotTk = get() + local fieldName = expect('Ident') + base = MkNode { + Type = 'FieldExpr', + Base = base, + Field = fieldName, + Token_Dot = dotTk, + GetFirstToken = function(self) + return self.Base:GetFirstToken() + end, + GetLastToken = function(self) + return self.Field + end, + } + elseif tk.Source == ':' then + local colonTk = get() + local methodName = expect('Ident') + local fargs = functionargs() + base = MkNode { + Type = 'MethodExpr', + Base = base, + Method = methodName, + FunctionArguments = fargs, + Token_Colon = colonTk, + GetFirstToken = function(self) + return self.Base:GetFirstToken() + end, + GetLastToken = function(self) + return self.FunctionArguments:GetLastToken() + end, + } + elseif tk.Source == '[' then + local obrac = get() + local index = expr() + local cbrac = expect('Symbol', ']') + base = MkNode { + Type = 'IndexExpr', + Base = base, + Index = index, + Token_OpenBracket = obrac, + Token_CloseBracket = cbrac, + GetFirstToken = function(self) + return self.Base:GetFirstToken() + end, + GetLastToken = function(self) + return self.Token_CloseBracket + end, + } + elseif tk.Source == '{' then + base = MkNode { + Type = 'CallExpr', + Base = base, + FunctionArguments = functionargs(), + GetFirstToken = function(self) + return self.Base:GetFirstToken() + end, + GetLastToken = function(self) + return self.FunctionArguments:GetLastToken() + end, + } + elseif tk.Source == '(' then + base = MkNode { + Type = 'CallExpr', + Base = base, + FunctionArguments = functionargs(), + GetFirstToken = function(self) + return self.Base:GetFirstToken() + end, + GetLastToken = function(self) + return self.FunctionArguments:GetLastToken() + end, + } + else + return base + end + end + end + + local function simpleexpr() + local tk = peek() + if tk.Type == 'Number' then + return MkNode { + Type = 'NumberLiteral', + Token = get(), + GetFirstToken = function(self) + return self.Token + end, + GetLastToken = function(self) + return self.Token + end, + } + elseif tk.Type == 'String' then + return MkNode { + Type = 'StringLiteral', + Token = get(), + GetFirstToken = function(self) + return self.Token + end, + GetLastToken = function(self) + return self.Token + end, + } + elseif tk.Source == 'nil' then + return MkNode { + Type = 'NilLiteral', + Token = get(), + GetFirstToken = function(self) + return self.Token + end, + GetLastToken = function(self) + return self.Token + end, + } + elseif tk.Source == 'true' or tk.Source == 'false' then + return MkNode { + Type = 'BooleanLiteral', + Token = get(), + GetFirstToken = function(self) + return self.Token + end, + GetLastToken = function(self) + return self.Token + end, + } + elseif tk.Source == '...' then + return MkNode { + Type = 'VargLiteral', + Token = get(), + GetFirstToken = function(self) + return self.Token + end, + GetLastToken = function(self) + return self.Token + end, + } + elseif tk.Source == '{' then + return tableexpr() + elseif tk.Source == 'function' then + return funcdecl(true) + else + return primaryexpr() + end + end + + local function subexpr(limit) + local curNode; + + -- Initial Base Expression + if isUnop() then + local opTk = get() + local ex = subexpr(UnaryPriority) + curNode = MkNode { + Type = 'UnopExpr', + Token_Op = opTk, + Rhs = ex, + GetFirstToken = function(self) + return self.Token_Op + end, + GetLastToken = function(self) + return self.Rhs:GetLastToken() + end, + } + else + curNode = simpleexpr() + assert(curNode, "nil simpleexpr") + end + + -- Apply Precedence Recursion Chain + while isBinop() and BinaryPriority[peek().Source][1] > limit do + local opTk = get() + local rhs = subexpr(BinaryPriority[opTk.Source][2]) + assert(rhs, "RhsNeeded") + curNode = MkNode { + Type = 'BinopExpr', + Lhs = curNode, + Rhs = rhs, + Token_Op = opTk, + GetFirstToken = function(self) + return self.Lhs:GetFirstToken() + end, + GetLastToken = function(self) + return self.Rhs:GetLastToken() + end, + } + end + + -- Return result + return curNode + end + + -- Expression + expr = function() + return subexpr(0) + end + + -- Expression statement + local function exprstat() + local ex = primaryexpr() + if ex.Type == 'MethodExpr' or ex.Type == 'CallExpr' then + -- all good, calls can be statements + return MkNode { + Type = 'CallExprStat', + Expression = ex, + GetFirstToken = function(self) + return self.Expression:GetFirstToken() + end, + GetLastToken = function(self) + return self.Expression:GetLastToken() + end, + } + else + -- Assignment expr + local lhs = { ex } + local lhsSeparator = {} + while peek().Source == ',' do + table.insert(lhsSeparator, get()) + local lhsPart = primaryexpr() + if lhsPart.Type == 'MethodExpr' or lhsPart.Type == 'CallExpr' then + error("Bad left hand side of assignment") + end + table.insert(lhs, lhsPart) + end + local eq = expect('Symbol', '=') + local rhs = { expr() } + local rhsSeparator = {} + while peek().Source == ',' do + table.insert(rhsSeparator, get()) + table.insert(rhs, expr()) + end + return MkNode { + Type = 'AssignmentStat', + Rhs = rhs, + Lhs = lhs, + Token_Equals = eq, + Token_LhsSeparatorList = lhsSeparator, + Token_RhsSeparatorList = rhsSeparator, + GetFirstToken = function(self) + return self.Lhs[1]:GetFirstToken() + end, + GetLastToken = function(self) + return self.Rhs[#self.Rhs]:GetLastToken() + end, + } + end + end + + -- If statement + local function ifstat() + local ifKw = get() + local condition = expr() + local thenKw = expect('Keyword', 'then') + local ifBody = block() + local elseClauses = {} + while peek().Source == 'elseif' or peek().Source == 'else' do + local elseifKw = get() + local elseifCondition, elseifThenKw; + if elseifKw.Source == 'elseif' then + elseifCondition = expr() + elseifThenKw = expect('Keyword', 'then') + end + local elseifBody = block() + table.insert(elseClauses, { + Condition = elseifCondition, + Body = elseifBody, + -- + ClauseType = elseifKw.Source, + Token = elseifKw, + Token_Then = elseifThenKw, + }) + if elseifKw.Source == 'else' then + break + end + end + local enKw = expect('Keyword', 'end') + return MkNode { + Type = 'IfStat', + Condition = condition, + Body = ifBody, + ElseClauseList = elseClauses, + -- + Token_If = ifKw, + Token_Then = thenKw, + Token_End = enKw, + GetFirstToken = function(self) + return self.Token_If + end, + GetLastToken = function(self) + return self.Token_End + end, + } + end + + -- Do statement + local function dostat() + local doKw = get() + local body, enKw = blockbody('end') + -- + return MkNode { + Type = 'DoStat', + Body = body, + -- + Token_Do = doKw, + Token_End = enKw, + GetFirstToken = function(self) + return self.Token_Do + end, + GetLastToken = function(self) + return self.Token_End + end, + } + end + + -- While statement + local function whilestat() + local whileKw = get() + local condition = expr() + local doKw = expect('Keyword', 'do') + local body, enKw = blockbody('end') + -- + return MkNode { + Type = 'WhileStat', + Condition = condition, + Body = body, + -- + Token_While = whileKw, + Token_Do = doKw, + Token_End = enKw, + GetFirstToken = function(self) + return self.Token_While + end, + GetLastToken = function(self) + return self.Token_End + end, + } + end + + -- For statement + local function forstat() + local forKw = get() + local loopVars, loopVarCommas = varlist() + local node = {} + if peek().Source == '=' then + local eqTk = get() + local exprList, exprCommaList = exprlist() + if #exprList < 2 or #exprList > 3 then + error("expected 2 or 3 values for range bounds") + end + local doTk = expect('Keyword', 'do') + local body, enTk = blockbody('end') + return MkNode { + Type = 'NumericForStat', + VarList = loopVars, + RangeList = exprList, + Body = body, + -- + Token_For = forKw, + Token_VarCommaList = loopVarCommas, + Token_Equals = eqTk, + Token_RangeCommaList = exprCommaList, + Token_Do = doTk, + Token_End = enTk, + GetFirstToken = function(self) + return self.Token_For + end, + GetLastToken = function(self) + return self.Token_End + end, + } + elseif peek().Source == 'in' then + local inTk = get() + local exprList, exprCommaList = exprlist() + local doTk = expect('Keyword', 'do') + local body, enTk = blockbody('end') + return MkNode { + Type = 'GenericForStat', + VarList = loopVars, + GeneratorList = exprList, + Body = body, + -- + Token_For = forKw, + Token_VarCommaList = loopVarCommas, + Token_In = inTk, + Token_GeneratorCommaList = exprCommaList, + Token_Do = doTk, + Token_End = enTk, + GetFirstToken = function(self) + return self.Token_For + end, + GetLastToken = function(self) + return self.Token_End + end, + } + else + error("`=` or in expected") + end + end + + -- Repeat statement + local function repeatstat() + local repeatKw = get() + local body, untilTk = blockbody('until') + local condition = expr() + return MkNode { + Type = 'RepeatStat', + Body = body, + Condition = condition, + -- + Token_Repeat = repeatKw, + Token_Until = untilTk, + GetFirstToken = function(self) + return self.Token_Repeat + end, + GetLastToken = function(self) + return self.Condition:GetLastToken() + end, + } + end + + -- Local var declaration + local function localdecl() + local localKw = get() + if peek().Source == 'function' then + -- Local function def + local funcStat = funcdecl(false) + if #funcStat.NameChain > 1 then + error(getTokenStartPosition(funcStat.Token_NameChainSeparator[1]) .. ": `(` expected.") + end + return MkNode { + Type = 'LocalFunctionStat', + FunctionStat = funcStat, + Token_Local = localKw, + GetFirstToken = function(self) + return self.Token_Local + end, + GetLastToken = function(self) + return self.FunctionStat:GetLastToken() + end, + } + elseif peek().Type == 'Ident' then + -- Local variable declaration + local varList, varCommaList, hasVararg = varlist() + local exprList, exprCommaList = {}, {} + local eqToken; + if peek().Source == '=' then + eqToken = get() + exprList, exprCommaList = exprlist() + end + return MkNode { + Type = 'LocalVarStat', + VarList = varList, + ExprList = exprList, + HasVararg = hasVararg, + Token_Local = localKw, + Token_Equals = eqToken, + Token_VarCommaList = varCommaList, + Token_ExprCommaList = exprCommaList, + GetFirstToken = function(self) + return self.Token_Local + end, + GetLastToken = function(self) + if #self.ExprList > 0 then + return self.ExprList[#self.ExprList]:GetLastToken() + else + return self.VarList[#self.VarList] + end + end, + } + else + error("`function` or ident expected") + end + end + + -- Return statement + local function retstat() + local returnKw = get() + local exprList; + local commaList; + if isBlockFollow() or peek().Source == ';' then + exprList = {} + commaList = {} + else + exprList, commaList = exprlist() + end + return { + Type = 'ReturnStat', + ExprList = exprList, + Token_Return = returnKw, + Token_CommaList = commaList, + GetFirstToken = function(self) + return self.Token_Return + end, + GetLastToken = function(self) + if #self.ExprList > 0 then + return self.ExprList[#self.ExprList]:GetLastToken() + else + return self.Token_Return + end + end, + } + end + + -- Break statement + local function breakstat() + local breakKw = get() + return { + Type = 'BreakStat', + Token_Break = breakKw, + GetFirstToken = function(self) + return self.Token_Break + end, + GetLastToken = function(self) + return self.Token_Break + end, + } + end + + local function labelstat() + local open1 = expect('Symbol', '::') + local name = expect('Ident') + local open2 = expect('Symbol', '::') + + return MkNode { + Type = 'LabelStat', + Label = name, + + Token_Open1 = open1, + Token_Name = name, + Token_Open2 = open2, + + GetFirstToken = function(self) + return self.Token_Open1 + end, + + GetLastToken = function(self) + return self.Token_Open2 + end, + } + end + + local function gotostat() + local gotoKw = get() + local label = expect('Ident') + + return MkNode { + Type = 'GotoStat', + Label = label, + + Token_Goto = gotoKw, + Token_Label = label, + + GetFirstToken = function(self) + return self.Token_Goto + end, + + GetLastToken = function(self) + return self.Token_Label + end, + } + end + + -- Expression + local function statement() + local tok = peek() + if tok.Source == 'if' then + return false, ifstat() + elseif tok.Source == 'while' then + return false, whilestat() + elseif tok.Source == 'do' then + return false, dostat() + elseif tok.Source == 'for' then + return false, forstat() + elseif tok.Source == 'repeat' then + return false, repeatstat() + elseif tok.Source == 'function' then + return false, funcdecl(false) + elseif tok.Source == 'local' then + return false, localdecl() + elseif tok.Source == 'return' then + return true, retstat() + elseif tok.Source == 'break' then + return true, breakstat() + elseif tok.Source == 'goto' then + return false, gotostat() + elseif tok.Source == '::' then + return false, labelstat() + else + return false, exprstat() + end + end + + -- Chunk + block = function() + local statements = {} + local semicolons = {} + local isLast = false + while not isLast and not isBlockFollow() do + -- Parse statement + local stat; + isLast, stat = statement() + table.insert(statements, stat) + local next = peek() + if next.Type == 'Symbol' and next.Source == ';' then + semicolons[#statements] = get() + end + end + return { + Type = 'StatList', + StatementList = statements, + SemicolonList = semicolons, + GetFirstToken = function(self) + if #self.StatementList == 0 then + return nil + else + return self.StatementList[1]:GetFirstToken() + end + end, + GetLastToken = function(self) + if #self.StatementList == 0 then + return nil + elseif self.SemicolonList[#self.StatementList] then + -- Last token may be one of the semicolon separators + return self.SemicolonList[#self.StatementList] + else + return self.StatementList[#self.StatementList]:GetLastToken() + end + end, + } + end + + return block() +end + +local function VisitAst(ast, visitors) + local ExprType = lookupify { + 'BinopExpr', 'UnopExpr', + 'NumberLiteral', 'StringLiteral', 'NilLiteral', 'BooleanLiteral', 'VargLiteral', + 'FieldExpr', 'IndexExpr', + 'MethodExpr', 'CallExpr', + 'FunctionLiteral', + 'VariableExpr', + 'ParenExpr', + 'TableLiteral', + } + + local StatType = lookupify { + 'StatList', + 'BreakStat', + 'ReturnStat', + 'LocalVarStat', + 'LocalFunctionStat', + 'FunctionStat', + 'RepeatStat', + 'GenericForStat', + 'NumericForStat', + 'WhileStat', + 'DoStat', + 'IfStat', + 'CallExprStat', + 'AssignmentStat', + } + + -- Check for typos in visitor construction + for visitorSubject, visitor in pairs(visitors) do + if not StatType[visitorSubject] and not ExprType[visitorSubject] then + error("Invalid visitor target: `" .. visitorSubject .. "`") + end + end + + -- Helpers to call visitors on a node + local function preVisit(exprOrStat) + local visitor = visitors[exprOrStat.Type] + if type(visitor) == 'function' then + return visitor(exprOrStat) + elseif visitor and visitor.Pre then + return visitor.Pre(exprOrStat) + end + end + local function postVisit(exprOrStat) + local visitor = visitors[exprOrStat.Type] + if visitor and type(visitor) == 'table' and visitor.Post then + return visitor.Post(exprOrStat) + end + end + + local visitExpr, visitStat; + + visitExpr = function(expr) + if preVisit(expr) then + -- Handler did custom child iteration or blocked child iteration + return + end + if expr.Type == 'BinopExpr' then + visitExpr(expr.Lhs) + visitExpr(expr.Rhs) + elseif expr.Type == 'UnopExpr' then + visitExpr(expr.Rhs) + elseif expr.Type == 'NumberLiteral' or expr.Type == 'StringLiteral' or + expr.Type == 'NilLiteral' or expr.Type == 'BooleanLiteral' or + expr.Type == 'VargLiteral' + then + -- No children to visit, single token literals + elseif expr.Type == 'FieldExpr' then + visitExpr(expr.Base) + elseif expr.Type == 'IndexExpr' then + visitExpr(expr.Base) + visitExpr(expr.Index) + elseif expr.Type == 'MethodExpr' or expr.Type == 'CallExpr' then + visitExpr(expr.Base) + if expr.FunctionArguments.CallType == 'ArgCall' then + for index, argExpr in pairs(expr.FunctionArguments.ArgList) do + visitExpr(argExpr) + end + elseif expr.FunctionArguments.CallType == 'TableCall' then + visitExpr(expr.FunctionArguments.TableExpr) + end + elseif expr.Type == 'FunctionLiteral' then + visitStat(expr.Body) + elseif expr.Type == 'VariableExpr' then + -- No children to visit + elseif expr.Type == 'ParenExpr' then + visitExpr(expr.Expression) + elseif expr.Type == 'TableLiteral' then + for index, entry in pairs(expr.EntryList) do + if entry.EntryType == 'Field' then + visitExpr(entry.Value) + elseif entry.EntryType == 'Index' then + visitExpr(entry.Index) + visitExpr(entry.Value) + elseif entry.EntryType == 'Value' then + visitExpr(entry.Value) + else + assert(false, "unreachable") + end + end + else + assert(false, "unreachable, type: " .. expr.Type .. ":" .. FormatTable(expr)) + end + postVisit(expr) + end + + visitStat = function(stat) + if preVisit(stat) then + -- Handler did custom child iteration or blocked child iteration + return + end + if stat.Type == 'StatList' then + for index, ch in pairs(stat.StatementList) do + visitStat(ch) + end + elseif stat.Type == 'BreakStat' then + -- No children to visit + elseif stat.Type == 'ReturnStat' then + for index, expr in pairs(stat.ExprList) do + visitExpr(expr) + end + elseif stat.Type == 'LocalVarStat' then + if stat.Token_Equals then + for index, expr in pairs(stat.ExprList) do + visitExpr(expr) + end + end + elseif stat.Type == 'LocalFunctionStat' then + visitStat(stat.FunctionStat.Body) + elseif stat.Type == 'FunctionStat' then + visitStat(stat.Body) + elseif stat.Type == 'RepeatStat' then + visitStat(stat.Body) + visitExpr(stat.Condition) + elseif stat.Type == 'GenericForStat' then + for index, expr in pairs(stat.GeneratorList) do + visitExpr(expr) + end + visitStat(stat.Body) + elseif stat.Type == 'NumericForStat' then + for index, expr in pairs(stat.RangeList) do + visitExpr(expr) + end + visitStat(stat.Body) + elseif stat.Type == 'WhileStat' then + visitExpr(stat.Condition) + visitStat(stat.Body) + elseif stat.Type == 'DoStat' then + visitStat(stat.Body) + elseif stat.Type == 'IfStat' then + visitExpr(stat.Condition) + visitStat(stat.Body) + for _, clause in pairs(stat.ElseClauseList) do + if clause.Condition then + visitExpr(clause.Condition) + end + visitStat(clause.Body) + end + elseif stat.Type == 'CallExprStat' then + visitExpr(stat.Expression) + elseif stat.Type == 'AssignmentStat' then + for index, ex in pairs(stat.Lhs) do + visitExpr(ex) + end + for index, ex in pairs(stat.Rhs) do + visitExpr(ex) + end + else + assert(false, "unreachable") + end + postVisit(stat) + end + + if StatType[ast.Type] then + visitStat(ast) + else + visitExpr(ast) + end +end + +local function AddVariableInfo(ast) + local globalVars = {} + local currentScope = nil + + -- Numbering generator for variable lifetimes + local locationGenerator = 0 + local function markLocation() + locationGenerator = locationGenerator + 1 + return locationGenerator + end + + -- Scope management + local function pushScope() + currentScope = { + ParentScope = currentScope, + ChildScopeList = {}, + VariableList = {}, + BeginLocation = markLocation(), + } + if currentScope.ParentScope then + currentScope.Depth = currentScope.ParentScope.Depth + 1 + table.insert(currentScope.ParentScope.ChildScopeList, currentScope) + else + currentScope.Depth = 1 + end + function currentScope:GetVar(varName) + for _, var in pairs(self.VariableList) do + if var.Name == varName then + return var + end + end + if self.ParentScope then + return self.ParentScope:GetVar(varName) + else + for _, var in pairs(globalVars) do + if var.Name == varName then + return var + end + end + end + end + end + local function popScope() + local scope = currentScope + + -- Mark where this scope ends + scope.EndLocation = markLocation() + + -- Mark all of the variables in the scope as ending there + for _, var in pairs(scope.VariableList) do + var.ScopeEndLocation = scope.EndLocation + end + + -- Move to the parent scope + currentScope = scope.ParentScope + + return scope + end + pushScope() -- push initial scope + + -- Add / reference variables + local function addLocalVar(name, setNameFunc, localInfo) + assert(localInfo, "Misisng localInfo") + assert(name, "Missing local var name") + local var = { + Type = 'Local', + Name = name, + RenameList = { setNameFunc }, + AssignedTo = false, + Info = localInfo, + UseCount = 0, + Scope = currentScope, + BeginLocation = markLocation(), + EndLocation = markLocation(), + ReferenceLocationList = { markLocation() }, + } + function var:Rename(newName) + self.Name = newName + for _, renameFunc in pairs(self.RenameList) do + renameFunc(newName) + end + end + + function var:Reference() + self.UseCount = self.UseCount + 1 + end + + table.insert(currentScope.VariableList, var) + return var + end + local function getGlobalVar(name) + for _, var in pairs(globalVars) do + if var.Name == name then + return var + end + end + local var = { + Type = 'Global', + Name = name, + RenameList = {}, + AssignedTo = false, + UseCount = 0, + Scope = nil, -- Globals have no scope + BeginLocation = markLocation(), + EndLocation = markLocation(), + ReferenceLocationList = {}, + } + function var:Rename(newName) + self.Name = newName + for _, renameFunc in pairs(self.RenameList) do + renameFunc(newName) + end + end + + function var:Reference() + self.UseCount = self.UseCount + 1 + end + + table.insert(globalVars, var) + return var + end + local function addGlobalReference(name, setNameFunc) + assert(name, "Missing var name") + local var = getGlobalVar(name) + table.insert(var.RenameList, setNameFunc) + return var + end + local function getLocalVar(scope, name) + -- First search this scope + -- Note: Reverse iterate here because Lua does allow shadowing a local + -- within the same scope, and the later defined variable should + -- be the one referenced. + for i = #scope.VariableList, 1, -1 do + if scope.VariableList[i].Name == name then + return scope.VariableList[i] + end + end + + -- Then search parent scope + if scope.ParentScope then + local var = getLocalVar(scope.ParentScope, name) + if var then + return var + end + end + + -- Then + return nil + end + local function referenceVariable(name, setNameFunc) + assert(name, "Missing var name") + local var = getLocalVar(currentScope, name) + if var then + table.insert(var.RenameList, setNameFunc) + else + var = addGlobalReference(name, setNameFunc) + end + -- Update the end location of where this variable is used, and + -- add this location to the list of references to this variable. + local curLocation = markLocation() + var.EndLocation = curLocation + table.insert(var.ReferenceLocationList, var.EndLocation) + return var + end + + local visitor = {} + visitor.FunctionLiteral = { + -- Function literal adds a new scope and adds the function literal arguments + -- as local variables in the scope. + Pre = function(expr) + pushScope() + for index, ident in pairs(expr.ArgList) do + local var = addLocalVar(ident.Source, function(name) + ident.Source = name + end, { + Type = 'Argument', + Index = index, + }) + end + end, + Post = function(expr) + popScope() + end, + } + visitor.VariableExpr = function(expr) + -- Variable expression references from existing local varibales + -- in the current scope, annotating the variable usage with variable + -- information. + expr.Variable = referenceVariable(expr.Token.Source, function(newName) + expr.Token.Source = newName + end) + end + visitor.StatList = { + -- StatList adds a new scope + Pre = function(stat) + pushScope() + end, + Post = function(stat) + popScope() + end, + } + visitor.LocalVarStat = { + Post = function(stat) + -- Local var stat adds the local variables to the current scope as locals + -- We need to visit the subexpressions first, because these new locals + -- will not be in scope for the initialization value expressions. That is: + -- `local bar = bar + 1` + -- Is valid code + for varNum, ident in pairs(stat.VarList) do + addLocalVar(ident.Source, function(name) + stat.VarList[varNum].Source = name + end, { + Type = 'Local', + }) + end + end, + } + visitor.LocalFunctionStat = { + Pre = function(stat) + -- Local function stat adds the function itself to the current scope as + -- a local variable, and creates a new scope with the function arguments + -- as local variables. + addLocalVar(stat.FunctionStat.NameChain[1].Source, function(name) + stat.FunctionStat.NameChain[1].Source = name + end, { + Type = 'LocalFunction', + }) + pushScope() + for index, ident in pairs(stat.FunctionStat.ArgList) do + addLocalVar(ident.Source, function(name) + ident.Source = name + end, { + Type = 'Argument', + Index = index, + }) + end + end, + Post = function() + popScope() + end, + } + visitor.FunctionStat = { + Pre = function(stat) + -- Function stat adds a new scope containing the function arguments + -- as local variables. + -- A function stat may also assign to a global variable if it is in + -- the form `function foo()` with no additional dots/colons in the + -- name chain. + local nameChain = stat.NameChain + local var; + if #nameChain == 1 then + -- If there is only one item in the name chain, then the first item + -- is a reference to a global variable. + var = addGlobalReference(nameChain[1].Source, function(name) + nameChain[1].Source = name + end) + else + var = referenceVariable(nameChain[1].Source, function(name) + nameChain[1].Source = name + end) + end + var.AssignedTo = true + pushScope() + for index, ident in pairs(stat.ArgList) do + addLocalVar(ident.Source, function(name) + ident.Source = name + end, { + Type = 'Argument', + Index = index, + }) + end + end, + Post = function() + popScope() + end, + } + visitor.GenericForStat = { + Pre = function(stat) + -- Generic fors need an extra scope holding the range variables + -- Need a custom visitor so that the generator expressions can be + -- visited before we push a scope, but the body can be visited + -- after we push a scope. + for _, ex in pairs(stat.GeneratorList) do + VisitAst(ex, visitor) + end + pushScope() + for index, ident in pairs(stat.VarList) do + addLocalVar(ident.Source, function(name) + ident.Source = name + end, { + Type = 'ForRange', + Index = index, + }) + end + VisitAst(stat.Body, visitor) + popScope() + return true -- Custom visit + end, + } + visitor.NumericForStat = { + Pre = function(stat) + -- Numeric fors need an extra scope holding the range variables + -- Need a custom visitor so that the generator expressions can be + -- visited before we push a scope, but the body can be visited + -- after we push a scope. + for _, ex in pairs(stat.RangeList) do + VisitAst(ex, visitor) + end + pushScope() + for index, ident in pairs(stat.VarList) do + addLocalVar(ident.Source, function(name) + ident.Source = name + end, { + Type = 'ForRange', + Index = index, + }) + end + VisitAst(stat.Body, visitor) + popScope() + return true -- Custom visit + end, + } + visitor.AssignmentStat = { + Post = function(stat) + -- For an assignment statement we need to mark the + -- "assigned to" flag on variables. + for _, ex in pairs(stat.Lhs) do + if ex.Variable then + ex.Variable.AssignedTo = true + end + end + end, + } + + VisitAst(ast, visitor) + + return globalVars, popScope() +end + +-- Prints out an AST to a string +local function PrintAst(ast) + local printStat, printExpr; + local str = {} + + local function printt(tk) + if not tk.LeadingWhite or not tk.Source then + error("Bad token: " .. FormatTable(tk)) + end + str[#str + 1] = tk.LeadingWhite + str[#str + 1] = tk.Source + end + + printExpr = function(expr) + if expr.Type == 'BinopExpr' then + printExpr(expr.Lhs) + printt(expr.Token_Op) + printExpr(expr.Rhs) + elseif expr.Type == 'UnopExpr' then + printt(expr.Token_Op) + printExpr(expr.Rhs) + elseif expr.Type == 'NumberLiteral' or expr.Type == 'StringLiteral' or + expr.Type == 'NilLiteral' or expr.Type == 'BooleanLiteral' or + expr.Type == 'VargLiteral' + then + -- Just print the token + printt(expr.Token) + elseif expr.Type == 'FieldExpr' then + printExpr(expr.Base) + printt(expr.Token_Dot) + printt(expr.Field) + elseif expr.Type == 'IndexExpr' then + printExpr(expr.Base) + printt(expr.Token_OpenBracket) + printExpr(expr.Index) + printt(expr.Token_CloseBracket) + elseif expr.Type == 'MethodExpr' or expr.Type == 'CallExpr' then + printExpr(expr.Base) + if expr.Type == 'MethodExpr' then + printt(expr.Token_Colon) + printt(expr.Method) + end + if expr.FunctionArguments.CallType == 'StringCall' then + printt(expr.FunctionArguments.Token) + elseif expr.FunctionArguments.CallType == 'ArgCall' then + printt(expr.FunctionArguments.Token_OpenParen) + for index, argExpr in pairs(expr.FunctionArguments.ArgList) do + printExpr(argExpr) + local sep = expr.FunctionArguments.Token_CommaList[index] + if sep then + printt(sep) + end + end + printt(expr.FunctionArguments.Token_CloseParen) + elseif expr.FunctionArguments.CallType == 'TableCall' then + printExpr(expr.FunctionArguments.TableExpr) + end + elseif expr.Type == 'FunctionLiteral' then + printt(expr.Token_Function) + printt(expr.Token_OpenParen) + for index, arg in pairs(expr.ArgList) do + printt(arg) + local comma = expr.Token_ArgCommaList[index] + if comma then + printt(comma) + end + end + printt(expr.Token_CloseParen) + printStat(expr.Body) + printt(expr.Token_End) + elseif expr.Type == 'VariableExpr' then + printt(expr.Token) + elseif expr.Type == 'ParenExpr' then + printt(expr.Token_OpenParen) + printExpr(expr.Expression) + printt(expr.Token_CloseParen) + elseif expr.Type == 'TableLiteral' then + printt(expr.Token_OpenBrace) + for index, entry in pairs(expr.EntryList) do + if entry.EntryType == 'Field' then + printt(entry.Field) + printt(entry.Token_Equals) + printExpr(entry.Value) + elseif entry.EntryType == 'Index' then + printt(entry.Token_OpenBracket) + printExpr(entry.Index) + printt(entry.Token_CloseBracket) + printt(entry.Token_Equals) + printExpr(entry.Value) + elseif entry.EntryType == 'Value' then + printExpr(entry.Value) + else + assert(false, "unreachable") + end + local sep = expr.Token_SeparatorList[index] + if sep then + printt(sep) + end + end + printt(expr.Token_CloseBrace) + else + assert(false, "unreachable, type: " .. expr.Type .. ":" .. FormatTable(expr)) + end + end + + printStat = function(stat) + if stat.Type == 'StatList' then + for index, ch in pairs(stat.StatementList) do + printStat(ch) + if stat.SemicolonList[index] then + printt(stat.SemicolonList[index]) + end + end + elseif stat.Type == 'BreakStat' then + printt(stat.Token_Break) + elseif stat.Type == 'ReturnStat' then + printt(stat.Token_Return) + for index, expr in pairs(stat.ExprList) do + printExpr(expr) + if stat.Token_CommaList[index] then + printt(stat.Token_CommaList[index]) + end + end + elseif stat.Type == 'LocalVarStat' then + printt(stat.Token_Local) + for index, var in pairs(stat.VarList) do + printt(var) + local comma = stat.Token_VarCommaList[index] + if comma then + printt(comma) + end + end + if stat.Token_Equals then + printt(stat.Token_Equals) + for index, expr in pairs(stat.ExprList) do + printExpr(expr) + local comma = stat.Token_ExprCommaList[index] + if comma then + printt(comma) + end + end + end + elseif stat.Type == 'LocalFunctionStat' then + printt(stat.Token_Local) + printt(stat.FunctionStat.Token_Function) + printt(stat.FunctionStat.NameChain[1]) + printt(stat.FunctionStat.Token_OpenParen) + for index, arg in pairs(stat.FunctionStat.ArgList) do + printt(arg) + local comma = stat.FunctionStat.Token_ArgCommaList[index] + if comma then + printt(comma) + end + end + printt(stat.FunctionStat.Token_CloseParen) + printStat(stat.FunctionStat.Body) + printt(stat.FunctionStat.Token_End) + elseif stat.Type == 'FunctionStat' then + printt(stat.Token_Function) + for index, part in pairs(stat.NameChain) do + printt(part) + local sep = stat.Token_NameChainSeparator[index] + if sep then + printt(sep) + end + end + printt(stat.Token_OpenParen) + for index, arg in pairs(stat.ArgList) do + printt(arg) + local comma = stat.Token_ArgCommaList[index] + if comma then + printt(comma) + end + end + printt(stat.Token_CloseParen) + printStat(stat.Body) + printt(stat.Token_End) + elseif stat.Type == 'RepeatStat' then + printt(stat.Token_Repeat) + printStat(stat.Body) + printt(stat.Token_Until) + printExpr(stat.Condition) + elseif stat.Type == 'GenericForStat' then + printt(stat.Token_For) + for index, var in pairs(stat.VarList) do + printt(var) + local sep = stat.Token_VarCommaList[index] + if sep then + printt(sep) + end + end + printt(stat.Token_In) + for index, expr in pairs(stat.GeneratorList) do + printExpr(expr) + local sep = stat.Token_GeneratorCommaList[index] + if sep then + printt(sep) + end + end + printt(stat.Token_Do) + printStat(stat.Body) + printt(stat.Token_End) + elseif stat.Type == 'NumericForStat' then + printt(stat.Token_For) + for index, var in pairs(stat.VarList) do + printt(var) + local sep = stat.Token_VarCommaList[index] + if sep then + printt(sep) + end + end + printt(stat.Token_Equals) + for index, expr in pairs(stat.RangeList) do + printExpr(expr) + local sep = stat.Token_RangeCommaList[index] + if sep then + printt(sep) + end + end + printt(stat.Token_Do) + printStat(stat.Body) + printt(stat.Token_End) + elseif stat.Type == 'WhileStat' then + printt(stat.Token_While) + printExpr(stat.Condition) + printt(stat.Token_Do) + printStat(stat.Body) + printt(stat.Token_End) + elseif stat.Type == 'DoStat' then + printt(stat.Token_Do) + printStat(stat.Body) + printt(stat.Token_End) + elseif stat.Type == 'IfStat' then + printt(stat.Token_If) + printExpr(stat.Condition) + printt(stat.Token_Then) + printStat(stat.Body) + for _, clause in pairs(stat.ElseClauseList) do + printt(clause.Token) + if clause.Condition then + printExpr(clause.Condition) + printt(clause.Token_Then) + end + printStat(clause.Body) + end + printt(stat.Token_End) + elseif stat.Type == 'CallExprStat' then + printExpr(stat.Expression) + elseif stat.Type == 'AssignmentStat' then + for index, ex in pairs(stat.Lhs) do + printExpr(ex) + local sep = stat.Token_LhsSeparatorList[index] + if sep then + printt(sep) + end + end + printt(stat.Token_Equals) + for index, ex in pairs(stat.Rhs) do + printExpr(ex) + local sep = stat.Token_RhsSeparatorList[index] + if sep then + printt(sep) + end + end + else + assert(false, "unreachable") + end + end + + printStat(ast) + return table.concat(str) +end + +-- Adds / removes whitespace in an AST to put it into a "standard formatting" +local function FormatAst(ast) + local formatStat, formatExpr; + + local currentIndent = 0 + + local function applyIndent(token) + local indentString = '\n' .. ('\t'):rep(currentIndent) + if token.LeadingWhite == '' or (token.LeadingWhite:sub(- #indentString, -1) ~= indentString) then + -- Trim existing trailing whitespace on LeadingWhite + -- Trim trailing tabs and spaces, and up to one newline + token.LeadingWhite = token.LeadingWhite:gsub("\n?[\t ]*$", "") + token.LeadingWhite = token.LeadingWhite .. indentString + end + end + + local function indent() + currentIndent = currentIndent + 1 + end + + local function undent() + currentIndent = currentIndent - 1 + assert(currentIndent >= 0, "Undented too far") + end + + local function leadingChar(tk) + if #tk.LeadingWhite > 0 then + return tk.LeadingWhite:sub(1, 1) + else + return tk.Source:sub(1, 1) + end + end + + local function padToken(tk) + if not WhiteChars[leadingChar(tk)] then + tk.LeadingWhite = ' ' .. tk.LeadingWhite + end + end + + local function padExpr(expr) + padToken(expr:GetFirstToken()) + end + + local function formatBody(openToken, bodyStat, closeToken) + indent() + formatStat(bodyStat) + undent() + applyIndent(closeToken) + end + + formatExpr = function(expr) + if expr.Type == 'BinopExpr' then + formatExpr(expr.Lhs) + formatExpr(expr.Rhs) + if expr.Token_Op.Source == '..' then + -- No padding on .. + else + padExpr(expr.Rhs) + padToken(expr.Token_Op) + end + elseif expr.Type == 'UnopExpr' then + formatExpr(expr.Rhs) + --(expr.Token_Op) + elseif expr.Type == 'NumberLiteral' or expr.Type == 'StringLiteral' or + expr.Type == 'NilLiteral' or expr.Type == 'BooleanLiteral' or + expr.Type == 'VargLiteral' + then + -- Nothing to do + --(expr.Token) + elseif expr.Type == 'FieldExpr' then + formatExpr(expr.Base) + --(expr.Token_Dot) + --(expr.Field) + elseif expr.Type == 'IndexExpr' then + formatExpr(expr.Base) + formatExpr(expr.Index) + --(expr.Token_OpenBracket) + --(expr.Token_CloseBracket) + elseif expr.Type == 'MethodExpr' or expr.Type == 'CallExpr' then + formatExpr(expr.Base) + if expr.Type == 'MethodExpr' then + --(expr.Token_Colon) + --(expr.Method) + end + if expr.FunctionArguments.CallType == 'StringCall' then + --(expr.FunctionArguments.Token) + elseif expr.FunctionArguments.CallType == 'ArgCall' then + --(expr.FunctionArguments.Token_OpenParen) + for index, argExpr in pairs(expr.FunctionArguments.ArgList) do + formatExpr(argExpr) + if index > 1 then + padExpr(argExpr) + end + local sep = expr.FunctionArguments.Token_CommaList[index] + if sep then + --(sep) + end + end + --(expr.FunctionArguments.Token_CloseParen) + elseif expr.FunctionArguments.CallType == 'TableCall' then + formatExpr(expr.FunctionArguments.TableExpr) + end + elseif expr.Type == 'FunctionLiteral' then + --(expr.Token_Function) + --(expr.Token_OpenParen) + for index, arg in pairs(expr.ArgList) do + --(arg) + if index > 1 then + padToken(arg) + end + local comma = expr.Token_ArgCommaList[index] + if comma then + --(comma) + end + end + --(expr.Token_CloseParen) + formatBody(expr.Token_CloseParen, expr.Body, expr.Token_End) + elseif expr.Type == 'VariableExpr' then + --(expr.Token) + elseif expr.Type == 'ParenExpr' then + formatExpr(expr.Expression) + --(expr.Token_OpenParen) + --(expr.Token_CloseParen) + elseif expr.Type == 'TableLiteral' then + --(expr.Token_OpenBrace) + if #expr.EntryList == 0 then + -- Nothing to do + else + indent() + for index, entry in pairs(expr.EntryList) do + if entry.EntryType == 'Field' then + applyIndent(entry.Field) + padToken(entry.Token_Equals) + formatExpr(entry.Value) + padExpr(entry.Value) + elseif entry.EntryType == 'Index' then + applyIndent(entry.Token_OpenBracket) + formatExpr(entry.Index) + --(entry.Token_CloseBracket) + padToken(entry.Token_Equals) + formatExpr(entry.Value) + padExpr(entry.Value) + elseif entry.EntryType == 'Value' then + formatExpr(entry.Value) + applyIndent(entry.Value:GetFirstToken()) + else + assert(false, "unreachable") + end + local sep = expr.Token_SeparatorList[index] + if sep then + --(sep) + end + end + undent() + applyIndent(expr.Token_CloseBrace) + end + --(expr.Token_CloseBrace) + else + assert(false, "unreachable, type: " .. expr.Type .. ":" .. FormatTable(expr)) + end + end + + formatStat = function(stat) + if stat.Type == 'StatList' then + for _, stat in pairs(stat.StatementList) do + formatStat(stat) + applyIndent(stat:GetFirstToken()) + end + elseif stat.Type == 'BreakStat' then + --(stat.Token_Break) + elseif stat.Type == 'ReturnStat' then + --(stat.Token_Return) + for index, expr in pairs(stat.ExprList) do + formatExpr(expr) + padExpr(expr) + if stat.Token_CommaList[index] then + --(stat.Token_CommaList[index]) + end + end + elseif stat.Type == 'LocalVarStat' then + --(stat.Token_Local) + for index, var in pairs(stat.VarList) do + padToken(var) + local comma = stat.Token_VarCommaList[index] + if comma then + --(comma) + end + end + if stat.Token_Equals then + padToken(stat.Token_Equals) + for index, expr in pairs(stat.ExprList) do + formatExpr(expr) + padExpr(expr) + local comma = stat.Token_ExprCommaList[index] + if comma then + --(comma) + end + end + end + elseif stat.Type == 'LocalFunctionStat' then + --(stat.Token_Local) + padToken(stat.FunctionStat.Token_Function) + padToken(stat.FunctionStat.NameChain[1]) + --(stat.FunctionStat.Token_OpenParen) + for index, arg in pairs(stat.FunctionStat.ArgList) do + if index > 1 then + padToken(arg) + end + local comma = stat.FunctionStat.Token_ArgCommaList[index] + if comma then + --(comma) + end + end + --(stat.FunctionStat.Token_CloseParen) + formatBody(stat.FunctionStat.Token_CloseParen, stat.FunctionStat.Body, stat.FunctionStat.Token_End) + elseif stat.Type == 'FunctionStat' then + --(stat.Token_Function) + for index, part in pairs(stat.NameChain) do + if index == 1 then + padToken(part) + end + local sep = stat.Token_NameChainSeparator[index] + if sep then + --(sep) + end + end + --(stat.Token_OpenParen) + for index, arg in pairs(stat.ArgList) do + if index > 1 then + padToken(arg) + end + local comma = stat.Token_ArgCommaList[index] + if comma then + --(comma) + end + end + --(stat.Token_CloseParen) + formatBody(stat.Token_CloseParen, stat.Body, stat.Token_End) + elseif stat.Type == 'RepeatStat' then + --(stat.Token_Repeat) + formatBody(stat.Token_Repeat, stat.Body, stat.Token_Until) + formatExpr(stat.Condition) + padExpr(stat.Condition) + elseif stat.Type == 'GenericForStat' then + --(stat.Token_For) + for index, var in pairs(stat.VarList) do + padToken(var) + local sep = stat.Token_VarCommaList[index] + if sep then + --(sep) + end + end + padToken(stat.Token_In) + for index, expr in pairs(stat.GeneratorList) do + formatExpr(expr) + padExpr(expr) + local sep = stat.Token_GeneratorCommaList[index] + if sep then + --(sep) + end + end + padToken(stat.Token_Do) + formatBody(stat.Token_Do, stat.Body, stat.Token_End) + elseif stat.Type == 'NumericForStat' then + --(stat.Token_For) + for index, var in pairs(stat.VarList) do + padToken(var) + local sep = stat.Token_VarCommaList[index] + if sep then + --(sep) + end + end + padToken(stat.Token_Equals) + for index, expr in pairs(stat.RangeList) do + formatExpr(expr) + padExpr(expr) + local sep = stat.Token_RangeCommaList[index] + if sep then + --(sep) + end + end + padToken(stat.Token_Do) + formatBody(stat.Token_Do, stat.Body, stat.Token_End) + elseif stat.Type == 'WhileStat' then + --(stat.Token_While) + formatExpr(stat.Condition) + padExpr(stat.Condition) + padToken(stat.Token_Do) + formatBody(stat.Token_Do, stat.Body, stat.Token_End) + elseif stat.Type == 'DoStat' then + --(stat.Token_Do) + formatBody(stat.Token_Do, stat.Body, stat.Token_End) + elseif stat.Type == 'IfStat' then + --(stat.Token_If) + formatExpr(stat.Condition) + padExpr(stat.Condition) + padToken(stat.Token_Then) + -- + local lastBodyOpen = stat.Token_Then + local lastBody = stat.Body + -- + for _, clause in pairs(stat.ElseClauseList) do + formatBody(lastBodyOpen, lastBody, clause.Token) + lastBodyOpen = clause.Token + -- + if clause.Condition then + formatExpr(clause.Condition) + padExpr(clause.Condition) + padToken(clause.Token_Then) + lastBodyOpen = clause.Token_Then + end + lastBody = clause.Body + end + -- + formatBody(lastBodyOpen, lastBody, stat.Token_End) + elseif stat.Type == 'CallExprStat' then + formatExpr(stat.Expression) + elseif stat.Type == 'AssignmentStat' then + for index, ex in pairs(stat.Lhs) do + formatExpr(ex) + if index > 1 then + padExpr(ex) + end + local sep = stat.Token_LhsSeparatorList[index] + if sep then + --(sep) + end + end + padToken(stat.Token_Equals) + for index, ex in pairs(stat.Rhs) do + formatExpr(ex) + padExpr(ex) + local sep = stat.Token_RhsSeparatorList[index] + if sep then + --(sep) + end + end + else + assert(false, "unreachable") + end + end + + formatStat(ast) +end + +-- Strips as much whitespace off of tokens in an AST as possible without causing problems +local function StripAst(ast) + local stripStat, stripExpr; + + local function stript(token) + token.LeadingWhite = '' + end + + -- Make to adjacent tokens as close as possible + local function joint(tokenA, tokenB) + -- Strip the second token's whitespace + stript(tokenB) + + -- Get the trailing A <-> leading B character pair + local lastCh = tokenA.Source:sub(-1, -1) + local firstCh = tokenB.Source:sub(1, 1) + + -- Cases to consider: + -- Touching minus signs -> comment: `- -42` -> `--42' is invalid + -- Touching words: `a b` -> `ab` is invalid + -- Touching digits: `2 3`, can't occurr in the Lua syntax as number literals aren't a primary expression + -- Abiguous syntax: `f(x)\n(x)()` is already disallowed, we can't cause a problem by removing newlines + + -- Figure out what separation is needed + if + (lastCh == '-' and firstCh == '-') or + (AllIdentChars[lastCh] and AllIdentChars[firstCh]) + then + tokenB.LeadingWhite = ' ' -- Use a separator + else + tokenB.LeadingWhite = '' -- Don't use a separator + end + end + + -- Join up a statement body and it's opening / closing tokens + local function bodyjoint(open, body, close) + stripStat(body) + stript(close) + local bodyFirst = body:GetFirstToken() + local bodyLast = body:GetLastToken() + if bodyFirst then + -- Body is non-empty, join body to open / close + joint(open, bodyFirst) + joint(bodyLast, close) + else + -- Body is empty, just join open and close token together + joint(open, close) + end + end + + stripExpr = function(expr) + if expr.Type == 'BinopExpr' then + stripExpr(expr.Lhs) + stript(expr.Token_Op) + stripExpr(expr.Rhs) + -- Handle the `a - -b` -/-> `a--b` case which would otherwise incorrectly generate a comment + -- Also handles operators "or" / "and" which definitely need joining logic in a bunch of cases + joint(expr.Token_Op, expr.Rhs:GetFirstToken()) + joint(expr.Lhs:GetLastToken(), expr.Token_Op) + elseif expr.Type == 'UnopExpr' then + stript(expr.Token_Op) + stripExpr(expr.Rhs) + -- Handle the `- -b` -/-> `--b` case which would otherwise incorrectly generate a comment + joint(expr.Token_Op, expr.Rhs:GetFirstToken()) + elseif expr.Type == 'NumberLiteral' or expr.Type == 'StringLiteral' or + expr.Type == 'NilLiteral' or expr.Type == 'BooleanLiteral' or + expr.Type == 'VargLiteral' + then + -- Just print the token + stript(expr.Token) + elseif expr.Type == 'FieldExpr' then + stripExpr(expr.Base) + stript(expr.Token_Dot) + stript(expr.Field) + elseif expr.Type == 'IndexExpr' then + stripExpr(expr.Base) + stript(expr.Token_OpenBracket) + stripExpr(expr.Index) + stript(expr.Token_CloseBracket) + elseif expr.Type == 'MethodExpr' or expr.Type == 'CallExpr' then + stripExpr(expr.Base) + if expr.Type == 'MethodExpr' then + stript(expr.Token_Colon) + stript(expr.Method) + end + if expr.FunctionArguments.CallType == 'StringCall' then + stript(expr.FunctionArguments.Token) + elseif expr.FunctionArguments.CallType == 'ArgCall' then + stript(expr.FunctionArguments.Token_OpenParen) + for index, argExpr in pairs(expr.FunctionArguments.ArgList) do + stripExpr(argExpr) + local sep = expr.FunctionArguments.Token_CommaList[index] + if sep then + stript(sep) + end + end + stript(expr.FunctionArguments.Token_CloseParen) + elseif expr.FunctionArguments.CallType == 'TableCall' then + stripExpr(expr.FunctionArguments.TableExpr) + end + elseif expr.Type == 'FunctionLiteral' then + stript(expr.Token_Function) + stript(expr.Token_OpenParen) + for index, arg in pairs(expr.ArgList) do + stript(arg) + local comma = expr.Token_ArgCommaList[index] + if comma then + stript(comma) + end + end + stript(expr.Token_CloseParen) + bodyjoint(expr.Token_CloseParen, expr.Body, expr.Token_End) + elseif expr.Type == 'VariableExpr' then + stript(expr.Token) + elseif expr.Type == 'ParenExpr' then + stript(expr.Token_OpenParen) + stripExpr(expr.Expression) + stript(expr.Token_CloseParen) + elseif expr.Type == 'TableLiteral' then + stript(expr.Token_OpenBrace) + for index, entry in pairs(expr.EntryList) do + if entry.EntryType == 'Field' then + stript(entry.Field) + stript(entry.Token_Equals) + stripExpr(entry.Value) + elseif entry.EntryType == 'Index' then + stript(entry.Token_OpenBracket) + stripExpr(entry.Index) + stript(entry.Token_CloseBracket) + stript(entry.Token_Equals) + stripExpr(entry.Value) + elseif entry.EntryType == 'Value' then + stripExpr(entry.Value) + else + assert(false, "unreachable") + end + local sep = expr.Token_SeparatorList[index] + if sep then + stript(sep) + end + end + stript(expr.Token_CloseBrace) + else + assert(false, "unreachable, type: " .. expr.Type .. ":" .. FormatTable(expr)) + end + end + + stripStat = function(stat) + if stat.Type == 'StatList' then + -- Strip all surrounding whitespace on statement lists along with separating whitespace + for i = 1, #stat.StatementList do + local chStat = stat.StatementList[i] + + -- Strip the statement and it's whitespace + stripStat(chStat) + stript(chStat:GetFirstToken()) + + -- If there was a last statement, join them appropriately + local lastChStat = stat.StatementList[i - 1] + if lastChStat then + -- See if we can remove a semi-colon, the only case where we can't is if + -- this and the last statement have a `);(` pair, where removing the semi-colon + -- would introduce ambiguous syntax. + if stat.SemicolonList[i - 1] and + (lastChStat:GetLastToken().Source ~= ')' or chStat:GetFirstToken().Source ~= ')') + then + stat.SemicolonList[i - 1] = nil + end + + -- If there isn't a semi-colon, we should safely join the two statements + -- (If there is one, then no whitespace leading chStat is always okay) + if not stat.SemicolonList[i - 1] then + joint(lastChStat:GetLastToken(), chStat:GetFirstToken()) + end + end + end + + -- A semi-colon is never needed on the last stat in a statlist: + stat.SemicolonList[#stat.StatementList] = nil + + -- The leading whitespace on the statlist should be stripped + if #stat.StatementList > 0 then + stript(stat.StatementList[1]:GetFirstToken()) + end + elseif stat.Type == 'BreakStat' then + stript(stat.Token_Break) + elseif stat.Type == 'ReturnStat' then + stript(stat.Token_Return) + for index, expr in pairs(stat.ExprList) do + stripExpr(expr) + if stat.Token_CommaList[index] then + stript(stat.Token_CommaList[index]) + end + end + if #stat.ExprList > 0 then + joint(stat.Token_Return, stat.ExprList[1]:GetFirstToken()) + end + elseif stat.Type == 'LocalVarStat' then + stript(stat.Token_Local) + for index, var in pairs(stat.VarList) do + if index == 1 then + joint(stat.Token_Local, var) + else + stript(var) + end + local comma = stat.Token_VarCommaList[index] + if comma then + stript(comma) + end + end + if stat.Token_Equals then + stript(stat.Token_Equals) + for index, expr in pairs(stat.ExprList) do + stripExpr(expr) + local comma = stat.Token_ExprCommaList[index] + if comma then + stript(comma) + end + end + end + elseif stat.Type == 'LocalFunctionStat' then + stript(stat.Token_Local) + joint(stat.Token_Local, stat.FunctionStat.Token_Function) + joint(stat.FunctionStat.Token_Function, stat.FunctionStat.NameChain[1]) + joint(stat.FunctionStat.NameChain[1], stat.FunctionStat.Token_OpenParen) + for index, arg in pairs(stat.FunctionStat.ArgList) do + stript(arg) + local comma = stat.FunctionStat.Token_ArgCommaList[index] + if comma then + stript(comma) + end + end + stript(stat.FunctionStat.Token_CloseParen) + bodyjoint(stat.FunctionStat.Token_CloseParen, stat.FunctionStat.Body, stat.FunctionStat.Token_End) + elseif stat.Type == 'FunctionStat' then + stript(stat.Token_Function) + for index, part in pairs(stat.NameChain) do + if index == 1 then + joint(stat.Token_Function, part) + else + stript(part) + end + local sep = stat.Token_NameChainSeparator[index] + if sep then + stript(sep) + end + end + stript(stat.Token_OpenParen) + for index, arg in pairs(stat.ArgList) do + stript(arg) + local comma = stat.Token_ArgCommaList[index] + if comma then + stript(comma) + end + end + stript(stat.Token_CloseParen) + bodyjoint(stat.Token_CloseParen, stat.Body, stat.Token_End) + elseif stat.Type == 'RepeatStat' then + stript(stat.Token_Repeat) + bodyjoint(stat.Token_Repeat, stat.Body, stat.Token_Until) + stripExpr(stat.Condition) + joint(stat.Token_Until, stat.Condition:GetFirstToken()) + elseif stat.Type == 'GenericForStat' then + stript(stat.Token_For) + for index, var in pairs(stat.VarList) do + if index == 1 then + joint(stat.Token_For, var) + else + stript(var) + end + local sep = stat.Token_VarCommaList[index] + if sep then + stript(sep) + end + end + joint(stat.VarList[#stat.VarList], stat.Token_In) + for index, expr in pairs(stat.GeneratorList) do + stripExpr(expr) + if index == 1 then + joint(stat.Token_In, expr:GetFirstToken()) + end + local sep = stat.Token_GeneratorCommaList[index] + if sep then + stript(sep) + end + end + joint(stat.GeneratorList[#stat.GeneratorList]:GetLastToken(), stat.Token_Do) + bodyjoint(stat.Token_Do, stat.Body, stat.Token_End) + elseif stat.Type == 'NumericForStat' then + stript(stat.Token_For) + for index, var in pairs(stat.VarList) do + if index == 1 then + joint(stat.Token_For, var) + else + stript(var) + end + local sep = stat.Token_VarCommaList[index] + if sep then + stript(sep) + end + end + joint(stat.VarList[#stat.VarList], stat.Token_Equals) + for index, expr in pairs(stat.RangeList) do + stripExpr(expr) + if index == 1 then + joint(stat.Token_Equals, expr:GetFirstToken()) + end + local sep = stat.Token_RangeCommaList[index] + if sep then + stript(sep) + end + end + joint(stat.RangeList[#stat.RangeList]:GetLastToken(), stat.Token_Do) + bodyjoint(stat.Token_Do, stat.Body, stat.Token_End) + elseif stat.Type == 'WhileStat' then + stript(stat.Token_While) + stripExpr(stat.Condition) + stript(stat.Token_Do) + joint(stat.Token_While, stat.Condition:GetFirstToken()) + joint(stat.Condition:GetLastToken(), stat.Token_Do) + bodyjoint(stat.Token_Do, stat.Body, stat.Token_End) + elseif stat.Type == 'DoStat' then + stript(stat.Token_Do) + stript(stat.Token_End) + bodyjoint(stat.Token_Do, stat.Body, stat.Token_End) + elseif stat.Type == 'IfStat' then + stript(stat.Token_If) + stripExpr(stat.Condition) + joint(stat.Token_If, stat.Condition:GetFirstToken()) + joint(stat.Condition:GetLastToken(), stat.Token_Then) + -- + local lastBodyOpen = stat.Token_Then + local lastBody = stat.Body + -- + for _, clause in pairs(stat.ElseClauseList) do + bodyjoint(lastBodyOpen, lastBody, clause.Token) + lastBodyOpen = clause.Token + -- + if clause.Condition then + stripExpr(clause.Condition) + joint(clause.Token, clause.Condition:GetFirstToken()) + joint(clause.Condition:GetLastToken(), clause.Token_Then) + lastBodyOpen = clause.Token_Then + end + stripStat(clause.Body) + lastBody = clause.Body + end + -- + bodyjoint(lastBodyOpen, lastBody, stat.Token_End) + elseif stat.Type == 'CallExprStat' then + stripExpr(stat.Expression) + elseif stat.Type == 'AssignmentStat' then + for index, ex in pairs(stat.Lhs) do + stripExpr(ex) + local sep = stat.Token_LhsSeparatorList[index] + if sep then + stript(sep) + end + end + stript(stat.Token_Equals) + for index, ex in pairs(stat.Rhs) do + stripExpr(ex) + local sep = stat.Token_RhsSeparatorList[index] + if sep then + stript(sep) + end + end + else + assert(false, "unreachable") + end + end + + stripStat(ast) +end + +local idGen = 0 +local VarDigits = {} +for i = ('a'):byte(), ('z'):byte() do table.insert(VarDigits, string.char(i)) end +for i = ('A'):byte(), ('Z'):byte() do table.insert(VarDigits, string.char(i)) end +for i = ('0'):byte(), ('9'):byte() do table.insert(VarDigits, string.char(i)) end +table.insert(VarDigits, '_') +local VarStartDigits = {} +for i = ('a'):byte(), ('z'):byte() do table.insert(VarStartDigits, string.char(i)) end +for i = ('A'):byte(), ('Z'):byte() do table.insert(VarStartDigits, string.char(i)) end +local function indexToVarName(index) + local id = '' + local d = index % #VarStartDigits + index = (index - d) / #VarStartDigits + id = id .. VarStartDigits[d + 1] + while index > 0 do + local d = index % #VarDigits + index = (index - d) / #VarDigits + id = id .. VarDigits[d + 1] + end + return id +end +local function genNextVarName() + local varToUse = idGen + idGen = idGen + 1 + return indexToVarName(varToUse) +end +local function genVarName() + local varName = '' + repeat + varName = genNextVarName() + until not Keywords[varName] + return varName +end +local function MinifyVariables(globalScope, rootScope) + -- externalGlobals is a set of global variables that have not been assigned to, that is + -- global variables defined "externally to the script". We are not going to be renaming + -- those, and we have to make sure that we don't collide with them when renaming + -- things so we keep track of them in this set. + local externalGlobals = {} + + -- First we want to rename all of the variables to unique temoraries, so that we can + -- easily use the scope::GetVar function to check whether renames are valid. + local temporaryIndex = 0 + for _, var in pairs(globalScope) do + if var.AssignedTo then + var:Rename('_TMP_' .. temporaryIndex .. '_') + temporaryIndex = temporaryIndex + 1 + else + -- Not assigned to, external global + externalGlobals[var.Name] = true + end + end + local function temporaryRename(scope) + for _, var in pairs(scope.VariableList) do + var:Rename('_TMP_' .. temporaryIndex .. '_') + temporaryIndex = temporaryIndex + 1 + end + for _, childScope in pairs(scope.ChildScopeList) do + temporaryRename(childScope) + end + end + + -- Now we go through renaming, first do globals, we probably want them + -- to have shorter names in general. + -- TODO: Rename all vars based on frequency patterns, giving variables + -- used more shorter names. + local nextFreeNameIndex = 0 + for _, var in pairs(globalScope) do + if var.AssignedTo then + local varName = '' + repeat + varName = indexToVarName(nextFreeNameIndex) + nextFreeNameIndex = nextFreeNameIndex + 1 + until not Keywords[varName] and not externalGlobals[varName] + var:Rename(varName) + end + end + + -- Now rename all local vars + rootScope.FirstFreeName = nextFreeNameIndex + local function doRenameScope(scope) + for _, var in pairs(scope.VariableList) do + local varName = '' + repeat + varName = indexToVarName(scope.FirstFreeName) + scope.FirstFreeName = scope.FirstFreeName + 1 + until not Keywords[varName] and not externalGlobals[varName] + var:Rename(varName) + end + for _, childScope in pairs(scope.ChildScopeList) do + childScope.FirstFreeName = scope.FirstFreeName + doRenameScope(childScope) + end + end + doRenameScope(rootScope) +end + +local function BeautifyVariables(globalScope, rootScope) + local externalGlobals = {} + for _, var in pairs(globalScope) do + if not var.AssignedTo then + externalGlobals[var.Name] = true + end + end + + local localNumber = 1 + local globalNumber = 1 + + local function setVarName(var, name) + var.Name = name + for _, setter in pairs(var.RenameList) do + setter(name) + end + end + + for _, var in pairs(globalScope) do + if var.AssignedTo then + setVarName(var, 'G_' .. globalNumber) + globalNumber = globalNumber + 1 + end + end + + local function modify(scope) + for _, var in pairs(scope.VariableList) do + local name = 'L_' .. localNumber .. '_' + if var.Info.Type == 'Argument' then + name = name .. 'arg' .. var.Info.Index + elseif var.Info.Type == 'LocalFunction' then + name = name .. 'func' + elseif var.Info.Type == 'ForRange' then + name = name .. 'forvar' .. var.Info.Index + end + setVarName(var, name) + localNumber = localNumber + 1 + end + for _, scope in pairs(scope.ChildScopeList) do + modify(scope) + end + end + modify(rootScope) +end + +local function validateCode(code, validate) + if validate then + local func,err = load(code, "@minifyvalidation", "t", {}) + if not func then + error(err) + end + end +end + +function lib.minify(src, ignoreValidation) + validateCode(src, not ignoreValidation) + local ast = CreateLuaParser(src) + local global_scope, root_scope = AddVariableInfo(ast) + MinifyVariables(global_scope, root_scope) + StripAst(ast) + local out = PrintAst(ast) + validateCode(out, not ignoreValidation) + return out +end + +function lib.beautify(src, ignoreValidation) + validateCode(src, ignoreValidation) + local ast = CreateLuaParser(src) + local global_scope, root_scope = AddVariableInfo(ast) + BeautifyVariables(global_scope, root_scope) + FormatAst(ast) + local out = PrintAst(ast) + validateCode(out, not ignoreValidation) + return out +end + +return lib diff --git a/Src/pid/data/lib/pid.lua b/Src/pid/data/lib/pid.lua new file mode 100644 index 0000000..2f6a823 --- /dev/null +++ b/Src/pid/data/lib/pid.lua @@ -0,0 +1,136 @@ +--:Minify:-- + +local pid = {} +pid.__index = pid + +local function clamp(value, minimum, maximum) + if minimum and value < minimum then + return minimum + end + if maximum and value > maximum then + return maximum + end + return value +end + +local function assertNumber(value, name) + if type(value) ~= "number" then + error("pid: " .. name .. " must be a number") + end + return value +end + +function pid.new(kp, ki, kd, options) + assertNumber(kp, "kp") + assertNumber(ki, "ki") + assertNumber(kd, "kd") + + options = options or {} + + local controller = setmetatable({ + kp = kp, + ki = ki, + kd = kd, + setpoint = options.setpoint or 0, + outputMin = options.outputMin, + outputMax = options.outputMax, + integralMin = options.integralMin, + integralMax = options.integralMax, + lastError = 0, + integral = 0, + lastMeasurement = nil, + lastOutput = 0, + lastTime = nil, + }, pid) + + return controller +end + +function pid:reset() + self.lastError = 0 + self.integral = 0 + self.lastMeasurement = nil + self.lastOutput = 0 + self.lastTime = nil +end + +function pid:setSetpoint(setpoint) + assertNumber(setpoint, "setpoint") + self.setpoint = setpoint +end + +function pid:setCoefficients(kp, ki, kd) + assertNumber(kp, "kp") + assertNumber(ki, "ki") + assertNumber(kd, "kd") + self.kp = kp + self.ki = ki + self.kd = kd +end + +function pid:setOutputLimits(minimum, maximum) + if minimum ~= nil then assertNumber(minimum, "outputMin") end + if maximum ~= nil then assertNumber(maximum, "outputMax") end + if minimum and maximum and minimum > maximum then + error("pid: outputMin must be <= outputMax") + end + self.outputMin = minimum + self.outputMax = maximum +end + +function pid:setIntegralLimits(minimum, maximum) + if minimum ~= nil then assertNumber(minimum, "integralMin") end + if maximum ~= nil then assertNumber(maximum, "integralMax") end + if minimum and maximum and minimum > maximum then + error("pid: integralMin must be <= integralMax") + end + self.integralMin = minimum + self.integralMax = maximum +end + +function pid:update(measurement, dt) + assertNumber(measurement, "measurement") + assertNumber(dt, "dt") + if dt <= 0 then + error("pid: dt must be greater than zero") + end + + local errorValue = self.setpoint - measurement + self.integral = clamp(self.integral + errorValue * dt, self.integralMin, self.integralMax) + local derivative = 0 + if self.lastTime ~= nil then + derivative = (errorValue - self.lastError) / dt + end + + local output = self.kp * errorValue + self.ki * self.integral + self.kd * derivative + output = clamp(output, self.outputMin, self.outputMax) + + self.lastError = errorValue + self.lastMeasurement = measurement + self.lastOutput = output + self.lastTime = (self.lastTime or 0) + dt + + return output +end + +function pid:compute(measurement, dt) + return self:update(measurement, dt) +end + +function pid:getState() + return { + setpoint = self.setpoint, + kp = self.kp, + ki = self.ki, + kd = self.kd, + integral = self.integral, + lastError = self.lastError, + lastOutput = self.lastOutput, + } +end + +function pid:resetIntegral() + self.integral = 0 +end + +return pid diff --git a/Src/sysinit/control/symlinks.json b/Src/sysinit/control/symlinks.json new file mode 100644 index 0000000..ee2740f --- /dev/null +++ b/Src/sysinit/control/symlinks.json @@ -0,0 +1,3 @@ +{ + "/sbin/init": "/usr/lib/sysinit/sysinit" +} \ No newline at end of file diff --git a/Src/sysinit/data/usr/lib/sysinit/sysinit b/Src/sysinit/data/usr/lib/sysinit/sysinit index 8e5859b..c8cd61d 100644 --- a/Src/sysinit/data/usr/lib/sysinit/sysinit +++ b/Src/sysinit/data/usr/lib/sysinit/sysinit @@ -2,6 +2,7 @@ local kernel=... local fs=require("fs") kernel.log("Sysinit started...") +kernel.saveLog() for i,v in pairs(kernel.processes) do kernel.log("Spawning kernel task "..i) @@ -41,6 +42,7 @@ for i,v in ipairs(files) do end end end +kernel.saveLog() while true do sleep(5) diff --git a/build.py b/build.py index 5715b27..7513b75 100644 --- a/build.py +++ b/build.py @@ -1,271 +1,272 @@ -#!/usr/bin/env python3 -""" -Usage: - python build.py [--arch cct|oc] [--release|--dev] - -Targets: - build - build-mini - build-micro - build-test - build-mini-test - build-micro-test - clean - prod - prod-mini - -Arch flags: - --arch cct - --arch oc - -Release flags: - --release - --dev -""" - -import sys -import shutil -import argparse -import subprocess -import json -from pathlib import Path -from typing import Union - -PROJECT_ROOT = Path(__file__).resolve().parent -SRC_ROOT = PROJECT_ROOT / "Src" -TEST_ROOT = PROJECT_ROOT / "Test" -BUILD_ROOT = PROJECT_ROOT / "Build" -PROD_ROOT = PROJECT_ROOT / "prod" - -ARCH_BOOT_DIR = { - "cct": Path("boot") / "cct", - "oc": Path("boot") / "oc", -} - - -def clean(): - if BUILD_ROOT.exists(): - print(f"Removing {BUILD_ROOT} ...") - shutil.rmtree(BUILD_ROOT) - else: - print("Nothing to clean.") - -def cleanprod(): - if PROD_ROOT.exists(): - print(f"Removing {PROD_ROOT} ...") - shutil.rmtree(PROD_ROOT) - else: - print("Nothing to clean.") - - -def has_minify_header(path: Path) -> bool: - try: - with path.open("r", encoding="utf-8", errors="ignore") as f: - for _ in range(3): - if "--:Minify:--" in f.readline(): - return True - except OSError: - pass - return False - - -def minify_file(src: Path) -> str: - result = subprocess.run( - ["luamin.cmd", "-f", str(src)], - capture_output=True, - text=True - ) - if result.returncode != 0: - print(f" ! luamin failed: {result.stderr.strip()}", file=sys.stderr) - sys.exit(1) - return result.stdout - - -def compress_lz4(data: bytes) -> bytes: - return lz4.frame.compress(data) - - -def process_root(src_root: Path, out_root: Path, minify: bool, micro: bool, arch:Union[str, None], prod:bool): - print(f"Building from {src_root}") - print(f"Output to {out_root}") - print() - - for pkg_dir in sorted(src_root.iterdir()): - if not pkg_dir.is_dir(): - continue - - if pkg_dir.name[:18] == "Hyperion-firmware-": - if pkg_dir.name != f"Hyperion-firmware-{arch}": - if prod != True: - continue - - data_dir=pkg_dir / "data" - - if not data_dir.is_dir(): - continue - - print(f"== Package: {pkg_dir.name} ==") - - for src in sorted(data_dir.rglob("*")): - if not src.is_file(): - continue - - rel = src.relative_to(data_dir) - - dst = out_root / rel - if prod: - dst = out_root / pkg_dir.name / rel - - dst.parent.mkdir(parents=True, exist_ok=True) - - print(f" Processing: {src.relative_to(src_root)}") - - if has_minify_header(src): - if minify: - print(" > Minifying") - content = minify_file(src) - if micro: - print(" > LZ4 compressing") - compressed = compress_lz4(content.encode("utf-8")) - dst.write_bytes(compressed) - else: - dst.write_text(content, encoding="utf-8") - else: - print(" > Copying") - shutil.copy2(src, dst) - else: - print(" > Copying") - shutil.copy2(src, dst) - - print() - - -def install_bootloader(arch: str, release: bool): - boot_dir = BUILD_ROOT / "$" / ARCH_BOOT_DIR[arch] - eeprom = boot_dir / "eeprom" - - eeprom_dst_name = "startup.lua" if release else "eeprom" - print(f" Installing: eeprom -> Build/{eeprom_dst_name}") - shutil.copy2(eeprom, BUILD_ROOT / eeprom_dst_name) - - -def run_build(minify: bool, micro: bool, include_test: bool, arch: Union[str, None], release: bool, prod: bool): - clean() - BUILD_ROOT.mkdir() - if prod: - cleanprod() - PROD_ROOT.mkdir() - - out_root = BUILD_ROOT / "$" if arch else BUILD_ROOT - - process_root(SRC_ROOT, out_root, minify, micro, arch, False) - if prod: - process_root(SRC_ROOT, PROD_ROOT, minify, micro, arch, True) - - if include_test: - process_root(TEST_ROOT, out_root, minify, micro) - - if arch: - print("Installing bootloader files ...") - install_bootloader(arch, release) - print() - - -def _make_firstboot_kmod(users): - lines = [] - lines.append("local kernel = ...") - lines.append("local auth = kernel.auth") - lines.append("") - - for username, password in users: - u = username.replace("\\", "\\\\").replace("'", "\\'") - p = password.replace("\\", "\\\\").replace("'", "\\'") - - if username == "root": - lines.append("do") - lines.append(" local ok, err = auth.setPassword(0, '" + p + "')") - lines.append(" if ok then") - lines.append(" kernel.log('FIRSTBOOT: root password set')") - lines.append(" else") - lines.append(" kernel.log('FIRSTBOOT: root password error: ' .. tostring(err), 'ERROR')") - lines.append(" end") - lines.append("end") - else: - lines.append("do") - lines.append(" local uid, err = auth.newUser('" + u + "', '" + p + "')") - lines.append(" if uid then") - lines.append(" kernel.log('FIRSTBOOT: created user " + u + " uid=' .. tostring(uid))") - lines.append(" else") - lines.append(" kernel.log('FIRSTBOOT: failed to create user " + u + ": ' .. tostring(err), 'ERROR')") - lines.append(" end") - lines.append("end") - lines.append("") - - lines.append("do") - lines.append(" local ok, err = pcall(function()") - lines.append(" kernel.vfs.remove('/lib/modules/Hyperion/50_firstboot_users.kmod')") - lines.append(" end)") - lines.append(" if not ok then") - lines.append(" kernel.log('FIRSTBOOT: could not self-delete: ' .. tostring(err), 'WARN')") - lines.append(" end") - lines.append("end") - - return "\n".join(lines) + "\n" - - -def inject_makeusers(users, arch): - base = BUILD_ROOT / "$" if arch else BUILD_ROOT - kmod_path = base / "lib" / "modules" / "Hyperion" / "50_firstboot_users.kmod" - kmod_path.parent.mkdir(parents=True, exist_ok=True) - kmod_path.write_text(_make_firstboot_kmod(users), encoding="utf-8") - print(" Wrote first-boot user setup -> " + str(kmod_path.relative_to(BUILD_ROOT))) - - -def main(): - parser = argparse.ArgumentParser(description="HyperionOS build script") - parser.add_argument("target", choices=["build", "build-mini", "build-micro", "build-test", "build-mini-test", "build-micro-test", "clean", "prod", "prod-mini"]) - parser.add_argument("--arch", choices=["cct", "oc"], default=None, - help="Target architecture") - parser.add_argument("--release", dest="release", action="store_true", default=True, - help="Release build: eeprom placed as startup.lua (default)") - parser.add_argument("--dev", dest="release", action="store_false", - help="Dev build: boot.lua and eeprom copied unchanged") - parser.add_argument( - "--makeuser", metavar=("USERNAME", "PASSWORD"), nargs=2, action="append", - default=[], - help=( - "Pre-create a user on first boot (dev builds only). " - "May be specified multiple times. " - "Example: --makeuser root secretpass --makeuser alice alicepass" - ), - ) - - args = parser.parse_args() - - if args.makeuser and args.release: - parser.error("--makeuser is only allowed with --dev builds") - - if args.target == "clean": - clean() - return - - prod = "prod" in args.target - minify = "mini" in args.target or "micro" in args.target - micro = "micro" in args.target - include_test = "test" in args.target - - if micro: - import lz4.block - - run_build(minify=minify, micro=micro, include_test=include_test, arch=args.arch, release=args.release, prod=prod) - - if args.makeuser: - print("Injecting first-boot user setup ...") - inject_makeusers(args.makeuser, args.arch) - print() - - print("Build complete.") - - -if __name__ == "__main__": +#!/usr/bin/env python3 +""" +Usage: + python build.py [--arch cct|oc] [--release|--dev] + +Targets: + build + build-mini + build-micro + build-test + build-mini-test + build-micro-test + clean + prod + prod-mini + +Arch flags: + --arch cct + --arch oc + +Release flags: + --release + --dev +""" + +import sys +import shutil +import argparse +import subprocess +import json +import os +from pathlib import Path +from typing import Union + +PROJECT_ROOT = Path(__file__).resolve().parent +SRC_ROOT = PROJECT_ROOT / "Src" +TEST_ROOT = PROJECT_ROOT / "Test" +BUILD_ROOT = PROJECT_ROOT / "Build" +PROD_ROOT = PROJECT_ROOT / "prod" + +ARCH_BOOT_DIR = { + "cct": Path("boot") / "cct", + "oc": Path("boot") / "oc", +} + + +def clean(): + if BUILD_ROOT.exists(): + print(f"Removing {BUILD_ROOT} ...") + shutil.rmtree(BUILD_ROOT) + else: + print("Nothing to clean.") + +def cleanprod(): + if PROD_ROOT.exists(): + print(f"Removing {PROD_ROOT} ...") + shutil.rmtree(PROD_ROOT) + else: + print("Nothing to clean.") + + +def has_minify_header(path: Path) -> bool: + try: + with path.open("r", encoding="utf-8", errors="ignore") as f: + for _ in range(3): + if "--:Minify:--" in f.readline(): + return True + except OSError: + pass + return False + + +def minify_file(src: Path) -> str: + result = subprocess.run( + ["npm", "exec", "luamin", "--", "-f", str(src)], + capture_output=True, + text=True + ) + if result.returncode != 0: + print(f" ! luamin failed: {result.stderr.strip()}", file=sys.stderr) + sys.exit(1) + return result.stdout + + +def compress_lz4(data: bytes) -> bytes: + return lz4.frame.compress(data) + + +def process_root(src_root: Path, out_root: Path, minify: bool, micro: bool, arch:Union[str, None], prod:bool): + print(f"Building from {src_root}") + print(f"Output to {out_root}") + print() + + for pkg_dir in sorted(src_root.iterdir()): + if not pkg_dir.is_dir(): + continue + + if pkg_dir.name[:18] == "Hyperion-firmware-": + if pkg_dir.name != f"Hyperion-firmware-{arch}": + if prod != True: + continue + + data_dir=pkg_dir / "data" + + if not data_dir.is_dir(): + continue + + print(f"== Package: {pkg_dir.name} ==") + + for src in sorted(data_dir.rglob("*")): + if not src.is_file(): + continue + + rel = src.relative_to(data_dir) + + dst = out_root / rel + if prod: + dst = out_root / pkg_dir.name / rel + + dst.parent.mkdir(parents=True, exist_ok=True) + + print(f" Processing: {src.relative_to(src_root)}") + + if has_minify_header(src): + if minify: + print(" > Minifying") + content = minify_file(src) + if micro: + print(" > LZ4 compressing") + compressed = compress_lz4(content.encode("utf-8")) + dst.write_bytes(compressed) + else: + dst.write_text(content, encoding="utf-8") + else: + print(" > Copying") + shutil.copy2(src, dst) + else: + print(" > Copying") + shutil.copy2(src, dst) + + print() + + +def install_bootloader(arch: str, release: bool): + boot_dir = BUILD_ROOT / "$" / ARCH_BOOT_DIR[arch] + eeprom = boot_dir / "eeprom" + + eeprom_dst_name = "startup.lua" if release else "eeprom" + print(f" Installing: eeprom -> Build/{eeprom_dst_name}") + shutil.copy2(eeprom, BUILD_ROOT / eeprom_dst_name) + + +def run_build(minify: bool, micro: bool, include_test: bool, arch: Union[str, None], release: bool, prod: bool): + clean() + BUILD_ROOT.mkdir() + if prod: + cleanprod() + PROD_ROOT.mkdir() + + out_root = BUILD_ROOT / "$" if arch else BUILD_ROOT + + process_root(SRC_ROOT, out_root, minify, micro, arch, False) + if prod: + process_root(SRC_ROOT, PROD_ROOT, minify, micro, arch, True) + + if include_test: + process_root(TEST_ROOT, out_root, minify, micro) + + if arch: + print("Installing bootloader files ...") + install_bootloader(arch, release) + print() + + +def _make_firstboot_kmod(users): + lines = [] + lines.append("local kernel = ...") + lines.append("local auth = kernel.auth") + lines.append("") + + for username, password in users: + u = username.replace("\\", "\\\\").replace("'", "\\'") + p = password.replace("\\", "\\\\").replace("'", "\\'") + + if username == "root": + lines.append("do") + lines.append(" local ok, err = auth.setPassword(0, '" + p + "')") + lines.append(" if ok then") + lines.append(" kernel.log('FIRSTBOOT: root password set')") + lines.append(" else") + lines.append(" kernel.log('FIRSTBOOT: root password error: ' .. tostring(err), 'ERROR')") + lines.append(" end") + lines.append("end") + else: + lines.append("do") + lines.append(" local uid, err = auth.newUser('" + u + "', '" + p + "')") + lines.append(" if uid then") + lines.append(" kernel.log('FIRSTBOOT: created user " + u + " uid=' .. tostring(uid))") + lines.append(" else") + lines.append(" kernel.log('FIRSTBOOT: failed to create user " + u + ": ' .. tostring(err), 'ERROR')") + lines.append(" end") + lines.append("end") + lines.append("") + + lines.append("do") + lines.append(" local ok, err = pcall(function()") + lines.append(" kernel.vfs.remove('/lib/modules/Hyperion/50_firstboot_users.kmod')") + lines.append(" end)") + lines.append(" if not ok then") + lines.append(" kernel.log('FIRSTBOOT: could not self-delete: ' .. tostring(err), 'WARN')") + lines.append(" end") + lines.append("end") + + return "\n".join(lines) + "\n" + + +def inject_makeusers(users, arch): + base = BUILD_ROOT / "$" if arch else BUILD_ROOT + kmod_path = base / "lib" / "modules" / "Hyperion" / "50_firstboot_users.kmod" + kmod_path.parent.mkdir(parents=True, exist_ok=True) + kmod_path.write_text(_make_firstboot_kmod(users), encoding="utf-8") + print(" Wrote first-boot user setup -> " + str(kmod_path.relative_to(BUILD_ROOT))) + + +def main(): + parser = argparse.ArgumentParser(description="HyperionOS build script") + parser.add_argument("target", choices=["build", "build-mini", "build-micro", "build-test", "build-mini-test", "build-micro-test", "clean", "prod", "prod-mini"]) + parser.add_argument("--arch", choices=["cct", "oc"], default=None, + help="Target architecture") + parser.add_argument("--release", dest="release", action="store_true", default=True, + help="Release build: eeprom placed as startup.lua (default)") + parser.add_argument("--dev", dest="release", action="store_false", + help="Dev build: boot.lua and eeprom copied unchanged") + parser.add_argument( + "--makeuser", metavar=("USERNAME", "PASSWORD"), nargs=2, action="append", + default=[], + help=( + "Pre-create a user on first boot (dev builds only). " + "May be specified multiple times. " + "Example: --makeuser root secretpass --makeuser alice alicepass" + ), + ) + + args = parser.parse_args() + + if args.makeuser and args.release: + parser.error("--makeuser is only allowed with --dev builds") + + if args.target == "clean": + clean() + return + + prod = "prod" in args.target + minify = "mini" in args.target or "micro" in args.target + micro = "micro" in args.target + include_test = "test" in args.target + + if micro: + import lz4.block + + run_build(minify=minify, micro=micro, include_test=include_test, arch=args.arch, release=args.release, prod=prod) + + if args.makeuser: + print("Injecting first-boot user setup ...") + inject_makeusers(args.makeuser, args.arch) + print() + + print("Build complete.") + + +if __name__ == "__main__": main() \ No newline at end of file diff --git a/docs/kernel/boot.cfg.md b/docs/kernel/boot.cfg.md index 83ea6bb..c2ec588 100644 --- a/docs/kernel/boot.cfg.md +++ b/docs/kernel/boot.cfg.md @@ -29,4 +29,7 @@ logTaskExit showModLoad log module loads + +tmpToDisk + writes tmp to disk instead of ram ``` \ No newline at end of file