nodes: introduced a notion of levels that streamlines parenthesizations

This commit is contained in:
satyr 2010-10-23 10:44:03 +09:00
parent 1130f4fef5
commit b82f495ec7
7 changed files with 232 additions and 248 deletions

View File

@ -6,7 +6,7 @@
return eval(CoffeeScript.compile(code, options));
};
CoffeeScript.run = function(code, options) {
(options != null) ? options.bare = true : undefined;
options != null ? options.bare = true : undefined;
return Function(CoffeeScript.compile(code, options))();
};
if (!(typeof window !== "undefined" && window !== null)) {

View File

@ -555,13 +555,13 @@
Operation: [
o('UNARY Expression', function() {
return new Op($1, $2);
}), o('- Expression', function() {
}), o('- Expression', (function() {
return new Op('-', $2);
}, {
}), {
prec: 'UNARY'
}), o('+ Expression', function() {
}), o('+ Expression', (function() {
return new Op('+', $2);
}, {
}), {
prec: 'UNARY'
}), o('-- SimpleAssignable', function() {
return new Op('--', $2);

View File

@ -197,7 +197,7 @@
if (match = HEREGEX.exec(this.chunk)) {
return this.heregexToken(match);
}
if ((_ref2 = this.tag(), __indexOf.call(NOT_REGEX, _ref2) >= 0)) {
if (_ref2 = this.tag(), __indexOf.call(NOT_REGEX, _ref2) >= 0) {
return 0;
}
if (!(match = REGEX.exec(this.chunk))) {
@ -236,7 +236,7 @@
tokens.push(['+', '+']);
}
tokens.pop();
if ((((_ref3 = tokens[0]) != null) ? _ref3[0] : undefined) !== 'STRING') {
if (((_ref3 = tokens[0]) != null ? _ref3[0] : undefined) !== 'STRING') {
this.tokens.push(['STRING', '""'], ['+', '+']);
}
(_this = this.tokens).push.apply(_this, tokens);
@ -366,7 +366,7 @@
tag = 'UNARY';
} else if (__indexOf.call(SHIFT, value) >= 0) {
tag = 'SHIFT';
} else if (__indexOf.call(LOGIC, value) >= 0 || value === '?' && ((prev != null) ? prev.spaced : undefined)) {
} else if (__indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : undefined)) {
tag = 'LOGIC';
} else if (prev && !prev.spaced) {
if (value === '(' && (_ref4 = prev[0], __indexOf.call(CALLABLE, _ref4) >= 0)) {
@ -568,11 +568,11 @@
};
Lexer.prototype.tag = function(index, tag) {
var tok;
return (tok = last(this.tokens, index)) && ((tag != null) ? tok[0] = tag : tok[0]);
return (tok = last(this.tokens, index)) && (tag != null ? tok[0] = tag : tok[0]);
};
Lexer.prototype.value = function(index, val) {
var tok;
return (tok = last(this.tokens, index)) && ((val != null) ? tok[1] = val : tok[1]);
return (tok = last(this.tokens, index)) && (val != null ? tok[1] = val : tok[1]);
};
Lexer.prototype.unfinished = function() {
var prev, value;
@ -586,7 +586,7 @@
return quote + quote;
}
body = body.replace(/\\([\s\S])/g, function(match, contents) {
return (contents === '\n' || contents === quote) ? contents : match;
return contents === '\n' || contents === quote ? contents : match;
});
body = body.replace(RegExp("" + quote, "g"), '\\$&');
return quote + this.escapeLines(body, heredoc) + quote;
@ -595,7 +595,7 @@
})();
JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'if', 'else', 'switch', 'for', 'while', 'try', 'catch', 'finally', 'class', 'extends', 'super'];
COFFEE_KEYWORDS = ['then', 'unless', 'until', 'loop', 'of', 'by', 'when'];
for (op in (COFFEE_ALIASES = {
for (op in COFFEE_ALIASES = {
and: '&&',
or: '||',
is: '==',
@ -605,7 +605,7 @@
no: 'FALSE',
on: 'TRUE',
off: 'FALSE'
})) {
}) {
COFFEE_KEYWORDS.push(op);
}
RESERVED = ['case', 'default', 'do', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', '__hasProp', '__extends', '__slice'];

View File

@ -1,5 +1,5 @@
(function() {
var Accessor, ArrayLiteral, Assign, Base, Call, Class, Closure, Code, Comment, Existence, Expressions, Extends, For, IDENTIFIER, IS_STRING, If, In, Index, Literal, NO, NUMBER, ObjectLiteral, Op, Param, Parens, Push, Return, SIMPLENUM, Scope, Splat, Switch, TAB, THIS, TRAILING_WHITESPACE, Throw, Try, UTILITIES, Value, While, YES, _ref, compact, del, ends, extend, flatten, last, merge, starts, utility;
var Accessor, ArrayLiteral, Assign, Base, Call, Class, Closure, Code, Comment, Existence, Expressions, Extends, For, IDENTIFIER, IS_STRING, If, In, Index, LVL_ACCESS, LVL_ASSIGN, LVL_COND, LVL_LIST, LVL_OP, LVL_PAREN, LVL_TOP, Literal, NO, NUMBER, ObjectLiteral, Op, Param, Parens, Push, Return, SIMPLENUM, Scope, Splat, Switch, TAB, THIS, TRAILING_WHITESPACE, Throw, Try, UTILITIES, Value, While, YES, _ref, compact, del, ends, extend, flatten, last, merge, starts, utility;
var __extends = function(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
@ -30,10 +30,13 @@
};
return Base;
})();
Base.prototype.compile = function(o) {
Base.prototype.compile = function(o, lvl) {
var top;
o = o ? merge(o) : {};
top = this.topSensitive() ? o.top : del(o, 'top');
o = o ? extend({}, o) : {};
if (lvl) {
o.level = lvl;
}
top = this.topSensitive ? o.top : del(o, 'top');
this.tab = o.indent;
return top || o.asStatement || this instanceof Comment || this.isPureStatement() || !this.isStatement(o) ? this.compileNode(o) : this.compileClosure(o);
};
@ -42,34 +45,22 @@
throw SyntaxError('cannot include a pure statement in an expression.');
}
o.sharedScope = o.scope;
return Closure.wrap(this).compile(o);
return Closure.wrap(this).compileNode(o);
};
Base.prototype.compileReference = function(o, options) {
var _len, compiled, i, node, pair, reference;
pair = (function() {
if (!this.isComplex()) {
return [this, this];
} else {
reference = new Literal(o.scope.freeVariable('ref'));
compiled = new Assign(reference, this);
return [compiled, reference];
}
}).call(this);
if ((options != null) ? options.precompile : undefined) {
for (i = 0, _len = pair.length; i < _len; i++) {
node = pair[i];
(pair[i] = node.compile(o));
}
Base.prototype.cache = function(o, lvl) {
var ref, sub;
if (!this.isComplex()) {
ref = lvl ? this.compile(o, lvl) : this;
return [ref, ref];
} else {
ref = new Literal(o.scope.freeVariable('ref'));
sub = new Assign(ref, this);
return lvl ? [sub.compile(o, lvl), ref.value] : [sub, ref];
}
return pair;
};
Base.prototype.compileBare = function(o) {
this.parenthetical = true;
return this.compile(o);
};
Base.prototype.compileLoopReference = function(o, name) {
var src, tmp;
src = tmp = this.compile(o);
src = tmp = this.compile(o, LVL_ASSIGN);
if (!(NUMBER.test(src) || IDENTIFIER.test(src) && o.scope.check(src, {
immediate: true
}))) {
@ -164,7 +155,7 @@
Base.prototype.isPureStatement = NO;
Base.prototype.isComplex = YES;
Base.prototype.isChainable = NO;
Base.prototype.topSensitive = NO;
Base.prototype.topSensitive = false;
Base.prototype.unfoldSoak = NO;
Base.prototype.assigns = NO;
return Base;
@ -207,9 +198,9 @@
}
return this;
};
Expressions.prototype.compile = function(o) {
Expressions.prototype.compile = function(o, lvl) {
o || (o = {});
return o.scope ? Expressions.__super__.compile.call(this, o) : this.compileRoot(o);
return o.scope ? Expressions.__super__.compile.call(this, o, lvl) : this.compileRoot(o);
};
Expressions.prototype.compileNode = function(o) {
var _i, _len, _ref2, _result, node;
@ -227,6 +218,7 @@
var code;
o.indent = this.tab = o.bare ? '' : TAB;
o.scope = new Scope(null, this, null);
o.level = LVL_TOP;
code = this.compileWithDeclarations(o);
code = code.replace(TRAILING_WHITESPACE, '');
return o.bare ? code : "(function() {\n" + code + "\n}).call(this);\n";
@ -303,10 +295,10 @@
Return.prototype.isStatement = YES;
Return.prototype.isPureStatement = YES;
Return.prototype.makeReturn = THIS;
Return.prototype.compile = function(o) {
Return.prototype.compile = function(o, lvl) {
var _ref2, expr;
expr = ((_ref2 = this.expression) != null) ? _ref2.makeReturn() : undefined;
return expr && !(expr instanceof Return) ? expr.compile(o) : Return.__super__.compile.call(this, o);
expr = (_ref2 = this.expression) != null ? _ref2.makeReturn() : undefined;
return expr && !(expr instanceof Return) ? expr.compile(o, lvl) : Return.__super__.compile.call(this, o, lvl);
};
Return.prototype.compileNode = function(o) {
var expr;
@ -315,7 +307,7 @@
if (this.expression.isStatement(o)) {
o.asStatement = true;
}
expr = ' ' + this.expression.compileBare(o);
expr = ' ' + this.expression.compile(o, LVL_PAREN);
}
return this.tab + 'return' + expr + ';';
};
@ -381,7 +373,7 @@
Value.prototype.cacheReference = function(o) {
var base, bref, name, nref;
name = last(this.properties);
if (this.properties.length < 2 && !this.base.isComplex() && !((name != null) ? name.isComplex() : undefined)) {
if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : undefined)) {
return [this, this];
}
base = new Value(this.base, this.properties.slice(0, -1));
@ -399,9 +391,9 @@
}
return [base.push(name), new Value(bref || base.base, [nref || name])];
};
Value.prototype.compile = function(o) {
Value.prototype.compile = function(o, lvl) {
this.base.tags.front = this.tags.front;
return !o.top || this.properties.length ? Value.__super__.compile.call(this, o) : this.base.compile(o);
return !o.top || this.properties.length ? Value.__super__.compile.call(this, o, lvl) : this.base.compile(o, lvl);
};
Value.prototype.compileNode = function(o) {
var _i, _len, code, ifn, prop, props;
@ -409,16 +401,13 @@
return ifn.compile(o);
}
props = this.properties;
if (this.parenthetical && !props.length) {
this.base.parenthetical = true;
}
code = this.base.compile(o);
code = this.base.compile(o, props.length && LVL_ACCESS);
if (props[0] instanceof Accessor && this.isSimpleNumber()) {
code = "(" + code + ")";
}
for (_i = 0, _len = props.length; _i < _len; _i++) {
prop = props[_i];
(code += prop.compile(o));
(code += prop.compileNode(o));
}
return code;
};
@ -441,8 +430,7 @@
snd.base = ref;
}
return new If(new Existence(fst), snd, {
soak: true,
operation: this.tags.operation
soak: true
});
}
}
@ -493,9 +481,6 @@
this.isNew = true;
return this;
};
Call.prototype.prefix = function() {
return this.isNew ? 'new ' : '';
};
Call.prototype.superReference = function(o) {
var method, name;
method = o.scope.method;
@ -524,8 +509,7 @@
rite.isNew = this.isNew;
left = new Literal("typeof " + (left.compile(o)) + " === \"function\"");
return new If(left, new Value(rite), {
soak: true,
operation: this.tags.operation
soak: true
});
}
call = this;
@ -563,7 +547,7 @@
if (ifn = this.unfoldSoak(o)) {
return ifn.compile(o);
}
((_ref2 = this.variable) != null) ? _ref2.tags.front = this.tags.front : undefined;
(_ref2 = this.variable) != null ? _ref2.tags.front = this.tags.front : undefined;
_ref3 = this.args;
for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
arg = _ref3[_i];
@ -576,11 +560,11 @@
_result = [];
for (_j = 0, _len2 = _ref4.length; _j < _len2; _j++) {
arg = _ref4[_j];
_result.push(arg.compileBare(o));
_result.push(arg.compile(o, LVL_LIST));
}
return _result;
}).call(this).join(', ');
return this.isSuper ? this.compileSuper(args, o) : "" + (this.prefix()) + (this.variable.compile(o)) + "(" + args + ")";
return this.isSuper ? this.compileSuper(args, o) : (this.isNew ? 'new ' : '') + this.variable.compile(o, LVL_ACCESS) + ("(" + args + ")");
};
Call.prototype.compileSuper = function(args, o) {
return "" + (this.superReference(o)) + ".call(this" + (args.length ? ', ' : '') + args + ")";
@ -595,17 +579,17 @@
base = Value.wrap(this.variable);
if ((name = base.properties.pop()) && base.isComplex()) {
ref = o.scope.freeVariable('this');
fun = "(" + ref + " = " + (base.compile(o)) + ")" + (name.compile(o));
fun = "(" + ref + " = " + (base.compile(o, LVL_ASSIGN)) + ")" + (name.compileNode(o));
} else {
fun = ref = base.compile(o);
fun = ref = base.compile(o, LVL_ACCESS);
if (name) {
fun += name.compile(o);
fun += name.compileNode(o);
}
}
return "" + fun + ".apply(" + ref + ", " + splatargs + ")";
}
idt = this.idt(1);
return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args);\n" + idt + "return typeof result === \"object\" ? result : child;\n" + this.tab + "})(" + (this.variable.compile(o)) + ", " + splatargs + ", function() {})";
return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args);\n" + idt + "return typeof result === \"object\" ? result : child;\n" + this.tab + "})(" + (this.variable.compile(o, LVL_LIST)) + ", " + splatargs + ", function() {})";
};
return Call;
})();
@ -631,7 +615,7 @@
function Accessor(_arg, tag) {
this.name = _arg;
Accessor.__super__.constructor.call(this);
this.prototype = tag === 'prototype' ? '.prototype' : '';
this.proto = tag === 'prototype' ? '.prototype' : '';
this.soakNode = tag === 'soak';
return this;
};
@ -642,7 +626,7 @@
Accessor.prototype.compileNode = function(o) {
var name;
name = this.name.compile(o);
return this.prototype + (IS_STRING.test(name) ? "[" + name + "]" : "." + name);
return this.proto + (IS_STRING.test(name) ? "[" + name + "]" : "." + name);
};
Accessor.prototype.isComplex = NO;
return Accessor;
@ -659,7 +643,7 @@
__extends(Index, Base);
Index.prototype.children = ['index'];
Index.prototype.compileNode = function(o) {
return (this.proto ? '.prototype' : '') + ("[" + (this.index.compileBare(o)) + "]");
return (this.proto ? '.prototype' : '') + ("[" + (this.index.compile(o, LVL_PAREN)) + "]");
};
Index.prototype.isComplex = function() {
return this.index.isComplex();
@ -756,8 +740,8 @@
_ref3 = this.objects;
for (i = 0, _len2 = _ref3.length; i < _len2; i++) {
obj = _ref3[i];
code = obj.compileBare(o);
objects.push(obj instanceof Comment ? "\n" + code + "\n" + o.indent : i === this.objects.length - 1 ? code : code + ', ');
code = obj.compile(o, LVL_LIST);
objects.push((obj instanceof Comment ? "\n" + code + "\n" + o.indent : i === this.objects.length - 1 ? code : code + ', '));
}
objects = objects.join('');
return 0 < objects.indexOf('\n') ? "[\n" + o.indent + objects + "\n" + this.tab + "]" : "[" + objects + "]";
@ -818,7 +802,7 @@
pvar = prop.variable, func = prop.value;
if (pvar && pvar.base.value === 'constructor') {
if (!(func instanceof Code)) {
_ref3 = func.compileReference(o), func = _ref3[0], ref = _ref3[1];
_ref3 = func.cache(o), func = _ref3[0], ref = _ref3[1];
if (func !== ref) {
props.push(func);
}
@ -888,7 +872,7 @@
Assign.prototype.METHOD_DEF = /^(?:(\S+)\.prototype\.)?([$A-Za-z_][$\w]*)$/;
Assign.prototype.CONDITIONAL = ['||=', '&&=', '?='];
Assign.prototype.children = ['variable', 'value'];
Assign.prototype.topSensitive = YES;
Assign.prototype.topSensitive = true;
Assign.prototype.compileNode = function(o) {
var _ref2, ifn, isValue, match, name, stmt, top, val;
if (isValue = this.variable instanceof Value) {
@ -899,18 +883,18 @@
delete o.top;
return ifn.compile(o);
}
if ((_ref2 = this.context, __indexOf.call(this.CONDITIONAL, _ref2) >= 0)) {
if (_ref2 = this.context, __indexOf.call(this.CONDITIONAL, _ref2) >= 0) {
return this.compileConditional(o);
}
}
top = del(o, 'top');
stmt = del(o, 'asStatement');
name = this.variable.compile(o);
name = this.variable.compile(o, LVL_ASSIGN);
if (this.value instanceof Code && (match = this.METHOD_DEF.exec(name))) {
this.value.name = match[2];
this.value.klass = match[1];
}
val = this.value.compileBare(o);
val = this.value.compile(o, LVL_ASSIGN);
if (this.context === 'object') {
return "" + name + ": " + val;
}
@ -921,7 +905,7 @@
if (stmt) {
return "" + this.tab + val + ";";
}
return top || this.parenthetical ? val : "(" + val + ")";
return top || o.level <= LVL_ASSIGN ? val : "(" + val + ")";
};
Assign.prototype.compilePatternMatch = function(o) {
var _len, _ref2, _ref3, accessClass, assigns, code, i, idx, isObject, obj, objects, olength, otop, ref, splat, top, val, valVar, value;
@ -929,9 +913,7 @@
otop = merge(o, {
top: true
});
if ((value = this.value).isStatement(o)) {
value = Closure.wrap(value);
}
value = this.value;
objects = this.variable.base.objects;
if (!(olength = objects.length)) {
return value.compile(o);
@ -983,7 +965,7 @@
assigns.push(valVar);
}
code = assigns.join(', ');
return top || this.parenthetical ? code : "(" + code + ")";
return top || o.level <= LVL_PAREN ? code : "(" + code + ")";
};
Assign.prototype.compileConditional = function(o) {
var _ref2, left, rite;
@ -1101,7 +1083,7 @@
__extends(Param, Base);
Param.prototype.children = ['name'];
Param.prototype.compileNode = function(o) {
return this.value.compile(o);
return this.value.compile(o, LVL_LIST);
};
Param.prototype.toString = function() {
var name;
@ -1131,7 +1113,7 @@
return this.name.assigns(name);
};
Splat.prototype.compileNode = function(o) {
return (this.index != null) ? this.compileParam(o) : this.name.compile(o);
return this.index != null ? this.compileParam(o) : this.name.compile(o);
};
Splat.prototype.compileParam = function(o) {
var _len, _ref2, assign, end, idx, len, name, pos, trailing, variadic;
@ -1140,7 +1122,7 @@
end = '';
if (this.trailings.length) {
len = o.scope.freeVariable('len');
o.scope.assign(len, "arguments.length");
o.scope.assign(len, 'arguments.length');
variadic = o.scope.freeVariable('result');
o.scope.assign(variadic, len + ' >= ' + this.arglength);
end = this.trailings.length ? ", " + len + " - " + this.trailings.length : undefined;
@ -1169,7 +1151,7 @@
end = -1;
for (i = 0, _len = list.length; i < _len; i++) {
arg = list[i];
code = arg.compile(o);
code = arg.compile(o, LVL_LIST);
prev = args[end];
if (!(arg instanceof Splat)) {
if (prev && starts(prev, '[') && ends(prev, ']')) {
@ -1192,15 +1174,15 @@
While = (function() {
function While(condition, opts) {
While.__super__.constructor.call(this);
this.condition = ((opts != null) ? opts.invert : undefined) ? condition.invert() : condition;
this.guard = (opts != null) ? opts.guard : undefined;
this.condition = (opts != null ? opts.invert : undefined) ? condition.invert() : condition;
this.guard = opts != null ? opts.guard : undefined;
return this;
};
return While;
})();
__extends(While, Base);
While.prototype.children = ['condition', 'guard', 'body'];
While.prototype.topSensitive = YES;
While.prototype.topSensitive = true;
While.prototype.isStatement = YES;
While.prototype.addBody = function(body) {
this.body = body;
@ -1214,7 +1196,7 @@
var cond, post, pre, rvar, set, top;
top = del(o, 'top') && !this.returns;
o.indent = this.idt(1);
cond = this.condition.compileBare(o);
cond = this.condition.compile(o, LVL_PAREN);
o.top = true;
set = '';
if (!top) {
@ -1255,10 +1237,8 @@
}
Op.__super__.constructor.call(this);
this.operator = this.CONVERSIONS[op] || op;
(this.first = first).tags.operation = true;
if (second) {
(this.second = second).tags.operation = true;
}
this.first = first;
this.second = second;
this.flip = !!flip;
return this;
};
@ -1286,7 +1266,7 @@
};
Op.prototype.isChainable = function() {
var _ref2;
return (_ref2 = this.operator, __indexOf.call(this.CHAINABLE, _ref2) >= 0);
return _ref2 = this.operator, __indexOf.call(this.CHAINABLE, _ref2) >= 0;
};
Op.prototype.invert = function() {
var op;
@ -1313,12 +1293,12 @@
return this.compileExistence(o);
}
this.first.tags.front = this.tags.front;
return "" + (this.first.compile(o)) + " " + this.operator + " " + (this.second.compile(o));
return "" + (this.first.compile(o, LVL_OP)) + " " + this.operator + " " + (this.second.compile(o, LVL_OP));
};
Op.prototype.compileChain = function(o) {
var _ref2, shared;
_ref2 = this.first.unwrap().second.compileReference(o), this.first.second = _ref2[0], shared = _ref2[1];
return "" + (this.first.compile(o)) + " && " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o));
_ref2 = this.first.unwrap().second.cache(o), this.first.second = _ref2[0], shared = _ref2[1];
return "" + (this.first.compile(o, LVL_OP)) + " && " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o, LVL_OP));
};
Op.prototype.compileExistence = function(o) {
var fst, ref;
@ -1329,13 +1309,12 @@
fst = this.first;
ref = fst.compile(o);
}
this.second.tags.operation = false;
return new Existence(fst).compile(o) + (" ? " + ref + " : " + (this.second.compileBare(o)));
return new Existence(fst).compile(o) + (" ? " + ref + " : " + (this.second.compile(o, LVL_ASSIGN)));
};
Op.prototype.compileUnary = function(o) {
var _ref2, parts, space;
space = (_ref2 = this.operator, __indexOf.call(this.PREFIX_OPERATORS, _ref2) >= 0) ? ' ' : '';
parts = [this.operator, space, this.first.compile(o)];
parts = [this.operator, space, this.first.compile(o, LVL_OP)];
return (this.flip ? parts.reverse() : parts).join('');
};
return Op;
@ -1361,9 +1340,7 @@
};
In.prototype.compileOrTest = function(o) {
var _len, _ref2, _ref3, _ref4, _result, cmp, cnj, i, item, ref, sub, tests;
_ref2 = this.object.compileReference(o, {
precompile: true
}), sub = _ref2[0], ref = _ref2[1];
_ref2 = this.object.cache(o, LVL_OP), sub = _ref2[0], ref = _ref2[1];
_ref3 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = _ref3[0], cnj = _ref3[1];
tests = (function() {
_ref4 = this.array.base.objects;
@ -1375,17 +1352,17 @@
return _result;
}).call(this);
tests = tests.join(cnj);
return this.parenthetical ? tests : "(" + tests + ")";
return o.level < LVL_OP ? tests : "(" + tests + ")";
};
In.prototype.compileLoopTest = function(o) {
var _ref2, code, ref, sub;
_ref2 = this.object.compileReference(merge(o, {
top: true
}), {
precompile: true
}), sub = _ref2[0], ref = _ref2[1];
_ref2 = this.object.cache(o, LVL_LIST), sub = _ref2[0], ref = _ref2[1];
code = utility('indexOf') + (".call(" + (this.array.compile(o)) + ", " + ref + ") ") + (this.negated ? '< 0' : '>= 0');
return sub === ref ? code : "(" + sub + ", " + code + ")";
if (sub === ref) {
return code;
}
code = sub + ', ' + code;
return o.level < LVL_LIST ? code : "(" + code + ")";
};
In.prototype.toString = function(idt) {
return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : ''));
@ -1461,7 +1438,7 @@
var code;
code = this.expression.compile(o);
code = IDENTIFIER.test(code) && !o.scope.check(code) ? "typeof " + code + " !== \"undefined\" && " + code + " !== null" : "" + code + " != null";
return this.parenthetical ? code : "(" + code + ")";
return o.level <= LVL_COND ? code : "(" + code + ")";
};
return Existence;
})();
@ -1476,7 +1453,7 @@
})();
__extends(Parens, Base);
Parens.prototype.children = ['expression'];
Parens.prototype.topSensitive = YES;
Parens.prototype.topSensitive = true;
Parens.prototype.isStatement = function(o) {
return this.expression.isStatement(o);
};
@ -1494,9 +1471,12 @@
expr.tags.front = this.tags.front;
return expr.compile(o);
}
code = expr.compileBare(o);
if (this.parenthetical || expr.isStatement(o)) {
return top ? this.tab + code + ';' : code;
code = expr.compile(o, LVL_PAREN);
if (o.level < LVL_OP && (expr instanceof Op || expr instanceof Call)) {
return code;
}
if (expr.isStatement(o)) {
return (top ? this.tab + code + ';' : code);
}
return "(" + code + ")";
};
@ -1525,7 +1505,7 @@
})();
__extends(For, Base);
For.prototype.children = ['body', 'source', 'guard', 'step', 'from', 'to'];
For.prototype.topSensitive = YES;
For.prototype.topSensitive = true;
For.prototype.isStatement = YES;
For.prototype.makeReturn = function() {
this.returns = true;
@ -1544,8 +1524,8 @@
var _ref2, _ref3, _ref4, _ref5, _ref6, body, cond, defPart, forPart, guardPart, idt, index, ivar, lvar, name, namePart, pvar, resultRet, rvar, scope, sourcePart, step, svar, tail, top, tvar, varPart, vars;
scope = o.scope;
top = del(o, 'top') && !this.returns;
name = !this.pattern && (((_ref2 = this.name) != null) ? _ref2.compile(o) : undefined);
index = ((_ref3 = this.index) != null) ? _ref3.compile(o) : undefined;
name = !this.pattern && ((_ref2 = this.name) != null ? _ref2.compile(o) : undefined);
index = (_ref3 = this.index) != null ? _ref3.compile(o) : undefined;
ivar = !index ? scope.freeVariable('i') : index;
varPart = '';
body = Expressions.wrap([this.body]);
@ -1662,7 +1642,7 @@
idt1 = this.idt(1);
idt2 = o.indent = this.idt(2);
o.top = true;
code = "" + this.tab + "switch (" + ((((_ref2 = this.subject) != null) ? _ref2.compile(o) : undefined) || true) + ") {";
code = "" + this.tab + "switch (" + (((_ref2 = this.subject) != null ? _ref2.compile(o) : undefined) || true) + ") {";
for (_i = 0, _len = this.cases.length; _i < _len; _i++) {
_ref3 = this.cases[_i], conditions = _ref3[0], block = _ref3[1];
_ref4 = flatten([conditions]);
@ -1701,14 +1681,14 @@
})();
__extends(If, Base);
If.prototype.children = ['condition', 'body', 'elseBody'];
If.prototype.topSensitive = YES;
If.prototype.topSensitive = true;
If.prototype.bodyNode = function() {
var _ref2;
return ((_ref2 = this.body) != null) ? _ref2.unwrap() : undefined;
return (_ref2 = this.body) != null ? _ref2.unwrap() : undefined;
};
If.prototype.elseBodyNode = function() {
var _ref2;
return ((_ref2 = this.elseBody) != null) ? _ref2.unwrap() : undefined;
return (_ref2 = this.elseBody) != null ? _ref2.unwrap() : undefined;
};
If.prototype.addElse = function(elseBody) {
if (this.isChain) {
@ -1721,7 +1701,7 @@
};
If.prototype.isStatement = function(o) {
var _ref2;
return this.statement || (this.statement = ((o != null) ? o.top : undefined) || this.bodyNode().isStatement(o) || (((_ref2 = this.elseBodyNode()) != null) ? _ref2.isStatement(o) : undefined));
return this.statement || (this.statement = (o != null ? o.top : undefined) || this.bodyNode().isStatement(o) || ((_ref2 = this.elseBodyNode()) != null ? _ref2.isStatement(o) : undefined));
};
If.prototype.compileNode = function(o) {
return this.isStatement(o) ? this.compileStatement(o) : this.compileExpression(o);
@ -1745,7 +1725,7 @@
condO = merge(o);
o.indent = this.idt(1);
o.top = true;
ifPart = "if (" + (this.condition.compileBare(condO)) + ") {\n" + (this.body.compile(o)) + "\n" + this.tab + "}";
ifPart = "if (" + (this.condition.compile(condO, LVL_PAREN)) + ") {\n" + (this.body.compile(o)) + "\n" + this.tab + "}";
if (!child) {
ifPart = this.tab + ifPart;
}
@ -1759,9 +1739,8 @@
};
If.prototype.compileExpression = function(o) {
var _ref2, code;
this.condition.tags.operation = true;
code = this.condition.compile(o) + ' ? ' + this.bodyNode().compileBare(o) + ' : ' + (((_ref2 = this.elseBodyNode()) != null) ? _ref2.compileBare(o) : undefined);
return this.tags.operation ? "(" + code + ")" : code;
code = this.condition.compile(o, LVL_COND) + ' ? ' + this.bodyNode().compile(o, LVL_ASSIGN) + ' : ' + ((_ref2 = this.elseBodyNode()) != null ? _ref2.compile(o, LVL_ASSIGN) : undefined);
return o.level >= LVL_COND ? "(" + code + ")" : code;
};
If.prototype.unfoldSoak = function() {
return this.soakNode && this;
@ -1773,9 +1752,6 @@
}
parent[name] = ifn.body;
ifn.body = new Value(parent);
if (parent.tags.operation) {
ifn.tags.operation = true;
}
return ifn;
};
return If;
@ -1822,6 +1798,13 @@
hasProp: 'Object.prototype.hasOwnProperty',
slice: 'Array.prototype.slice'
};
LVL_TOP = 0;
LVL_PAREN = 1;
LVL_LIST = 2;
LVL_ASSIGN = 3;
LVL_COND = 4;
LVL_OP = 5;
LVL_ACCESS = 6;
TAB = ' ';
TRAILING_WHITESPACE = /[ \t]+$/gm;
IDENTIFIER = /^[$A-Za-z_][$\w]*$/;

View File

@ -45,9 +45,9 @@
if (!token || levels < 0) {
return action.call(this, token, i - 1);
}
if ((_ref = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0)) {
if (_ref = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0) {
levels += 1;
} else if ((_ref2 = token[0], __indexOf.call(EXPRESSION_END, _ref2) >= 0)) {
} else if (_ref2 = token[0], __indexOf.call(EXPRESSION_END, _ref2) >= 0) {
levels -= 1;
}
i += 1;
@ -64,15 +64,15 @@
prev = tokens[i - 1];
post = tokens[i + 1];
after = tokens[i + 2];
if (((after != null) ? after[0] : undefined) === 'INDENT') {
if ((after != null ? after[0] : undefined) === 'INDENT') {
tokens.splice(i + 2, 1);
if (((before != null) ? before[0] : undefined) === 'OUTDENT' && ((post != null) ? post[0] : undefined) === 'TERMINATOR') {
if ((before != null ? before[0] : undefined) === 'OUTDENT' && (post != null ? post[0] : undefined) === 'TERMINATOR') {
tokens.splice(i - 2, 1);
} else {
tokens.splice(i, 0, after);
}
} else if (prev && ((_ref = prev[0]) !== 'TERMINATOR' && _ref !== 'INDENT' && _ref !== 'OUTDENT')) {
if (((post != null) ? post[0] : undefined) === 'TERMINATOR' && ((after != null) ? after[0] : undefined) === 'OUTDENT') {
if ((post != null ? post[0] : undefined) === 'TERMINATOR' && (after != null ? after[0] : undefined) === 'OUTDENT') {
tokens.splice.apply(tokens, [i + 2, 0].concat(tokens.splice(i, 2)));
if (tokens[i + 2][0] !== 'TERMINATOR') {
tokens.splice(i + 2, 0, ['TERMINATOR', '\n', prev[2]]);
@ -147,14 +147,14 @@
}
_ref = this.tokens.slice(i + 1, i + 4), one = _ref[0], two = _ref[1], three = _ref[2];
tag = token[0];
return (tag === 'TERMINATOR' || tag === 'OUTDENT') && !(((two != null) ? two[0] : undefined) === ':' || ((one != null) ? one[0] : undefined) === '@' && ((three != null) ? three[0] : undefined) === ':') || tag === ',' && ((_ref2 = (one != null) ? one[0] : undefined) !== 'IDENTIFIER' && _ref2 !== 'NUMBER' && _ref2 !== 'STRING' && _ref2 !== '@' && _ref2 !== 'TERMINATOR' && _ref2 !== 'OUTDENT');
return (tag === 'TERMINATOR' || tag === 'OUTDENT') && !((two != null ? two[0] : undefined) === ':' || (one != null ? one[0] : undefined) === '@' && (three != null ? three[0] : undefined) === ':') || tag === ',' && ((_ref2 = one != null ? one[0] : undefined) !== 'IDENTIFIER' && _ref2 !== 'NUMBER' && _ref2 !== 'STRING' && _ref2 !== '@' && _ref2 !== 'TERMINATOR' && _ref2 !== 'OUTDENT');
};
action = function(token, i) {
return this.tokens.splice(i, 0, ['}', '}', token[2]]);
};
return this.scanTokens(function(token, i, tokens) {
var _ref, idx, tag, tok;
if ((_ref = tag = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0)) {
if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) {
stack.push(tag === 'INDENT' && this.tag(i - 1) === '{' ? '{' : tag);
return 1;
}
@ -201,7 +201,7 @@
if (prev && !prev.spaced && tag === '?') {
token.call = true;
}
if (!(callObject || ((prev != null) ? prev.spaced : undefined) && (prev.call || (_ref2 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref2) >= 0)) && (__indexOf.call(IMPLICIT_CALL, tag) >= 0 || !(token.spaced || token.newLine) && __indexOf.call(IMPLICIT_UNSPACED_CALL, tag) >= 0))) {
if (!(callObject || (prev != null ? prev.spaced : undefined) && (prev.call || (_ref2 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref2) >= 0)) && (__indexOf.call(IMPLICIT_CALL, tag) >= 0 || !(token.spaced || token.newLine) && __indexOf.call(IMPLICIT_UNSPACED_CALL, tag) >= 0))) {
return 1;
}
tokens.splice(i, 0, ['CALL_START', '(', token[2]]);
@ -250,7 +250,7 @@
return token[1] !== ';' && (_ref3 = token[0], __indexOf.call(SINGLE_CLOSERS, _ref3) >= 0) && !(token[0] === 'ELSE' && (starter !== 'IF' && starter !== 'THEN'));
};
action = function(token, i) {
return this.tokens.splice(this.tag(i - 1) === ',' ? i - 1 : i, 0, outdent);
return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent);
};
this.detectEnd(i + 2, condition, action);
if (tag === 'THEN') {
@ -326,7 +326,7 @@
}
return this.scanTokens(function(token, i, tokens) {
var _ref, inv, match, mtag, oppos, tag, val;
if ((_ref = tag = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0)) {
if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) {
stack.push(token);
return 1;
}
@ -360,7 +360,7 @@
};
exports.Rewriter.prototype.tag = function(i) {
var _ref;
return ((_ref = this.tokens[i]) != null) ? _ref[0] : undefined;
return (_ref = this.tokens[i]) != null ? _ref[0] : undefined;
};
BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END']];
INVERSES = {};

View File

@ -75,10 +75,10 @@
Scope.prototype.check = function(name, options) {
var _ref2, immediate;
immediate = !!this.type(name);
if (immediate || ((options != null) ? options.immediate : undefined)) {
if (immediate || (options != null ? options.immediate : undefined)) {
return immediate;
}
return !!(((_ref2 = this.parent) != null) ? _ref2.check(name) : undefined);
return !!((_ref2 = this.parent) != null ? _ref2.check(name) : undefined);
};
Scope.prototype.temporary = function(name, index) {
return name.length > 1 ? '_' + name + (index > 1 ? index : '') : '_' + (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a');
@ -101,7 +101,7 @@
index++;
}
this.add(temp, 'var');
((_ref2 = last(this.garbage)) != null) ? _ref2.push(temp) : undefined;
(_ref2 = last(this.garbage)) != null ? _ref2.push(temp) : undefined;
return temp;
};
Scope.prototype.assign = function(name, value) {

View File

@ -41,10 +41,11 @@ exports.Base = class Base
# If a Node is *topSensitive*, that means that it needs to compile differently
# depending on whether it's being used as part of a larger expression, or is a
# top-level statement within the function body.
compile: (o) ->
o = if o then merge o else {}
top = if @topSensitive() then o.top else del o, 'top'
@tab = o.indent
compile: (o, lvl) ->
o = if o then extend {}, o else {}
o.level = lvl if lvl
top = if @topSensitive then o.top else del o, 'top'
@tab = o.indent
if top or o.asStatement or this instanceof Comment or
@isPureStatement() or not @isStatement(o)
@compileNode o
@ -57,29 +58,23 @@ exports.Base = class Base
if @containsPureStatement()
throw SyntaxError 'cannot include a pure statement in an expression.'
o.sharedScope = o.scope
Closure.wrap(this).compile o
Closure.wrap(this).compileNode o
# If the code generation wishes to use the result of a complex expression
# in multiple places, ensure that the expression is only ever evaluated once,
# by assigning it to a temporary variable.
compileReference: (o, options) ->
pair = unless @isComplex()
[this, this]
# by assigning it to a temporary variable. Pass a level to precompile.
cache: (o, lvl) ->
unless @isComplex()
ref = if lvl then @compile o, lvl else this
[ref, ref]
else
reference = new Literal o.scope.freeVariable 'ref'
compiled = new Assign reference, this
[compiled, reference]
(pair[i] = node.compile o) for node, i in pair if options?.precompile
pair
# Compile unparenthesized.
compileBare: (o) ->
@parenthetical = on
@compile o
ref = new Literal o.scope.freeVariable 'ref'
sub = new Assign ref, this
if lvl then [sub.compile(o, lvl), ref.value] else [sub, ref]
# Compile to a source/variable pair suitable for looping.
compileLoopReference: (o, name) ->
src = tmp = @compile o
src = tmp = @compile o, LVL_ASSIGN
unless NUMBER.test(src) or IDENTIFIER.test(src) and o.scope.check(src, immediate: on)
src = "#{ tmp = o.scope.freeVariable name } = #{src}"
[src, tmp]
@ -99,9 +94,9 @@ exports.Base = class Base
# and returning true when the block finds a match. `contains` does not cross
# scope boundaries.
contains: (block) ->
contains = false
contains = no
@traverseChildren false, (node) ->
if block(node)
if block node
contains = true
return false
contains
@ -152,7 +147,7 @@ exports.Base = class Base
isPureStatement : NO
isComplex : YES
isChainable : NO
topSensitive : NO
topSensitive : no
unfoldSoak : NO
# Is this node used to assign a certain variable?
@ -201,9 +196,9 @@ exports.Expressions = class Expressions extends Base
this
# An **Expressions** is the only node that can serve as the root.
compile: (o) ->
compile: (o, lvl) ->
o or= {}
if o.scope then super(o) else @compileRoot(o)
if o.scope then super o, lvl else @compileRoot o
compileNode: (o) ->
(@compileExpression node, merge o for node in @expressions).join '\n'
@ -215,6 +210,7 @@ exports.Expressions = class Expressions extends Base
compileRoot: (o) ->
o.indent = @tab = if o.bare then '' else TAB
o.scope = new Scope null, this, null
o.level = LVL_TOP
code = @compileWithDeclarations o
code = code.replace TRAILING_WHITESPACE, ''
if o.bare then code else "(function() {\n#{code}\n}).call(this);\n"
@ -288,15 +284,15 @@ exports.Return = class Return extends Base
makeReturn: THIS
compile: (o) ->
compile: (o, lvl) ->
expr = @expression?.makeReturn()
if expr and expr not instanceof Return then expr.compile o else super o
if expr and expr not instanceof Return then expr.compile o, lvl else super o, lvl
compileNode: (o) ->
expr = ''
if @expression
o.asStatement = true if @expression.isStatement o
expr = ' ' + @expression.compileBare o
expr = ' ' + @expression.compile o, LVL_PAREN
@tab + 'return' + expr + ';'
#### Value
@ -374,22 +370,21 @@ exports.Value = class Value extends Base
[base.push(name), new Value(bref or base.base, [nref or name])]
# Override compile to unwrap the value when possible.
compile: (o) ->
compile: (o, lvl) ->
@base.tags.front = @tags.front
if not o.top or @properties.length then super o else @base.compile o
if not o.top or @properties.length then super o, lvl else @base.compile o, lvl
# We compile a value to JavaScript by compiling and joining each property.
# Things get much more insteresting if the chain of properties has *soak*
# operators `?.` interspersed. Then we have to take care not to accidentally
# evaluate a anything twice when building the soak chain.
# evaluate anything twice when building the soak chain.
compileNode: (o) ->
return ifn.compile o if ifn = @unfoldSoak o
props = @properties
@base.parenthetical = yes if @parenthetical and not props.length
code = @base.compile o
code = "(#{code})" if props[0] instanceof Accessor and @isSimpleNumber()
(code += prop.compile o) for prop in props
return code
code = @base.compile o, props.length and LVL_ACCESS
code = "(#{code})" if props[0] instanceof Accessor and @isSimpleNumber()
(code += prop.compileNode o) for prop in props
code
# Unfold a soak into an `If`: `a?.b` -> `a.b if a?`
unfoldSoak: (o) ->
@ -404,7 +399,7 @@ exports.Value = class Value extends Base
ref = new Literal o.scope.freeVariable 'ref'
fst = new Parens new Assign ref, fst
snd.base = ref
return new If new Existence(fst), snd, soak: on, operation: @tags.operation
return new If new Existence(fst), snd, soak: on
null
@wrap: (node) -> if node instanceof Value then node else new Value node
@ -448,9 +443,6 @@ exports.Call = class Call extends Base
@isNew = true
this
prefix: ->
if @isNew then 'new ' else ''
# Grab the reference to the superclass' implementation of the current method.
superReference: (o) ->
{method} = o.scope
@ -474,7 +466,7 @@ exports.Call = class Call extends Base
rite = new Call rite, @args
rite.isNew = @isNew
left = new Literal "typeof #{ left.compile o } === \"function\""
return new If left, new Value(rite), soak: yes, operation: @tags.operation
return new If left, new Value(rite), soak: yes
call = this
list = []
loop
@ -500,11 +492,11 @@ exports.Call = class Call extends Base
@variable?.tags.front = @tags.front
for arg in @args when arg instanceof Splat
return @compileSplat o
args = (arg.compileBare o for arg in @args).join ', '
args = (arg.compile o, LVL_LIST for arg in @args).join ', '
if @isSuper
@compileSuper args, o
else
"#{@prefix()}#{@variable.compile o}(#{args})"
(if @isNew then 'new ' else '') + @variable.compile(o, LVL_ACCESS) + "(#{args})"
# `super()` is converted into a call against the superclass's implementation
# of the current function.
@ -522,10 +514,10 @@ exports.Call = class Call extends Base
base = Value.wrap @variable
if (name = base.properties.pop()) and base.isComplex()
ref = o.scope.freeVariable 'this'
fun = "(#{ref} = #{ base.compile o })#{ name.compile o }"
fun = "(#{ref} = #{ base.compile o, LVL_ASSIGN })#{ name.compileNode o }"
else
fun = ref = base.compile o
fun += name.compile o if name
fun = ref = base.compile o, LVL_ACCESS
fun += name.compileNode o if name
return "#{fun}.apply(#{ref}, #{splatargs})"
idt = @idt 1
"""
@ -533,7 +525,7 @@ exports.Call = class Call extends Base
#{idt}ctor.prototype = func.prototype;
#{idt}var child = new ctor, result = func.apply(child, args);
#{idt}return typeof result === "object" ? result : child;
#{@tab}})(#{ @variable.compile o }, #{splatargs}, function() {})
#{@tab}})(#{ @variable.compile o, LVL_LIST }, #{splatargs}, function() {})
"""
#### Extends
@ -562,12 +554,12 @@ exports.Accessor = class Accessor extends Base
constructor: (@name, tag) ->
super()
@prototype = if tag is 'prototype' then '.prototype' else ''
@soakNode = tag is 'soak'
@proto = if tag is 'prototype' then '.prototype' else ''
@soakNode = tag is 'soak'
compileNode: (o) ->
name = @name.compile o
@prototype + if IS_STRING.test(name) then "[#{name}]" else ".#{name}"
@proto + if IS_STRING.test name then "[#{name}]" else ".#{name}"
isComplex: NO
@ -582,7 +574,7 @@ exports.Index = class Index extends Base
super()
compileNode: (o) ->
(if @proto then '.prototype' else '') + "[#{ @index.compileBare o }]"
(if @proto then '.prototype' else '') + "[#{ @index.compile o, LVL_PAREN }]"
isComplex: -> @index.isComplex()
@ -615,7 +607,7 @@ exports.ObjectLiteral = class ObjectLiteral extends Base
else if prop not instanceof Assign and prop not instanceof Comment
prop = new Assign prop, prop, 'object'
indent + prop.compile(o) + join
props = props.join('')
props = props.join ''
obj = "{#{ if props then '\n' + props + '\n' + @idt() else '' }}"
if @tags.front then "(#{obj})" else obj
@ -643,7 +635,7 @@ exports.ArrayLiteral = class ArrayLiteral extends Base
return @compileSplatLiteral o
objects = []
for obj, i in @objects
code = obj.compileBare o
code = obj.compile o, LVL_LIST
objects.push (if obj instanceof Comment
"\n#{code}\n#{o.indent}"
else if i is @objects.length - 1
@ -707,7 +699,7 @@ exports.Class = class Class extends Base
{variable: pvar, value: func} = prop
if pvar and pvar.base.value is 'constructor'
if func not instanceof Code
[func, ref] = func.compileReference o
[func, ref] = func.cache o
props.push func if func isnt ref
apply = new Call new Value(ref, [new Accessor new Literal 'apply']),
[new Literal('this'), new Literal('arguments')]
@ -757,7 +749,7 @@ exports.Assign = class Assign extends Base
children: ['variable', 'value']
topSensitive: YES
topSensitive: yes
constructor: (@variable, @value, @context) ->
super()
@ -775,16 +767,16 @@ exports.Assign = class Assign extends Base
return @compileConditional o if @context in @CONDITIONAL
top = del o, 'top'
stmt = del o, 'asStatement'
name = @variable.compile o
name = @variable.compile o, LVL_ASSIGN
if @value instanceof Code and match = @METHOD_DEF.exec name
@value.name = match[2]
@value.klass = match[1]
val = @value.compileBare o
val = @value.compile o, LVL_ASSIGN
return "#{name}: #{val}" if @context is 'object'
o.scope.find name unless isValue and (@variable.hasProperties() or @variable.namespaced)
val = name + " #{ @context or '=' } " + val
return "#{@tab}#{val};" if stmt
if top or @parenthetical then val else "(#{val})"
if top or o.level <= LVL_ASSIGN then val else "(#{val})"
# Brief implementation of recursive pattern matching, when assigning array or
# object literals to a value. Peeks at their properties to assign inner names.
@ -793,7 +785,7 @@ exports.Assign = class Assign extends Base
compilePatternMatch: (o) ->
top = del o, 'top'
otop = merge o, top: yes
if (value = @value).isStatement o then value = Closure.wrap value
{value} = this
{objects} = @variable.base
return value.compile o unless olength = objects.length
isObject = @variable.isObject()
@ -836,7 +828,7 @@ exports.Assign = class Assign extends Base
assigns.push new Assign(obj, val).compile otop
assigns.push valVar unless top
code = assigns.join ', '
if top or @parenthetical then code else "(#{code})"
if top or o.level <= LVL_PAREN then code else "(#{code})"
# When compiling a conditional assignment, take care to ensure that the
# operands are only evaluated once, even though we have to reference them
@ -931,7 +923,7 @@ exports.Param = class Param extends Base
@value = new Literal @name
compileNode: (o) ->
@value.compile o
@value.compile o, LVL_LIST
toString: ->
{name} = @
@ -964,7 +956,7 @@ exports.Splat = class Splat extends Base
end = ''
if @trailings.length
len = o.scope.freeVariable 'len'
o.scope.assign len, "arguments.length"
o.scope.assign len, 'arguments.length'
variadic = o.scope.freeVariable 'result'
o.scope.assign variadic, len + ' >= ' + @arglength
end = if @trailings.length then ", #{len} - #{@trailings.length}"
@ -974,22 +966,23 @@ exports.Splat = class Splat extends Base
trailing = new Literal o.scope.freeVariable 'arg'
assign.value = trailing
pos = @trailings.length - idx
o.scope.assign(trailing.compile(o), "arguments[#{variadic} ? #{len} - #{pos} : #{@index + idx}]")
"#{name} = #{utility('slice')}.call(arguments, #{@index}#{end})"
o.scope.assign trailing.compile(o),
"arguments[#{variadic} ? #{len} - #{pos} : #{ @index + idx }]"
"#{name} = #{ utility 'slice' }.call(arguments, #{@index}#{end})"
# A compiling a splat as a destructuring assignment means slicing arguments
# from the right-hand-side's corresponding array.
compileValue: (o, name, index, trailings) ->
trail = if trailings then ", #{name}.length - #{trailings}" else ''
"#{utility 'slice'}.call(#{name}, #{index}#{trail})"
"#{ utility 'slice' }.call(#{name}, #{index}#{trail})"
# Utility function that converts arbitrary number of elements, mixed with
# splats, to a proper array
@compileSplattedArray: (list, o) ->
args = []
end = -1
end = -1
for arg, i in list
code = arg.compile o
code = arg.compile o, LVL_LIST
prev = args[end]
if arg not instanceof Splat
if prev and starts(prev, '[') and ends(prev, ']')
@ -1011,7 +1004,7 @@ exports.While = class While extends Base
children: ['condition', 'guard', 'body']
topSensitive: YES
topSensitive: yes
isStatement : YES
constructor: (condition, opts) ->
@ -1031,11 +1024,11 @@ exports.While = class While extends Base
# *while* can be used as a part of a larger expression -- while loops may
# return an array containing the computed result of each iteration.
compileNode: (o) ->
top = del(o, 'top') and not @returns
o.indent = @idt 1
cond = @condition.compileBare o
o.top = true
set = ''
top = del(o, 'top') and not @returns
o.indent = @idt 1
cond = @condition.compile o, LVL_PAREN
o.top = true
set = ''
unless top
rvar = o.scope.freeVariable 'result'
set = "#{@tab}#{rvar} = [];\n"
@ -1084,9 +1077,9 @@ exports.Op = class Op extends Base
first = new Parens first if first instanceof Code and first.bound
super()
@operator = @CONVERSIONS[op] or op
(@first = first ).tags.operation = yes
(@second = second).tags.operation = yes if second
@flip = !!flip
@first = first
@second = second
@flip = !!flip
isUnary: ->
not @second
@ -1116,16 +1109,16 @@ exports.Op = class Op extends Base
return @compileChain o if @isChainable() and @first.unwrap().isChainable()
return @compileExistence o if @operator is '?'
@first.tags.front = @tags.front
"#{ @first.compile o } #{@operator} #{ @second.compile o }"
"#{ @first.compile o, LVL_OP } #{@operator} #{ @second.compile o, LVL_OP }"
# Mimic Python's chained comparisons when multiple comparison operators are
# used sequentially. For example:
#
# bin/coffee -e "puts 50 < 65 > 10"
# bin/coffee -e 'console.log 50 < 65 > 10'
# true
compileChain: (o) ->
[@first.second, shared] = @first.unwrap().second.compileReference o
"#{ @first.compile o } && #{ shared.compile o } #{@operator} #{ @second.compile o }"
[@first.second, shared] = @first.unwrap().second.cache o
"#{ @first.compile o, LVL_OP } && #{ shared.compile o } #{@operator} #{ @second.compile o, LVL_OP }"
compileExistence: (o) ->
if @first.isComplex()
@ -1134,13 +1127,12 @@ exports.Op = class Op extends Base
else
fst = @first
ref = fst.compile o
@second.tags.operation = no
new Existence(fst).compile(o) + " ? #{ref} : #{ @second.compileBare o }"
new Existence(fst).compile(o) + " ? #{ref} : #{ @second.compile o, LVL_ASSIGN }"
# Compile a unary **Op**.
compileUnary: (o) ->
space = if @operator in @PREFIX_OPERATORS then ' ' else ''
parts = [@operator, space, @first.compile(o)]
parts = [@operator, space, @first.compile(o, LVL_OP)]
(if @flip then parts.reverse() else parts).join ''
#### In
@ -1162,18 +1154,20 @@ exports.In = class In extends Base
@compileLoopTest o
compileOrTest: (o) ->
[sub, ref] = @object.compileReference o, precompile: yes
[sub, ref] = @object.cache o, LVL_OP
[cmp, cnj] = if @negated then [' !== ', ' && '] else [' === ', ' || ']
tests = for item, i in @array.base.objects
(if i then ref else sub) + cmp + item.compile o
tests = tests.join cnj
if @parenthetical then tests else "(#{tests})"
if o.level < LVL_OP then tests else "(#{tests})"
compileLoopTest: (o) ->
[sub, ref] = @object.compileReference merge(o, top: yes), precompile: yes
[sub, ref] = @object.cache o, LVL_LIST
code = utility('indexOf') + ".call(#{ @array.compile o }, #{ref}) " +
if @negated then '< 0' else '>= 0'
if sub is ref then code else "(#{sub}, #{code})"
return code if sub is ref
code = sub + ', ' + code
if o.level < LVL_LIST then code else "(#{code})"
toString: (idt) ->
super idt, @constructor.name + if @negated then '!' else ''
@ -1244,7 +1238,7 @@ exports.Existence = class Existence extends Base
"typeof #{code} !== \"undefined\" && #{code} !== null"
else
"#{code} != null"
if @parenthetical then code else "(#{code})"
if o.level <= LVL_COND then code else "(#{code})"
#### Parens
@ -1257,7 +1251,7 @@ exports.Parens = class Parens extends Base
children: ['expression']
topSensitive: YES
topSensitive: yes
constructor: (@expression) ->
super()
@ -1276,9 +1270,9 @@ exports.Parens = class Parens extends Base
if expr instanceof Value and expr.isAtomic()
expr.tags.front = @tags.front
return expr.compile o
code = expr.compileBare o
if @parenthetical or expr.isStatement o
return if top then @tab + code + ';' else code
code = expr.compile o, LVL_PAREN
return code if o.level < LVL_OP and (expr instanceof Op or expr instanceof Call)
return (if top then @tab + code + ';' else code) if expr.isStatement o
"(#{code})"
#### For
@ -1294,7 +1288,7 @@ exports.For = class For extends Base
children: ['body', 'source', 'guard', 'step', 'from', 'to']
topSensitive: YES
topSensitive: yes
isStatement : YES
constructor: (@body, head) ->
@ -1426,7 +1420,7 @@ exports.If = class If extends Base
children: ['condition', 'body', 'elseBody']
topSensitive: YES
topSensitive: yes
constructor: (condition, @body, tags) ->
@tags = tags or= {}
@ -1474,7 +1468,7 @@ exports.If = class If extends Base
condO = merge o
o.indent = @idt 1
o.top = true
ifPart = "if (#{ @condition.compileBare condO }) {\n#{ @body.compile o }\n#{@tab}}"
ifPart = "if (#{ @condition.compile condO, LVL_PAREN }) {\n#{ @body.compile o }\n#{@tab}}"
ifPart = @tab + ifPart unless child
return ifPart unless @elseBody
ifPart + ' else ' + if @isChain
@ -1484,11 +1478,10 @@ exports.If = class If extends Base
# Compile the If as a conditional operator.
compileExpression: (o) ->
@condition.tags.operation = on
code = @condition.compile(o) + ' ? ' +
@bodyNode().compileBare(o) + ' : ' +
@elseBodyNode()?.compileBare o
if @tags.operation then "(#{code})" else code
code = @condition .compile(o, LVL_COND) + ' ? ' +
@bodyNode().compile(o, LVL_ASSIGN) + ' : ' +
@elseBodyNode()?.compile o, LVL_ASSIGN
if o.level >= LVL_COND then "(#{code})" else code
unfoldSoak: -> @soakNode and this
@ -1497,7 +1490,6 @@ exports.If = class If extends Base
return unless ifn = parent[name].unfoldSoak o
parent[name] = ifn.body
ifn.body = new Value parent
ifn.tags.operation = on if parent.tags.operation
ifn
# Faux-Nodes
@ -1580,6 +1572,15 @@ UTILITIES =
hasProp: 'Object.prototype.hasOwnProperty'
slice: 'Array.prototype.slice'
# Levels indicates a node's position in the AST.
LVL_TOP = 0 # ...;
LVL_PAREN = 1 # (...)
LVL_LIST = 2 # [...]
LVL_ASSIGN = 3 # x = ...
LVL_COND = 4 # ... ? a : b
LVL_OP = 5 # +...
LVL_ACCESS = 6 # ...[0]
# Tabs are two spaces for pretty printing.
TAB = ' '