working on api docs
This commit is contained in:
1 parent
56d8fb2016
commit
38d56ced19
43 files changed
+5669
-618
No files matched your search
+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"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user