fix(setup): use upstream traceur with explicit patches

Also correct the transpile to ES6

Also support generics correctly

All patches are hooked in via `/tools/transpiler/index.js`
https://github.com/google/traceur-compiler/issues/1700
https://github.com/google/traceur-compiler/issues/1699
https://github.com/google/traceur-compiler/issues/1708
https://github.com/google/traceur-compiler/issues/1625
https://github.com/google/traceur-compiler/issues/1706
This commit is contained in:
Tobias Bosch 2015-02-06 13:38:52 -08:00
parent 63d8107d1c
commit f39c6dc2c7
46 changed files with 515 additions and 125 deletions

View File

@ -14,7 +14,6 @@ module.exports = function(config) {
{pattern: 'tools/transpiler/spec/**', included: false},
'node_modules/traceur/bin/traceur-runtime.js',
'traceur-runtime-patch.js',
'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js',
// Including systemjs because it defines `__eval`, which produces correct stack traces.
'node_modules/systemjs/dist/system.src.js',

View File

@ -8,6 +8,7 @@ export class AbstractChangeDetector extends ChangeDetector {
mode:string;
constructor() {
super();
this.children = [];
this.mode = CHECK_ALWAYS;
}

View File

@ -19,15 +19,15 @@ export class ArrayChanges {
_length:int;
_linkedRecords:_DuplicateMap;
_unlinkedRecords:_DuplicateMap;
_previousItHead:CollectionChangeRecord<V>;
_itHead:CollectionChangeRecord<V>;
_itTail:CollectionChangeRecord<V>;
_additionsHead:CollectionChangeRecord<V>;
_additionsTail:CollectionChangeRecord<V>;
_movesHead:CollectionChangeRecord<V>;
_movesTail:CollectionChangeRecord<V> ;
_removalsHead:CollectionChangeRecord<V>;
_removalsTail:CollectionChangeRecord<V>;
_previousItHead:CollectionChangeRecord;
_itHead:CollectionChangeRecord;
_itTail:CollectionChangeRecord;
_additionsHead:CollectionChangeRecord;
_additionsTail:CollectionChangeRecord;
_movesHead:CollectionChangeRecord;
_movesTail:CollectionChangeRecord;
_removalsHead:CollectionChangeRecord;
_removalsTail:CollectionChangeRecord;
constructor() {
this._collection = null;

View File

@ -4,6 +4,7 @@ export class ExpressionChangedAfterItHasBeenChecked extends Error {
message:string;
constructor(proto:ProtoRecord, change:any) {
super();
this.message = `Expression '${proto.expressionAsString}' has changed after it was checked. ` +
`Previous value: '${change.previousValue}'. Current value: '${change.currentValue}'`;
}
@ -19,6 +20,7 @@ export class ChangeDetectionError extends Error {
location:string;
constructor(proto:ProtoRecord, originalException:any) {
super();
this.originalException = originalException;
this.location = proto.expressionAsString;
this.message = `${this.originalException} in [${this.location}]`;

View File

@ -36,6 +36,7 @@ export class EmptyExpr extends AST {
export class Structural extends AST {
value:AST;
constructor(value:AST) {
super();
this.value = value;
}
@ -64,6 +65,7 @@ export class ImplicitReceiver extends AST {
export class Chain extends AST {
expressions:List;
constructor(expressions:List) {
super();
this.expressions = expressions;
}
@ -86,6 +88,7 @@ export class Conditional extends AST {
trueExp:AST;
falseExp:AST;
constructor(condition:AST, trueExp:AST, falseExp:AST){
super();
this.condition = condition;
this.trueExp = trueExp;
this.falseExp = falseExp;
@ -110,6 +113,7 @@ export class AccessMember extends AST {
getter:Function;
setter:Function;
constructor(receiver:AST, name:string, getter:Function, setter:Function) {
super();
this.receiver = receiver;
this.name = name;
this.getter = getter;
@ -155,6 +159,7 @@ export class KeyedAccess extends AST {
obj:AST;
key:AST;
constructor(obj:AST, key:AST) {
super();
this.obj = obj;
this.key = key;
}
@ -187,6 +192,7 @@ export class Formatter extends AST {
args:List<AST>;
allArgs:List<AST>;
constructor(exp:AST, name:string, args:List) {
super();
this.exp = exp;
this.name = name;
this.args = args;
@ -201,6 +207,7 @@ export class Formatter extends AST {
export class LiteralPrimitive extends AST {
value;
constructor(value) {
super();
this.value = value;
}
@ -216,6 +223,7 @@ export class LiteralPrimitive extends AST {
export class LiteralArray extends AST {
expressions:List;
constructor(expressions:List) {
super();
this.expressions = expressions;
}
@ -232,6 +240,7 @@ export class LiteralMap extends AST {
keys:List;
values:List;
constructor(keys:List, values:List) {
super();
this.keys = keys;
this.values = values;
}
@ -253,6 +262,7 @@ export class Interpolation extends AST {
strings:List;
expressions:List;
constructor(strings:List, expressions:List) {
super();
this.strings = strings;
this.expressions = expressions;
}
@ -271,6 +281,7 @@ export class Binary extends AST {
left:AST;
right:AST;
constructor(operation:string, left:AST, right:AST) {
super();
this.operation = operation;
this.left = left;
this.right = right;
@ -310,6 +321,7 @@ export class Binary extends AST {
export class PrefixNot extends AST {
expression:AST;
constructor(expression:AST) {
super();
this.expression = expression;
}
@ -326,6 +338,7 @@ export class Assignment extends AST {
target:AST;
value:AST;
constructor(target:AST, value:AST) {
super();
this.target = target;
this.value = value;
}
@ -345,6 +358,7 @@ export class MethodCall extends AST {
args:List;
name:string;
constructor(receiver:AST, name:string, fn:Function, args:List) {
super();
this.receiver = receiver;
this.fn = fn;
this.args = args;
@ -375,6 +389,7 @@ export class FunctionCall extends AST {
target:AST;
args:List;
constructor(target:AST, args:List) {
super();
this.target = target;
this.args = args;
}
@ -397,6 +412,7 @@ export class ASTWithSource extends AST {
source:string;
location:string;
constructor(ast:AST, source:string, location:string) {
super();
this.source = source;
this.location = location;
this.ast = ast;
@ -429,6 +445,7 @@ export class TemplateBinding {
name:string;
expression:ASTWithSource;
constructor(key:string, keyIsVar:boolean, name:string, expression:ASTWithSource) {
super();
this.key = key;
this.keyIsVar = keyIsVar;
// only either name or expression will be filled.

View File

@ -184,6 +184,7 @@ const $NBSP = 160;
export class ScannerError extends Error {
message:string;
constructor(message) {
super();
this.message = message;
}

View File

@ -104,6 +104,7 @@ export class DynamicProtoChangeDetector extends ProtoChangeDetector {
_recordBuilder:ProtoRecordBuilder;
constructor() {
super();
this._records = null;
this._recordBuilder = new ProtoRecordBuilder();
}
@ -131,6 +132,7 @@ export class JitProtoChangeDetector extends ProtoChangeDetector {
_recordBuilder:ProtoRecordBuilder;
constructor() {
super();
this._factory = null;
this._recordBuilder = new ProtoRecordBuilder();
}

View File

@ -9,6 +9,7 @@ export class EventEmitter extends DependencyAnnotation {
eventName: string;
@CONST()
constructor(eventName) {
super();
this.eventName = eventName;
}
}

View File

@ -8,6 +8,7 @@ import {DependencyAnnotation} from 'angular2/di';
export class Parent extends DependencyAnnotation {
@CONST()
constructor() {
super();
}
}
@ -18,5 +19,6 @@ export class Parent extends DependencyAnnotation {
export class Ancestor extends DependencyAnnotation {
@CONST()
constructor() {
super();
}
}

View File

@ -15,6 +15,7 @@ import {DirectiveMetadata} from './directive_metadata';
import {Component} from '../annotations/annotations';
import {Content} from './shadow_dom_emulation/content_tag';
import {ShadowDomStrategy} from './shadow_dom_strategy';
import {CompileStep} from './pipeline/compile_step';
/**
* Cache that stores the ProtoView of the template of a component.

View File

@ -640,6 +640,7 @@ export class ElementInjector extends TreeNode {
class OutOfBoundsAccess extends Error {
message:string;
constructor(index) {
super();
this.message = `Index ${index} is out-of-bounds.`;
}

View File

@ -30,6 +30,7 @@ import {ShadowDomStrategy} from '../shadow_dom_strategy';
export class DirectiveParser extends CompileStep {
_selectorMatcher:SelectorMatcher;
constructor(directives:List<DirectiveMetadata>) {
super();
this._selectorMatcher = new SelectorMatcher();
for (var i=0; i<directives.length; i++) {
var directiveMetadata = directives[i];

View File

@ -89,6 +89,7 @@ export class ElementBinderBuilder extends CompileStep {
_parser:Parser;
_compilationUnit:any;
constructor(parser:Parser, compilationUnit:any) {
super();
this._parser = parser;
this._compilationUnit = compilationUnit;
}

View File

@ -32,6 +32,7 @@ export class PropertyBindingParser extends CompileStep {
_parser:Parser;
_compilationUnit:any;
constructor(parser:Parser, compilationUnit:any) {
super();
this._parser = parser;
this._compilationUnit = compilationUnit;
}

View File

@ -25,6 +25,7 @@ export class ProtoViewBuilder extends CompileStep {
changeDetection:ChangeDetection;
_shadowDomStrategy:ShadowDomStrategy;
constructor(changeDetection:ChangeDetection, shadowDomStrategy:ShadowDomStrategy) {
super();
this._shadowDomStrategy = shadowDomStrategy;
this.changeDetection = changeDetection;
}

View File

@ -17,6 +17,7 @@ export class TextInterpolationParser extends CompileStep {
_parser:Parser;
_compilationUnit:any;
constructor(parser:Parser, compilationUnit:any) {
super();
this._parser = parser;
this._compilationUnit = compilationUnit;
}

View File

@ -36,6 +36,7 @@ export class ViewSplitter extends CompileStep {
_parser:Parser;
_compilationUnit:any;
constructor(parser:Parser, compilationUnit:any) {
super();
this._parser = parser;
this._compilationUnit = compilationUnit;
}

View File

@ -10,7 +10,7 @@ var _scriptTemplate = DOM.createScriptTag('type', 'ng/content')
class ContentStrategy {
nodes: List<Node>;
insert(nodes:List<Nodes>){}
insert(nodes:List<Node>){}
}
/**
@ -23,6 +23,7 @@ class RenderedContent extends ContentStrategy {
endScript:Element;
constructor(contentEl:Element) {
super();
this._replaceContentElementWithScriptTags(contentEl);
this.nodes = [];
}
@ -64,6 +65,7 @@ class IntermediateContent extends ContentStrategy {
destinationLightDom:LightDom;
constructor(destinationLightDom:LightDom) {
super();
this.destinationLightDom = destinationLightDom;
this.nodes = [];
}

View File

@ -18,6 +18,7 @@ export class EmulatedShadowDomStrategy extends ShadowDomStrategy {
_styleHost: Element;
constructor(styleHost: Element = null) {
super();
if (isBlank(styleHost)) {
styleHost = DOM.defaultDoc().head;
}

View File

@ -1,6 +1,6 @@
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {isBlank, isPresent, BaseException, stringify} from 'angular2/src/facade/lang';
import {TemplateElement, DOM} from 'angular2/src/facade/dom';
import {TemplateElement, DOM, Element} from 'angular2/src/facade/dom';
import {StringMapWrapper} from 'angular2/src/facade/collection';
import {TemplateConfig} from 'angular2/src/core/annotations/template_config';

View File

@ -32,6 +32,7 @@ export class ProviderError extends Error {
constructResolvingMessage:Function;
message;
constructor(key:Key, constructResolvingMessage:Function) {
super();
this.keys = [key];
this.constructResolvingMessage = constructResolvingMessage;
this.message = this.constructResolvingMessage(this.keys);
@ -87,6 +88,7 @@ export class InstantiationError extends ProviderError {
export class InvalidBindingError extends Error {
message:string;
constructor(binding) {
super();
this.message = `Invalid binding ${binding}`;
}
@ -98,6 +100,7 @@ export class InvalidBindingError extends Error {
export class NoAnnotationError extends Error {
message:string;
constructor(typeOrFunc) {
super();
this.message = `Cannot resolve all parameters for ${stringify(typeOrFunc)}`;
}

View File

@ -16,6 +16,7 @@ export class Foreach extends OnChange {
viewPort: ViewPort;
iterable;
constructor(viewPort: ViewPort) {
super();
this.viewPort = viewPort;
}
onChange(changes) {

View File

@ -18,7 +18,6 @@ export class CONST {}
export class ABSTRACT {}
export class IMPLEMENTS {}
export function isPresent(obj):boolean {
return obj !== undefined && obj !== null;
}
@ -103,6 +102,7 @@ export class StringJoiner {
export class NumberParseError extends Error {
constructor(message) {
super();
this.message = message;
}

View File

@ -89,6 +89,7 @@ export class ControlGroupDirective extends ControlGroupDirectiveBase {
_directives:List<ControlNameDirective>;
constructor() {
super();
this._directives = ListWrapper.create();
}
@ -121,6 +122,7 @@ export class NewControlGroupDirective extends ControlGroupDirectiveBase {
_directives:List<ControlNameDirective>;
constructor() {
super();
this._directives = ListWrapper.create();
}

View File

@ -9,6 +9,7 @@ export class XHRMock extends XHR {
_requests: List<Promise>;
constructor() {
super();
this._expectations = [];
this._definitions = MapWrapper.create();
this._requests = [];

View File

@ -604,6 +604,7 @@ class TestDispatcher extends ChangeDispatcher {
onChange:Function;
constructor() {
super();
this.log = null;
this.loggedValues = null;
this.onChange = (_, __) => {};

View File

@ -237,6 +237,7 @@ class TestableCompiler extends Compiler {
class MockStep extends CompileStep {
processClosure:Function;
constructor(process) {
super();
this.processClosure = process;
}
process(parent:CompileElement, current:CompileElement, control:CompileControl) {
@ -247,6 +248,7 @@ class MockStep extends CompileStep {
class FakeShadowDomStrategy extends NativeShadowDomStrategy {
templateHtml: string;
constructor(templateHtml: string) {
super();
this.templateHtml = templateHtml;
}

View File

@ -199,6 +199,7 @@ export function main() {
class MockStep extends CompileStep {
processClosure:Function;
constructor(process) {
super();
this.processClosure = process;
}
process(parent:CompileElement, current:CompileElement, control:CompileControl) {

View File

@ -412,6 +412,7 @@ class Context {
class MockStep extends CompileStep {
processClosure:Function;
constructor(process) {
super();
this.processClosure = process;
}
process(parent:CompileElement, current:CompileElement, control:CompileControl) {

View File

@ -101,6 +101,7 @@ function assertBinding(pipelineElement, shouldBePresent) {
class MockStep extends CompileStep {
processClosure:Function;
constructor(process) {
super();
this.processClosure = process;
}
process(parent:CompileElement, current:CompileElement, control:CompileControl) {

View File

@ -124,6 +124,7 @@ export function main() {
class MockStep extends CompileStep {
processClosure:Function;
constructor(process) {
super();
this.processClosure = process;
}
process(parent:CompileElement, current:CompileElement, control:CompileControl) {

View File

@ -169,6 +169,7 @@ class TestableProtoElementInjectorBuilder extends ProtoElementInjectorBuilder {
debugObjects:List;
constructor() {
super();
this.debugObjects = [];
}
@ -192,6 +193,7 @@ class TestableProtoElementInjectorBuilder extends ProtoElementInjectorBuilder {
class MockStep extends CompileStep {
processClosure:Function;
constructor(process) {
super();
this.processClosure = process;
}
process(parent:CompileElement, current:CompileElement, control:CompileControl) {

View File

@ -94,6 +94,7 @@ export function main() {
class MockStep extends CompileStep {
processClosure:Function;
constructor(process) {
super();
this.processClosure = process;
}
process(parent:CompileElement, current:CompileElement, control:CompileControl) {

View File

@ -189,6 +189,7 @@ class TestDirectiveMetadataReader extends DirectiveMetadataReader {
shadowDomStrategy;
constructor(shadowDomStrategy) {
super();
this.shadowDomStrategy = shadowDomStrategy;
}

View File

@ -2,7 +2,7 @@ import {describe, xit, it, expect, beforeEach, ddescribe, iit, el} from 'angular
import {View, ProtoView} from 'angular2/src/core/compiler/view';
import {ViewPort} from 'angular2/src/core/compiler/viewport';
import {proxy, IMPLEMENTS} from 'angular2/src/facade/lang';
import {DOM} from 'angular2/src/facade/dom';
import {DOM, Node} from 'angular2/src/facade/dom';
import {ListWrapper, MapWrapper} from 'angular2/src/facade/collection';
import {Injector} from 'angular2/di';
import {ProtoElementInjector, ElementInjector} from 'angular2/src/core/compiler/element_injector';
@ -33,7 +33,7 @@ class AttachableChangeDetector {
@IMPLEMENTS(View)
class HydrateAwareFakeView {
isHydrated: boolean;
nodes: List<Nodes>;
nodes: List<Node>;
changeDetector: ChangeDetector;
rootElementInjectors;
constructor(isHydrated) {

View File

@ -60,8 +60,7 @@ function setupReflector() {
});
reflector.registerType(Compiler, {
'factory': (cd, templateLoader, reader, parser, compilerCache, strategy)
=> new Compiler(cd, templateLoader, reader, parser, compilerCache, strategy),
'factory': (cd, templateLoader, reader, parser, compilerCache, strategy) => new Compiler(cd, templateLoader, reader, parser, compilerCache, strategy),
'parameters': [[ChangeDetection], [TemplateLoader], [DirectiveMetadataReader],
[Parser], [CompilerCache], [ShadowDomStrategy]],
'annotations': []

View File

@ -1,3 +1,5 @@
var _global = typeof window === 'object' ? window : global;
// TODO(vojta):
// - extract into multiple files
// - different error types
@ -11,7 +13,32 @@ function argPositionName(i) {
return POSITION_NAME[position] || (position + 'th');
}
var primitives = $traceurRuntime.type;
var primitives;
var genericType;
if (typeof $traceurRuntime === 'object') {
primitives = $traceurRuntime.type;
genericType = $traceurRuntime.genericType;
} else {
// Allow to work without traceur runtime as well!
primitives = {
any: {name: 'any'},
boolean: {name: 'boolean'},
number: {name: 'number'},
string: {name: 'string'},
symbol: {name: 'symbol'},
void: {name: 'void'}
};
genericType = function(type, args) {
return {
type: type,
args: args
}
}
}
Object.keys(primitives).forEach(function(name) {
primitives[name].__assertName = name;
});
export function proxy(){
}
@ -81,6 +108,11 @@ function prettyPrint(value) {
}
function isType(value, T, errors) {
if (T && T.type) {
// needed for generics.
// TODO(tbosch): read out T.args and do assertions based on them as well!
T = T.type;
}
if (T === primitives.void) {
return typeof value === 'undefined';
}
@ -198,33 +230,25 @@ function returnType(actual, T) {
return actual;
}
// `int` is not a valid JS type, and traceur will leave
// it untouched. However, we want to be able to use it,
// so we provide it as a global
var intType = _global['int'] = define('int', function(value) {
return typeof value === 'number' && value%1 === 0;
});
// TODO(vojta): define these with DSL?
var string = define('string', function(value) {
var string = type.string = define('string', function(value) {
return typeof value === 'string';
});
// function string() {}
// string.assert = function(value) {
// return typeof value === 'string';
// };
var boolean = define('boolean', function(value) {
var boolean = type.boolean = define('boolean', function(value) {
return typeof value === 'boolean';
});
// function boolean() {}
// boolean.assert = function(value) {
// return typeof value === 'boolean';
// };
var number = define('number', function(value) {
var number = type.number = define('number', function(value) {
return typeof value === 'number';
});
// function number() {}
// number.assert = function(value) {
// return typeof value === 'number';
// };
function arrayOf(...types) {
return assert.define('array of ' + types.map(prettyPrint).join('/'), function(value) {
@ -320,6 +344,10 @@ function assert(value) {
// throw if no type provided
assert.type = type;
for (var prop in primitives) {
assert.type[prop] = primitives[prop];
}
assert.genericType = genericType;
// throw if odd number of args
assert.argumentTypes = assertArgumentTypes;
@ -334,6 +362,7 @@ assert.fail = fail;
assert.string = string;
assert.number = number;
assert.boolean = boolean;
assert.int = intType;
// custom types
assert.arrayOf = arrayOf;

View File

@ -165,7 +165,6 @@ describe('primitive value check', function() {
});
// ## Describing more complex types
//
// Often, a simple type check using `instanceof` or `typeof` is not enough.
@ -370,11 +369,39 @@ describe('Traceur', function() {
.toThrowError('Expected to return an instance of void, got null!');
});
});
// Note: `int` is not part of JS types, but rtts_assert exposes a global
// so that it can be used as well.
describe('int', function() {
it('should pass', function() {
var x:int = 10;
});
it('should fail', function() {
expect(() => {
var x:int = 'ok';
}).toThrowError('Expected an instance of int, got "ok"!');
});
it('should fail', function() {
expect(() => {
var x:int = 12.3;
}).toThrowError('Expected an instance of int, got 12.3!');
});
});
describe('generics', function() {
it('should pass', function() {
var list:Array<string> = [];
});
// TODO(tbosch): add assertions based on generics to rtts_assert
});
});
// <center><small>
// This documentation was generated from [assert.spec.js](https://github.com/vojtajina/assert/blob/master/test/assert.spec.js) using [Docco](http://jashkenas.github.io/docco/).
// </small></center>
}

View File

@ -15,7 +15,7 @@
"dependencies": {
"es6-module-loader": "^0.9.2",
"systemjs": "^0.9.1",
"traceur": "vojtajina/traceur-compiler#disable-getters-setters",
"traceur": "0.0.82",
"which": "~1",
"zone.js": "0.4.0",
"googleapis": "1.0.x",

View File

@ -10,6 +10,7 @@ var TRACEUR_PATH = traceur.RUNTIME_PATH.replace('traceur-runtime.js', 'traceur.j
var SELF_SOURCE_REGEX = /transpiler\/src/;
var SELF_COMPILE_OPTIONS = {
modules: 'register',
memberVariables: false,
moduleName: true,
script: false // parse as a module
};
@ -74,6 +75,12 @@ function reloadCompiler() {
}
return m;
};
useRttsAssertModuleForConvertingTypesToExpressions();
supportSuperCallsInEs6Patch();
convertTypesToExpressionsInEs6Patch();
removeNonStaticFieldDeclarationsInEs6Patch();
disableGetterSetterAssertionPatch();
}
function loadModule(filepath, transpile) {
@ -106,3 +113,105 @@ function extend(source, props) {
}
return res;
}
// TODO(tbosch): remove when traceur is fixed.
// see https://github.com/google/traceur-compiler/issues/1700
function supportSuperCallsInEs6Patch() {
var traceurVersion = System.map['traceur'];
var ParseTreeMapWriter = System.get(traceurVersion+'/src/outputgeneration/ParseTreeMapWriter').ParseTreeMapWriter;
var _enterBranch = ParseTreeMapWriter.prototype.enterBranch;
ParseTreeMapWriter.prototype.enterBranch = function(location) {
if (!location.start) {
// This would throw...
return;
}
return _enterBranch.apply(this, arguments);
}
}
// TODO(tbosch): Remove when traceur is fixed.
// see https://github.com/google/traceur-compiler/issues/1699
function convertTypesToExpressionsInEs6Patch() {
var traceurVersion = System.map['traceur'];
var TypeToExpressionTransformer = System.get(traceurVersion+'/src/codegeneration/TypeToExpressionTransformer').TypeToExpressionTransformer;
var PureES6Transformer = System.get(traceurVersion+'/src/codegeneration/PureES6Transformer').PureES6Transformer;
var UniqueIdentifierGenerator = System.get(traceurVersion+'/src/codegeneration/UniqueIdentifierGenerator').UniqueIdentifierGenerator;
var _transform = PureES6Transformer.prototype.transform;
PureES6Transformer.prototype.transform = function() {
if (!this._patched) {
this._patched = true;
this.treeTransformers_.splice(0,0, function(tree) {
return new TypeToExpressionTransformer(new UniqueIdentifierGenerator(), this.reporter_).transformAny(tree);
});
}
return _transform.apply(this, arguments);
};
}
// TODO(tbosch): Don't write field declarations in classes when we output to ES6.
// This just patches the writer and does not support moving initializers to the constructor.
// See src/codegeneration/ClassTransformer.js for how to support initializers as well.
// see https://github.com/google/traceur-compiler/issues/1708
function removeNonStaticFieldDeclarationsInEs6Patch() {
var traceurVersion = System.map['traceur'];
var ParseTreeWriter = System.get(traceurVersion+'/src/outputgeneration/ParseTreeWriter').ParseTreeWriter;
var options = System.get(traceurVersion + "/src/Options.js").options;
var _visitPropertyVariableDeclaration = ParseTreeWriter.prototype.visitPropertyVariableDeclaration;
ParseTreeWriter.prototype.visitPropertyVariableDeclaration = function() {
if (options.outputLanguage !== 'es6') {
return _visitPropertyVariableDeclaration.apply(this, arguments);
}
};
}
// TODO(tbosch): Disable getter/setters for assertions until traceur has a flag
// that allows to disable them while keeping assertions and member fields enabled.
// see https://github.com/google/traceur-compiler/issues/1625
// Why:
// - traceur uses field names based on numbers, which can lead to collisions when creating a subclass in a separate compiler run.
// - this rename of fields makes debugging via the repl harder (e.g. via DevTools console)
// - this rename can break JSON conversion of instances
function disableGetterSetterAssertionPatch() {
var traceurVersion = System.map['traceur'];
var MemberVariableTransformer = System.get(traceurVersion+'/src/codegeneration/MemberVariableTransformer').MemberVariableTransformer;
var AnonBlock = System.get(traceurVersion+'/src/syntax/trees/ParseTrees.js').AnonBlock;
MemberVariableTransformer.prototype.transformPropertyVariableDeclaration = function(tree) {
return new AnonBlock(tree.location, []);
}
}
// TODO(tbosch): Get all types from `assert` module and not from `$traceurRuntime`.
// With this a transpile to ES6 does no more include the `$traceurRuntime`.
// see https://github.com/google/traceur-compiler/issues/1706
function useRttsAssertModuleForConvertingTypesToExpressions() {
var traceurVersion = System.map['traceur'];
var original = System.get(traceurVersion+'/src/codegeneration/TypeToExpressionTransformer').TypeToExpressionTransformer;
var patch = System.get('transpiler/src/patch/TypeToExpressionTransformer').TypeToExpressionTransformer;
for (var prop in patch.prototype) {
original.prototype[prop] = patch.prototype[prop];
}
var TypeAssertionTransformer = System.get(traceurVersion+'/src/codegeneration/TypeAssertionTransformer').TypeAssertionTransformer;
var createIdentifierExpression = System.get(traceurVersion+'/src/codegeneration/ParseTreeFactory').createIdentifierExpression;
var parseExpression = System.get(traceurVersion+'/src/codegeneration/PlaceholderParser.js').parseExpression;
TypeAssertionTransformer.prototype.transformBindingElementParameter_ = function(element, typeAnnotation) {
// Copied from https://github.com/google/traceur-compiler/commits/master/src/codegeneration/TypeAssertionTransformer.js
if (!element.binding.isPattern()) {
if (typeAnnotation) {
this.paramTypes_.atLeastOneParameterTyped = true;
} else {
// PATCH start
typeAnnotation = parseExpression(["assert.type.any"]);
// PATCH end
}
this.paramTypes_.arguments.push(
createIdentifierExpression(element.binding.identifierToken),
typeAnnotation);
return;
}
// NYI
}
}

View File

@ -3,49 +3,53 @@ import {ListWrapper, MapWrapper} from 'angular2/src/facade/collection';
import {IterableList} from './fixtures/facade';
export function main() {
describe('for..of', function() {
it('should iterate iterable', function() {
var values = ['a', 'b', 'c'];
var result = ListWrapper.create();
for (var value of new IterableList(values)) {
ListWrapper.push(result, value);
}
expect(result).toEqual(values);
});
// TODO(tbosch): For ... of is not supported by our Dart transpiler right now.
// Vojta had a traceur branch that reverted https://github.com/google/traceur-compiler/commit/2d12b2f9cea86e4f234c90dcc188b4c7a2881359
// to make it work, but we should first implement this in a proper way before we start using it!
it('should iterate iterable without var declaration list', function() {
var values = ['a', 'b', 'c'];
var result = ListWrapper.create();
var value;
for (value of new IterableList(values)) {
ListWrapper.push(result, value);
}
expect(value).toEqual('c');
expect(result).toEqual(values);
});
// describe('for..of', function() {
// it('should iterate iterable', function() {
// var values = ['a', 'b', 'c'];
// var result = ListWrapper.create();
// for (var value of new IterableList(values)) {
// ListWrapper.push(result, value);
// }
// expect(result).toEqual(values);
// });
it('should iterate maps', function() {
var values = [['a', 1], ['b', 2], ['c', 3]];
var result = ListWrapper.create();
var map = MapWrapper.createFromPairs(values);
for (var [key, value] of MapWrapper.iterable(map)) {
ListWrapper.push(result, [key, value]);
}
expect(result).toEqual(values);
});
// it('should iterate iterable without var declaration list', function() {
// var values = ['a', 'b', 'c'];
// var result = ListWrapper.create();
// var value;
// for (value of new IterableList(values)) {
// ListWrapper.push(result, value);
// }
// expect(value).toEqual('c');
// expect(result).toEqual(values);
// });
it('should iterate maps without var declaration list', function() {
var values = [['a', 1], ['b', 2], ['c', 3]];
var result = ListWrapper.create();
var map = MapWrapper.createFromPairs(values);
var key, value;
for ([key, value] of MapWrapper.iterable(map)) {
ListWrapper.push(result, [key, value]);
}
expect(key).toEqual('c');
expect(value).toEqual(3);
expect(result).toEqual(values);
});
});
// it('should iterate maps', function() {
// var values = [['a', 1], ['b', 2], ['c', 3]];
// var result = ListWrapper.create();
// var map = MapWrapper.createFromPairs(values);
// for (var [key, value] of MapWrapper.iterable(map)) {
// ListWrapper.push(result, [key, value]);
// }
// expect(result).toEqual(values);
// });
// it('should iterate maps without var declaration list', function() {
// var values = [['a', 1], ['b', 2], ['c', 3]];
// var result = ListWrapper.create();
// var map = MapWrapper.createFromPairs(values);
// var key, value;
// for ([key, value] of MapWrapper.iterable(map)) {
// ListWrapper.push(result, [key, value]);
// }
// expect(key).toEqual('c');
// expect(value).toEqual(3);
// expect(result).toEqual(values);
// });
// });
}

View File

@ -19,7 +19,9 @@ import {
SEMI_COLON,
STAR,
STATIC,
VAR
VAR,
OPEN_ANGLE,
CLOSE_ANGLE
} from 'traceur/src/syntax/TokenType';
import {
@ -53,7 +55,7 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
if (tree.isFinal) {
this.write_('final');
}
this.writeType_(tree.typeAnnotation);
this.writeTypeAndSpace_(tree.typeAnnotation);
}
this.writeSpace_();
@ -78,7 +80,7 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
}
visitVariableDeclaration(tree) {
this.writeType_(tree.typeAnnotation);
this.writeTypeAndSpace_(tree.typeAnnotation);
this.visitAny(tree.lvalue);
if (tree.initializer !== null) {
@ -123,7 +125,7 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
}
if (tree.name) {
this.writeType_(tree.typeAnnotation);
this.writeTypeAndSpace_(tree.typeAnnotation);
this.visitAny(tree.name);
}
@ -152,7 +154,7 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
this.write_(ASYNC);
}
this.writeType_(tree.typeAnnotation);
this.writeTypeAndSpace_(tree.typeAnnotation);
this.visitAny(tree.name);
this.write_(OPEN_PAREN);
this.visitAny(tree.parameterList);
@ -200,7 +202,7 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
this.writeSpace_();
}
this.writeType_(tree.typeAnnotation);
this.writeTypeAndSpace_(tree.typeAnnotation);
this.visitAny(tree.name);
this.write_(OPEN_PAREN);
this.visitAny(tree.parameterList);
@ -246,7 +248,7 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
// resetting type annotation so it doesn't filter down recursively
this.currentParameterTypeAnnotation_ = null;
this.writeType_(typeAnnotation);
this.writeTypeAndSpace_(typeAnnotation);
this.visitAny(tree.binding);
if (tree.initializer) {
@ -257,22 +259,44 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
}
}
writeTypeAndSpace_(typeAnnotation) {
this.writeType_(typeAnnotation);
this.writeSpace_();
}
writeType_(typeAnnotation) {
if (!typeAnnotation) {
return;
}
var typeNameNode;
var args = [];
if (typeAnnotation.typeName) {
typeNameNode = typeAnnotation.typeName;
args = typeAnnotation.args.args;
} else {
typeNameNode = typeAnnotation;
args = [];
}
// TODO(vojta): Figure out why `typeAnnotation` has different structure when used with a variable.
// TODO(vojta): Figure out why `typeNameNode` has different structure when used with a variable.
// This should probably be fixed in Traceur.
var typeName = typeAnnotation.typeToken && typeAnnotation.typeToken.value || (typeAnnotation.name && typeAnnotation.name.value) || null;
var typeName = typeNameNode.typeToken && typeNameNode.typeToken.value || (typeNameNode.name && typeNameNode.name.value) || null;
if (!typeName) {
return;
}
this.write_(this.normalizeType_(typeName));
this.writeSpace_();
if (args.length) {
this.write_(OPEN_ANGLE);
this.writeType_(args[0]);
for (var i=1; i<args.length; i++) {
this.write_(COMMA);
this.writeSpace_();
this.writeType_(args[i]);
}
this.write_(CLOSE_ANGLE);
}
}
// EXPORTS
@ -427,7 +451,7 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
this.write_(STATIC);
this.writeSpace_();
}
this.writeType_(tree.typeAnnotation);
this.writeTypeAndSpace_(tree.typeAnnotation);
this.writeSpace_();
this.write_(GET);
this.writeSpace_();

View File

@ -8,28 +8,15 @@ export class Parser extends TraceurParser {
super(file, errorReporter);
}
parseTypeName_() {
// Copy of original implementation
var typeName = super.parseTypeName_();
// Generics support
if (this.eatIf_(OPEN_ANGLE)) {
var generics = [];
do {
generics.push(this.eatId_());
} while(this.eatIf_(COMMA));
this.eat_(CLOSE_ANGLE);
// TODO: save the generics into the typeName and use them e.g. for assertions, ...
}
return typeName;
}
// TODO: add support for object type literals to traceur!
parseObjectType_() {
//TODO(misko): save the type information
this.eat_(OPEN_CURLY);
do {
var identifier = this.eatId_();
this.eat_(COLON);
var type = this.parseNamedOrPredefinedType_();
var typeParameters = this.parseTypeParametersOpt_();
// TODO(misko): save the type information
} while (this.eatIf_(COMMA));
this.eat_(CLOSE_CURLY);
}

View File

@ -0,0 +1,43 @@
// Based on https://github.com/google/traceur-compiler/blob/master/src/codegeneration/TypeToExpressionTransformer.js
// Copyright 2012 Traceur Authors.
// Licensed under the Apache License, Version 2.0 (the 'License');
//
// Modifications:
// - use `assert` import, instead of `$traceurRuntime....` so
// that a transpilation to ES6 does not contain any traceur references.
import {ParseTreeTransformer} from 'traceur/src/codegeneration/ParseTreeTransformer.js';
import {
ArgumentList,
IdentifierExpression,
MemberExpression
} from 'traceur/src/syntax/trees/ParseTrees.js';
import {
parseExpression
} from 'traceur/src/codegeneration/PlaceholderParser.js';
export class TypeToExpressionTransformer extends ParseTreeTransformer {
transformTypeName(tree) {
if (tree.moduleName) {
var operand = this.transformAny(tree.moduleName);
return new MemberExpression(tree.location, operand, tree.name);
}
return new IdentifierExpression(tree.location, tree.name);
}
transformPredefinedType(tree) {
return parseExpression `assert.type.${tree.typeToken})`;
}
transformTypeReference(tree) {
var typeName = this.transformAny(tree.typeName);
var args = this.transformAny(tree.args);
var argumentList = new ArgumentList(tree.location, [typeName, ...args]);
return parseExpression `assert.genericType(${argumentList})`;
}
transformTypeArguments(tree) {
return this.transformList(tree.args);
}
}

View File

@ -1,21 +1,24 @@
var compiler = require('../index');
// fixme: copied from top of gulpfile
var OPTIONS = {
sourceMaps: true,
var DEFAULT_OPTIONS = {
sourceMaps: false,
annotations: true, // parse annotations
types: true, // parse types
script: false, // parse as a module
memberVariables: true, // parse class fields
outputLanguage: 'dart'
memberVariables: true // parse class fields
};
describe('transpile to dart', function(){
var options;
beforeEach(function() {
options = merge(DEFAULT_OPTIONS, {outputLanguage: 'dart'});
});
// https://github.com/angular/angular/issues/509
describe('string interpolation', function() {
it('should not interpolate inside old quotes', function(){
var result = compiler.compile(OPTIONS, "test.js",
var result = compiler.compile(options, "test.js",
"var a:number = 1;" +
"var s1:string = \"${a}\";" +
"var s2:string = '\\${a}';" +
@ -28,7 +31,7 @@ describe('transpile to dart', function(){
});
it('should not interpolate without curly braces', function() {
var result = compiler.compile(OPTIONS, "test.js",
var result = compiler.compile(options, "test.js",
"var a:number = 1;" +
"var s1:string = `$a`;" +
"var s2:string = `\\$a`;");
@ -39,7 +42,7 @@ describe('transpile to dart', function(){
});
it('should interpolate inside template quotes', function() {
var result = compiler.compile(OPTIONS, "test.js",
var result = compiler.compile(options, "test.js",
"var a:number = 1;" +
"var s1:string = `${a}`;");
expect(result.js).toBe("library test_dart;\n" +
@ -47,4 +50,121 @@ describe('transpile to dart', function(){
"String s1 = '''${a}''';\n");
});
});
describe('generic', function() {
it('should support types without generics', function() {
var result = compiler.compile(options, "test.js",
"var a:List = [];");
expect(result.js).toBe("library test_dart;\nList a = [];\n");
});
it('should support one level generics', function() {
var result = compiler.compile(options, "test.js",
"var a:List<string> = [];");
expect(result.js).toBe("library test_dart;\nList<String> a = [];\n");
});
it('should support multiple one level generics', function() {
var result = compiler.compile(options, "test.js",
"var a:List<A,B> = [];");
expect(result.js).toBe("library test_dart;\nList<A, B> a = [];\n");
});
it('should support nested generics', function() {
var result = compiler.compile(options, "test.js",
"var a:List<A<B>> = [];");
expect(result.js).toBe("library test_dart;\nList<A<B>> a = [];\n");
});
});
});
describe('transpile to es6', function() {
var options;
beforeEach(function() {
options = merge(DEFAULT_OPTIONS, {outputLanguage: 'es6', typeAssertions: 'true'});
});
it('should preserve generic type information', function() {
var result = compiler.compile(options, "test.js",
"function f(a:List<string>){}");
expect(result.js).toBe('function f(a) {\n'+
' assert.argumentTypes(a, assert.genericType(List, assert.type.string));\n'+
'}\n'+
'Object.defineProperty(f, "parameters", {get: function() {\n'+
' return [[assert.genericType(List, assert.type.string)]];\n'+
' }});\n');
});
it('should allow super() calls when transpiling to ES6 with source maps', function() {
options = merge(options, {sourceMaps: true});
var result = compiler.compile(options, "test.js",
"class Test {" +
" constructor() { super(); }" +
"}");
expect(result.js).toBe("class Test {\n" +
" constructor() {\n"+
" super();\n"+
" }\n"+
"}\n\n"+
"//# sourceMappingURL=test.map\n");
});
it('should convert types to expressions', function() {
var result = compiler.compile(options, "test.js",
"function f(a:string) {}");
expect(result.js).toBe('function f(a) {\n'+
' assert.argumentTypes(a, assert.type.string);\n'+
'}\n' +
'Object.defineProperty(f, "parameters", {get: function() {\n' +
' return [[assert.type.string]];\n' +
' }});\n');
});
it('should not convert type properties to getter/setters', function() {
var result = compiler.compile(options, "test.js",
"class Test {" +
" constructor() { this.a = 1; }" +
"}");
expect(result.js).toBe("class Test {\n" +
" constructor() {\n"+
" this.a = 1;\n"+
" }\n"+
"}\n");
});
it('should remove class field declarations', function() {
var result = compiler.compile(options, "test.js",
"class Test {" +
" a:number = 1;" +
"}");
expect(result.js).toBe("class Test {}\n");
});
it('should convert types to expressions on "assert" module', function() {
var result = compiler.compile(options, "test.js",
"function f(a:string, b) { return a+b; }");
expect(result.js).toBe('function f(a, b) {\n'+
' assert.argumentTypes(a, assert.type.string, b, assert.type.any);\n'+
' return a + b;\n'+
'}\n'+
'Object.defineProperty(f, "parameters", {get: function() {\n'+
' return [[assert.type.string], []];\n'+
' }});\n');
});
});
function merge(a, b) {
var result = {};
for (var prop in a) {
result[prop] = a[prop];
}
for (var prop in b) {
result[prop] = b[prop];
}
return result;
}

View File

@ -1,6 +0,0 @@
(function(type) {
Object.keys(type).forEach(function(name) {
type[name].__assertName = name;
});
})(window.$traceurRuntime.type);