Starting destructuring.

This commit is contained in:
Fábio Santos
2015-01-15 03:03:38 +00:00
committed by Richard van Velzen
parent 252fc65558
commit 32f76f7ff8
7 changed files with 317 additions and 41 deletions

View File

@@ -644,6 +644,7 @@ function parse($TEXT, options) {
prev : null,
peeked : null,
in_function : 0,
in_parameters : false,
in_directives : true,
in_loop : 0,
labels : []
@@ -957,35 +958,58 @@ function parse($TEXT, options) {
};
var function_ = function(ctor) {
var start = S.token
var in_statement = ctor === AST_Defun;
var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;
if (in_statement && !name)
unexpected();
expect("(");
var args = params_or_seq_().as_params(croak);
var body = _function_body();
return new ctor({
name: name,
argnames: (function(first, a){
while (!is("punc", ")")) {
if (first) first = false; else expect(",");
a.push(as_symbol(AST_SymbolFunarg));
}
next();
return a;
})(true, []),
body: (function(loop, labels){
++S.in_function;
S.in_directives = true;
S.in_loop = 0;
S.labels = [];
var a = block_();
--S.in_function;
S.in_loop = loop;
S.labels = labels;
return a;
})(S.in_loop, S.labels)
start : args.start,
end : body.end,
name : name,
argnames: args,
body : body
});
};
function params_or_seq_() {
var start = S.token
expect("(");
var first = true;
var a = [];
S.in_parameters = true;
while (!is("punc", ")")) {
if (first) first = false; else expect(",");
a.push(expression(false));
}
S.in_parameters = false;
var end = S.token
next();
return new AST_ArrowParametersOrSeq({
start: start,
end: end,
expressions: a
});
}
function _function_body() {
var loop = S.in_loop;
var labels = S.labels;
++S.in_function;
S.in_directives = true;
S.in_loop = 0;
S.labels = [];
var a = block_();
--S.in_function;
S.in_loop = loop;
S.labels = labels;
return a;
}
function if_() {
var cond = parenthesised(), body = statement(), belse = null;
if (is("keyword", "else")) {
@@ -1224,6 +1248,7 @@ function parse($TEXT, options) {
});
var object_ = embed_tokens(function() {
var start = S.token;
expect("{");
var first = true, a = [];
while (!is("punc", "}")) {
@@ -1254,14 +1279,33 @@ function parse($TEXT, options) {
continue;
}
}
expect(":");
a.push(new AST_ObjectKeyVal({
start : start,
quote : start.quote,
key : name,
value : expression(false),
end : prev()
}));
if (!is("punc", ":")) {
// It's one of those object destructurings, the value is its own name
if (!S.in_parameters) {
croak("Invalid syntax", S.token.line, S.token.col);
}
a.push(new AST_ObjectSymbol({
start: start,
end: start,
symbol: new AST_SymbolRef({
start: start,
end: start,
name: name
})
}));
} else {
if (S.in_parameters) {
croak("Cannot destructure", S.token.line, S.token.col);
}
expect(":");
a.push(new AST_ObjectKeyVal({
start : start,
key : name,
value : expression(false),
end : prev()
}));
}
}
next();
return new AST_Object({ properties: a });