working on api docs

This commit is contained in:
Astronand committed 2026-11-26 21:06:36 -05:00
1 parent 56d8fb2016
commit 38d56ced19
43 files changed
+5669 -618

No files matched your search

Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../luamin/bin/luamin
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../luaparse/bin/luaparse
+28
View File
@@ -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
View File
@@ -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
View File
@@ -0,0 +1,115 @@
# luamin, a Lua minifier written in JavaScript
[![Build status](https://travis-ci.org/mathiasbynens/luamin.svg?branch=master)](https://travis-ci.org/mathiasbynens/luamin) [![Dependency status](https://gemnasium.com/mathiasbynens/luamin.svg)](https://gemnasium.com/mathiasbynens/luamin)
luamin uses the excellent [luaparse](https://oxyc.github.io/luaparse/) library to parse Lua code into an Abstract Syntax Tree. Based on that AST, luamin then generates a (hopefully) more compact yet semantically equivalent Lua program. [Here’s an online demo.](https://mothereff.in/lua-minifier)
luamin was inspired by the [LuaMinify](https://github.com/stravant/LuaMinify) and [Esmangle](https://github.com/Constellation/esmangle) projects.
Feel free to fork if you see possible improvements!
## Installation and usage
Via [npm](https://www.npmjs.com/):
```bash
npm install luamin
```
Via [Bower](http://bower.io/):
```bash
bower install luamin
```
Via [Component](https://github.com/component/component):
```bash
component install mathiasbynens/luamin
```
In a browser:
```html
<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
| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |
## License
luamin is available under the [MIT](https://mths.be/mit) license.
+113
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -0,0 +1,274 @@
# luaparse [![Build Status](https://travis-ci.org/oxyc/luaparse.svg)](https://travis-ci.org/oxyc/luaparse)
A Lua parser written in JavaScript, for my bachelor's thesis at Arcada.
## Installation
Install through `bower install luaparse` or `npm install luaparse`.
## Usage
CommonJS
```js
var parser = require('luaparse');
var ast = parser.parse('i = 0');
console.log(JSON.stringify(ast));
```
AMD
```js
require(['luaparse'], function(parser) {
var ast = parser.parse('i = 0');
console.log(JSON.stringify(ast));
});
```
Browser
```html
<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
View File
@@ -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
View File
File diff suppressed because it is too large. Load diff
+48
View File
@@ -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"
}
}