feat(transpiler): add support for arrow functions

fixes #28
This commit is contained in:
Victor Berchet 2014-10-02 11:51:10 +02:00 committed by Vojta Jina
parent 1214f423b4
commit d1b90e125b
3 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,46 @@
import {describe, it, expect} from 'test_lib/test_lib';
var inc = x => x + 1;
var objLiteral = val => ({'key': val});
var max = (a, b) => {
if (a > b) {
return a;
} else {
return b;
}
};
class LexicalThis {
constructor() {
this.zero = 0;
}
getZero() {
return (() => this.zero)();
}
}
export function main() {
describe('arrow functions', function() {
it('should support implicit return', function() {
expect(inc(0)).toBe(1);
});
it('should support object literal', function() {
var o = objLiteral('val');
expect(o['key']).toBe('val');
});
it('should support complex body', function() {
expect(max(0, 1)).toBe(1);
expect(max(1, 0)).toBe(1);
});
it('should support lexical this', function() {
var lthis = new LexicalThis();
expect(lthis.getZero()).toBe(0);
});
});
}

View File

@ -0,0 +1,26 @@
import {FunctionExpression} from 'traceur/src/syntax/trees/ParseTrees';
import {ParseTreeTransformer} from 'traceur/src/codegeneration/ParseTreeTransformer';
import {FUNCTION_BODY} from 'traceur/src/syntax/trees/ParseTreeType';
import alphaRenameThisAndArguments from 'traceur/src/codegeneration/alphaRenameThisAndArguments';
import {
createFunctionBody,
createReturnStatement
} from 'traceur/src/codegeneration/ParseTreeFactory';
/**
* Transforms an arrow function expression into a function declaration by adding a function
* body and return statement if needed.
*/
export class ArrowFunctionTransformer extends ParseTreeTransformer {
transformArrowFunctionExpression(tree) {
var body = this.transformAny(tree.body);
var parameterList = this.transformAny(tree.parameterList);
if (body.type !== FUNCTION_BODY) {
body = createFunctionBody([createReturnStatement(body)]);
}
return new FunctionExpression(tree.location, null, tree.functionKind, parameterList, null, [],
body);
}
}

View File

@ -2,6 +2,7 @@ import {MultiTransformer} from 'traceur/src/codegeneration/MultiTransformer';
import {UniqueIdentifierGenerator} from 'traceur/src/codegeneration/UniqueIdentifierGenerator';
import {options} from 'traceur/src/Options';
import {ArrowFunctionTransformer} from './ArrowFunctionTransformer';
import {ClassTransformer} from './ClassTransformer';
import {InstanceOfTransformer} from './InstanceOfTransformer';
import {MultiVarTransformer} from './MultiVarTransformer';
@ -22,6 +23,7 @@ export class DartTransformer extends MultiTransformer {
};
append(NamedParamsTransformer);
append(ArrowFunctionTransformer);
append(MultiVarTransformer);
append(InstanceOfTransformer);
append(StrictEqualityTransformer);