Adding arrow functions

This commit is contained in:
Fábio Santos
2015-01-11 20:07:19 +00:00
parent 9d7d365c2b
commit fa5c4f2d03
6 changed files with 129 additions and 2 deletions

View File

@@ -510,6 +510,16 @@ function tokenizer($TEXT, filename, html5_comments) {
return S.regex_allowed ? read_regexp("") : read_operator("/");
};
function handle_eq_sign() {
next();
if (peek() === ">") {
next();
return token("arrow", "=>");
} else {
return read_operator("=");
}
};
function handle_dot() {
next();
return is_digit(peek().charCodeAt(0))
@@ -559,6 +569,7 @@ function tokenizer($TEXT, filename, html5_comments) {
case 34: case 39: return read_string(ch);
case 46: return handle_dot();
case 47: return handle_slash();
case 61: return handle_eq_sign();
}
if (is_digit(code)) return read_num();
if (PUNC_CHARS(ch)) return token("punc", next());
@@ -975,6 +986,41 @@ function parse($TEXT, options) {
});
};
var arrow_function = function(args) {
expect_token("arrow", "=>");
if (args instanceof AST_SymbolRef) {
args = [args];
} else if (args instanceof AST_Seq) {
args = args.to_array();
} else if (args instanceof AST_Node) {
croak("Invalid syntax", args.start.line, args.start.col);
}
for (var i = 0; i < args.length; i++) {
if (!(args[i] instanceof AST_SymbolRef)) {
croak("Invalid parameter for an arrow function", args[i].start.line, args[i].start.col);
}
args[i] = new AST_SymbolFunarg({
name: args[i].name,
start: args[i].start,
end: args[i].end
})
}
return new AST_Arrow({
argnames: args,
body: (function(){
if (is("punc", "{")) {
return _function_body();
} else {
return expression(true);
}
})()
});
};
var function_ = function(ctor) {
var start = S.token
@@ -1486,6 +1532,13 @@ function parse($TEXT, options) {
var maybe_assign = function(no_in) {
var start = S.token;
if (start.value == "(" && peek().value == ")") {
next(); // (
next(); // )
return arrow_function([]);
}
var left = maybe_conditional(no_in), val = S.token.value;
if (is("operator") && ASSIGNMENT(val)) {
if (is_assignable(left)) {
@@ -1500,6 +1553,9 @@ function parse($TEXT, options) {
}
croak("Invalid assignment");
}
if (is("arrow")) {
return arrow_function(left)
}
return left;
};