diff --git a/.vscode/settings.json b/.vscode/settings.json index d0c891f..ca37735 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,15 +1,7 @@ { - "Lua.diagnostics.globals": [ - "isEqualToAny", - "isEqualToAll", - "syscall", - "printf", - "printInline", - "toHex", - "userinput" + "Lua.workspace.library": [ + "./typings" ], - "Lua.diagnostics.disable": [ - "need-check-nil", - "param-type-mismatch" - ] + "Lua.workspace.checkThirdParty": false, + "Lua.diagnostics.globals": [] } \ 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 a795a71..437c5f1 100644 --- a/Src/Hyperion-firmware-cct/data/boot/cct/initdisks +++ b/Src/Hyperion-firmware-cct/data/boot/cct/initdisks @@ -258,7 +258,7 @@ internal["root"] = createDisk("root", "/root", false, { end, getLabel = function() local h = fs.open("/.rootlabel", "r") - if not h then return "$" end + if not h then return "root" end local label = h.readAll() h.close() return label @@ -266,14 +266,23 @@ internal["root"] = createDisk("root", "/root", false, { }) local function refresh() + local exclude = {root=true,rom=true,["$"]=true} disks={} - for _, disk in ipairs({peripheral.find("drive")}) do - if disk.isDiskPresent() then - disks[tostring(disk.getDiskID())]=createDisk("cctdisk"..tostring(disk.getDiskID()), disk.getMountPath(), false, fs) + for i,v in ipairs(fs.list("/")) do + if fs.isDir("/"..v) and not exclude[v] then + local uid="" + local h=fs.open("/"..v.."/.fsid", "r") + if not h then + uid=string.format("%X",math.random(0,2^32)) + local h2=fs.open("/"..v.."/.fsid", "w") + h2.write(uid) + h2.close() + else uid=h.readAll(); h.close() end + disks[uid]=createDisk(uid,"/"..v,false,{}) end end end - + local function iter() refresh() local combined = {} diff --git a/Src/Hyperion-kernel/data/boot/kernel.lua b/Src/Hyperion-kernel/data/boot/kernel.lua index 41dea06..6187e79 100644 --- a/Src/Hyperion-kernel/data/boot/kernel.lua +++ b/Src/Hyperion-kernel/data/boot/kernel.lua @@ -27,19 +27,19 @@ kernel.sleep=sleep _G.sleep=nil local windowsExp = false -function kernel.log(msg, level, c, nopanic) +function kernel.log(msg, tag, 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" + kernel.LOG_Text = kernel.LOG_Text..tostring(EFI:date()).." "..kernel.users[kernel.uid].." "..kernel.process.."["..tostring(tag 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) + screen:print(tostring(EFI:date()).." "..kernel.users[kernel.uid].." "..kernel.process.."["..tostring(tag 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.write(file,tostring(EFI:date()).." "..kernel.users[kernel.uid].." "..kernel.process.."["..tostring(tag or "INFO").."]: "..msg.."\n") kernel.vfs.close(file) kernel.currentTask=kernel.standbyTask end @@ -379,7 +379,16 @@ function kernel.runWhenLoaded(func) kernel.runhooks[#kernel.runhooks+1] = func return #kernel.runhooks end - +--[[ +function kernel.loadModule(data) + if kernel.vfs.exists(data) then + local f=kernel.vfs.open(data,"r") + data=kernel.vfs.read(1024*1024*4) + kernel.vfs.close(f) + end + local func=load(data, "RuntimeModule") +end +]] kernel.kernelTask = { name="kernel", status="R", @@ -518,4 +527,4 @@ elseif kernel.status=="halt" then else EFI.status="shutdown" return true -end +end \ No newline at end of file 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 aeb4bd6..92f097b 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/10_vfs.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/10_vfs.kmod @@ -1,9 +1,13 @@ --:Minify:-- +---@type HyperionOS.kernel local kernel = ... + +---@type HyperionOS.kernel.vfs local vfs = {} kernel.vfs = vfs vfs.mounts = {} vfs.disks = kernel.disks +vfs.openfiles = {} -- Metafile format (version 2) -- File header: 1 byte = version (0x02) @@ -1229,4 +1233,4 @@ end sys["getOpenFds"]= vfs.getOpenFds sys["fsinfo"] = vfs.fsinfo -kernel.log("VFS module loaded") +kernel.log("VFS module loaded") \ No newline at end of file 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 3309e94..f1033f7 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/12_devfs.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/12_devfs.kmod @@ -301,11 +301,70 @@ for i,v in pairs(kernel.vfs.mounts) do end +local function newdev(path, device) + if kernel.uid ~= 0 then error("EACCES") end + if type(path) ~= "string" or path == "" then + error("EINVAL") + end + if type(device) ~= "function" then + error("EINVAL") + end + + -- Normalize path + path = path:gsub("^/+", ""):gsub("/+$", "") + + if path == "" then error("EINVAL") end + + local steps = kernel.vfs.splitPath(path) + + if #steps == 0 then error("EINVAL") end + + local step = data + + -- Create intermediate directories + for i = 1, #steps - 1 do + local name = steps[i] + + if name == "." or name == ".." then + error("EINVAL") + end + + local entry = step[name] + + if entry == nil then + entry = {} + step[name] = entry + elseif type(entry) ~= "table" then + error("ENOTDIR") + end + + step = entry + end + + local name = steps[#steps] + + if name == "." or name == ".." then + error("EINVAL") + end + + -- Don't overwrite existing devices or directories + if step[name] ~= nil then + error("EEXIST") + end + + -- Register device + step[name] = device + + return true +end + data["raw"]={["by-type"]={}} data["gfx"]={} data["input"]={} data["tty"]={} kernel.devfs={} +kernel.devfs.newdev=newdev +kernel.syscalls.newdev=kernel.devfs.newdev kernel.devfs.data=data kernel.devfs.proxy=proxy kernel.disks["devfs0000"]=proxy \ 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 4b85415..16f2385 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/45_hypervisor.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/45_hypervisor.kmod @@ -230,7 +230,6 @@ function sys.getTask(pid) siblings = siblings, parent = task.parent.pid, cwd = task.cwd, - term = task.term, } end diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/70_stdlibadv.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/70_stdlibadv.kmod index 8e0679e..35acf48 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/70_stdlibadv.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/70_stdlibadv.kmod @@ -21,22 +21,25 @@ function printInline(...) syscall.write(1, output) end + + function userinput(fd, helpstr, replacestr, fdo) + fd = fd or 0 + fdo = fdo or 1 local str = "" if helpstr then print(helpstr) end while true do local inp = syscall.read(fd) - if inp~="" and inp~=nil then - if inp~="\n" then - if replacestr then - syscall.write(fdo, replacestr) - else - syscall.write(fdo, inp) - end - str = inp - else + if inp and inp ~= "" then + if inp == "\n" then break end + if replacestr then + syscall.write(fdo, replacestr) + else + syscall.write(fdo, inp) + end + str = str .. inp end end return str diff --git a/Src/Hyperion-kernel/data/lib/modules/hyperion/90_kgc.kmod b/Src/Hyperion-kernel/data/lib/modules/hyperion/90_kgc.kmod index 9d36446..6f3151c 100644 --- a/Src/Hyperion-kernel/data/lib/modules/hyperion/90_kgc.kmod +++ b/Src/Hyperion-kernel/data/lib/modules/hyperion/90_kgc.kmod @@ -7,6 +7,8 @@ kernel.processes.kgc = function() -- kernel.reqcache[i] = nil -- end --end + + sleep(5) end end \ No newline at end of file diff --git a/Src/coreutils/data/bin/login b/Src/coreutils/data/bin/login index 611a451..591573e 100644 --- a/Src/coreutils/data/bin/login +++ b/Src/coreutils/data/bin/login @@ -103,7 +103,14 @@ local function spawnShell(username, uid, shell, homedir) local shellfunc, err = load(fs.readAllText(shell)) - local ok, err = pcall(syscall.spawn, shellfunc, username .. ":shell", nil,nil,nil,true) + local function loader() + syscall.open("/dev/input/keyboard1", "r") + syscall.open("/dev/tty/1", "w") + syscall.open("/dev/null", "w") + shellfunc() + end + + local ok, err = pcall(syscall.spawn, loader, username .. ":shell", nil,nil,nil,true) if not ok then syscall.write(1, "login: failed to launch shell: " .. tostring(err) .. "\n") sleep(2) diff --git a/Src/coreutils/data/etc/sysinit/autorun/login b/Src/coreutils/data/etc/sysinit/autorun/login index 611a451..591573e 100644 --- a/Src/coreutils/data/etc/sysinit/autorun/login +++ b/Src/coreutils/data/etc/sysinit/autorun/login @@ -103,7 +103,14 @@ local function spawnShell(username, uid, shell, homedir) local shellfunc, err = load(fs.readAllText(shell)) - local ok, err = pcall(syscall.spawn, shellfunc, username .. ":shell", nil,nil,nil,true) + local function loader() + syscall.open("/dev/input/keyboard1", "r") + syscall.open("/dev/tty/1", "w") + syscall.open("/dev/null", "w") + shellfunc() + end + + local ok, err = pcall(syscall.spawn, loader, username .. ":shell", nil,nil,nil,true) if not ok then syscall.write(1, "login: failed to launch shell: " .. tostring(err) .. "\n") sleep(2) diff --git a/Src/hysh/data/bin/chown b/Src/hysh/data/bin/chown index ffabaf4..db17f5f 100644 --- a/Src/hysh/data/bin/chown +++ b/Src/hysh/data/bin/chown @@ -147,4 +147,4 @@ for i = 2, #args do end end -syscall.exit(exitCode) +syscall.exit(exitCode) \ No newline at end of file diff --git a/Src/hysh/data/bin/hysh b/Src/hysh/data/bin/hysh index 24af6d7..75251bc 100644 --- a/Src/hysh/data/bin/hysh +++ b/Src/hysh/data/bin/hysh @@ -1,11 +1,16 @@ --:Minify:-- 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 fs = require("fs") + +local fds=syscall.getOpenFds() +syscall.log(table.serialize(fds)) +if not fds[0] or not fds[1] then + syscall.log("opening fds") + syscall.open("/dev/input/keyboard1", "r") + syscall.open("/dev/tty/1", "w") +end + local gfx = syscall.devctl(1,"gfx") syscall.devctl(1,"clear") diff --git a/Src/wget/authors.txt b/Src/wget/authors.txt new file mode 100644 index 0000000..73c23ff --- /dev/null +++ b/Src/wget/authors.txt @@ -0,0 +1,2 @@ +Hyperion +Astronand \ No newline at end of file diff --git a/Src/wget/data/bin/wget b/Src/wget/data/bin/wget new file mode 100644 index 0000000..ec70368 --- /dev/null +++ b/Src/wget/data/bin/wget @@ -0,0 +1,10 @@ +--:Minify:-- +local args={...} +if type(args[1])~="string" then print("Usage: wget [url]"); syscall.exit() end +local http = require("http") +local fs = require("fs") +print("GET: "..args[1]) +local resp = http.get(args[1]) +local clean_url = args[1]:match("^([^?#]+)") +local filename = clean_url:match("^.+/(.+)$") +fs.writeAllText(filename, resp.body) \ No newline at end of file diff --git a/Src/wget/dependencies.txt b/Src/wget/dependencies.txt new file mode 100644 index 0000000..151d486 --- /dev/null +++ b/Src/wget/dependencies.txt @@ -0,0 +1 @@ +Hyperion-core \ No newline at end of file diff --git a/Src/wget/description.txt b/Src/wget/description.txt new file mode 100644 index 0000000..b6527d2 --- /dev/null +++ b/Src/wget/description.txt @@ -0,0 +1 @@ +simple wget command \ No newline at end of file diff --git a/Src/wget/version.txt b/Src/wget/version.txt new file mode 100644 index 0000000..afaf360 --- /dev/null +++ b/Src/wget/version.txt @@ -0,0 +1 @@ +1.0.0 \ No newline at end of file diff --git a/bootstrap/cct-bootstrap.lua b/bootstrap/cct-bootstrap.lua index 271cb50..8448d82 100644 --- a/bootstrap/cct-bootstrap.lua +++ b/bootstrap/cct-bootstrap.lua @@ -1,609 +1,746 @@ print("Running CC:Tweaked vm bootstrap") +print("Virtualizing filesystem") -local bootloader=[=[ ----@diagnostic disable-next-line: undefined-global -local lterm = term -local function write(text, term) - local x, y = term.getCursorPos() - local w, h = term.getSize() +local oldfs = fs +local newfs = {} - for i = 1, #text do - local c = text:sub(i, i) +-- Mount table +local mounts = { + ["/"] = { + fs = "ram", + root = "/" + }, - if c == "\n" then - y = y + 1 - x = 1 - elseif c == "\t" then - local tabSize = 4 - local spaces = tabSize - ((x - 1) % tabSize) - term.write(string.rep(" ", spaces)) - x = x + spaces - elseif c == "\b" then - if x > 1 then - x = x - 1 - term.setCursorPos(x, y) - term.write(" ") - term.setCursorPos(x, y) + ["/computer/"] = { + fs = "oldfs", + root = "/root/" + }, + + ["/computer_boot/"] = { + fs = "oldfs", + root = "/$/" + }, + + ["/eeprom"] = { + fs = "oldfs", + root = "/eeprom" + } +} + + +-- Backing filesystems +local disks = { + oldfs = oldfs, + + ram = { + type = "dir", + children = {} + } +} + +-- Normalize virtual paths +local function normalize(path) + path = tostring(path or ""):gsub("\\", "/") + + local parts = {} + + for part in path:gmatch("[^/]+") do + if part == ".." then + if #parts > 0 then + table.remove(parts) end - else - if x <= w and y <= h then - term.setCursorPos(x, y) - term.write(c) - x = x + 1 - end - end - - if x > w then - x = 1 - y = y + 1 - end - - if y - 1 >= h then - term.scroll(1) - y = h - term.setCursorPos(x, y) + elseif part ~= "." then + parts[#parts + 1] = part end end - term.setCursorPos(x, y) + return "/" .. table.concat(parts, "/") end -local function displaySuperBadError(err) - lterm.setBackgroundColor(0x1) - lterm.setTextColor(0x4) - lterm.clear() - lterm.setCursorPos(1, 1) - lterm.write("A critical error occurred while loading the system:") - lterm.setCursorPos(1, 3) - write(err, lterm) - while true do end +-- Resolve virtual path into physical filesystem path +local function resolve(path) + path = normalize(path) + + local selected + local selectedLength = -1 + local selectedMount + + for mount, info in pairs(mounts) do + local prefix = mount == "/" and "/" or mount:gsub("/+$", "") + + local matches + + if prefix == "/" then + matches = true + else + matches = path == prefix or + path:sub(1, #prefix + 1) == prefix .. "/" + end + + if matches and #prefix > selectedLength then + selected = info + selectedLength = #prefix + selectedMount = prefix + end + end + + if not selected then + error("No filesystem mounted for " .. path, 2) + end + + local relative + + if selectedMount == "/" then + relative = path:sub(2) + else + relative = path:sub(#selectedMount + 1):gsub("^/", "") + end + + local physical = selected.root + + if relative ~= "" then + physical = physical:gsub("/+$", "") .. "/" .. relative + end + + if physical == "" then + physical = "/" + end + + return disks[selected.fs], relative, selected.fs, physical end -term.setCursorBlink(false) -local ok, err = xpcall(function() - --p - local apis = {BOOT_DRIVE_PATH = BOOT_DRIVE_PATH} +-- RAM filesystem helpers +local function getNode(root, path) + local node = root - local lua = { - coroutine = true, - debug = true, - _VERSION = true, - assert = true, - collectgarbage = true, - error = true, - gcinfo = true, - getmetatable = true, - ipairs = true, - __inext = true, - load = true, - math = true, - next = true, - pairs = true, - pcall = true, - rawequal = true, - rawget = true, - rawlen = true, - rawset = true, - select = true, - setmetatable = true, - string = true, - table = true, - tonumber = true, - tostring = true, - type = true, - xpcall = true, - _G = true - } - - local debug = debug - for i, v in pairs(_G) do - if not lua[i] or lua[i] == nil then - apis[i] = v - _G[i] = nil - end - end - --p - - local acekeys={ - [apis.keys.enter]="\n", - [apis.keys.tab]="\t", - [apis.keys.backspace]="\b", - [apis.keys.up]="\17", - [apis.keys.down]="\18", - [apis.keys.left]="\19", - [apis.keys.right]="\20", - } - - function sleep(time) - local stoptime = apis.os.clock() + (time) - while stoptime > apis.os.clock() do end + if path == "" then + return node end - apis.term.setPaletteColor(0x1, 0xFFFFFF) -- #000000 - apis.term.setPaletteColor(0x2, 0xFF0000) -- #FFFFFF - apis.term.setPaletteColor(0x4, 0x00FF00) -- #FF0000 - apis.term.setPaletteColor(0x8, 0x0000FF) -- #00FF00 - apis.term.setPaletteColor(0x10, 0x00FFFF) -- #0000FF - apis.term.setPaletteColor(0x20, 0xFF00FF) -- #00FFFF - apis.term.setPaletteColor(0x40, 0xFFFF00) -- #FF00FF - apis.term.setPaletteColor(0x80, 0xFF6D00) -- #FFFF00 - apis.term.setPaletteColor(0x100, 0x6DFF55) -- #FF6D00 - apis.term.setPaletteColor(0x200, 0x24FFFF) -- #6DFF55 - apis.term.setPaletteColor(0x400, 0x924900) -- #24FFFF - apis.term.setPaletteColor(0x800, 0x6D6D55) -- #924900 - apis.term.setPaletteColor(0x1000, 0xDBDBAA) -- #6D6D55 - apis.term.setPaletteColor(0x2000, 0x6D00FF) -- #DBDBAA - apis.term.setPaletteColor(0x4000, 0xB6FF00) -- #6D00FF - apis.term.setPaletteColor(0x8000, 0x000000) -- #B6FF00 - local eventQueue = {} - local function queueEvent(event, ...) - table.insert(eventQueue, {event, ...}) - end - - local colors = { - [0xFFFFFF]=0x0001, - [0x000000]=0x8000 - } - - local fg,bg=0x6D6D55,0x000000 - local l1f,l1d,l2,ops={},{},{},0 - - local function findClosest(tbl, target) - local closest = nil - local smallestDiff = math.huge - - for k, _ in pairs(tbl) do - if k==target then return k end - local diff = math.abs(k - target) - if diff < smallestDiff then - smallestDiff = diff - closest = k - end - end - - return closest - end - - local function aprox(c24) - ops = ops + 1 - - if ops % 1024 == 0 then - l1d = {} - l1f = {} - end - - if ops % 8192 == 0 then - l2 = {} - end - - if l2[c24] ~= nil then - return l2[c24] - end - - if l1d[c24] ~= nil then - l1f[c24] = l1f[c24] + 1 - - if l1f[c24] >= 16 then - l2[c24] = l1d[c24] - l1d[c24] = nil - l1f[c24] = nil - return l2[c24] - end - - return l1d[c24] - end - - local closestKey = findClosest(colors, c24) - if not closestKey then return nil end - - local value = colors[closestKey] - - l1d[c24] = value - l1f[c24] = 1 - - return value - end - --p - local p={} - local native = apis.peripheral - local sides = {"top", "bottom", "left", "right", "front", "back"} - - function p.getNames() - local results = {} - for n = 1, #sides do - local side = sides[n] - if native.isPresent(side) then - table.insert(results, side) - if native.hasType(side, "peripheral_hub") then - local remote = native.call(side, "getNamesRemote") - for _, name in ipairs(remote) do - table.insert(results, name) - end - end - end - end - return results - end - - function p.isPresent(name) - if native.isPresent(name) then - return true - end - - for n = 1, #sides do - local side = sides[n] - if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then - return true - end - end - return false - end - - function p.getType(peripheral) - if type(peripheral) == "string" then - if native.isPresent(peripheral) then - return native.getType(peripheral) - end - for n = 1, #sides do - local side = sides[n] - if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", peripheral) then - return native.call(side, "getTypeRemote", peripheral) - end - end + for part in path:gmatch("[^/]+") do + if not node or node.type ~= "dir" then return nil - else - local mt = getmetatable(peripheral) - if not mt or mt.__name ~= "peripheral" or type(mt.types) ~= "table" then - error("bad argument #1 (table is not a peripheral)", 2) - end - return table.unpack(mt.types) end + + node = node.children[part] end - function p.hasType(peripheral, peripheral_type) - if type(peripheral) == "string" then - if native.isPresent(peripheral) then - return native.hasType(peripheral, peripheral_type) - end - for n = 1, #sides do - local side = sides[n] - if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", peripheral) then - return native.call(side, "hasTypeRemote", peripheral, peripheral_type) - end - end - return nil - else - local mt = getmetatable(peripheral) - if not mt or mt.__name ~= "peripheral" or type(mt.types) ~= "table" then - error("bad argument #1 (table is not a peripheral)", 2) - end - return mt.types[peripheral_type] ~= nil - end - end + return node +end - function p.getMethods(name) - if native.isPresent(name) then - return native.getMethods(name) - end - for n = 1, #sides do - local side = sides[n] - if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then - return native.call(side, "getMethodsRemote", name) - end - end +local function getParent(root, path) + local parentPath, name = path:match("^(.*)/([^/]+)$") + + if not name then return nil end - function p.getName(peripheral) - local mt = getmetatable(peripheral) - if not mt or mt.__name ~= "peripheral" or type(mt.name) ~= "string" then - error("bad argument #1 (table is not a peripheral)", 2) - end - return mt.name - end + local parent = getNode(root, parentPath or "") - function p.call(name, method, ...) - if native.isPresent(name) then - return native.call(name, method, ...) - end - - for n = 1, #sides do - local side = sides[n] - if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then - return native.call(side, "callRemote", name, method, ...) - end - end + if not parent or parent.type ~= "dir" then return nil end - function p.wrap(name) - local methods = p.getMethods(name) - if not methods then + return parent, name +end + +local function ensureDir(root, path) + local node = root + + for part in path:gmatch("[^/]+") do + if not node.children[part] then + node.children[part] = { + type = "dir", + children = {} + } + end + + node = node.children[part] + + if node.type ~= "dir" then + return false + end + end + + return true +end + +local function cloneNode(node) + if node.type == "file" then + return { + type = "file", + data = node.data + } + end + + local copy = { + type = "dir", + children = {} + } + + for name, child in pairs(node.children) do + copy.children[name] = cloneNode(child) + end + + return copy +end + +-- RAM file handles +local function makeHandle(node, mode) + local position = (mode == "a" or mode == "ab") and #node.data or 0 + local closed = false + + local handle = {} + + local function check() + if closed then + error("attempt to use a closed file", 3) + end + end + + function handle.read(count) + check() + + if position >= #node.data then return nil end - local types = { p.getType(name) } - for i = 1, #types do types[types[i]] = true end - local result = setmetatable({}, { - __name = "peripheral", - name = name, - type = types[1], - types = types, - }) - for _, method in ipairs(methods) do - result[method] = function(...) - return p.call(name, method, ...) - end - end + count = count or 1 + + local result = node.data:sub(position + 1, position + count) + position = position + #result + return result end - function p.find(ty, filter) - local results = {} - for _, name in ipairs(p.getNames()) do - if p.hasType(name, ty) then - local wrapped = p.wrap(name) - if filter == nil or filter(name, wrapped) then - table.insert(results, wrapped) + function handle.readAll() + check() + + local result = node.data:sub(position + 1) + position = #node.data + + return result + end + + function handle.readLine() + check() + + if position >= #node.data then + return nil + end + + local ending = node.data:find("\n", position + 1, true) + + if ending then + local result = node.data:sub(position + 1, ending - 1) + position = ending + + return result + end + + local result = node.data:sub(position + 1) + position = #node.data + + return result + end + + function handle.write(value) + check() + + if mode == "r" or mode == "rb" then + error("attempt to write to a read-only file", 2) + end + + value = tostring(value) + + if mode == "a" or mode == "ab" then + node.data = node.data .. value + position = #node.data + else + node.data = + node.data:sub(1, position) .. + value .. + node.data:sub(position + #value + 1) + + position = position + #value + end + end + + function handle.writeLine(value) + handle.write(tostring(value) .. "\n") + end + + function handle.flush() + check() + end + + function handle.seek(whence, offset) + check() + + whence = whence or "cur" + offset = offset or 0 + + if whence == "set" then + position = offset + elseif whence == "cur" then + position = position + offset + elseif whence == "end" then + position = #node.data + offset + else + error("invalid whence", 2) + end + + position = math.max(0, position) + + return position + end + + function handle.close() + closed = true + end + + return handle +end + +-- Basic path functions +function newfs.combine(...) + local args = {...} + local result = table.concat(args, "/") + + return normalize(result) +end + +function newfs.getName(path) + return normalize(path):match("([^/]+)$") or "" +end + +function newfs.getDir(path) + return normalize(path):match("^(.*)/[^/]+$") or "/" +end + +function newfs.getDrive(path) + local _, _, disk = resolve(path) + + return disk +end + +-- Filesystem information +function newfs.exists(path) + local root, relative, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.exists(physical) + end + + return getNode(root, relative) ~= nil +end + +function newfs.isDir(path) + local root, relative, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.isDir(physical) + end + + local node = getNode(root, relative) + + return node ~= nil and node.type == "dir" +end + +function newfs.isReadOnly(path) + local _, _, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.isReadOnly(physical) + end + + return false +end + +function newfs.getSize(path) + local root, relative, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.getSize(physical) + end + + local node = getNode(root, relative) + + if not node then + return 0 + end + + if node.type == "file" then + return #node.data + end + + local function calculate(n) + local size = 0 + + for _, child in pairs(n.children) do + if child.type == "file" then + size = size + #child.data + else + size = size + calculate(child) + end + end + + return size + end + + return calculate(node) +end + +function newfs.getFreeSpace(path) + local _, _, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.getFreeSpace(physical) + end + + return math.huge +end + +function newfs.getCapacity(path) + local _, _, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.getCapacity(physical) + end + + return math.huge +end + +-- Directory operations +function newfs.makeDir(path) + local root, relative, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.makeDir(physical) + end + + return ensureDir(root, relative) +end + +function newfs.list(path) + local root, relative, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.list(physical) + end + + local node = getNode(root, relative) + + if not node or node.type ~= "dir" then + error("Not a directory", 2) + end + + local result = {} + + for name in pairs(node.children) do + result[#result + 1] = name + end + + table.sort(result) + + return result +end + +function newfs.delete(path) + local root, relative, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.delete(physical) + end + + if relative == "" then + error("Cannot delete filesystem root", 2) + end + + local parent, name = getParent(root, relative) + + if parent then + parent.children[name] = nil + end +end + +-- File operations +function newfs.open(path, mode) + mode = mode or "r" + + local root, relative, disk, physical = resolve(path) + + if disk == "oldfs" then + return oldfs.open(physical, mode) + end + + local node = getNode(root, relative) + + if mode == "r" or mode == "rb" then + if not node or node.type ~= "file" then + return nil + end + else + if relative == "" then + return nil + end + + local parent, name = getParent(root, relative) + + if not parent then + return nil + end + + if not node then + node = { + type = "file", + data = "" + } + + parent.children[name] = node + elseif node.type ~= "file" then + return nil + end + + if mode == "w" or mode == "wb" then + node.data = "" + end + end + + return makeHandle(node, mode) +end + +-- Copy and move operations +function newfs.copy(from, to) + local src, srcPath, srcDisk, srcPhysical = resolve(from) + local dst, dstPath, dstDisk, dstPhysical = resolve(to) + + if srcDisk == dstDisk then + if srcDisk == "oldfs" then + return oldfs.copy(srcPhysical, dstPhysical) + end + + local source = getNode(src, srcPath) + + if not source then + error("Source does not exist", 2) + end + + local parent, name = getParent(dst, dstPath) + + if not parent then + error("Destination parent does not exist", 2) + end + + parent.children[name] = cloneNode(source) + + return + end + + local function copyNode(source, destination) + if source.type == "file" then + local handle = newfs.open(destination, "w") + + if not handle then + error("Cannot create destination: " .. destination) + end + + handle.write(source.data) + handle.close() + + return + end + + newfs.makeDir(destination) + + for name, child in pairs(source.children) do + copyNode(child, newfs.combine(destination, name)) + end + end + + local source + + if srcDisk == "ram" then + source = getNode(src, srcPath) + elseif oldfs.isDir(srcPhysical) then + source = { + type = "dir", + children = {} + } + + local function readDir(path, node) + for _, name in ipairs(oldfs.list(path)) do + local childPath = oldfs.combine(path, name) + + if oldfs.isDir(childPath) then + local child = { + type = "dir", + children = {} + } + + node.children[name] = child + readDir(childPath, child) + else + local handle = oldfs.open(childPath, "r") + local data = handle.readAll() + handle.close() + + node.children[name] = { + type = "file", + data = data + } end end end - return table.unpack(results) - end - --p - local allscreens = {p.find("monitor")} - for i=1, #allscreens do - allscreens[i].setTextScale(.5) - allscreens[i].clear() - allscreens[i].setCursorPos(1,1) + + readDir(srcPhysical, source) + else + local handle = oldfs.open(srcPhysical, "r") + + if handle then + source = { + type = "file", + data = handle.readAll() + } + + handle.close() + end end - allscreens[#allscreens+1] = apis.term + if not source then + error("Source does not exist", 2) + end - local EFI = { - getEpochMs = function() return apis.os.epoch("utc") end, - getUptime = function() return apis.os.clock() * 1000 end, - date = function() return apis.os.date("!%Y-%m-%dT%H:%M:%SZ", apis.os.epoch("utc") / 1000) end, - getMachineEvent = function() - if #eventQueue > 0 then - return table.unpack(table.remove(eventQueue, 1)) - else - return nil + copyNode(source, to) +end + +function newfs.move(from, to) + local _, _, srcDisk, srcPhysical = resolve(from) + local _, _, dstDisk, dstPhysical = resolve(to) + + if srcDisk == dstDisk then + if srcDisk == "oldfs" then + return oldfs.move(srcPhysical, dstPhysical) + end + + local src, srcPath = resolve(from) + local dst, dstPath = resolve(to) + + if srcPath == "" then + error("Cannot move filesystem root", 2) + end + + local sourceParent, sourceName = getParent(src, srcPath) + local destinationParent, destinationName = getParent(dst, dstPath) + + if not sourceParent or not destinationParent then + error("Invalid move destination", 2) + end + + local node = sourceParent.children[sourceName] + + if not node then + error("Source does not exist", 2) + end + + sourceParent.children[sourceName] = nil + destinationParent.children[destinationName] = node + + return + end + + newfs.copy(from, to) + newfs.delete(from) +end + +-- Search +function newfs.find(path, pattern) + local results = {} + + local function walk(current) + for _, name in ipairs(newfs.list(current)) do + local full = newfs.combine(current, name) + + if full:match(pattern) then + results[#results + 1] = full end - end, - getEEPROM = function() return getFile(eeprom) end, - setEEPROM = function(_, text) - local h = apis.fs.open(eeprom, "w") - h.write(text) - h.close() - end, - initfs=fs, - disks=initFs, - screenCtl={ - print = function(_, text) - for i=1, #allscreens do - write(text.."\n", allscreens[i]) - end - end, - printInline = function(_, text) - for i=1, #allscreens do - write(text, allscreens[i]) - end - end, - clear = function() - for i=1, #allscreens do - allscreens[i].clear() - allscreens[i].setCursorPos(1, 1) - end - end, - resetCursor = function() - for i=1, #allscreens do - allscreens[i].setCursorPos(1, 1) - end - end, - setBackgroundColor = function(_, color) - bg=color - for i=1, #allscreens do - allscreens[i].setBackgroundColor(aprox(color)) - end - end, - setTextColor = function(_, color) - fg=color - for i=1, #allscreens do - allscreens[i].setTextColor(aprox(color)) - end - end, - getBackgroundColor = function() - return bg - end, - getTextColor = function() - return fg - end, - enable=function() - for i=1, #allscreens do - allscreens[i].clear() - allscreens[i].setCursorPos(1, 1) - end - end, - disable=function() end - }, - architecture="vm", - getNvram = function() return getFile("/nvram.dat") end, - setNvram = function(_, text) - local h = apis.fs.open("/nvram.dat", "w") - h.write(text) - h.close() - end, - firmware=apis, - reboot=false, - beep=function() end + + if newfs.isDir(full) then + walk(full) + end + end + end + + walk(path) + + return results +end + +-- Completion +function newfs.complete(path, location, includeFiles, includeDirs) + local results = {} + + location = location or "/" + path = path or "" + + local base = newfs.combine(location, newfs.getDir(path)) + local partial = newfs.getName(path) + + if not newfs.exists(base) or not newfs.isDir(base) then + return results + end + + for _, name in ipairs(newfs.list(base)) do + if name:sub(1, #partial) == partial then + local full = newfs.combine(base, name) + + if newfs.isDir(full) and includeDirs ~= false then + results[#results + 1] = name .. "/" + elseif not newfs.isDir(full) and includeFiles ~= false then + results[#results + 1] = name + end + end + end + + return results +end + +-- Attributes +function newfs.attributes(path) + local root, relative, disk, physical = resolve(path) + + if disk == "oldfs" then + if oldfs.attributes then + return oldfs.attributes(physical) + end + + return nil + end + + local node = getNode(root, relative) + + if not node then + return nil + end + + local now = os.epoch and os.epoch("utc") or 0 + + return { + size = node.type == "file" and #node.data or 0, + isDir = node.type == "dir", + isReadOnly = false, + created = now, + modified = now } - - apis.term.setBackgroundColor(0x8000) - apis.term.setTextColor(0x1000) - apis.term.clear() - apis.term.setCursorPos(1, 1) - - local kernelCoro = coroutine.create(function() - --pf - ---@diagnostic disable-next-line: param-type-mismatch - local ok, err = xpcall(Kernel, debug.traceback, EFI) - if not ok and not EFI.reboot then displaySuperBadError(err) end - if err then - apis.os.reboot() - else - apis.os.shutdown() - end - end) - - function coroutine.resumeWithTimeout(co, timeout, ...) - local startTime = EFI.getEpochMs() - debug.sethook(co, function() - if EFI.getEpochMs() > startTime + timeout then - return coroutine.yield("timeout") - end - end, "", 1000) - local ret = {coroutine.resume(co, ...)} - if ret[1] and ret[2] == "timeout" then - return "timeout" - elseif ret[1] == false then - return "error", ret[2] - else - debug.sethook(co) - return "success", table.unpack(ret, 2) - end - end - - EFI.screenCtl:print("Loaded in " .. tostring(apis.os.clock()) .. " seconds.\n") - --p - - while true do - local status, err = coroutine.resumeWithTimeout(kernelCoro, 50) - apis.os.queueEvent("NoSleep") - local exit = false - while not exit do - local event = {coroutine.yield()} - if event[1] == "key" then - queueEvent(table.unpack(event)) - queueEvent("keyPressed", 1, event[2]) - if acekeys[event[2]] then - queueEvent("keyTyped", 1, acekeys[event[2]]) - end - elseif event[1] == "char" then - queueEvent(table.unpack(event)) - queueEvent("keyTyped", 1, event[2]) - elseif event[1] == "key_up" then - queueEvent(table.unpack(event)) - queueEvent("keyReleased", 1, event[2]) - elseif event[1] == "NoSleep" then - exit = true - else - queueEvent(table.unpack(event)) - end - end - if status == "error" or coroutine.status(kernelCoro) == "dead" then - if EFI.reboot then - apis.os.reboot() - end - displaySuperBadError("Kernel error: " .. tostring(err)) - coroutine.yield("key") - elseif status == "success" then - if EFI.reboot then - apis.os.reboot() - end - displaySuperBadError("Kernel error: Attempted to yield main thread") - coroutine.yield("key") - end - initFs:refresh() - end -end, debug.traceback) - -if not ok then displaySuperBadError("Fatal error during boot: " .. err) end -while true do coroutine.yield("key") end -]=] - -local args = {} -local keptAPIs = {keys=true, bit32 = true, bit = true, ccemux = true, config = true, coroutine = true, debug = true, fs = true, http = true, mounter = true, os = true, periphemu = true, peripheral = true, redstone = true, rs = true, term = true, utf8 = true, _HOST = true, _CC_DEFAULT_SETTINGS = true, _CC_DISABLE_LUA51_FEATURES = true, _VERSION = true, assert = true, collectgarbage = true, error = true, gcinfo = true, getfenv = true, getmetatable = true, ipairs = true, __inext = true,load = true, loadstring = true, math = true, newproxy = true, next = true, pairs = true, pcall = true, rawequal = true, rawget = true, rawlen = true, rawset = true, select = true, setfenv = true, setmetatable = true, string = true, table = true, tonumber = true, tostring = true, type = true, unpack = true, xpcall = true, turtle = true, pocket = true, commands = true, _G = true} -local t = {} -for k in pairs(_G) do if not keptAPIs[k] then table.insert(t, k) end end -for _,k in ipairs(t) do _G[k] = nil end -local native = _G.term.native() -for _, method in ipairs {"nativePaletteColor", "nativePaletteColour", "screenshot"} do native[method] = _G.term[method] end -_G.term = native -if _G.http then - _G.http.checkURL = _G.http.checkURLAsync - _G.http.websocket = _G.http.websocketAsync end -if _G.commands then _G.commands = _G.commands.native end -if _G.turtle then _G.turtle.native, _G.turtle.craft = nil end -local delete = {os = {"version", "pullEventRaw", "pullEvent", "run", "loadAPI", "unloadAPI", "sleep"}, http = _G.http and {"get", "post", "put", "delete", "patch", "options", "head", "trace", "listen", "checkURLAsync", "websocketAsync"}, fs = {"complete", "isDriveRoot"}} -for k,v in pairs(delete) do for _,a in ipairs(v) do _G[k][a] = nil end end -local olderror = error -_G.error = function() end -_G.term.redirect = function() end -function _G.term.native() - _G.term.native = nil - _G.term.redirect = nil - _G.error = olderror - term.setBackgroundColor(32768) - term.setTextColor(1) - term.setCursorPos(1, 1) - term.setCursorBlink(true) - term.clear() - local file = bootloader - if file == nil then - term.setCursorBlink(false) - term.setTextColor(16384) - term.write("Could not find /boot/cct/boot.lua. UnBIOS cannot continue.") - term.setCursorPos(1, 2) - term.write("Press any key to continue") - coroutine.yield("key") - os.shutdown() - end - local fn, err = loadstring(file.readAll(), "@bootloader") - file.close() - if fn == nil then - term.setCursorBlink(false) - term.setTextColor(16384) - term.write("Could not load /boot/cc/boot.lua. UnBIOS cannot continue.") - term.setCursorPos(1, 2) - term.write(err) - term.setCursorPos(1, 3) - term.write("Press any key to continue") - coroutine.yield("key") - os.shutdown() - end - setfenv(fn, _G) - local oldshutdown = os.shutdown - os.shutdown = function() - os.shutdown = oldshutdown - return fn() - end -end -if debug then - local function restoreValue(tab, idx, name, hint) - local i, key, value = 1, debug.getupvalue(tab[idx], hint) - while key ~= name and key ~= nil do - key, value = debug.getupvalue(tab[idx], i) - i=i+1 - end - tab[idx] = value or tab[idx] - end - restoreValue(_G, "loadstring", "nativeloadstring", 1) - restoreValue(_G, "load", "nativeload", 5) - if http then restoreValue(http, "request", "nativeHTTPRequest", 3) end - restoreValue(os, "shutdown", "nativeShutdown", 1) - restoreValue(os, "reboot", "nativeReboot", 1) - if turtle then - restoreValue(turtle, "equipLeft", "v", 1) - restoreValue(turtle, "equipRight", "v", 1) - end - do - local i, key, value = 1, debug.getupvalue(peripheral.isPresent, 2) - while key ~= "native" and key ~= nil do - key, value = debug.getupvalue(peripheral.isPresent, i) - i=i+1 - end - _G.peripheral = value or peripheral - end -end \ No newline at end of file + +-- Replace CC:Tweaked filesystem +fs = newfs + +print("Installing packages") +print("Moving boot partition") + +fs.makeDir("/$/") +fs.move("/root/boot/", "/$/") + +print("RAM filesystem initialized") diff --git a/docs/kernel/boot.cfg.md b/docs/kernel/boot.cfg.md index 73b5b62..3f5425b 100644 --- a/docs/kernel/boot.cfg.md +++ b/docs/kernel/boot.cfg.md @@ -4,7 +4,7 @@ The /boot/boot.cfg file contains configs for booting ``` initPath - path that init takes to load the init system (systemd) + path that init takes to load the init system allowGloabalOverwrites allow modifying of gloabal env (usually for debug purposes) diff --git a/manifest.lua b/manifest.lua deleted file mode 100644 index 19c2a9a..0000000 --- a/manifest.lua +++ /dev/null @@ -1,9 +0,0 @@ ---#region userspace -syscall={} - - ---#endregion userspace - ---#region kernel - ---#endregion kernel \ No newline at end of file diff --git a/node_modules/.bin/luamin b/node_modules/.bin/luamin new file mode 120000 index 0000000..794870b --- /dev/null +++ b/node_modules/.bin/luamin @@ -0,0 +1 @@ +../luamin/bin/luamin \ No newline at end of file diff --git a/node_modules/.bin/luaparse b/node_modules/.bin/luaparse new file mode 120000 index 0000000..2be8989 --- /dev/null +++ b/node_modules/.bin/luaparse @@ -0,0 +1 @@ +../luaparse/bin/luaparse \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..ce59d34 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,28 @@ +{ + "name": "HyperionOS", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/luamin": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/luamin/-/luamin-1.0.4.tgz", + "integrity": "sha512-z1h0bclRD/QGsS/Dz4Skp9z0qPTmmm+IKcrCapGmdTczPWVdN9f9jk6WqkNrcifQr8+n9Pzsm9WkwpOH1JBUAQ==", + "license": "MIT", + "dependencies": { + "luaparse": "^0.2.1" + }, + "bin": { + "luamin": "bin/luamin" + } + }, + "node_modules/luaparse": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/luaparse/-/luaparse-0.2.1.tgz", + "integrity": "sha512-VKBcryd5nJte4ZNR29NOk8F/UkMipjeb4yoxcSS51z6QAzg9DXUC2WsfLniS0J1eh3pr/ZL3e9ha6V8fhoLbBQ==", + "license": "MIT", + "bin": { + "luaparse": "bin/luaparse" + } + } + } +} diff --git a/node_modules/luamin/LICENSE-MIT.txt b/node_modules/luamin/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/luamin/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +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. diff --git a/node_modules/luamin/README.md b/node_modules/luamin/README.md new file mode 100644 index 0000000..28e7f16 --- /dev/null +++ b/node_modules/luamin/README.md @@ -0,0 +1,115 @@ +# luamin, a Lua minifier written in JavaScript + +[![Build status](https://travis-ci.org/mathiasbynens/luamin.svg?branch=master)](https://travis-ci.org/mathiasbynens/luamin) [![Dependency status](https://gemnasium.com/mathiasbynens/luamin.svg)](https://gemnasium.com/mathiasbynens/luamin) + +luamin uses the excellent [luaparse](https://oxyc.github.io/luaparse/) library to parse Lua code into an Abstract Syntax Tree. Based on that AST, luamin then generates a (hopefully) more compact yet semantically equivalent Lua program. [Here’s an online demo.](https://mothereff.in/lua-minifier) + +luamin was inspired by the [LuaMinify](https://github.com/stravant/LuaMinify) and [Esmangle](https://github.com/Constellation/esmangle) projects. + +Feel free to fork if you see possible improvements! + +## Installation and usage + +Via [npm](https://www.npmjs.com/): + +```bash +npm install luamin +``` + +Via [Bower](http://bower.io/): + +```bash +bower install luamin +``` + +Via [Component](https://github.com/component/component): + +```bash +component install mathiasbynens/luamin +``` + +In a browser: + +```html + +``` + +In [Narwhal](http://narwhaljs.org/), [Node.js](https://nodejs.org/), and [RingoJS](http://ringojs.org/): + +```js +var luamin = require('luamin'); +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('luamin.js'); +``` + +Using an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require( + { + 'paths': { + 'luamin': 'path/to/luamin' + } + }, + ['luamin'], + function(luamin) { + console.log(luamin); + } +); +``` + +Usage example: + +```js +var luaCode = 'a = ((1 + 2) - 3) * (4 / (5 ^ 6)) -- foo'; +luamin.minify(luaCode); // 'a=(1+2-3)*4/5^6' + +// `minify` also accepts luaparse-compatible ASTs as its argument: +var ast = luaparse.parse(luaCode, { 'scope': true }); +luamin.minify(ast); // 'a=(1+2-3)*4/5^6' +``` + +### Using the `luamin` binary + +To use the `luamin` binary in your shell, simply install luamin globally using npm: + +```bash +npm install -g luamin +``` + +After that you will be able to minify Lua scripts from the command line: + +```bash +$ luamin -c 'a = ((1 + 2) - 3) * (4 / (5 ^ 6))' +a=(1+2-3)*4/5^6 +$ luamin -f foo.lua +a=(1+2-3)*4/5^6 +``` + +See `luamin --help` for the full list of options. + +## Support + +luamin has been tested in at least Chrome 25-48, Firefox 3-44, Safari 4-9, Opera 10-35, IE 6-11, Edge, Node.js v0.10.0–v5, Narwhal 0.3.2, RingoJS 0.8-0.11, PhantomJS 1.9.0, and Rhino 1.7.6. + +## Unit tests & code coverage + +After cloning this repository, run `npm install` to install the dependencies needed for luamin development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. + +Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, and web browsers as well, use `grunt test`. + +To generate [the code coverage report](http://rawgithub.com/mathiasbynens/luamin/master/coverage/luamin/luamin.js.html), use `grunt cover`. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +luamin is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/luamin/bin/luamin b/node_modules/luamin/bin/luamin new file mode 100644 index 0000000..dd0bfde --- /dev/null +++ b/node_modules/luamin/bin/luamin @@ -0,0 +1,113 @@ +#!/usr/bin/env node +(function() { + + var fs = require('fs'); + var luamin = require('../luamin.js'); + var minify = luamin.minify; + var snippets = process.argv.splice(2); + var option = snippets.shift(); + var isFile = false; + var isAST = false; + var stdin = process.stdin; + var data; + var log = console.log; + var main = function() { + + if (/^(?:-h|--help|undefined)$/.test(option)) { + log('luamin v%s - https://mths.be/luamin', luamin.version); + log([ + '\nUsage:\n', + '\tluamin [-c | --code] [snippet ...]', + '\tluamin [-f | --file] [file ...]', + '\tluamin [-a | --ast] [AST ...]', + '\tluamin [-v | --version]', + '\tluamin [-h | --help]', + '\nExamples:\n', + '\tluamin -c \'a = ((1 + 2) - 3) * (4 / (5 ^ 6))\'', + '\tluamin -f foo.lua', + '\techo \'a = "foo" .. "bar"\' | luamin -c', + '\tluaparse --scope \'a = 42\' | luamin -a' + ].join('\n')); + return process.exit(1); + } + + if (/^(?:-v|--version)$/.test(option)) { + log('v%s', luamin.version); + return process.exit(1); + } + + if (/^(?:-f|--file)$/.test(option)) { + isFile = true; + } else if (/^(?:-a|--ast)$/.test(option)) { + isAST = true; + } else if (!/^(?:-c|--code)$/.test(option)) { + log('Unrecognized option `%s`.', option); + log('Try `luamin --help` for more information.'); + return process.exit(1); + } + + if (!snippets.length) { + log('Error: option `%s` requires an argument.', option); + log('Try `luamin --help` for more information.'); + return process.exit(1); + } + + snippets.forEach(function(snippet) { + var result; + if (isFile) { + try { + snippet = fs.readFileSync(snippet, 'utf8'); + } catch(error) { + log('Error: no such file. (`%s`)', snippet); + return process.exit(1); + } + } + try { + if (isAST) { + snippet = JSON.parse(snippet); + } + result = minify(snippet); + log(result); + } catch(error) { + log(error.message + '\n'); + if (isAST) { + log('Error: failed to minify. Make sure the AST contains a ' + + '`globals` property and is'); + log('fully compatible with luaparse.'); + } else { // it’s a snippet or an AST + log('Error: failed to minify. Make sure the Lua code is valid.'); + } + log('If you think this is a bug in luamin, please report it:'); + log('https://github.com/mathiasbynens/luamin/issues/new'); + log( + '\nStack trace using luamin@%s and luaparse@%s:\n', + luamin.version, + require('luaparse').version + ); + log(error.stack); + return process.exit(1); + } + }); + // Return with exit status 0 outside of the `forEach` loop, in case + // multiple snippets or files were passed in. + return process.exit(0); + + }; + + if (stdin.isTTY) { + // handle shell arguments + main(); + } else { + // handle pipe + data = ''; + stdin.on('data', function(chunk) { + data += chunk; + }); + stdin.on('end', function() { + snippets.unshift(data.trim()); + main(); + }); + stdin.resume(); + } + +}()); diff --git a/node_modules/luamin/luamin.js b/node_modules/luamin/luamin.js new file mode 100644 index 0000000..a37f6b1 --- /dev/null +++ b/node_modules/luamin/luamin.js @@ -0,0 +1,671 @@ +/*! https://mths.be/luamin v1.0.4 by @mathias */ +;(function(root) { + + // Detect free variables `exports` + var freeExports = typeof exports == 'object' && exports; + + // Detect free variable `module` + var freeModule = typeof module == 'object' && module && + module.exports == freeExports && module; + + // Detect free variable `global`, from Node.js or Browserified code, + // and use it as `root` + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + var luaparse = root.luaparse || require('luaparse'); + luaparse.defaultOptions.comments = false; + luaparse.defaultOptions.scope = true; + var parse = luaparse.parse; + + var regexAlphaUnderscore = /[a-zA-Z_]/; + var regexAlphaNumUnderscore = /[a-zA-Z0-9_]/; + var regexDigits = /[0-9]/; + + // http://www.lua.org/manual/5.2/manual.html#3.4.7 + // http://www.lua.org/source/5.2/lparser.c.html#priority + var PRECEDENCE = { + 'or': 1, + 'and': 2, + '<': 3, '>': 3, '<=': 3, '>=': 3, '~=': 3, '==': 3, + '..': 5, + '+': 6, '-': 6, // binary - + '*': 7, '/': 7, '%': 7, + 'unarynot': 8, 'unary#': 8, 'unary-': 8, // unary - + '^': 10 + }; + + var IDENTIFIER_PARTS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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', '_']; + var IDENTIFIER_PARTS_MAX = IDENTIFIER_PARTS.length - 1; + + var each = function(array, fn) { + var index = -1; + var length = array.length; + var max = length - 1; + while (++index < length) { + fn(array[index], index < max); + } + }; + + var indexOf = function(array, value) { + var index = -1; + var length = array.length; + while (++index < length) { + if (array[index] == value) { + return index; + } + } + }; + + var hasOwnProperty = {}.hasOwnProperty; + var extend = function(destination, source) { + var key; + if (source) { + for (key in source) { + if (hasOwnProperty.call(source, key)) { + destination[key] = source[key]; + } + } + } + return destination; + }; + + var generateZeroes = function(length) { + var zero = '0'; + var result = ''; + if (length < 1) { + return result; + } + if (length == 1) { + return zero; + } + while (length) { + if (length & 1) { + result += zero; + } + if (length >>= 1) { + zero += zero; + } + } + return result; + }; + + // http://www.lua.org/manual/5.2/manual.html#3.1 + function isKeyword(id) { + switch (id.length) { + case 2: + return 'do' == id || 'if' == id || 'in' == id || 'or' == id; + case 3: + return 'and' == id || 'end' == id || 'for' == id || 'nil' == id || + 'not' == id; + case 4: + return 'else' == id || 'goto' == id || 'then' == id || 'true' == id; + case 5: + return 'break' == id || 'false' == id || 'local' == id || + 'until' == id || 'while' == id; + case 6: + return 'elseif' == id || 'repeat' == id || 'return' == id; + case 8: + return 'function' == id; + } + return false; + } + + var currentIdentifier; + var identifierMap; + var identifiersInUse; + var generateIdentifier = function(originalName) { + // Preserve `self` in methods + if (originalName == 'self') { + return originalName; + } + + if (hasOwnProperty.call(identifierMap, originalName)) { + return identifierMap[originalName]; + } + var length = currentIdentifier.length; + var position = length - 1; + var character; + var index; + while (position >= 0) { + character = currentIdentifier.charAt(position); + index = indexOf(IDENTIFIER_PARTS, character); + if (index != IDENTIFIER_PARTS_MAX) { + currentIdentifier = currentIdentifier.substring(0, position) + + IDENTIFIER_PARTS[index + 1] + generateZeroes(length - (position + 1)); + if ( + isKeyword(currentIdentifier) || + indexOf(identifiersInUse, currentIdentifier) > -1 + ) { + return generateIdentifier(originalName); + } + identifierMap[originalName] = currentIdentifier; + return currentIdentifier; + } + --position; + } + currentIdentifier = 'a' + generateZeroes(length); + if (indexOf(identifiersInUse, currentIdentifier) > -1) { + return generateIdentifier(originalName); + } + identifierMap[originalName] = currentIdentifier; + return currentIdentifier; + }; + + /*--------------------------------------------------------------------------*/ + + var joinStatements = function(a, b, separator) { + separator || (separator = ' '); + + var lastCharA = a.slice(-1); + var firstCharB = b.charAt(0); + + if (lastCharA == '' || firstCharB == '') { + return a + b; + } + if (regexAlphaUnderscore.test(lastCharA)) { + if (regexAlphaNumUnderscore.test(firstCharB)) { + // e.g. `while` + `1` + // e.g. `local a` + `local b` + return a + separator + b; + } else { + // e.g. `not` + `(2>3 or 3<2)` + // e.g. `x` + `^` + return a + b; + } + } + if (regexDigits.test(lastCharA)) { + if ( + firstCharB == '(' || + !(firstCharB == '.' || + regexAlphaUnderscore.test(firstCharB)) + ) { + // e.g. `1` + `+` + // e.g. `1` + `==` + return a + b; + } else { + // e.g. `1` + `..` + // e.g. `1` + `and` + return a + separator + b; + } + } + if (lastCharA == firstCharB && lastCharA == '-') { + // e.g. `1-` + `-2` + return a + separator + b; + } + return a + b; + }; + + var formatBase = function(base) { + var result = ''; + var type = base.type; + var needsParens = base.inParens && ( + type == 'BinaryExpression' || + type == 'FunctionDeclaration' || + type == 'TableConstructorExpression' || + type == 'LogicalExpression' || + type == 'StringLiteral' + ); + if (needsParens) { + result += '('; + } + result += formatExpression(base); + if (needsParens) { + result += ')'; + } + return result; + }; + + var formatExpression = function(expression, options) { + + options = extend({ + 'precedence': 0, + 'preserveIdentifiers': false + }, options); + + var result = ''; + var currentPrecedence; + var associativity; + var operator; + + var expressionType = expression.type; + + if (expressionType == 'Identifier') { + + result = expression.isLocal && !options.preserveIdentifiers + ? generateIdentifier(expression.name) + : expression.name; + + } else if ( + expressionType == 'StringLiteral' || + expressionType == 'NumericLiteral' || + expressionType == 'BooleanLiteral' || + expressionType == 'NilLiteral' || + expressionType == 'VarargLiteral' + ) { + + result = expression.raw; + + } else if ( + expressionType == 'LogicalExpression' || + expressionType == 'BinaryExpression' + ) { + + // If an expression with precedence x + // contains an expression with precedence < x, + // the inner expression must be wrapped in parens. + operator = expression.operator; + currentPrecedence = PRECEDENCE[operator]; + associativity = 'left'; + + result = formatExpression(expression.left, { + 'precedence': currentPrecedence, + 'direction': 'left', + 'parent': operator + }); + result = joinStatements(result, operator); + result = joinStatements(result, formatExpression(expression.right, { + 'precedence': currentPrecedence, + 'direction': 'right', + 'parent': operator + })); + + if (operator == '^' || operator == '..') { + associativity = "right"; + } + + if ( + currentPrecedence < options.precedence || + ( + currentPrecedence == options.precedence && + associativity != options.direction && + options.parent != '+' && + !(options.parent == '*' && (operator == '/' || operator == '*')) + ) + ) { + // The most simple case here is that of + // protecting the parentheses on the RHS of + // `1 - (2 - 3)` but deleting them from `(1 - 2) - 3`. + // This is generally the right thing to do. The + // semantics of `+` are special however: `1 + (2 - 3)` + // == `1 + 2 - 3`. `-` and `+` are the only two operators + // who share their precedence level. `*` also can + // commute in such a way with `/`, but not with `%` + // (all three share a precedence). So we test for + // all of these conditions and avoid emitting + // parentheses in the cases where we don’t have to. + result = '(' + result + ')'; + } + + } else if (expressionType == 'UnaryExpression') { + + operator = expression.operator; + currentPrecedence = PRECEDENCE['unary' + operator]; + + result = joinStatements( + operator, + formatExpression(expression.argument, { + 'precedence': currentPrecedence + }) + ); + + if ( + currentPrecedence < options.precedence && + // In principle, we should parenthesize the RHS of an + // expression like `3^-2`, because `^` has higher precedence + // than unary `-` according to the manual. But that is + // misleading on the RHS of `^`, since the parser will + // always try to find a unary operator regardless of + // precedence. + !( + (options.parent == '^') && + options.direction == 'right' + ) + ) { + result = '(' + result + ')'; + } + + } else if (expressionType == 'CallExpression') { + + result = formatBase(expression.base) + '('; + + each(expression.arguments, function(argument, needsComma) { + result += formatExpression(argument); + if (needsComma) { + result += ','; + } + }); + result += ')'; + + } else if (expressionType == 'TableCallExpression') { + + result = formatExpression(expression.base) + + formatExpression(expression.arguments); + + } else if (expressionType == 'StringCallExpression') { + + result = formatExpression(expression.base) + + formatExpression(expression.argument); + + } else if (expressionType == 'IndexExpression') { + + result = formatBase(expression.base) + '[' + + formatExpression(expression.index) + ']'; + + } else if (expressionType == 'MemberExpression') { + + result = formatBase(expression.base) + expression.indexer + + formatExpression(expression.identifier, { + 'preserveIdentifiers': true + }); + + } else if (expressionType == 'FunctionDeclaration') { + + result = 'function('; + if (expression.parameters.length) { + each(expression.parameters, function(parameter, needsComma) { + // `Identifier`s have a `name`, `VarargLiteral`s have a `value` + result += parameter.name + ? generateIdentifier(parameter.name) + : parameter.value; + if (needsComma) { + result += ','; + } + }); + } + result += ')'; + result = joinStatements(result, formatStatementList(expression.body)); + result = joinStatements(result, 'end'); + + } else if (expressionType == 'TableConstructorExpression') { + + result = '{'; + + each(expression.fields, function(field, needsComma) { + if (field.type == 'TableKey') { + result += '[' + formatExpression(field.key) + ']=' + + formatExpression(field.value); + } else if (field.type == 'TableValue') { + result += formatExpression(field.value); + } else { // at this point, `field.type == 'TableKeyString'` + result += formatExpression(field.key, { + // TODO: keep track of nested scopes (#18) + 'preserveIdentifiers': true + }) + '=' + formatExpression(field.value); + } + if (needsComma) { + result += ','; + } + }); + + result += '}'; + + } else { + + throw TypeError('Unknown expression type: `' + expressionType + '`'); + + } + + return result; + }; + + var formatStatementList = function(body) { + var result = ''; + each(body, function(statement) { + result = joinStatements(result, formatStatement(statement), ';'); + }); + return result; + }; + + var formatStatement = function(statement) { + var result = ''; + var statementType = statement.type; + + if (statementType == 'AssignmentStatement') { + + // left-hand side + each(statement.variables, function(variable, needsComma) { + result += formatExpression(variable); + if (needsComma) { + result += ','; + } + }); + + // right-hand side + result += '='; + each(statement.init, function(init, needsComma) { + result += formatExpression(init); + if (needsComma) { + result += ','; + } + }); + + } else if (statementType == 'LocalStatement') { + + result = 'local '; + + // left-hand side + each(statement.variables, function(variable, needsComma) { + // Variables in a `LocalStatement` are always local, duh + result += generateIdentifier(variable.name); + if (needsComma) { + result += ','; + } + }); + + // right-hand side + if (statement.init.length) { + result += '='; + each(statement.init, function(init, needsComma) { + result += formatExpression(init); + if (needsComma) { + result += ','; + } + }); + } + + } else if (statementType == 'CallStatement') { + + result = formatExpression(statement.expression); + + } else if (statementType == 'IfStatement') { + + result = joinStatements( + 'if', + formatExpression(statement.clauses[0].condition) + ); + result = joinStatements(result, 'then'); + result = joinStatements( + result, + formatStatementList(statement.clauses[0].body) + ); + each(statement.clauses.slice(1), function(clause) { + if (clause.condition) { + result = joinStatements(result, 'elseif'); + result = joinStatements(result, formatExpression(clause.condition)); + result = joinStatements(result, 'then'); + } else { + result = joinStatements(result, 'else'); + } + result = joinStatements(result, formatStatementList(clause.body)); + }); + result = joinStatements(result, 'end'); + + } else if (statementType == 'WhileStatement') { + + result = joinStatements('while', formatExpression(statement.condition)); + result = joinStatements(result, 'do'); + result = joinStatements(result, formatStatementList(statement.body)); + result = joinStatements(result, 'end'); + + } else if (statementType == 'DoStatement') { + + result = joinStatements('do', formatStatementList(statement.body)); + result = joinStatements(result, 'end'); + + } else if (statementType == 'ReturnStatement') { + + result = 'return'; + + each(statement.arguments, function(argument, needsComma) { + result = joinStatements(result, formatExpression(argument)); + if (needsComma) { + result += ','; + } + }); + + } else if (statementType == 'BreakStatement') { + + result = 'break'; + + } else if (statementType == 'RepeatStatement') { + + result = joinStatements('repeat', formatStatementList(statement.body)); + result = joinStatements(result, 'until'); + result = joinStatements(result, formatExpression(statement.condition)) + + } else if (statementType == 'FunctionDeclaration') { + + result = (statement.isLocal ? 'local ' : '') + 'function '; + result += formatExpression(statement.identifier); + result += '('; + + if (statement.parameters.length) { + each(statement.parameters, function(parameter, needsComma) { + // `Identifier`s have a `name`, `VarargLiteral`s have a `value` + result += parameter.name + ? generateIdentifier(parameter.name) + : parameter.value; + if (needsComma) { + result += ','; + } + }); + } + + result += ')'; + result = joinStatements(result, formatStatementList(statement.body)); + result = joinStatements(result, 'end'); + + } else if (statementType == 'ForGenericStatement') { + // see also `ForNumericStatement` + + result = 'for '; + + each(statement.variables, function(variable, needsComma) { + // The variables in a `ForGenericStatement` are always local + result += generateIdentifier(variable.name); + if (needsComma) { + result += ','; + } + }); + + result += ' in'; + + each(statement.iterators, function(iterator, needsComma) { + result = joinStatements(result, formatExpression(iterator)); + if (needsComma) { + result += ','; + } + }); + + result = joinStatements(result, 'do'); + result = joinStatements(result, formatStatementList(statement.body)); + result = joinStatements(result, 'end'); + + } else if (statementType == 'ForNumericStatement') { + + // The variables in a `ForNumericStatement` are always local + result = 'for ' + generateIdentifier(statement.variable.name) + '='; + result += formatExpression(statement.start) + ',' + + formatExpression(statement.end); + + if (statement.step) { + result += ',' + formatExpression(statement.step); + } + + result = joinStatements(result, 'do'); + result = joinStatements(result, formatStatementList(statement.body)); + result = joinStatements(result, 'end'); + + } else if (statementType == 'LabelStatement') { + + // The identifier names in a `LabelStatement` can safely be renamed + result = '::' + generateIdentifier(statement.label.name) + '::'; + + } else if (statementType == 'GotoStatement') { + + // The identifier names in a `GotoStatement` can safely be renamed + result = 'goto ' + generateIdentifier(statement.label.name); + + } else { + + throw TypeError('Unknown statement type: `' + statementType + '`'); + + } + + return result; + }; + + var minify = function(argument) { + // `argument` can be a Lua code snippet (string) + // or a luaparse-compatible AST (object) + var ast = typeof argument == 'string' + ? parse(argument) + : argument; + + // (Re)set temporary identifier values + identifierMap = {}; + identifiersInUse = []; + // This is a shortcut to help generate the first identifier (`a`) faster + currentIdentifier = '9'; + + // Make sure global variable names aren't renamed + if (ast.globals) { + each(ast.globals, function(object) { + var name = object.name; + identifierMap[name] = name; + identifiersInUse.push(name); + }); + } else { + throw Error('Missing required AST property: `globals`'); + } + + return formatStatementList(ast.body); + }; + + /*--------------------------------------------------------------------------*/ + + var luamin = { + 'version': '1.0.4', + 'minify': minify + }; + + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define(function() { + return luamin; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = luamin; + } else { // in Narwhal or RingoJS v0.7.0- + extend(freeExports, luamin); + } + } else { // in Rhino or a web browser + root.luamin = luamin; + } + +}(this)); diff --git a/node_modules/luamin/man/luamin.1 b/node_modules/luamin/man/luamin.1 new file mode 100644 index 0000000..d30eb2d --- /dev/null +++ b/node_modules/luamin/man/luamin.1 @@ -0,0 +1,76 @@ +.Dd April 19, 2013 +.Dt luamin 1 +.Sh NAME +.Nm luamin +.Nd minify Lua code +.Sh SYNOPSIS +.Nm +.Op Fl c | -code Ar snippet +.br +.Op Fl f | -file Ar file +.br +.Op Fl a | -ast Ar ast +.br +.Op Fl v | -version +.br +.Op Fl h | -help +.Sh DESCRIPTION +.Nm +is a Lua minifier written in JavaScript. It can compress Lua code snippets, or even Abstract Syntax Trees that represent Lua programs. +.Sh OPTIONS +.Bl -ohang -offset +.It Sy "-v, --version" +Print luamin's version. +.It Sy "-h, --help" +Show the help screen. +.It Sy "-c, --code " +Print minified version of the given Lua snippet. +.It Sy "-f, --file " +Print minified version of the given Lua file. +.It Sy "-a, --ast " +Print minified version of the given Lua AST. The AST must be compatible with +.Xr luaparse 1 +and must contain a +.Va globals +property. Such ASTs can be generated using +.Xr luaparse 1 +by enabling the +.Va scope +option. +.El +.Sh EXIT STATUS +The +.Nm luamin +utility exits with one of the following values: +.Pp +.Bl -tag -width flag -compact +.It Li 0 +.Nm +successfully minified the Lua code and printed the result. +.It Li 1 +.Nm +wasn't instructed to minify any code (for example, the +.Ar --help +flag was set); or, an error occurred. +.El +.Sh EXAMPLES +.Bl -ohang -offset +.It Sy "luamin -c 'a = ((1 + 2) - 3) * (4 / (5 ^ 6))'" +Print a minified version of the given Lua code snippet. +.It Sy "luamin -f foo.lua" +Read the Lua code in the file +.Ar foo.lua +and print a minified version. +.It Sy echo\ 'a\ =\ "foo"\ ..\ "bar"'\ |\ luamin\ -c +Print a minified version of the Lua snippet that gets piped in. +.It Sy "luaparse --scope 'a = 42' | luamin -a" +Print a minified version of the Lua code that corresponds to the given Abstract Syntax Tree that gets piped in. +.El +.Sh SEE ALSO +.Xr luaparse 1 +.Sh BUGS +luamin's bug tracker is located at . +.Sh AUTHOR +Mathias Bynens +.Sh WWW + diff --git a/node_modules/luamin/package.json b/node_modules/luamin/package.json new file mode 100644 index 0000000..642494f --- /dev/null +++ b/node_modules/luamin/package.json @@ -0,0 +1,48 @@ +{ + "name": "luamin", + "version": "1.0.4", + "description": "A Lua minifier written in JavaScript", + "homepage": "https://mths.be/luamin", + "main": "luamin.js", + "bin": "bin/luamin", + "keywords": [ + "lua", + "minify", + "minifier" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/luamin.git" + }, + "bugs": "https://github.com/mathiasbynens/luamin/issues", + "files": [ + "LICENSE-MIT.txt", + "luamin.js", + "bin/", + "man/" + ], + "directories": { + "bin": "bin", + "man": "man", + "test": "tests" + }, + "scripts": { + "test": "node tests/tests.js" + }, + "dependencies": { + "luaparse": "^0.2.1" + }, + "devDependencies": { + "grunt": "^0.4.4", + "grunt-shell": "^1.1.2", + "istanbul": "^0.4.2", + "qunit-extras": "^1.4.5", + "qunitjs": "~1.11.0", + "requirejs": "^2.1.22" + } +} diff --git a/node_modules/luaparse/LICENSE b/node_modules/luaparse/LICENSE new file mode 100644 index 0000000..14f9f84 --- /dev/null +++ b/node_modules/luaparse/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) Oskar Schöldström 2012-2014 + +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. diff --git a/node_modules/luaparse/README.md b/node_modules/luaparse/README.md new file mode 100644 index 0000000..2cc055a --- /dev/null +++ b/node_modules/luaparse/README.md @@ -0,0 +1,274 @@ +# luaparse [![Build Status](https://travis-ci.org/oxyc/luaparse.svg)](https://travis-ci.org/oxyc/luaparse) + +A Lua parser written in JavaScript, for my bachelor's thesis at Arcada. + +## Installation + +Install through `bower install luaparse` or `npm install luaparse`. + +## Usage + +CommonJS + +```js +var parser = require('luaparse'); +var ast = parser.parse('i = 0'); +console.log(JSON.stringify(ast)); +``` + +AMD + +```js +require(['luaparse'], function(parser) { + var ast = parser.parse('i = 0'); + console.log(JSON.stringify(ast)); +}); +``` + +Browser + +```html + + +``` + +## Parser Interface + +Basic usage: + +```js +luaparse.parse(code, options); +``` + +The output of the parser is an Abstract Syntax Tree (AST) formatted in JSON. + +The available options are: + +- `wait: false` Explicitly tell the parser when the input ends. +- `comments: true` Store comments as an array in the chunk object. +- `scope: false` Track identifier scopes. +- `locations: false` Store location information on each syntax node. +- `ranges: false` Store the start and end character locations on each syntax + node. +- `onCreateNode: null` A callback which will be invoked when a syntax node + has been completed. The node which has been created will be passed as the + only parameter. +- `onCreateScope: null` A callback which will be invoked when a new scope is + created. +- `onDestroyScope: null` A callback which will be invoked when the current + scope is destroyed. + +The default options are also exposed through `luaparse.defaultOptions` where +they can be overriden globally. + +There is a second interface which might be preferable when using the `wait` +option. + +```js +var parser = luaparse.parse({ wait: true }); +parser.write('foo = "'); +parser.write('bar'); +var ast = parser.end('"'); +``` + +This would be identical to: + +```js +var ast = luaparse.parse('foo = "bar"'); +``` + +### AST format + +If the following code is executed: + +```js +luaparse.parse('foo = "bar"'); +``` + +then the returned value will be: + +```js +{ + "type": "Chunk", + "body": [ + { + "type": "AssignmentStatement", + "variables": [ + { + "type": "Identifier", + "name": "foo" + } + ], + "init": [ + { + "type": "StringLiteral", + "value": "bar", + "raw": "\"bar\"" + } + ] + } + ], + "comments": [] +} +``` + +### Custom AST + +The default AST structure is somewhat inspired by the Mozilla Parser API but +can easily be overriden to customize the structure or to inject custom logic. + +`luaparse.ast` is an object containing all functions used to create the AST, if +you for example wanted to trigger an event on node creations you could use the +following: + +```js +var luaparse = require('luaparse'), + events = new (require('events').EventEmitter); + +Object.keys(luaparse.ast).forEach(function(type) { + var original = luaparse.ast[type]; + luaparse.ast[type] = function() { + var node = original.apply(null, arguments); + events.emit(node.type, node); + return node; + }; +}); +events.on('Identifier', function(node) { console.log(node); }); +luaparse.parse('i = "foo"'); +``` + +_this is only an example to illustrate what is possible and this particular +example might not suit your needs as the end location of the node has not been +determined yet. If you desire events you should use the `onCreateNode` callback +instead)._ + + +### Lexer + +The lexer used by luaparse can be used independently of the recursive descent +parser. The lex function is exposed as `luaparse.lex()` and it will return the +next token up until `EOF` is reached. + +Each token consists of: + +- `type` expressed as an enum flag which can be matched with `luaparse.tokenTypes`. +- `value` +- `line`, `lineStart` +- `range` can be used to slice out raw values, eg. `foo = "bar"` will return a +`StringLiteral` token with the value `bar`. Slicing out the range on the other +hand will return `"bar"`. + +```js +var parser = luaparse.parse('foo = "bar"', { wait: true }); +parser.lex(); // { type: 8, value: "foo", line: 1, lineStart: 0, range: [0, 3] } +parser.lex(); // { type: 32, value: "=", line: 1, lineStart: 0, range: [4, 5]} +parser.lex(); // { type: 2, value: "bar", line: 1, lineStart: 0, range: [6, 11] } +parser.lex(); // { type: 1, value: "", line: 1, lineStart: 0, range: [11 11] } +parser.lex(); // { type: 1, value: "", line: 1, lineStart: 0, range: [11 11] } +``` + +## Examples + +Have a look in the [examples directory](https://github.com/oxyc/luaparse/tree/master/examples) +of the repository for some code examples or check them out [live](https://oxyc.github.io/luaparse/examples.html). + +## luaparse(1) + +The `luaparse` executable can be used in your shell by installing `luaparse` globally using npm: + +```bash +$ npm install -g luaparse +$ luaparse --help + +Usage: luaparse [option]... [file|code]... + +Options: + -c|--code [code] parse code snippet + -f|--file [file] parse from file + -b|--beautify output an indenteted AST + --[no]-comments store comments. defaults to true + --[no]-scope store variable scope. defaults to false + --[no]-locations store location data on syntax nodes. defaults to false + --[no]-ranges store start and end character locations. defaults to false + -q|--quiet suppress output + -h|--help + -v|--version + --verbose + +Examples: + luaparse --no-comments -c "locale foo = \"bar\"" + luaparse foo.lua bar.lua +``` + +Example usage + +```bash +$ luaparse "i = 0" + +{"type":"Chunk","body":[{"type":"AssignmentStatement","variables":[{"type":"Identifier","name":"i"}],"init":[{"type":"NumericLiteral","value":0,"raw":"0"}]}],"comments":[]} +``` + +## Support + +Has been tested in at least IE6+, Firefox 3+, Safari 4+, Chrome 10+, Opera 10+, +Node 0.4.0+, RingoJS 0.8-0.9, Narwhal 0.3.2, Rhino 1.7R4-1.7R5, Nashorn 1.8.0. + +## Quality Assurance + +_TL;DR simply run `make qa`. This will run all quality assurance scripts but +assumes you have it set up correctly._ + +Begin by cloning the repository and installing the development dependencies +with `npm install`. To test AMD loading for browsers you should run `bower +install` which will download RequireJS. + +The luaparse test suite uses [testem](https://github.com/airportyh/testem) as a +test runner, and because of this it's very easy to run the tests using +different javascript engines or even on locally installed browsers. Currently +the default runner uses [PhantomJS](http://phantomjs.org/) and node so when +using `make test` or `npm test` you should have PhantomJS installed. + +### Test runners + +- `make test` uses PhantomJS and node. +- `make testem-engines` uses PhantomJS, node, narwhal, ringo, rhino and rhino +1.7R5. This requires that you have the engines installed. +- `make test-node` uses a custom command line reporter to make the output +easier on the eyes while practicing TDD. +- By installing `testem` globally you can also run the tests in a locally +installed browser. + +### Other quality assurance measures + +- You can check the function complexity using [complexity-report](https://github.com/philbooth/complexityReport.js) +using `make complexity-analysis` +- Running `make coverage` will generate the [coverage report](https://oxyc.github.io/luaparse/coverage.html). +To simply check that all code has coverage you can run `make coverage-analysis`. +- `make lint`, `make benchmark`, `make profile`. + +### Documentation + +By running `make docs` all [documentation](https://oxyc.github.io/luaparse/) +will be generated. + +## Projects using luaparse + +- [luamin](http://mths.be/luamin), a Lua minifier written by Mathias Bynens. +- [Ace](https://github.com/ajaxorg/ace), an online code editor. + +## Acknowledgements + +* Initial tests are scaffolded from [yueliang][yueliang] and then manually checked for error. +* Much of the code is based on [LuaMinify][luaminify], the [Lua][lua] source and [Esprima][esprima]. All awesome projects. + +## License + +MIT + +[luaminify]: https://github.com/stravant/LuaMinify +[yueliang]: http://yueliang.luaforge.net/ +[lua]: http://www.lua.org +[esprima]: http://esprima.org diff --git a/node_modules/luaparse/bin/luaparse b/node_modules/luaparse/bin/luaparse new file mode 100644 index 0000000..f998be4 --- /dev/null +++ b/node_modules/luaparse/bin/luaparse @@ -0,0 +1,120 @@ +#!/usr/bin/env node +/*jshint node:true*/ +/*globals console:true */ +'use strict'; + +var fs = require('fs') + , util = require('util') + , luaparse = require('../luaparse') + , args = process.argv.splice(2) + , stdin = process.stdin + , isTTY = stdin.isTTY + , beautify = false + , quiet = false + , verbose = false + , input = '' + , options = {} + , snippets = []; + +function usage() { + console.log([ + "Usage: luaparse [option]... [file|code]..." + , "\nOptions:" + , " -c|--code [code] parse code snippet" + , " -f|--file [file] parse from file" + , " -b|--beautify output an indenteted AST" + , " --[no]-comments store comments. defaults to true" + , " --[no]-scope store variable scope. defaults to false" + , " --[no]-locations store location data on syntax nodes. defaults to false" + , " --[no]-ranges store start and end character locations. defaults to false" + , " -q|--quiet suppress output" + , " -h|--help" + , " -v|--version" + , " --verbose" + , "\nExamples:" + , " luaparse --no-comments -c \"locale foo = \\\"bar\\\"\"" + , " luaparse foo.lua bar.lua" + ].join("\n")); +} + +if (isTTY && !args.length) { + usage(); + process.exit(0); +} + +for (var i = 0, l = args.length; i < l; i++) { + var arg = args[i], match, flag, bool, snippet; + if (match = /^(?:-|--)(?:(no)-)?(\w+)$/.exec(arg)) { + bool = 'no' !== match[1]; + flag = match[2]; + + switch (flag) { + case 'b': case 'beautify': + beautify = true; + continue; + case 'q': case 'quiet': + quiet = true; + continue; + case 'verbose': + verbose = true; + continue; + case 'c': case 'code': + snippets.push({ name: args[++i], code: args[i] }); + continue; + case 'f': case 'file': + snippets.push({ name: args[++i], code: fs.readFileSync(args[i], 'utf-8') }); + continue; + case 'comments': case 'scope': case 'locations': case 'ranges': + options[flag] = bool; + continue; + case 'v': case 'version': + console.log("luaparse v%s", luaparse.version); + process.exit(0); + break; + case 'h': case 'help': + usage(); + process.exit(0); + break; + default: + if (!quiet) console.log("Unknown option: %s", match[0]); + process.exit(2); + } + } + // Default to autodetecting code or file. + snippet = fs.existsSync(arg) ? + { name: arg, code: fs.readFileSync(arg, 'utf-8') } : + { name: arg, code: arg }; + + snippets.push(snippet); +} + +function done() { + var success = true; + snippets.forEach(function(snippet) { + var message, ast; + try { + ast = luaparse.parse(snippet.code, options); + message = beautify ? JSON.stringify(ast, null, ' ') + : JSON.stringify(ast); + } catch(e) { + message = util.format("%s: %s", snippet.name, e.message); + if (verbose) console.log(e.stack); + success = false; + } + + if (!quiet) console.log(message); + }); + + if (!success) process.exit(1); +} + +if (stdin.isTTY) done(); +else { + // @TODO doesn't work in node 0.9.4-0.9.11 because `end` is never emitted. + stdin.setEncoding('utf8'); + stdin.on('data', function(chunk) { input += chunk; }); + stdin.on('end', function() { snippets.unshift(input.trim()); done(); }); + stdin.resume(); +} + +/* vim: set sw=2 ts=2 et tw=80 ft=javascript : */ diff --git a/node_modules/luaparse/luaparse.js b/node_modules/luaparse/luaparse.js new file mode 100644 index 0000000..4210383 --- /dev/null +++ b/node_modules/luaparse/luaparse.js @@ -0,0 +1,2105 @@ +/* global exports:true, module:true, require:true, define:true, global:true */ + +(function (root, name, factory) { + /* jshint eqeqeq:false */ + 'use strict'; + + // Used to determine if values are of the language type `Object` + var objectTypes = { + 'function': true + , 'object': true + } + // Detect free variable `exports` + , freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports + // Detect free variable `module` + , freeModule = objectTypes[typeof module] && module && !module.nodeType && module + // Detect free variable `global`, from Node.js or Browserified code, and + // use it as `window` + , freeGlobal = freeExports && freeModule && typeof global == 'object' && global + // Detect the popular CommonJS extension `module.exports` + , moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { + root = freeGlobal; + } + + // Some AMD build optimizers, like r.js, check for specific condition + // patterns like the following: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // defined as an anonymous module. + define(['exports'], factory); + // In case the source has been processed and wrapped in a define module use + // the supplied `exports` object. + if (freeExports && moduleExports) factory(freeModule.exports); + } + // check for `exports` after `define` in case a build optimizer adds an + // `exports` object + else if (freeExports && freeModule) { + // in Node.js or RingoJS v0.8.0+ + if (moduleExports) factory(freeModule.exports); + // in Narwhal or RingoJS v0.7.0- + else factory(freeExports); + } + // in a browser or Rhino + else { + factory((root[name] = {})); + } +}(this, 'luaparse', function (exports) { + 'use strict'; + + exports.version = '0.2.1'; + + var input, options, length; + + // Options can be set either globally on the parser object through + // defaultOptions, or during the parse call. + var defaultOptions = exports.defaultOptions = { + // Explicitly tell the parser when the input ends. + wait: false + // Store comments as an array in the chunk object. + , comments: true + // Track identifier scopes by adding an isLocal attribute to each + // identifier-node. + , scope: false + // Store location information on each syntax node as + // `loc: { start: { line, column }, end: { line, column } }`. + , locations: false + // Store the start and end character locations on each syntax node as + // `range: [start, end]`. + , ranges: false + // A callback which will be invoked when a syntax node has been completed. + // The node which has been created will be passed as the only parameter. + , onCreateNode: null + // A callback which will be invoked when a new scope is created. + , onCreateScope: null + // A callback which will be invoked when the current scope is destroyed. + , onDestroyScope: null + }; + + // The available tokens expressed as enum flags so they can be checked with + // bitwise operations. + + var EOF = 1, StringLiteral = 2, Keyword = 4, Identifier = 8 + , NumericLiteral = 16, Punctuator = 32, BooleanLiteral = 64 + , NilLiteral = 128, VarargLiteral = 256; + + exports.tokenTypes = { EOF: EOF, StringLiteral: StringLiteral + , Keyword: Keyword, Identifier: Identifier, NumericLiteral: NumericLiteral + , Punctuator: Punctuator, BooleanLiteral: BooleanLiteral + , NilLiteral: NilLiteral, VarargLiteral: VarargLiteral + }; + + // As this parser is a bit different from luas own, the error messages + // will be different in some situations. + + var errors = exports.errors = { + unexpected: 'unexpected %1 \'%2\' near \'%3\'' + , expected: '\'%1\' expected near \'%2\'' + , expectedToken: '%1 expected near \'%2\'' + , unfinishedString: 'unfinished string near \'%1\'' + , malformedNumber: 'malformed number near \'%1\'' + , invalidVar: 'invalid left-hand side of assignment near \'%1\'' + }; + + // ### Abstract Syntax Tree + // + // The default AST structure is inspired by the Mozilla Parser API but can + // easily be customized by overriding these functions. + + var ast = exports.ast = { + labelStatement: function(label) { + return { + type: 'LabelStatement' + , label: label + }; + } + + , breakStatement: function() { + return { + type: 'BreakStatement' + }; + } + + , gotoStatement: function(label) { + return { + type: 'GotoStatement' + , label: label + }; + } + + , returnStatement: function(args) { + return { + type: 'ReturnStatement' + , 'arguments': args + }; + } + + , ifStatement: function(clauses) { + return { + type: 'IfStatement' + , clauses: clauses + }; + } + , ifClause: function(condition, body) { + return { + type: 'IfClause' + , condition: condition + , body: body + }; + } + , elseifClause: function(condition, body) { + return { + type: 'ElseifClause' + , condition: condition + , body: body + }; + } + , elseClause: function(body) { + return { + type: 'ElseClause' + , body: body + }; + } + + , whileStatement: function(condition, body) { + return { + type: 'WhileStatement' + , condition: condition + , body: body + }; + } + + , doStatement: function(body) { + return { + type: 'DoStatement' + , body: body + }; + } + + , repeatStatement: function(condition, body) { + return { + type: 'RepeatStatement' + , condition: condition + , body: body + }; + } + + , localStatement: function(variables, init) { + return { + type: 'LocalStatement' + , variables: variables + , init: init + }; + } + + , assignmentStatement: function(variables, init) { + return { + type: 'AssignmentStatement' + , variables: variables + , init: init + }; + } + + , callStatement: function(expression) { + return { + type: 'CallStatement' + , expression: expression + }; + } + + , functionStatement: function(identifier, parameters, isLocal, body) { + return { + type: 'FunctionDeclaration' + , identifier: identifier + , isLocal: isLocal + , parameters: parameters + , body: body + }; + } + + , forNumericStatement: function(variable, start, end, step, body) { + return { + type: 'ForNumericStatement' + , variable: variable + , start: start + , end: end + , step: step + , body: body + }; + } + + , forGenericStatement: function(variables, iterators, body) { + return { + type: 'ForGenericStatement' + , variables: variables + , iterators: iterators + , body: body + }; + } + + , chunk: function(body) { + return { + type: 'Chunk' + , body: body + }; + } + + , identifier: function(name) { + return { + type: 'Identifier' + , name: name + }; + } + + , literal: function(type, value, raw) { + type = (type === StringLiteral) ? 'StringLiteral' + : (type === NumericLiteral) ? 'NumericLiteral' + : (type === BooleanLiteral) ? 'BooleanLiteral' + : (type === NilLiteral) ? 'NilLiteral' + : 'VarargLiteral'; + + return { + type: type + , value: value + , raw: raw + }; + } + + , tableKey: function(key, value) { + return { + type: 'TableKey' + , key: key + , value: value + }; + } + , tableKeyString: function(key, value) { + return { + type: 'TableKeyString' + , key: key + , value: value + }; + } + , tableValue: function(value) { + return { + type: 'TableValue' + , value: value + }; + } + + + , tableConstructorExpression: function(fields) { + return { + type: 'TableConstructorExpression' + , fields: fields + }; + } + , binaryExpression: function(operator, left, right) { + var type = ('and' === operator || 'or' === operator) ? + 'LogicalExpression' : + 'BinaryExpression'; + + return { + type: type + , operator: operator + , left: left + , right: right + }; + } + , unaryExpression: function(operator, argument) { + return { + type: 'UnaryExpression' + , operator: operator + , argument: argument + }; + } + , memberExpression: function(base, indexer, identifier) { + return { + type: 'MemberExpression' + , indexer: indexer + , identifier: identifier + , base: base + }; + } + + , indexExpression: function(base, index) { + return { + type: 'IndexExpression' + , base: base + , index: index + }; + } + + , callExpression: function(base, args) { + return { + type: 'CallExpression' + , base: base + , 'arguments': args + }; + } + + , tableCallExpression: function(base, args) { + return { + type: 'TableCallExpression' + , base: base + , 'arguments': args + }; + } + + , stringCallExpression: function(base, argument) { + return { + type: 'StringCallExpression' + , base: base + , argument: argument + }; + } + + , comment: function(value, raw) { + return { + type: 'Comment' + , value: value + , raw: raw + }; + } + }; + + // Wrap up the node object. + + function finishNode(node) { + // Pop a `Marker` off the location-array and attach its location data. + if (trackLocations) { + var location = locations.pop(); + location.complete(); + if (options.locations) node.loc = location.loc; + if (options.ranges) node.range = location.range; + } + if (options.onCreateNode) options.onCreateNode(node); + return node; + } + + + // Helpers + // ------- + + var slice = Array.prototype.slice + , toString = Object.prototype.toString + , indexOf = function indexOf(array, element) { + for (var i = 0, length = array.length; i < length; i++) { + if (array[i] === element) return i; + } + return -1; + }; + + // Iterate through an array of objects and return the index of an object + // with a matching property. + + function indexOfObject(array, property, element) { + for (var i = 0, length = array.length; i < length; i++) { + if (array[i][property] === element) return i; + } + return -1; + } + + // A sprintf implementation using %index (beginning at 1) to input + // arguments in the format string. + // + // Example: + // + // // Unexpected function in token + // sprintf('Unexpected %2 in %1.', 'token', 'function'); + + function sprintf(format) { + var args = slice.call(arguments, 1); + format = format.replace(/%(\d)/g, function (match, index) { + return '' + args[index - 1] || ''; + }); + return format; + } + + // Returns a new object with the properties from all objectes passed as + // arguments. Last argument takes precedence. + // + // Example: + // + // this.options = extend(options, { output: false }); + + function extend() { + var args = slice.call(arguments) + , dest = {} + , src, prop; + + for (var i = 0, length = args.length; i < length; i++) { + src = args[i]; + for (prop in src) if (src.hasOwnProperty(prop)) { + dest[prop] = src[prop]; + } + } + return dest; + } + + // ### Error functions + + // #### Raise an exception. + // + // Raise an exception by passing a token, a string format and its paramters. + // + // The passed tokens location will automatically be added to the error + // message if it exists, if not it will default to the lexers current + // position. + // + // Example: + // + // // [1:0] expected [ near ( + // raise(token, "expected %1 near %2", '[', token.value); + + function raise(token) { + var message = sprintf.apply(null, slice.call(arguments, 1)) + , error, col; + + if ('undefined' !== typeof token.line) { + col = token.range[0] - token.lineStart; + error = new SyntaxError(sprintf('[%1:%2] %3', token.line, col, message)); + error.line = token.line; + error.index = token.range[0]; + error.column = col; + } else { + col = index - lineStart + 1; + error = new SyntaxError(sprintf('[%1:%2] %3', line, col, message)); + error.index = index; + error.line = line; + error.column = col; + } + throw error; + } + + // #### Raise an unexpected token error. + // + // Example: + // + // // expected near '0' + // raiseUnexpectedToken('', token); + + function raiseUnexpectedToken(type, token) { + raise(token, errors.expectedToken, type, token.value); + } + + // #### Raise a general unexpected error + // + // Usage should pass either a token object or a symbol string which was + // expected. We can also specify a nearby token such as , this will + // default to the currently active token. + // + // Example: + // + // // Unexpected symbol 'end' near '' + // unexpected(token); + // + // If there's no token in the buffer it means we have reached . + + function unexpected(found, near) { + if ('undefined' === typeof near) near = lookahead.value; + if ('undefined' !== typeof found.type) { + var type; + switch (found.type) { + case StringLiteral: type = 'string'; break; + case Keyword: type = 'keyword'; break; + case Identifier: type = 'identifier'; break; + case NumericLiteral: type = 'number'; break; + case Punctuator: type = 'symbol'; break; + case BooleanLiteral: type = 'boolean'; break; + case NilLiteral: + return raise(found, errors.unexpected, 'symbol', 'nil', near); + } + return raise(found, errors.unexpected, type, found.value, near); + } + return raise(found, errors.unexpected, 'symbol', found, near); + } + + // Lexer + // ----- + // + // The lexer, or the tokenizer reads the input string character by character + // and derives a token left-right. To be as efficient as possible the lexer + // prioritizes the common cases such as identifiers. It also works with + // character codes instead of characters as string comparisons was the + // biggest bottleneck of the parser. + // + // If `options.comments` is enabled, all comments encountered will be stored + // in an array which later will be appended to the chunk object. If disabled, + // they will simply be disregarded. + // + // When the lexer has derived a valid token, it will be returned as an object + // containing its value and as well as its position in the input string (this + // is always enabled to provide proper debug messages). + // + // `lex()` starts lexing and returns the following token in the stream. + + var index + , token + , previousToken + , lookahead + , comments + , tokenStart + , line + , lineStart; + + exports.lex = lex; + + function lex() { + skipWhiteSpace(); + + // Skip comments beginning with -- + while (45 === input.charCodeAt(index) && + 45 === input.charCodeAt(index + 1)) { + scanComment(); + skipWhiteSpace(); + } + if (index >= length) return { + type : EOF + , value: '' + , line: line + , lineStart: lineStart + , range: [index, index] + }; + + var charCode = input.charCodeAt(index) + , next = input.charCodeAt(index + 1); + + // Memorize the range index where the token begins. + tokenStart = index; + if (isIdentifierStart(charCode)) return scanIdentifierOrKeyword(); + + switch (charCode) { + case 39: case 34: // '" + return scanStringLiteral(); + + // 0-9 + case 48: case 49: case 50: case 51: case 52: case 53: + case 54: case 55: case 56: case 57: + return scanNumericLiteral(); + + case 46: // . + // If the dot is followed by a digit it's a float. + if (isDecDigit(next)) return scanNumericLiteral(); + if (46 === next) { + if (46 === input.charCodeAt(index + 2)) return scanVarargLiteral(); + return scanPunctuator('..'); + } + return scanPunctuator('.'); + + case 61: // = + if (61 === next) return scanPunctuator('=='); + return scanPunctuator('='); + + case 62: // > + if (61 === next) return scanPunctuator('>='); + if (62 === next) return scanPunctuator('>>'); + return scanPunctuator('>'); + + case 60: // < + if (60 === next) return scanPunctuator('<<'); + if (61 === next) return scanPunctuator('<='); + return scanPunctuator('<'); + + case 126: // ~ + if (61 === next) return scanPunctuator('~='); + return scanPunctuator('~'); + + case 58: // : + if (58 === next) return scanPunctuator('::'); + return scanPunctuator(':'); + + case 91: // [ + // Check for a multiline string, they begin with [= or [[ + if (91 === next || 61 === next) return scanLongStringLiteral(); + return scanPunctuator('['); + + case 47: // / + // Check for integer division op (//) + if (47 === next) return scanPunctuator('//'); + return scanPunctuator('/'); + + // * ^ % , { } ] ( ) ; & # - + | + case 42: case 94: case 37: case 44: case 123: case 124: case 125: + case 93: case 40: case 41: case 59: case 38: case 35: case 45: case 43: + return scanPunctuator(input.charAt(index)); + } + + return unexpected(input.charAt(index)); + } + + // Whitespace has no semantic meaning in lua so simply skip ahead while + // tracking the encounted newlines. Any kind of eol sequence is counted as a + // single line. + + function consumeEOL() { + var charCode = input.charCodeAt(index) + , peekCharCode = input.charCodeAt(index + 1); + + if (isLineTerminator(charCode)) { + // Count \n\r and \r\n as one newline. + if (10 === charCode && 13 === peekCharCode) index++; + if (13 === charCode && 10 === peekCharCode) index++; + line++; + lineStart = ++index; + + return true; + } + return false; + } + + function skipWhiteSpace() { + while (index < length) { + var charCode = input.charCodeAt(index); + if (isWhiteSpace(charCode)) { + index++; + } else if (!consumeEOL()) { + break; + } + } + } + + // Identifiers, keywords, booleans and nil all look the same syntax wise. We + // simply go through them one by one and defaulting to an identifier if no + // previous case matched. + + function scanIdentifierOrKeyword() { + var value, type; + + // Slicing the input string is prefered before string concatenation in a + // loop for performance reasons. + while (isIdentifierPart(input.charCodeAt(++index))); + value = input.slice(tokenStart, index); + + // Decide on the token type and possibly cast the value. + if (isKeyword(value)) { + type = Keyword; + } else if ('true' === value || 'false' === value) { + type = BooleanLiteral; + value = ('true' === value); + } else if ('nil' === value) { + type = NilLiteral; + value = null; + } else { + type = Identifier; + } + + return { + type: type + , value: value + , line: line + , lineStart: lineStart + , range: [tokenStart, index] + }; + } + + // Once a punctuator reaches this function it should already have been + // validated so we simply return it as a token. + + function scanPunctuator(value) { + index += value.length; + return { + type: Punctuator + , value: value + , line: line + , lineStart: lineStart + , range: [tokenStart, index] + }; + } + + // A vararg literal consists of three dots. + + function scanVarargLiteral() { + index += 3; + return { + type: VarargLiteral + , value: '...' + , line: line + , lineStart: lineStart + , range: [tokenStart, index] + }; + } + + // Find the string literal by matching the delimiter marks used. + + function scanStringLiteral() { + var delimiter = input.charCodeAt(index++) + , stringStart = index + , string = '' + , charCode; + + while (index < length) { + charCode = input.charCodeAt(index++); + if (delimiter === charCode) break; + if (92 === charCode) { // \ + string += input.slice(stringStart, index - 1) + readEscapeSequence(); + stringStart = index; + } + // EOF or `\n` terminates a string literal. If we haven't found the + // ending delimiter by now, raise an exception. + else if (index >= length || isLineTerminator(charCode)) { + string += input.slice(stringStart, index - 1); + raise({}, errors.unfinishedString, string + String.fromCharCode(charCode)); + } + } + string += input.slice(stringStart, index - 1); + + return { + type: StringLiteral + , value: string + , line: line + , lineStart: lineStart + , range: [tokenStart, index] + }; + } + + // Expect a multiline string literal and return it as a regular string + // literal, if it doesn't validate into a valid multiline string, throw an + // exception. + + function scanLongStringLiteral() { + var string = readLongString(); + // Fail if it's not a multiline literal. + if (false === string) raise(token, errors.expected, '[', token.value); + + return { + type: StringLiteral + , value: string + , line: line + , lineStart: lineStart + , range: [tokenStart, index] + }; + } + + // Numeric literals will be returned as floating-point numbers instead of + // strings. The raw value should be retrieved from slicing the input string + // later on in the process. + // + // If a hexadecimal number is encountered, it will be converted. + + function scanNumericLiteral() { + var character = input.charAt(index) + , next = input.charAt(index + 1); + + var value = ('0' === character && 'xX'.indexOf(next || null) >= 0) ? + readHexLiteral() : readDecLiteral(); + + return { + type: NumericLiteral + , value: value + , line: line + , lineStart: lineStart + , range: [tokenStart, index] + }; + } + + // Lua hexadecimals have an optional fraction part and an optional binary + // exoponent part. These are not included in JavaScript so we will compute + // all three parts separately and then sum them up at the end of the function + // with the following algorithm. + // + // Digit := toDec(digit) + // Fraction := toDec(fraction) / 16 ^ fractionCount + // BinaryExp := 2 ^ binaryExp + // Number := ( Digit + Fraction ) * BinaryExp + + function readHexLiteral() { + var fraction = 0 // defaults to 0 as it gets summed + , binaryExponent = 1 // defaults to 1 as it gets multiplied + , binarySign = 1 // positive + , digit, fractionStart, exponentStart, digitStart; + + digitStart = index += 2; // Skip 0x part + + // A minimum of one hex digit is required. + if (!isHexDigit(input.charCodeAt(index))) + raise({}, errors.malformedNumber, input.slice(tokenStart, index)); + + while (isHexDigit(input.charCodeAt(index))) index++; + // Convert the hexadecimal digit to base 10. + digit = parseInt(input.slice(digitStart, index), 16); + + // Fraction part i optional. + if ('.' === input.charAt(index)) { + fractionStart = ++index; + + while (isHexDigit(input.charCodeAt(index))) index++; + fraction = input.slice(fractionStart, index); + + // Empty fraction parts should default to 0, others should be converted + // 0.x form so we can use summation at the end. + fraction = (fractionStart === index) ? 0 + : parseInt(fraction, 16) / Math.pow(16, index - fractionStart); + } + + // Binary exponents are optional + if ('pP'.indexOf(input.charAt(index) || null) >= 0) { + index++; + + // Sign part is optional and defaults to 1 (positive). + if ('+-'.indexOf(input.charAt(index) || null) >= 0) + binarySign = ('+' === input.charAt(index++)) ? 1 : -1; + + exponentStart = index; + + // The binary exponent sign requires a decimal digit. + if (!isDecDigit(input.charCodeAt(index))) + raise({}, errors.malformedNumber, input.slice(tokenStart, index)); + + while (isDecDigit(input.charCodeAt(index))) index++; + binaryExponent = input.slice(exponentStart, index); + + // Calculate the binary exponent of the number. + binaryExponent = Math.pow(2, binaryExponent * binarySign); + } + + return (digit + fraction) * binaryExponent; + } + + // Decimal numbers are exactly the same in Lua and in JavaScript, because of + // this we check where the token ends and then parse it with native + // functions. + + function readDecLiteral() { + while (isDecDigit(input.charCodeAt(index))) index++; + // Fraction part is optional + if ('.' === input.charAt(index)) { + index++; + // Fraction part defaults to 0 + while (isDecDigit(input.charCodeAt(index))) index++; + } + // Exponent part is optional. + if ('eE'.indexOf(input.charAt(index) || null) >= 0) { + index++; + // Sign part is optional. + if ('+-'.indexOf(input.charAt(index) || null) >= 0) index++; + // An exponent is required to contain at least one decimal digit. + if (!isDecDigit(input.charCodeAt(index))) + raise({}, errors.malformedNumber, input.slice(tokenStart, index)); + + while (isDecDigit(input.charCodeAt(index))) index++; + } + + return parseFloat(input.slice(tokenStart, index)); + } + + + // Translate escape sequences to the actual characters. + + function readEscapeSequence() { + var sequenceStart = index; + switch (input.charAt(index)) { + // Lua allow the following escape sequences. + // We don't escape the bell sequence. + case 'n': index++; return '\n'; + case 'r': index++; return '\r'; + case 't': index++; return '\t'; + case 'v': index++; return '\x0B'; + case 'b': index++; return '\b'; + case 'f': index++; return '\f'; + // Skips the following span of white-space. + case 'z': index++; skipWhiteSpace(); return ''; + // Byte representation should for now be returned as is. + case 'x': + // \xXX, where XX is a sequence of exactly two hexadecimal digits + if (isHexDigit(input.charCodeAt(index + 1)) && + isHexDigit(input.charCodeAt(index + 2))) { + index += 3; + // Return it as is, without translating the byte. + return '\\' + input.slice(sequenceStart, index); + } + return '\\' + input.charAt(index++); + default: + // \ddd, where ddd is a sequence of up to three decimal digits. + if (isDecDigit(input.charCodeAt(index))) { + while (isDecDigit(input.charCodeAt(++index))); + return '\\' + input.slice(sequenceStart, index); + } + // Simply return the \ as is, it's not escaping any sequence. + return input.charAt(index++); + } + } + + // Comments begin with -- after which it will be decided if they are + // multiline comments or not. + // + // The multiline functionality works the exact same way as with string + // literals so we reuse the functionality. + + function scanComment() { + tokenStart = index; + index += 2; // -- + + var character = input.charAt(index) + , content = '' + , isLong = false + , commentStart = index + , lineStartComment = lineStart + , lineComment = line; + + if ('[' === character) { + content = readLongString(); + // This wasn't a multiline comment after all. + if (false === content) content = character; + else isLong = true; + } + // Scan until next line as long as it's not a multiline comment. + if (!isLong) { + while (index < length) { + if (isLineTerminator(input.charCodeAt(index))) break; + index++; + } + if (options.comments) content = input.slice(commentStart, index); + } + + if (options.comments) { + var node = ast.comment(content, input.slice(tokenStart, index)); + + // `Marker`s depend on tokens available in the parser and as comments are + // intercepted in the lexer all location data is set manually. + if (options.locations) { + node.loc = { + start: { line: lineComment, column: tokenStart - lineStartComment } + , end: { line: line, column: index - lineStart } + }; + } + if (options.ranges) { + node.range = [tokenStart, index]; + } + if (options.onCreateNode) options.onCreateNode(node); + comments.push(node); + } + } + + // Read a multiline string by calculating the depth of `=` characters and + // then appending until an equal depth is found. + + function readLongString() { + var level = 0 + , content = '' + , terminator = false + , character, stringStart; + + index++; // [ + + // Calculate the depth of the comment. + while ('=' === input.charAt(index + level)) level++; + // Exit, this is not a long string afterall. + if ('[' !== input.charAt(index + level)) return false; + + index += level + 1; + + // If the first character is a newline, ignore it and begin on next line. + if (isLineTerminator(input.charCodeAt(index))) consumeEOL(); + + stringStart = index; + while (index < length) { + // To keep track of line numbers run the `consumeEOL()` which increments + // its counter. + if (isLineTerminator(input.charCodeAt(index))) consumeEOL(); + + character = input.charAt(index++); + + // Once the delimiter is found, iterate through the depth count and see + // if it matches. + if (']' === character) { + terminator = true; + for (var i = 0; i < level; i++) { + if ('=' !== input.charAt(index + i)) terminator = false; + } + if (']' !== input.charAt(index + level)) terminator = false; + } + + // We reached the end of the multiline string. Get out now. + if (terminator) break; + } + content += input.slice(stringStart, index - 1); + index += level + 1; + + return content; + } + + // ## Lex functions and helpers. + + // Read the next token. + // + // This is actually done by setting the current token to the lookahead and + // reading in the new lookahead token. + + function next() { + previousToken = token; + token = lookahead; + lookahead = lex(); + } + + // Consume a token if its value matches. Once consumed or not, return the + // success of the operation. + + function consume(value) { + if (value === token.value) { + next(); + return true; + } + return false; + } + + // Expect the next token value to match. If not, throw an exception. + + function expect(value) { + if (value === token.value) next(); + else raise(token, errors.expected, value, token.value); + } + + // ### Validation functions + + function isWhiteSpace(charCode) { + return 9 === charCode || 32 === charCode || 0xB === charCode || 0xC === charCode; + } + + function isLineTerminator(charCode) { + return 10 === charCode || 13 === charCode; + } + + function isDecDigit(charCode) { + return charCode >= 48 && charCode <= 57; + } + + function isHexDigit(charCode) { + return (charCode >= 48 && charCode <= 57) || (charCode >= 97 && charCode <= 102) || (charCode >= 65 && charCode <= 70); + } + + // From [Lua 5.2](http://www.lua.org/manual/5.2/manual.html#8.1) onwards + // identifiers cannot use locale-dependet letters. + + function isIdentifierStart(charCode) { + return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || 95 === charCode; + } + + function isIdentifierPart(charCode) { + return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || 95 === charCode || (charCode >= 48 && charCode <= 57); + } + + // [3.1 Lexical Conventions](http://www.lua.org/manual/5.2/manual.html#3.1) + // + // `true`, `false` and `nil` will not be considered keywords, but literals. + + function isKeyword(id) { + switch (id.length) { + case 2: + return 'do' === id || 'if' === id || 'in' === id || 'or' === id; + case 3: + return 'and' === id || 'end' === id || 'for' === id || 'not' === id; + case 4: + return 'else' === id || 'goto' === id || 'then' === id; + case 5: + return 'break' === id || 'local' === id || 'until' === id || 'while' === id; + case 6: + return 'elseif' === id || 'repeat' === id || 'return' === id; + case 8: + return 'function' === id; + } + return false; + } + + function isUnary(token) { + if (Punctuator === token.type) return '#-~'.indexOf(token.value) >= 0; + if (Keyword === token.type) return 'not' === token.value; + return false; + } + + // @TODO this needs to be rethought. + function isCallExpression(expression) { + switch (expression.type) { + case 'CallExpression': + case 'TableCallExpression': + case 'StringCallExpression': + return true; + } + return false; + } + + // Check if the token syntactically closes a block. + + function isBlockFollow(token) { + if (EOF === token.type) return true; + if (Keyword !== token.type) return false; + switch (token.value) { + case 'else': case 'elseif': + case 'end': case 'until': + return true; + default: + return false; + } + } + + // Scope + // ----- + + // Store each block scope as a an array of identifier names. Each scope is + // stored in an FILO-array. + var scopes + // The current scope index + , scopeDepth + // A list of all global identifier nodes. + , globals; + + // Create a new scope inheriting all declarations from the previous scope. + function createScope() { + var scope = Array.apply(null, scopes[scopeDepth++]); + scopes.push(scope); + if (options.onCreateScope) options.onCreateScope(); + } + + // Exit and remove the current scope. + function destroyScope() { + var scope = scopes.pop(); + scopeDepth--; + if (options.onDestroyScope) options.onDestroyScope(); + } + + // Add identifier name to the current scope if it doesnt already exist. + function scopeIdentifierName(name) { + if (-1 !== indexOf(scopes[scopeDepth], name)) return; + scopes[scopeDepth].push(name); + } + + // Add identifier to the current scope + function scopeIdentifier(node) { + scopeIdentifierName(node.name); + attachScope(node, true); + } + + // Attach scope information to node. If the node is global, store it in the + // globals array so we can return the information to the user. + function attachScope(node, isLocal) { + if (!isLocal && -1 === indexOfObject(globals, 'name', node.name)) + globals.push(node); + + node.isLocal = isLocal; + } + + // Is the identifier name available in this scope. + function scopeHasName(name) { + return (-1 !== indexOf(scopes[scopeDepth], name)); + } + + // Location tracking + // ----------------- + // + // Locations are stored in FILO-array as a `Marker` object consisting of both + // `loc` and `range` data. Once a `Marker` is popped off the list an end + // location is added and the data is attached to a syntax node. + + var locations = [] + , trackLocations; + + function createLocationMarker() { + return new Marker(token); + } + + function Marker(token) { + if (options.locations) { + this.loc = { + start: { + line: token.line + , column: token.range[0] - token.lineStart + } + , end: { + line: 0 + , column: 0 + } + }; + } + if (options.ranges) this.range = [token.range[0], 0]; + } + + // Complete the location data stored in the `Marker` by adding the location + // of the *previous token* as an end location. + Marker.prototype.complete = function() { + if (options.locations) { + this.loc.end.line = previousToken.line; + this.loc.end.column = previousToken.range[1] - previousToken.lineStart; + } + if (options.ranges) { + this.range[1] = previousToken.range[1]; + } + }; + + // Create a new `Marker` and add it to the FILO-array. + function markLocation() { + if (trackLocations) locations.push(createLocationMarker()); + } + + // Push an arbitrary `Marker` object onto the FILO-array. + function pushLocation(marker) { + if (trackLocations) locations.push(marker); + } + + // Parse functions + // --------------- + + // Chunk is the main program object. Syntactically it's the same as a block. + // + // chunk ::= block + + function parseChunk() { + next(); + markLocation(); + if (options.scope) createScope(); + var body = parseBlock(); + if (options.scope) destroyScope(); + if (EOF !== token.type) unexpected(token); + // If the body is empty no previousToken exists when finishNode runs. + if (trackLocations && !body.length) previousToken = token; + return finishNode(ast.chunk(body)); + } + + // A block contains a list of statements with an optional return statement + // as its last statement. + // + // block ::= {stat} [retstat] + + function parseBlock(terminator) { + var block = [] + , statement; + + while (!isBlockFollow(token)) { + // Return has to be the last statement in a block. + if ('return' === token.value) { + block.push(parseStatement()); + break; + } + statement = parseStatement(); + // Statements are only added if they are returned, this allows us to + // ignore some statements, such as EmptyStatement. + if (statement) block.push(statement); + } + + // Doesn't really need an ast node + return block; + } + + // There are two types of statements, simple and compound. + // + // statement ::= break | goto | do | while | repeat | return + // | if | for | function | local | label | assignment + // | functioncall | ';' + + function parseStatement() { + markLocation(); + if (Keyword === token.type) { + switch (token.value) { + case 'local': next(); return parseLocalStatement(); + case 'if': next(); return parseIfStatement(); + case 'return': next(); return parseReturnStatement(); + case 'function': next(); + var name = parseFunctionName(); + return parseFunctionDeclaration(name); + case 'while': next(); return parseWhileStatement(); + case 'for': next(); return parseForStatement(); + case 'repeat': next(); return parseRepeatStatement(); + case 'break': next(); return parseBreakStatement(); + case 'do': next(); return parseDoStatement(); + case 'goto': next(); return parseGotoStatement(); + } + } + + if (Punctuator === token.type) { + if (consume('::')) return parseLabelStatement(); + } + // Assignments memorizes the location and pushes it manually for wrapper + // nodes. Additionally empty `;` statements should not mark a location. + if (trackLocations) locations.pop(); + + // When a `;` is encounted, simply eat it without storing it. + if (consume(';')) return; + + return parseAssignmentOrCallStatement(); + } + + // ## Statements + + // label ::= '::' Name '::' + + function parseLabelStatement() { + var name = token.value + , label = parseIdentifier(); + + if (options.scope) { + scopeIdentifierName('::' + name + '::'); + attachScope(label, true); + } + + expect('::'); + return finishNode(ast.labelStatement(label)); + } + + // break ::= 'break' + + function parseBreakStatement() { + return finishNode(ast.breakStatement()); + } + + // goto ::= 'goto' Name + + function parseGotoStatement() { + var name = token.value + , label = parseIdentifier(); + + return finishNode(ast.gotoStatement(label)); + } + + // do ::= 'do' block 'end' + + function parseDoStatement() { + if (options.scope) createScope(); + var body = parseBlock(); + if (options.scope) destroyScope(); + expect('end'); + return finishNode(ast.doStatement(body)); + } + + // while ::= 'while' exp 'do' block 'end' + + function parseWhileStatement() { + var condition = parseExpectedExpression(); + expect('do'); + if (options.scope) createScope(); + var body = parseBlock(); + if (options.scope) destroyScope(); + expect('end'); + return finishNode(ast.whileStatement(condition, body)); + } + + // repeat ::= 'repeat' block 'until' exp + + function parseRepeatStatement() { + if (options.scope) createScope(); + var body = parseBlock(); + expect('until'); + var condition = parseExpectedExpression(); + if (options.scope) destroyScope(); + return finishNode(ast.repeatStatement(condition, body)); + } + + // retstat ::= 'return' [exp {',' exp}] [';'] + + function parseReturnStatement() { + var expressions = []; + + if ('end' !== token.value) { + var expression = parseExpression(); + if (null != expression) expressions.push(expression); + while (consume(',')) { + expression = parseExpectedExpression(); + expressions.push(expression); + } + consume(';'); // grammar tells us ; is optional here. + } + return finishNode(ast.returnStatement(expressions)); + } + + // if ::= 'if' exp 'then' block {elif} ['else' block] 'end' + // elif ::= 'elseif' exp 'then' block + + function parseIfStatement() { + var clauses = [] + , condition + , body + , marker; + + // IfClauses begin at the same location as the parent IfStatement. + // It ends at the start of `end`, `else`, or `elseif`. + if (trackLocations) { + marker = locations[locations.length - 1]; + locations.push(marker); + } + condition = parseExpectedExpression(); + expect('then'); + if (options.scope) createScope(); + body = parseBlock(); + if (options.scope) destroyScope(); + clauses.push(finishNode(ast.ifClause(condition, body))); + + if (trackLocations) marker = createLocationMarker(); + while (consume('elseif')) { + pushLocation(marker); + condition = parseExpectedExpression(); + expect('then'); + if (options.scope) createScope(); + body = parseBlock(); + if (options.scope) destroyScope(); + clauses.push(finishNode(ast.elseifClause(condition, body))); + if (trackLocations) marker = createLocationMarker(); + } + + if (consume('else')) { + // Include the `else` in the location of ElseClause. + if (trackLocations) { + marker = new Marker(previousToken); + locations.push(marker); + } + if (options.scope) createScope(); + body = parseBlock(); + if (options.scope) destroyScope(); + clauses.push(finishNode(ast.elseClause(body))); + } + + expect('end'); + return finishNode(ast.ifStatement(clauses)); + } + + // There are two types of for statements, generic and numeric. + // + // for ::= Name '=' exp ',' exp [',' exp] 'do' block 'end' + // for ::= namelist 'in' explist 'do' block 'end' + // namelist ::= Name {',' Name} + // explist ::= exp {',' exp} + + function parseForStatement() { + var variable = parseIdentifier() + , body; + + // The start-identifier is local. + + if (options.scope) { + createScope(); + scopeIdentifier(variable); + } + + // If the first expression is followed by a `=` punctuator, this is a + // Numeric For Statement. + if (consume('=')) { + // Start expression + var start = parseExpectedExpression(); + expect(','); + // End expression + var end = parseExpectedExpression(); + // Optional step expression + var step = consume(',') ? parseExpectedExpression() : null; + + expect('do'); + body = parseBlock(); + expect('end'); + if (options.scope) destroyScope(); + + return finishNode(ast.forNumericStatement(variable, start, end, step, body)); + } + // If not, it's a Generic For Statement + else { + // The namelist can contain one or more identifiers. + var variables = [variable]; + while (consume(',')) { + variable = parseIdentifier(); + // Each variable in the namelist is locally scoped. + if (options.scope) scopeIdentifier(variable); + variables.push(variable); + } + expect('in'); + var iterators = []; + + // One or more expressions in the explist. + do { + var expression = parseExpectedExpression(); + iterators.push(expression); + } while (consume(',')); + + expect('do'); + body = parseBlock(); + expect('end'); + if (options.scope) destroyScope(); + + return finishNode(ast.forGenericStatement(variables, iterators, body)); + } + } + + // Local statements can either be variable assignments or function + // definitions. If a function definition is found, it will be delegated to + // `parseFunctionDeclaration()` with the isLocal flag. + // + // This AST structure might change into a local assignment with a function + // child. + // + // local ::= 'local' 'function' Name funcdecl + // | 'local' Name {',' Name} ['=' exp {',' exp}] + + function parseLocalStatement() { + var name; + + if (Identifier === token.type) { + var variables = [] + , init = []; + + do { + name = parseIdentifier(); + + variables.push(name); + } while (consume(',')); + + if (consume('=')) { + do { + var expression = parseExpectedExpression(); + init.push(expression); + } while (consume(',')); + } + + // Declarations doesn't exist before the statement has been evaluated. + // Therefore assignments can't use their declarator. And the identifiers + // shouldn't be added to the scope until the statement is complete. + if (options.scope) { + for (var i = 0, l = variables.length; i < l; i++) { + scopeIdentifier(variables[i]); + } + } + + return finishNode(ast.localStatement(variables, init)); + } + if (consume('function')) { + name = parseIdentifier(); + + if (options.scope) { + scopeIdentifier(name); + createScope(); + } + + // MemberExpressions are not allowed in local function statements. + return parseFunctionDeclaration(name, true); + } else { + raiseUnexpectedToken('', token); + } + } + + function validateVar(node) { + // @TODO we need something not dependent on the exact AST used. see also isCallExpression() + if (node.inParens || (['Identifier', 'MemberExpression', 'IndexExpression'].indexOf(node.type) === -1)) { + raise(token, errors.invalidVar, token.value); + } + } + + // assignment ::= varlist '=' explist + // var ::= Name | prefixexp '[' exp ']' | prefixexp '.' Name + // varlist ::= var {',' var} + // explist ::= exp {',' exp} + // + // call ::= callexp + // callexp ::= prefixexp args | prefixexp ':' Name args + + function parseAssignmentOrCallStatement() { + // Keep a reference to the previous token for better error messages in case + // of invalid statement + var previous = token + , expression, marker; + + if (trackLocations) marker = createLocationMarker(); + expression = parsePrefixExpression(); + + if (null == expression) return unexpected(token); + if (',='.indexOf(token.value) >= 0) { + var variables = [expression] + , init = [] + , exp; + + validateVar(expression); + while (consume(',')) { + exp = parsePrefixExpression(); + if (null == exp) raiseUnexpectedToken('', token); + validateVar(exp); + variables.push(exp); + } + expect('='); + do { + exp = parseExpectedExpression(); + init.push(exp); + } while (consume(',')); + + pushLocation(marker); + return finishNode(ast.assignmentStatement(variables, init)); + } + if (isCallExpression(expression)) { + pushLocation(marker); + return finishNode(ast.callStatement(expression)); + } + // The prefix expression was neither part of an assignment or a + // callstatement, however as it was valid it's been consumed, so raise + // the exception on the previous token to provide a helpful message. + return unexpected(previous); + } + + + + // ### Non-statements + + // Identifier ::= Name + + function parseIdentifier() { + markLocation(); + var identifier = token.value; + if (Identifier !== token.type) raiseUnexpectedToken('', token); + next(); + return finishNode(ast.identifier(identifier)); + } + + // Parse the functions parameters and body block. The name should already + // have been parsed and passed to this declaration function. By separating + // this we allow for anonymous functions in expressions. + // + // For local functions there's a boolean parameter which needs to be set + // when parsing the declaration. + // + // funcdecl ::= '(' [parlist] ')' block 'end' + // parlist ::= Name {',' Name} | [',' '...'] | '...' + + function parseFunctionDeclaration(name, isLocal) { + var parameters = []; + expect('('); + + // The declaration has arguments + if (!consume(')')) { + // Arguments are a comma separated list of identifiers, optionally ending + // with a vararg. + while (true) { + if (Identifier === token.type) { + var parameter = parseIdentifier(); + // Function parameters are local. + if (options.scope) scopeIdentifier(parameter); + + parameters.push(parameter); + + if (consume(',')) continue; + else if (consume(')')) break; + } + // No arguments are allowed after a vararg. + else if (VarargLiteral === token.type) { + parameters.push(parsePrimaryExpression()); + expect(')'); + break; + } else { + raiseUnexpectedToken(' or \'...\'', token); + } + } + } + + var body = parseBlock(); + expect('end'); + if (options.scope) destroyScope(); + + isLocal = isLocal || false; + return finishNode(ast.functionStatement(name, parameters, isLocal, body)); + } + + // Parse the function name as identifiers and member expressions. + // + // Name {'.' Name} [':' Name] + + function parseFunctionName() { + var base, name, marker; + + if (trackLocations) marker = createLocationMarker(); + base = parseIdentifier(); + + if (options.scope) { + attachScope(base, scopeHasName(base.name)); + createScope(); + } + + while (consume('.')) { + pushLocation(marker); + name = parseIdentifier(); + base = finishNode(ast.memberExpression(base, '.', name)); + } + + if (consume(':')) { + pushLocation(marker); + name = parseIdentifier(); + base = finishNode(ast.memberExpression(base, ':', name)); + if (options.scope) scopeIdentifierName('self'); + } + + return base; + } + + // tableconstructor ::= '{' [fieldlist] '}' + // fieldlist ::= field {fieldsep field} fieldsep + // field ::= '[' exp ']' '=' exp | Name = 'exp' | exp + // + // fieldsep ::= ',' | ';' + + function parseTableConstructor() { + var fields = [] + , key, value; + + while (true) { + markLocation(); + if (Punctuator === token.type && consume('[')) { + key = parseExpectedExpression(); + expect(']'); + expect('='); + value = parseExpectedExpression(); + fields.push(finishNode(ast.tableKey(key, value))); + } else if (Identifier === token.type) { + if ('=' === lookahead.value) { + key = parseIdentifier(); + next(); + value = parseExpectedExpression(); + fields.push(finishNode(ast.tableKeyString(key, value))); + } else { + value = parseExpectedExpression(); + fields.push(finishNode(ast.tableValue(value))); + } + } else { + if (null == (value = parseExpression())) { + locations.pop(); + break; + } + fields.push(finishNode(ast.tableValue(value))); + } + if (',;'.indexOf(token.value) >= 0) { + next(); + continue; + } + break; + } + expect('}'); + return finishNode(ast.tableConstructorExpression(fields)); + } + + // Expression parser + // ----------------- + // + // Expressions are evaluated and always return a value. If nothing is + // matched null will be returned. + // + // exp ::= (unop exp | primary | prefixexp ) { binop exp } + // + // primary ::= nil | false | true | Number | String | '...' + // | functiondef | tableconstructor + // + // prefixexp ::= (Name | '(' exp ')' ) { '[' exp ']' + // | '.' Name | ':' Name args | args } + // + + function parseExpression() { + var expression = parseSubExpression(0); + return expression; + } + + // Parse an expression expecting it to be valid. + + function parseExpectedExpression() { + var expression = parseExpression(); + if (null == expression) raiseUnexpectedToken('', token); + else return expression; + } + + + // Return the precedence priority of the operator. + // + // As unary `-` can't be distinguished from binary `-`, unary precedence + // isn't described in this table but in `parseSubExpression()` itself. + // + // As this function gets hit on every expression it's been optimized due to + // the expensive CompareICStub which took ~8% of the parse time. + + function binaryPrecedence(operator) { + var charCode = operator.charCodeAt(0) + , length = operator.length; + + if (1 === length) { + switch (charCode) { + case 94: return 12; // ^ + case 42: case 47: case 37: return 10; // * / % + case 43: case 45: return 9; // + - + case 38: return 6; // & + case 126: return 5; // ~ + case 124: return 4; // | + case 60: case 62: return 3; // < > + } + } else if (2 === length) { + switch (charCode) { + case 47: return 10; // // + case 46: return 8; // .. + case 60: case 62: + if('<<' === operator || '>>' === operator) return 7; // << >> + return 3; // <= >= + case 61: case 126: return 3; // == ~= + case 111: return 1; // or + } + } else if (97 === charCode && 'and' === operator) return 2; + return 0; + } + + // Implement an operator-precedence parser to handle binary operator + // precedence. + // + // We use this algorithm because it's compact, it's fast and Lua core uses + // the same so we can be sure our expressions are parsed in the same manner + // without excessive amounts of tests. + // + // exp ::= (unop exp | primary | prefixexp ) { binop exp } + + function parseSubExpression(minPrecedence) { + var operator = token.value + // The left-hand side in binary operations. + , expression, marker; + + if (trackLocations) marker = createLocationMarker(); + + // UnaryExpression + if (isUnary(token)) { + markLocation(); + next(); + var argument = parseSubExpression(10); + if (argument == null) raiseUnexpectedToken('', token); + expression = finishNode(ast.unaryExpression(operator, argument)); + } + if (null == expression) { + // PrimaryExpression + expression = parsePrimaryExpression(); + + // PrefixExpression + if (null == expression) { + expression = parsePrefixExpression(); + } + } + // This is not a valid left hand expression. + if (null == expression) return null; + + var precedence; + while (true) { + operator = token.value; + + precedence = (Punctuator === token.type || Keyword === token.type) ? + binaryPrecedence(operator) : 0; + + if (precedence === 0 || precedence <= minPrecedence) break; + // Right-hand precedence operators + if ('^' === operator || '..' === operator) precedence--; + next(); + var right = parseSubExpression(precedence); + if (null == right) raiseUnexpectedToken('', token); + // Push in the marker created before the loop to wrap its entirety. + if (trackLocations) locations.push(marker); + expression = finishNode(ast.binaryExpression(operator, expression, right)); + + } + return expression; + } + + // prefixexp ::= prefix {suffix} + // prefix ::= Name | '(' exp ')' + // suffix ::= '[' exp ']' | '.' Name | ':' Name args | args + // + // args ::= '(' [explist] ')' | tableconstructor | String + + function parsePrefixExpression() { + var base, name, marker; + + if (trackLocations) marker = createLocationMarker(); + + // The prefix + if (Identifier === token.type) { + name = token.value; + base = parseIdentifier(); + // Set the parent scope. + if (options.scope) attachScope(base, scopeHasName(name)); + } else if (consume('(')) { + base = parseExpectedExpression(); + expect(')'); + base.inParens = true; // XXX: quick and dirty. needed for validateVar + } else { + return null; + } + + // The suffix + var expression, identifier; + while (true) { + if (Punctuator === token.type) { + switch (token.value) { + case '[': + pushLocation(marker); + next(); + expression = parseExpectedExpression(); + base = finishNode(ast.indexExpression(base, expression)); + expect(']'); + break; + case '.': + pushLocation(marker); + next(); + identifier = parseIdentifier(); + base = finishNode(ast.memberExpression(base, '.', identifier)); + break; + case ':': + pushLocation(marker); + next(); + identifier = parseIdentifier(); + base = finishNode(ast.memberExpression(base, ':', identifier)); + // Once a : is found, this has to be a CallExpression, otherwise + // throw an error. + pushLocation(marker); + base = parseCallExpression(base); + break; + case '(': case '{': // args + pushLocation(marker); + base = parseCallExpression(base); + break; + default: + return base; + } + } else if (StringLiteral === token.type) { + pushLocation(marker); + base = parseCallExpression(base); + } else { + break; + } + } + + return base; + } + + // args ::= '(' [explist] ')' | tableconstructor | String + + function parseCallExpression(base) { + if (Punctuator === token.type) { + switch (token.value) { + case '(': + next(); + + // List of expressions + var expressions = []; + var expression = parseExpression(); + if (null != expression) expressions.push(expression); + while (consume(',')) { + expression = parseExpectedExpression(); + expressions.push(expression); + } + + expect(')'); + return finishNode(ast.callExpression(base, expressions)); + + case '{': + markLocation(); + next(); + var table = parseTableConstructor(); + return finishNode(ast.tableCallExpression(base, table)); + } + } else if (StringLiteral === token.type) { + return finishNode(ast.stringCallExpression(base, parsePrimaryExpression())); + } + + raiseUnexpectedToken('function arguments', token); + } + + // primary ::= String | Numeric | nil | true | false + // | functiondef | tableconstructor | '...' + + function parsePrimaryExpression() { + var literals = StringLiteral | NumericLiteral | BooleanLiteral | NilLiteral | VarargLiteral + , value = token.value + , type = token.type + , marker; + + if (trackLocations) marker = createLocationMarker(); + + if (type & literals) { + pushLocation(marker); + var raw = input.slice(token.range[0], token.range[1]); + next(); + return finishNode(ast.literal(type, value, raw)); + } else if (Keyword === type && 'function' === value) { + pushLocation(marker); + next(); + if (options.scope) createScope(); + return parseFunctionDeclaration(null); + } else if (consume('{')) { + pushLocation(marker); + return parseTableConstructor(); + } + } + + // Parser + // ------ + + // Export the main parser. + // + // - `wait` Hold parsing until end() is called. Defaults to false + // - `comments` Store comments. Defaults to true. + // - `scope` Track identifier scope. Defaults to false. + // - `locations` Store location information. Defaults to false. + // - `ranges` Store the start and end character locations. Defaults to + // false. + // - `onCreateNode` Callback which will be invoked when a syntax node is + // created. + // - `onCreateScope` Callback which will be invoked when a new scope is + // created. + // - `onDestroyScope` Callback which will be invoked when the current scope + // is destroyed. + // + // Example: + // + // var parser = require('luaparser'); + // parser.parse('i = 0'); + + exports.parse = parse; + + function parse(_input, _options) { + if ('undefined' === typeof _options && 'object' === typeof _input) { + _options = _input; + _input = undefined; + } + if (!_options) _options = {}; + + input = _input || ''; + options = extend(defaultOptions, _options); + + // Rewind the lexer + index = 0; + line = 1; + lineStart = 0; + length = input.length; + // When tracking identifier scope, initialize with an empty scope. + scopes = [[]]; + scopeDepth = 0; + globals = []; + locations = []; + + if (options.comments) comments = []; + if (!options.wait) return end(); + return exports; + } + + // Write to the source code buffer without beginning the parse. + exports.write = write; + + function write(_input) { + input += String(_input); + length = input.length; + return exports; + } + + // Send an EOF and begin parsing. + exports.end = end; + + function end(_input) { + if ('undefined' !== typeof _input) write(_input); + + // Ignore shebangs. + if (input && input.substr(0, 2) === '#!') input = input.replace(/^.*/, function (line) { + return line.replace(/./g, ' '); + }); + + length = input.length; + trackLocations = options.locations || options.ranges; + // Initialize with a lookahead token. + lookahead = lex(); + + var chunk = parseChunk(); + if (options.comments) chunk.comments = comments; + if (options.scope) chunk.globals = globals; + + if (locations.length > 0) + throw new Error('Location tracking failed. This is most likely a bug in luaparse'); + + return chunk; + } + +})); +/* vim: set sw=2 ts=2 et tw=79 : */ diff --git a/node_modules/luaparse/package.json b/node_modules/luaparse/package.json new file mode 100644 index 0000000..e2e7d2a --- /dev/null +++ b/node_modules/luaparse/package.json @@ -0,0 +1,48 @@ +{ + "name": "luaparse", + "version": "0.2.1", + "description": "A Lua parser in JavaScript", + "keywords": [ + "ast", + "lua", + "parser", + "parsing" + ], + "homepage": "https://oxyc.github.io/luaparse/", + "bugs": "https://github.com/oxyc/luaparse/issues", + "license": "MIT", + "author": "Oskar Schöldström (http://www.oxy.fi/)", + "files": [ + "README.md", + "LICENSE", + "luaparse.js", + "bin/luaparse" + ], + "main": "luaparse.js", + "bin": "./bin/luaparse", + "man": "./docs/luaparse.1", + "repository": { + "type": "git", + "url": "https://github.com/oxyc/luaparse.git" + }, + "scripts": { + "test": "make qa" + }, + "devDependencies": { + "benchmark": "~1.0.0", + "complexity-report": "~0.10.5", + "docco": "~0.6.3", + "gulp": "~3.8.10", + "gulp-add-src": "^0.2.0", + "gulp-filelog": "^0.4.1", + "gulp-header": "^1.2.2", + "gulp-jshint": "^1.9.0", + "gulp-rename": "^1.2.0", + "gulp-striphtml": "0.0.1", + "gulp-uglify": "^1.0.1", + "istanbul": "~0.3.2", + "marked": "~0.3.2", + "spec": "git://github.com/kitcambridge/spec.git#gh-pages", + "testem": "~0.6.9" + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..851354e --- /dev/null +++ b/package-lock.json @@ -0,0 +1,33 @@ +{ + "name": "HyperionOS", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "luamin": "^1.0.4" + } + }, + "node_modules/luamin": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/luamin/-/luamin-1.0.4.tgz", + "integrity": "sha512-z1h0bclRD/QGsS/Dz4Skp9z0qPTmmm+IKcrCapGmdTczPWVdN9f9jk6WqkNrcifQr8+n9Pzsm9WkwpOH1JBUAQ==", + "license": "MIT", + "dependencies": { + "luaparse": "^0.2.1" + }, + "bin": { + "luamin": "bin/luamin" + } + }, + "node_modules/luaparse": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/luaparse/-/luaparse-0.2.1.tgz", + "integrity": "sha512-VKBcryd5nJte4ZNR29NOk8F/UkMipjeb4yoxcSS51z6QAzg9DXUC2WsfLniS0J1eh3pr/ZL3e9ha6V8fhoLbBQ==", + "license": "MIT", + "bin": { + "luaparse": "bin/luaparse" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..2529193 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "luamin": "^1.0.4" + } +} diff --git a/typings/Hyperion-kernel/EFI.d.lua b/typings/Hyperion-kernel/EFI.d.lua new file mode 100644 index 0000000..7c23ad2 --- /dev/null +++ b/typings/Hyperion-kernel/EFI.d.lua @@ -0,0 +1,57 @@ +---@meta EFI + +---@class HyperionOS.kernel.EFI Bootloader interface +---@field yield fun() yeilds os to bootloader to prevent watchdog +---@field getEpochMs fun(): number gets current epoch ms +---@field getUptime fun(): number gets current uptime in ms +---@field date fun(): string "!%Y-%m-%dT%H:%M:%SZ" of current ms utc +---@field getMachineEvent fun(): ... returns queued machine events +---@field getEEPROM fun(): string returns current EEPROM program +---@field setEEPROM fun(self, code:string) sets the EEPROM code to code +---@field initfs table initfs api +---@field disks table disks api +---@field screenctl HyperionOS.kernel.EFI.screen screen control handle +---@field architecture string architecture signature +---@field getNvram fun(): string reads non-volitile ram +---@field setNvram fun(self, data:string) sets non-volitile ram +---@field firmware table extra apis for drivers to use +---@field status string run status +---@field beep fun(self, freq:number, ms:number) beep tone + +---@class HyperionOS.kernel.EFI.screen +---@field print fun(self, text:string) prints with following \n +---@field printInline fun(self, text:string) prints to screen +---@field clear fun(self) clears screen +---@field resetCursor fun(self) moves cursor to 1,1 +---@field setBackgroundColor fun(self, color24:number) sets background color +---@field setTextColor fun(self, color24:number) sets text color +---@field getBackgroundColor fun(self): number returns background color24 +---@field getTextColor fun(self): number returns text color24 +---@field enable fun(self) enables the screens +---@field disable fun(self) disables the screen + +---@class file +---@field read fun(amount:number) reads x bytes from file (r) +---@field write fun(data:string) writes data to a file (w, a) +---@field flush fun() flushes appending writes (w, a) +---@field seek fun(whence:"set"|"cur"|"end", offset:number): number moves the file pointer and returns the new position +---@field close fun() closes the open file + +---@class disk +---@field address string ID of disk +---@field isReadOnly fun(self): boolean Is disk read only? +---@field spaceUsed fun(self): number Returns bytes used +---@field spaceTotal fun(self): number Returns disk size in bytes +---@field list fun(self, path:string) get contents of a directory +---@field fileExists fun(self, path:string) does a file exist? +---@field directoryExists fun(self, path:string) does a directory exist? +---@field type fun(self, path:string): string returns type of a path +---@field makeDirectory fun(self, path:string) makes a directory +---@field remove fun(self, path:string) delete a file or directory +---@field setLabel fun(self, label:string) sets disk label +---@field getLabel fun(self): string returns disk label +---@field attributes fun(self, path:string) returns path attributes (ex: size and date modified) +---@field open fun(self, path:string, mode:string): file opens a file returns handle + +---@class HyperionOS.kernel +---@field EFI HyperionOS.kernel.EFI \ No newline at end of file diff --git a/typings/Hyperion-kernel/kernel-config.d.lua b/typings/Hyperion-kernel/kernel-config.d.lua new file mode 100644 index 0000000..5225c31 --- /dev/null +++ b/typings/Hyperion-kernel/kernel-config.d.lua @@ -0,0 +1,15 @@ +---@meta +---@class HyperionOS.kernel.config +---@field initPath string The path that init takes to load the init system +---@field allowGlobalOverwrites boolean Allow modifying of gloabal env (usually for debug purposes) +---@field enableAdvancedDebug boolean Allow debug into the kernel +---@field maxOpenFiles number The maximum open files allowed for the whole system +---@field maxFilesPerTask number The maximum open files allowed for each task +---@field preempt boolean Enable/Disable preemptive multitasking +---@field debugSyscalls boolean Logs syscalls and their return values aswell as what task executed them (WILL HARM PREFORMANCE) +---@field logTaskExit boolean Logs task exits and errors +---@field showModLoad boolean Log module loading +---@field tmpToDisk boolean Writes /tmp to disk instead of ramfs +---@field logSymlinkTraverse boolean Logs symlink traversal (can harm preformance) +---@field moreLogsaves boolean Enables log debug save points (can harm boot time +---@field logPathResolution boolean Logs how a vfs path resolves to a disk path (can harm preformance) \ No newline at end of file diff --git a/typings/Hyperion-kernel/kernel.d.lua b/typings/Hyperion-kernel/kernel.d.lua new file mode 100644 index 0000000..dcd3bc1 --- /dev/null +++ b/typings/Hyperion-kernel/kernel.d.lua @@ -0,0 +1,112 @@ +---@meta Hyperion-kernel +--#region kernel + +---@class HyperionOS.kernel +--- NOT AVAILBLE IN USERSPACE +--- AT TOP DO "local kernel=..." OF YOUR MODULE +local kernel={} + +---@class HyperionOS.kernel +---@field LOG_Text string +---@field version string Human readable version +---@field tag string version tag +---@field process string current process name +---@field users table user translation table +---@field hostname string computer hostname +---@field groups table unused +---@field uid number current task user id +---@field gid number unused? +---@field status string run status +---@field key table a uniq table to identifiy as the kernel if needed +---@field cache {preload:{}} unused +---@field unixSockets table unixSockets table +---@field config HyperionOS.kernel.config + +kernel._G=_G +kernel.sleep=sleep + +---@class HyperionOS.userspace.syscall +local syscall +kernel.syscalls=syscall + +--- Logs a message to the system log and console. +--- @param msg string The message to log +--- @param tag? string Log tag (defaults to "INFO") +--- @param c? number 24-bit RGB color (defaults to 0x6D6D6D) +--- @param nopanic? boolean Prevents a logging error from triggering a kernel panic +function kernel.log(msg, tag, c, nopanic) end + +--- Crash the OS and display a message +--- @param msg string +function kernel.panic(msg) end +kernel.PANIC=kernel.panic + +--#endregion kernel + +--#region userspace + +--- Returns the current system time in milliseconds. +--- @return number +function syscall.time() end + +--- Returns the current system date. +--- @return string +function syscall.date() end + +--- Logs a message to the system log and console. +--- @param msg string The message to log +--- @param tag? string Log tag (defaults to "INFO") +--- @param c? number 24-bit RGB color (defaults to 0x6D6D6D) +--- @param nopanic? boolean Prevents a logging error from triggering a kernel panic +function syscall.log(msg, tag, c, nopanic) end + +--- Returns the HyperionOS version tag. +--- @return string +function syscall.tag() end + +--- Returns the system uptime. +--- @return number +function syscall.getUptime() end + +--- Returns a username. +--- @param uid? number User ID (defaults to current user) +--- @return string? +function syscall.getUsername(uid) end + +--- Returns the system hostname. +--- @return string +function syscall.getHostname() end + +--- Returns the host environment identifier. +--- @return string +function syscall.getHost() end + +--- Returns the HyperionOS version. +--- @return string +function syscall.version() end + +--- Changes the system hostname. Requires root. +--- @param name string New hostname +function syscall.setHostname(name) end + +--- Returns the system architecture. +--- @return string +function syscall.arch() end + +--- Returns a list of registered syscall names. +--- @return string[] +function syscall.sysdump() end + +--- Reboots the system. Requires root or wheel group. +function syscall.reboot() end + +--- Shuts down the system. Requires root or wheel group. +function syscall.shutdown() end + +--- Halts the system. Requires root or wheel group. +function syscall.halt() end + +--- Saves the system log. Requires root or wheel group. +function syscall.saveLog() end + +--#endregion userspace \ No newline at end of file diff --git a/typings/Hyperion-kernel/modules/loopdev.d.lua b/typings/Hyperion-kernel/modules/loopdev.d.lua new file mode 100644 index 0000000..cfdff69 --- /dev/null +++ b/typings/Hyperion-kernel/modules/loopdev.d.lua @@ -0,0 +1,42 @@ +--#region loopdev + +---@meta + +--#region kernel +---@class HyperionOS.kernel +---@field vfs HyperionOS.types.LoopDeviceInfo + +---@class LoopDeviceInfo +---@field path string Original directory or image path +---@field mode "bind"|"image" Loop device mode + +---Attaches a loop device backed by a directory or filesystem image. +---Requires root privileges. +---@param path string Directory or .hfs image path +---@param forceImage? boolean Force image mode instead of directory bind mode +---@return string id Loop device ID +function syscall.losetup(path, forceImage) end + +---Detaches a loop device. +---The device must be unmounted first. +---Requires root privileges. +---@param id string Loop device ID +function syscall.lodetach(id) end + +---Lists currently attached loop devices. +---@return table devices +function syscall.lolist() end + +---Creates a BHFS binary filesystem image from a VFS directory. +---Requires root privileges. +---@param srcdir string Source directory +---@return string image BHFS binary image data +function syscall.loimgcreate(srcdir) end + +---Writes a BHFS image string to a file. +---Requires root privileges. +---@param image string BHFS binary image data +---@param dest string Destination file path +function syscall.loimgwrite(image, dest) end + +--#endregion loopdev \ No newline at end of file diff --git a/typings/Hyperion-kernel/modules/vfs.d.lua b/typings/Hyperion-kernel/modules/vfs.d.lua new file mode 100644 index 0000000..7814462 --- /dev/null +++ b/typings/Hyperion-kernel/modules/vfs.d.lua @@ -0,0 +1,393 @@ +---@meta + +--#region kernel +---@class HyperionOS.kernel +---@field vfs HyperionOS.kernel.vfs + +---@class HyperionOS.kernel.vfs +local vfs={} + +--- Opens a file and returns its file descriptor. +--- @param path string File path +--- @param mode string Open mode ("r", "w", or "a") +--- @return integer fd +function vfs.open(path, mode) end + +--- Closes a file descriptor. +--- @param fd integer +function vfs.close(fd) end + +--- Reads data from a file descriptor. +--- @param fd integer +--- @param count? integer Number of bytes to read +--- @return string +function vfs.read(fd, count) end + +--- Writes data to a file descriptor. +--- @param fd integer +--- @param content string Data to write +function vfs.write(fd, content) end + +--- Reads data from a file at a specific offset without changing its position. +--- @param fd integer +--- @param count integer Number of bytes to read +--- @param offset integer File offset +--- @return string +function vfs.pread(fd, count, offset) end + +--- Writes data to a file at a specific offset without changing its position. +--- @param fd integer +--- @param content string Data to write +--- @param offset integer File offset +function vfs.pwrite(fd, content, offset) end + +--- Changes the current file position. +--- @param fd integer +--- @param offset integer +--- @param whence? string Position reference ("set", "cur", or "end") +--- @return integer +function vfs.lseek(fd, offset, whence) end + +--- Flushes pending file writes. +--- @param fd integer +function vfs.fsync(fd) end + +--- Copies data between file descriptors. +--- @param outfd integer Destination file descriptor +--- @param infd integer Source file descriptor +--- @param count? integer Number of bytes to copy +function vfs.sendfile(outfd, infd, count) end + +--- Gets file information by path, following symlinks. +--- @param path string +--- @return table +function vfs.stat(path) end + +--- Gets file information by path without following symlinks. +--- @param path string +--- @return table +function vfs.lstat(path) end + +--- Gets file information from an open file descriptor. +--- @param fd integer +--- @return table +function vfs.fstat(fd) end + +--- Creates a directory. +--- @param path string +function vfs.mkdir(path) end + +--- Removes a file, directory, or symlink. +--- @param path string +function vfs.remove(path) end + +--- Lists the contents of a directory. +--- @param path string +--- @return string[] +function vfs.listdir(path) end + +--- Changes file permissions. +--- @param path string +--- @param perms integer Permission bitmask +function vfs.chmod(path, perms) end + +--- Changes permissions using a file descriptor. +--- @param fd integer +--- @param perms integer Permission bitmask +function vfs.fchmod(fd, perms) end + +--- Changes file ownership. +--- @param path string +--- @param uid integer User ID +--- @param gid integer Group ID +function vfs.chown(path, uid, gid) end + +--- Changes ownership using a file descriptor. +--- @param fd integer +--- @param uid integer User ID +--- @param gid integer Group ID +function vfs.fchown(fd, uid, gid) end + +--- Checks whether a path exists. +--- @param path string +--- @return boolean +function vfs.exists(path) end + +--- Returns the type of a path. +--- @param path string +--- @return string|nil +function vfs.type(path) end + +--- Mounts a disk or bind mount. +--- @param target string Mount point +--- @param diskOrId string|table Disk ID or disk object +--- @param bind? boolean Whether this is a bind mount +--- @param floating? boolean Whether this is a floating mount +--- @return boolean +function vfs.mount(target, diskOrId, bind, floating) end + +--- Unmounts a filesystem. +--- @param target string Mount point +--- @return boolean +function vfs.umount(target) end + +--- Returns the current working directory. +--- @return string +function vfs.getcwd() end + +--- Changes the current working directory. +--- @param path string +function vfs.chdir(path) end + +--- Changes the process root directory. Requires root. +--- @param path string +function vfs.chroot(path) end + +--- Duplicates a file descriptor. +--- @param oldfd integer +--- @return integer +function vfs.dup(oldfd) end + +--- Duplicates a file descriptor to a specific descriptor number. +--- @param oldfd integer +--- @param newfd integer +--- @return integer +function vfs.dup2(oldfd, newfd) end + +--- Calls a method on an open device. +--- @param fd integer Device file descriptor +--- @param method string Device method name +--- @param ... any Method arguments +--- @return any ... +function vfs.devctl(fd, method, ...) end + +--- Lists available methods on an open device. +--- @param fd integer Device file descriptor +--- @return string[] +function vfs.devlst(fd) end + +--- Creates a symbolic link. +--- @param target string Link target +--- @param linkPath string Path of the new symlink +function vfs.symlink(target, linkPath) end + +--- Reads the target of a symbolic link. +--- @param path string +--- @return string +function vfs.readlink(path) end + +--- Checks access permissions for a path. +--- @param path string +--- @param mode string Permission checks ("r", "w", "x", or combinations) +--- @return boolean +function vfs.access(path, mode) end + +--- Gets the SUID owner associated with an open file descriptor. +--- @param fd integer +--- @return integer|nil +function vfs.fget_suid(fd) end + +--- Returns the paths associated with open file descriptors. +--- @return string[] +function vfs.getOpenFds() end + +--- Returns filesystem mount and disk information. +--- @return table +function vfs.fsinfo() end + +--#endregion kernel + +--#region userspace + +---@class HyperionOS.userspace.syscall +local syscall={} + +--- Opens a file and returns its file descriptor. +--- @param path string File path +--- @param mode string Open mode ("r", "w", or "a") +--- @return integer fd +function syscall.open(path, mode) end + +--- Closes a file descriptor. +--- @param fd integer +function syscall.close(fd) end + +--- Reads data from a file descriptor. +--- @param fd integer +--- @param count? integer Number of bytes to read +--- @return string +function syscall.read(fd, count) end + +--- Writes data to a file descriptor. +--- @param fd integer +--- @param content string Data to write +function syscall.write(fd, content) end + +--- Reads data from a file at a specific offset without changing its position. +--- @param fd integer +--- @param count integer Number of bytes to read +--- @param offset integer File offset +--- @return string +function syscall.pread(fd, count, offset) end + +--- Writes data to a file at a specific offset without changing its position. +--- @param fd integer +--- @param content string Data to write +--- @param offset integer File offset +function syscall.pwrite(fd, content, offset) end + +--- Changes the current file position. +--- @param fd integer +--- @param offset integer +--- @param whence? string Position reference ("set", "cur", or "end") +--- @return integer +function syscall.lseek(fd, offset, whence) end + +--- Flushes pending file writes. +--- @param fd integer +function syscall.fsync(fd) end + +--- Copies data between file descriptors. +--- @param outfd integer Destination file descriptor +--- @param infd integer Source file descriptor +--- @param count? integer Number of bytes to copy +function syscall.sendfile(outfd, infd, count) end + +--- Gets file information by path, following symlinks. +--- @param path string +--- @return table +function syscall.stat(path) end + +--- Gets file information by path without following symlinks. +--- @param path string +--- @return table +function syscall.lstat(path) end + +--- Gets file information from an open file descriptor. +--- @param fd integer +--- @return table +function syscall.fstat(fd) end + +--- Creates a directory. +--- @param path string +function syscall.mkdir(path) end + +--- Removes a file, directory, or symlink. +--- @param path string +function syscall.remove(path) end + +--- Lists the contents of a directory. +--- @param path string +--- @return string[] +function syscall.listdir(path) end + +--- Changes file permissions. +--- @param path string +--- @param perms integer Permission bitmask +function syscall.chmod(path, perms) end + +--- Changes permissions using a file descriptor. +--- @param fd integer +--- @param perms integer Permission bitmask +function syscall.fchmod(fd, perms) end + +--- Changes file ownership. +--- @param path string +--- @param uid integer User ID +--- @param gid integer Group ID +function syscall.chown(path, uid, gid) end + +--- Changes ownership using a file descriptor. +--- @param fd integer +--- @param uid integer User ID +--- @param gid integer Group ID +function syscall.fchown(fd, uid, gid) end + +--- Checks whether a path exists. +--- @param path string +--- @return boolean +function syscall.exists(path) end + +--- Returns the type of a path. +--- @param path string +--- @return string|nil +function syscall.type(path) end + +--- Mounts a disk or bind mount. +--- @param target string Mount point +--- @param diskOrId string|table Disk ID or disk object +--- @param bind? boolean Whether this is a bind mount +--- @param floating? boolean Whether this is a floating mount +--- @return boolean +function syscall.mount(target, diskOrId, bind, floating) end + +--- Unmounts a filesystem. +--- @param target string Mount point +--- @return boolean +function syscall.umount(target) end + +--- Returns the current working directory. +--- @return string +function syscall.getcwd() end + +--- Changes the current working directory. +--- @param path string +function syscall.chdir(path) end + +--- Changes the process root directory. Requires root. +--- @param path string +function syscall.chroot(path) end + +--- Duplicates a file descriptor. +--- @param oldfd integer +--- @return integer +function syscall.dup(oldfd) end + +--- Duplicates a file descriptor to a specific descriptor number. +--- @param oldfd integer +--- @param newfd integer +--- @return integer +function syscall.dup2(oldfd, newfd) end + +--- Calls a method on an open device. +--- @param fd integer Device file descriptor +--- @param method string Device method name +--- @param ... any Method arguments +--- @return any ... +function syscall.devctl(fd, method, ...) end + +--- Lists available methods on an open device. +--- @param fd integer Device file descriptor +--- @return string[] +function syscall.devlst(fd) end + +--- Creates a symbolic link. +--- @param target string Link target +--- @param linkPath string Path of the new symlink +function syscall.symlink(target, linkPath) end + +--- Reads the target of a symbolic link. +--- @param path string +--- @return string +function syscall.readlink(path) end + +--- Checks access permissions for a path. +--- @param path string +--- @param mode string Permission checks ("r", "w", "x", or combinations) +--- @return boolean +function syscall.access(path, mode) end + +--- Gets the SUID owner associated with an open file descriptor. +--- @param fd integer +--- @return integer|nil +function syscall.fget_suid(fd) end + +--- Returns the paths associated with open file descriptors. +--- @return string[] +function syscall.getOpenFds() end + +--- Returns filesystem mount and disk information. +--- @return table +function syscall.fsinfo() end + +--#endregion userspace \ No newline at end of file diff --git a/typings/HyperionOS.d.lua b/typings/HyperionOS.d.lua new file mode 100644 index 0000000..71c2c25 --- /dev/null +++ b/typings/HyperionOS.d.lua @@ -0,0 +1,6 @@ +---@meta +---@class HyperionOS +---@field version "1.2.5" + +---@type HyperionOS.userspace.syscall +syscall={} \ No newline at end of file diff --git a/typings/userspace-manifest.lua b/typings/userspace-manifest.lua new file mode 100644 index 0000000..693425e --- /dev/null +++ b/typings/userspace-manifest.lua @@ -0,0 +1,509 @@ + +--#region vfs + +--#endregion vfs + +--#region signals + +---@class SignalHandle +---@field error string Error message if the handler fails +---@field active boolean Whether the signal handler is active + +---Sends a signal to a process. +---@param pid number|string Process ID +---@param sig number Signal number (0–256) +function syscall.sigsend(pid, sig) end + +---Registers a signal handler for the current process. +---@param handler fun(sig: number) Signal callback +---@return SignalHandle handle Signal handler state +function syscall.sigcatch(handler) end + +---Removes the current process's signal handler and pending signals. +function syscall.sigignore() end + +--#endregion signals + +--#region socket + +---Creates a new socket file descriptor. +---@return number fd Socket file descriptor +function syscall.socket() end + +---Connects a socket to an address using a registered protocol handler. +---@param fd number Socket file descriptor +---@param address string Remote address +---@return boolean|nil success +---@return string|nil error Error code on failure +function syscall.connect(fd, address) end + +---Starts listening on a socket. +---@param fd number Socket file descriptor +---@param backlog? number Maximum pending connections +---@return any result +---@return string|nil error Error code on failure +function syscall.listen(fd, backlog) end + +---Sends data through a connected socket. +---@param fd number Socket file descriptor +---@param data string Data to send +---@return any result +---@return string|nil error Error code on failure +function syscall.send(fd, data) end + +---Receives data from a connected socket. +---May yield while waiting for data. +---@param fd number Socket file descriptor +---@param amount? number Maximum amount of data to receive +---@return string|nil data Received data +---@return string|nil error Error code on failure +function syscall.recv(fd, amount) end + +---Shuts down a socket connection. +---@param fd number Socket file descriptor +---@return boolean|nil success +---@return string|nil error Error code on failure +function syscall.sockshutdown(fd) end + +---Returns the registered socket protocol prefixes. +---@return string[] endpoints +function syscall.socketendpoints() end + +--#endregion socket + +--#region auth + +---@class PasswdEntry +---@field uid number User ID +---@field gid number Group ID +---@field username string Username +---@field homedir string Home directory +---@field shell string Login shell + +---@class UserInfo: PasswdEntry +---@field locked boolean Whether the account is locked + +---Authenticates a user and sets the current task's user and group IDs. +---@param uid number User ID +---@param password string Password +---@return boolean|nil success +---@return string|nil error +function syscall.login(uid, password) end + +---Changes a user's password. +---Root can change any user's password; users can change their own. +---@param uid number User ID +---@param newPassword string New password (minimum 6 characters) +---@return boolean|nil success +---@return string|nil error +function syscall.setpassword(uid, newPassword) end + +---Changes a user's username. Root only. +---@param uid number User ID +---@param newUsername string New username +---@return boolean|nil success +---@return string|nil error +function syscall.setusername(uid, newUsername) end + +---Creates a new user account. Root only. +---@param username string Username +---@param password string Password (minimum 6 characters) +---@param gid? number Group ID (defaults to the new UID) +---@param homedir? string Home directory (defaults to /home/username) +---@param shell? string Login shell (defaults to /bin/hysh) +---@return number|nil uid New user ID +---@return string|nil error +function syscall.newuser(username, password, gid, homedir, shell) end + +---Returns the current user's username. +---@return string|nil username +---@return string|nil error +function syscall.whoami() end + +---Gets a user's UID by username. +---@param username string Username +---@return number|nil uid +function syscall.getuidbyname(username) end + +---Gets a user's passwd information. +---@param uid number User ID +---@return PasswdEntry|nil entry +function syscall.getpasswd(uid) end + +---Elevates the current task to root after authenticating another account. +---@param targetUsername string Username to authenticate against +---@param password string Account password +---@return boolean|nil success +---@return number|string|nil previousUidOrError +function syscall.elevate(targetUsername, password) end + +---Deletes a user account. Root only. Cannot delete UID 0. +---@param uid number User ID +---@return boolean|nil success +---@return string|nil error +function syscall.deleteuser(uid) end + +---Locks a user account. Root only. Cannot lock UID 0. +---@param uid number User ID +---@return boolean|nil success +---@return string|nil error +function syscall.lockuser(uid) end + +---Unlocks a user account. Root only. +---@param uid number User ID +---@return boolean|nil success +---@return string|nil error +function syscall.unlockuser(uid) end + +---Lists all user accounts. +---@return UserInfo[] users +function syscall.listusers() end + +---Changes a user's login shell. +---Root or the account owner can change it. +---@param uid number User ID +---@param shell string Shell path +---@return boolean|nil success +---@return string|nil error +function syscall.setshell(uid, shell) end + +---Changes a user's home directory. Root only. +---@param uid number User ID +---@param homedir string Home directory path +---@return boolean|nil success +---@return string|nil error +function syscall.sethomedir(uid, homedir) end + +---Changes a user's primary group ID. Root only. +---@param uid number User ID +---@param gid number New group ID +---@return boolean|nil success +---@return string|nil error +function syscall.setgid(uid, gid) end + +--#endregion auth + +--#region hpv + +---@class TaskInfo +---@field name string Task name or executable path +---@field status string Current task state (R=running, S=sleeping, D=waiting for I/O, T=stopped, ST=stopped while sleeping, Z=exited) +---@field pid number Unique process/task identifier +---@field tgid number Thread group identifier +---@field username string|nil Username associated with the task's real UID +---@field uid number Real user ID +---@field euid number Effective user ID used for permission checks +---@field exit number|nil Exit code, if the task has exited +---@field sleep number Sleep deadline in milliseconds +---@field ivs number Internal virtual scheduling value +---@field vs number Virtual scheduling value +---@field children number[] PIDs of child tasks +---@field siblings number[] PIDs of tasks sharing the same parent +---@field parent number PID of the parent task +---@field cwd string Current working directory + +---Create a new task running a Lua function. +---@param func fun(...: any): any Function executed by the new task +---@param name? string Task name; defaults to an automatically generated name +---@param envars? table Environment variables inherited by the task +---@param args? any[] Arguments passed to the function +---@param tgid? number Thread group ID; defaults to the current task's group +---@param clearFds? boolean If true, do not inherit the current task's file descriptors +---@return number pid PID of the newly created task +function syscall.spawn(func, name, envars, args, tgid, clearFds) end + +---Create a new task by loading and executing a Lua executable file. +---@param path string Path to the executable +---@param name? string Task name; defaults to the executable path +---@param envars? table Environment variables for the new task +---@param args? any[] Arguments passed to the executable +---@param tgid? number Thread group ID; defaults to the current task's group +---@param keepFds? boolean If true, inherit the current task's file descriptors +---@return number pid PID of the newly created task +function syscall.execspawn(path, name, envars, args, tgid, keepFds) end + +---Replace the current task's program with another executable. +---@param path string Path to the executable +---@param args? any[] Arguments passed to the executable +---@param envars? table Environment variables for the executable +---@param clearFds? boolean If true, close file descriptors greater than 2 before execution +function syscall.exec(path, args, envars, clearFds) end + +---Suspend the current task for the specified number of seconds. +---@param seconds number Duration to sleep +function syscall.sleep(seconds) end + +---Retrieve information about a task by its PID. +---@param pid number PID of the task to inspect +---@return TaskInfo|nil task Task information, or nil if the task does not exist +function syscall.getTask(pid) end + +---Collect the exit status of a child task that has finished. +---@param pid number PID of the child task +---@return boolean success Whether collection succeeded +---@return number|string|nil exitCodeOrError Exit code on success, or an error message on failure +function syscall.collect(pid) end + +---Terminate a task. +---@param pid number PID of the task to terminate +---@param force? boolean Allow termination of a task waiting for I/O +---@return boolean success Whether the task was terminated +---@return string|nil error Error message if termination failed +function syscall.kill(pid, force) end + +---Stop a running or sleeping task. +---@param pid number PID of the task to stop +---@return boolean success Whether the task was stopped +---@return string|nil error Error message if stopping failed +function syscall.stop(pid) end + +---Resume a previously stopped task. +---@param pid number PID of the task to resume +---@return boolean success Whether the task was resumed +---@return string|nil error Error message if resuming failed +function syscall.continue(pid) end + +---Get the PID of the currently running task. +---@return number pid Current task PID +function syscall.getpid() end + +---Get the PID of the current task's parent. +---@return number pid Parent task PID +function syscall.getppid() end + +---Get the PIDs of all currently tracked tasks. +---@return number[] pids List of task PIDs +function syscall.getTasks() end + +---Retrieve an environment variable from the current task. +---@param key string Environment variable name +---@return any value Environment variable value, or nil if unset +function syscall.getEnviron(key) end + +---Set an environment variable for the current task. +---@param key string Environment variable name +---@param value any Value to assign +function syscall.setEnviron(key, value) end + +---Exit the current task. +---@param code? number Optional numeric exit code +function syscall.exit(code) end + +---Set the real and effective user IDs of the current task. +---@param uid number User ID to assign; requires effective root privileges unless setting the real UID to its existing value +function syscall.setuid(uid) end + +---Get the real user ID of the current task. +---@return number uid Current task's real UID +function syscall.getuid() end + +---Get the effective user ID of the current task. +---@return number euid Current task's effective UID +function syscall.geteuid() end + +--#endregion hpv + +--#region gpio + +---@param pin number|string GPIO pin identifier +---@param data any Value to write +---@return any result +function syscall.gpio_write(pin, data) end + +---@param pin number|string GPIO pin identifier +---@param data number Analog value to write +---@return any result +function syscall.gpio_writeAnalog(pin, data) end + +---@param pin number|string GPIO pin identifier +---@return any value +function syscall.gpio_read(pin) end + +---@param pin number|string GPIO pin identifier +---@return number|nil value +function syscall.gpio_readAnalog(pin) end + +--#endregion gpio + +--#endregion syscalls + + + +--#region globals + +---@class DataList +---@field contents table +---@field push fun(self: DataList, ...: any) +---@field pop fun(self: DataList): any + +--- Rounds a number to the nearest integer. +--- @param x number +--- @return integer +function math.round(x) end + +--- Checks whether a string ends with a suffix. +--- @param str string +--- @param suffix string +--- @return boolean +function string.hasSuffix(str, suffix) end + +--- Checks whether a string starts with a prefix. +--- @param str string +--- @param prefix string +--- @return boolean +function string.hasPrefix(str, prefix) end + +--- Returns the part of a string after the given prefix. +--- @param str string +--- @param prefix string +--- @return string +function string.getSuffix(str, prefix) end + +--- Returns the part of a string before the given suffix. +--- @param str string +--- @param suffix string +--- @return string +function string.getPrefix(str, suffix) end + +--- Joins multiple values into a string. +--- @param str string First value +--- @param ... any Additional values +--- @return string +function string.join(str, ...) end + +--- Joins multiple values using a delimiter. +--- @param str string Delimiter +--- @param ... any Values to join +--- @return string +function string.delim(str, ...) end + +--- Splits a string using a single-character delimiter. +--- @param str string +--- @param delim string Single-character delimiter +--- @param maxResultCountOrNil? number Maximum number of results +--- @return string[]|false +function string.split(str, delim, maxResultCountOrNil) end + +--- Creates a deep copy of a value, preserving circular references. +--- @generic T +--- @param orig T +--- @param copies? table +--- @return T +function table.deepcopy(orig, copies) end + +--- Returns the value stored at the matching key, or false. +--- @param tabl table +--- @param query any +--- @return any|false +function table.hasKey(tabl, query) end + +--- Returns the key associated with a matching value, or false. +--- @param tabl table +--- @param query any +--- @return any|false +function table.hasVal(tabl, query) end + +--- Creates a read-only proxy for a table. +--- @param tabl table +--- @param typ? string Custom type name +--- @return table +function table.readOnly(tabl, typ) end + +--- Serializes a table into a Lua-style table representation. +--- @param tbl table +--- @return string +function table.serialize(tbl) end + +--- Returns the type of an object, optionally returning its original Lua type. +--- @param object any +--- @param trueType? boolean Use the original Lua type +--- @return string +function type(object, trueType) end + +--- Gets the metatable of an object, respecting custom user metatables. +--- @param object any +--- @return table|nil +function getmetatable(object) end + +--- Checks whether a value equals any of the supplied values. +--- @param a any +--- @param ... any Values to compare +--- @return boolean +function isEqualToAny(a, ...) end + +--- Checks whether a value equals all of the supplied values. +--- @param a any +--- @param ... any Values to compare +--- @return boolean +function isEqualToAll(a, ...) end + +--- Returns all keys in a table. +--- @param t table +--- @return any[] +function table.keys(t) end + +--- Returns all values in a table. +--- @param t table +--- @return any[] +function table.values(t) end + +--- Returns the index of a value in an array, or -1 if not found. +--- @param t table +--- @param value any +--- @return integer +function table.indexOf(t, value) end + +--- Merges multiple tables into one table. +--- @param ... table Tables to merge +--- @return table +function table.merge(...) end + +--- Replaces occurrences of a substring. +--- @param s string +--- @param target string +--- @param repl string +--- @return string +function string.replace(s, target, repl) end + +--- Converts a number to a hexadecimal string. +--- @param num number +--- @return string +function toHex(num) end + +--- Creates a stack. +--- @return DataList +function stack() end + +--- Creates a queue. +--- @return DataList +function queue() end + +---Loads a module from the configured search paths. +---Modules are cached and returned through a read-only wrapper. +---@param module string Module name or path +---@vararg any Arguments passed to the module's loader +---@return table module Read-only module wrapper +function require(module, ...) end + +---Sleep the current task for a number of seconds. +---@param seconds number +function sleep(seconds) end + +---@param ... any Values to print, separated by tabs +function print(...) end + +---@param fmt string Format string +---@param ... any Format arguments +function printf(fmt, ...) end + +---@param ... any Values to print inline, separated by tabs +function printInline(...) end + +---@param fd? number Input file descriptor (defaults to 0) +---@param helpstr? string Prompt displayed before reading +---@param replacestr? string Replacement text echoed for each input +---@param fdo? number Output file descriptor used for echo (defaults to 1) +---@return string input +function userinput(fd, helpstr, replacestr, fdo) end + +--#endregion globals \ No newline at end of file