working on api docs
This commit is contained in:
1 parent
56d8fb2016
commit
38d56ced19
42 files changed
+5627
-576
No files matched your search
Vendored
+4
-12
@@ -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": []
|
||||
}
|
||||
@@ -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,10 +266,19 @@ 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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -230,7 +230,6 @@ function sys.getTask(pid)
|
||||
siblings = siblings,
|
||||
parent = task.parent.pid,
|
||||
cwd = task.cwd,
|
||||
term = task.term,
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
@@ -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 inp and inp ~= "" then
|
||||
if inp == "\n" then
|
||||
break
|
||||
end
|
||||
if replacestr then
|
||||
syscall.write(fdo, replacestr)
|
||||
else
|
||||
syscall.write(fdo, inp)
|
||||
end
|
||||
str = inp
|
||||
else
|
||||
break
|
||||
end
|
||||
str = str .. inp
|
||||
end
|
||||
end
|
||||
return str
|
||||
|
||||
@@ -7,6 +7,8 @@ kernel.processes.kgc = function()
|
||||
-- kernel.reqcache[i] = nil
|
||||
-- end
|
||||
--end
|
||||
|
||||
|
||||
sleep(5)
|
||||
end
|
||||
end
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
Hyperion
|
||||
Astronand
|
||||
@@ -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)
|
||||
@@ -0,0 +1 @@
|
||||
Hyperion-core
|
||||
@@ -0,0 +1 @@
|
||||
simple wget command
|
||||
@@ -0,0 +1 @@
|
||||
1.0.0
|
||||
+669
-532
File diff suppressed because it is too large.
Load diff
@@ -4,7 +4,7 @@ The /boot/boot.cfg file contains configs for booting
|
||||
|
||||
```
|
||||
initPath<String>
|
||||
path that init takes to load the init system (systemd)
|
||||
path that init takes to load the init system
|
||||
|
||||
allowGloabalOverwrites<bool>
|
||||
allow modifying of gloabal env (usually for debug purposes)
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
--#region userspace
|
||||
syscall={}
|
||||
|
||||
|
||||
--#endregion userspace
|
||||
|
||||
--#region kernel
|
||||
|
||||
--#endregion kernel
|
||||
+1
@@ -0,0 +1 @@
|
||||
../luamin/bin/luamin
|
||||
+1
@@ -0,0 +1 @@
|
||||
../luaparse/bin/luaparse
|
||||
+28
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
Copyright Mathias Bynens <https://mathiasbynens.be/>
|
||||
|
||||
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.
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
# luamin, a Lua minifier written in JavaScript
|
||||
|
||||
[](https://travis-ci.org/mathiasbynens/luamin) [](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
|
||||
<script src="luamin.js"></script>
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
| [](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.
|
||||
+113
@@ -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();
|
||||
}
|
||||
|
||||
}());
|
||||
+671
@@ -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));
|
||||
+76
@@ -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 <snippet>"
|
||||
Print minified version of the given Lua snippet.
|
||||
.It Sy "-f, --file <file>"
|
||||
Print minified version of the given Lua file.
|
||||
.It Sy "-a, --ast <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 <https://github.com/mathiasbynens/luamin/issues>.
|
||||
.Sh AUTHOR
|
||||
Mathias Bynens <https://mathiasbynens.be/>
|
||||
.Sh WWW
|
||||
<https://mths.be/luamin>
|
||||
+48
@@ -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"
|
||||
}
|
||||
}
|
||||
+20
@@ -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.
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
# luaparse [](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
|
||||
<script src="luaparse.js"></script>
|
||||
<script>
|
||||
var ast = luaparse.parse('i = 0');
|
||||
console.log(JSON.stringify(ast));
|
||||
</script>
|
||||
```
|
||||
|
||||
## 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: "<eof>", line: 1, lineStart: 0, range: [11 11] }
|
||||
parser.lex(); // { type: 1, value: "<eof>", 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
|
||||
+120
@@ -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 : */
|
||||
+2105
File diff suppressed because it is too large.
Load diff
+48
@@ -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 <public@oxy.fi> (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"
|
||||
}
|
||||
}
|
||||
Generated
+33
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"luamin": "^1.0.4"
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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<string, LoopDeviceInfo> 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
|
||||
@@ -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
|
||||
@@ -0,0 +1,6 @@
|
||||
---@meta
|
||||
---@class HyperionOS
|
||||
---@field version "1.2.5"
|
||||
|
||||
---@type HyperionOS.userspace.syscall
|
||||
syscall={}
|
||||
@@ -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<string, any> 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<string, any> 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<string, any> 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
|
||||
Reference in new issue
Block a user