Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support spread operator in call expressions #1931

Merged
merged 3 commits into from
Feb 10, 2015
Merged

Support spread operator in call expressions #1931

merged 3 commits into from
Feb 10, 2015

Conversation

ahejlsberg
Copy link
Member

This PR adds support for the spread (...) operator in call expressions with down-level code generation for ES3/5. For example:

function drawText(x: number, y: number, ...strings: string[]) {
    // draw text
}

drawText(10, 20, "hello");
drawText(10, 20, "hello", "world");
var a = ["one", "two"];
drawText(10, 20, ...a);
drawText(10, 20, "zero", ...a, "three");

The function calls are emitted unchanged for ES6, but when the target is ES3 or ES5, the calls are rewritten as follows:

drawText(10, 20, "hello");
drawText(10, 20, "hello", "world");
var a = ["one", "two"];
drawText.apply(void 0, [10, 20].concat(a));
drawText.apply(void 0, [10, 20, "zero"].concat(a, ["three"]));

Type checking requires spread elements to match up with a rest parameter. Thus, in a typed function call it is not possible to use a spread element for non-rest parameters. For example:

var pos = [10, 20];
drawText(...pos, "hello", "world");  // Error
(<any>drawText)(...pos, "hello", "world");  // But ok in untyped call

A temporary variable may be injected to ensure the this argument is only evaluated once. For example:

interface Context {
    drawText(x: number, y: number, ...strings: string[]);
}

declare function getContext(): Context;

var text = ["hello", "world"];
getContext().drawText(10, 20, ...text);

This generates the code:

var text = ["hello", "world"];
(_a = getContext()).drawText.apply(_a, [10, 20].concat(text));
var _a;


(<Function>xa[1].foo)(...[1, 2, "abc"]);

class C {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class C/D can be pull out into its own test cases

ahejlsberg added a commit that referenced this pull request Feb 10, 2015
Support spread operator in call expressions
@ahejlsberg ahejlsberg merged commit 4b92e42 into master Feb 10, 2015
@ahejlsberg ahejlsberg deleted the spreadCall branch February 10, 2015 17:25
@DickvdBrink DickvdBrink mentioned this pull request Mar 8, 2015
@tinganho tinganho mentioned this pull request May 7, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants