feat(dart/transform): Add a `di` transformer

Add a transformer for `di` which generates `.ng_deps.dart` files for all
`.dart` files it is run on. These `.ng_deps.dart` files register
metadata for any `@Injectable` classes.

Fix unit tests for changes introduced by the di transformer.

When using `pub (build|serve) --mode=ngstatic`, we will also generate
getters and setters, parse templates, and remove import of `dart:mirrors`
in the Angular transform. Because this is still relatively immature, we
use the mode to keep it opt-in for now.

Closes #700
This commit is contained in:
Tim Blasi 2015-03-19 14:10:28 -07:00
parent 788461b7e2
commit 09948f4403
39 changed files with 147 additions and 73 deletions

View File

@ -15,5 +15,7 @@ dependencies:
dart_style: '^0.1.3'
html: '^0.12.0'
stack_trace: '^1.1.1'
transformers:
- angular2/src/transform/di_transformer
dev_dependencies:
guinness: "^0.1.17"

View File

@ -7,3 +7,4 @@ const REGISTER_TYPE_METHOD_NAME = 'registerType';
const REGISTER_GETTERS_METHOD_NAME = 'registerGetters';
const REGISTER_SETTERS_METHOD_NAME = 'registerSetters';
const REGISTER_METHODS_METHOD_NAME = 'registerMethods';
const TRANSFORM_MODE = 'ngstatic';

View File

@ -13,9 +13,14 @@ class TransformerOptions {
/// application's [ReflectionCapabilities] are set.
final String reflectionEntryPoint;
TransformerOptions._internal(this.entryPoint, this.reflectionEntryPoint);
/// The `BarbackMode#name` we are running in.
final String modeName;
factory TransformerOptions(String entryPoint, {String reflectionEntryPoint}) {
TransformerOptions._internal(
this.entryPoint, this.reflectionEntryPoint, this.modeName);
factory TransformerOptions(String entryPoint,
{String reflectionEntryPoint, String modeName: 'release'}) {
if (entryPoint == null) {
throw new ArgumentError.notNull(ENTRY_POINT_PARAM);
} else if (entryPoint.isEmpty) {
@ -24,6 +29,7 @@ class TransformerOptions {
if (reflectionEntryPoint == null || entryPoint.isEmpty) {
reflectionEntryPoint = entryPoint;
}
return new TransformerOptions._internal(entryPoint, reflectionEntryPoint);
return new TransformerOptions._internal(
entryPoint, reflectionEntryPoint, modeName);
}
}

View File

@ -0,0 +1,26 @@
library angular2.src.transform.di_transformer;
import 'package:barback/barback.dart';
import 'package:dart_style/dart_style.dart';
import 'directive_linker/transformer.dart';
import 'directive_processor/transformer.dart';
import 'bind_generator/transformer.dart';
import 'reflection_remover/transformer.dart';
import 'common/formatter.dart' as formatter;
import 'common/options.dart';
export 'common/options.dart';
/// Removes the mirror-based initialization logic and replaces it with static
/// logic.
class DiTransformerGroup extends TransformerGroup {
DiTransformerGroup()
: super([[new DirectiveProcessor(null)], [new DirectiveLinker()]]) {
formatter.init(new DartFormatter());
}
factory DiTransformerGroup.asPlugin(BarbackSettings settings) {
return new DiTransformerGroup();
}
}

View File

@ -16,9 +16,7 @@ import 'linker.dart';
/// `setupReflection` call the necessary `setupReflection` method in all
/// dependencies.
class DirectiveLinker extends Transformer {
final TransformerOptions options;
DirectiveLinker(this.options);
DirectiveLinker();
@override
bool isPrimary(AssetId id) => id.path.endsWith(DEPS_EXTENSION);
@ -28,10 +26,11 @@ class DirectiveLinker extends Transformer {
log.init(transform);
try {
var reader = new AssetReader.fromTransform(transform);
var assetId = transform.primaryInput.id;
var transformedCode =
await linkNgDeps(new AssetReader.fromTransform(transform), assetId);
var formattedCode = formatter.format(transformedCode, uri: assetId.path);
var assetPath = assetId.path;
var transformedCode = await linkNgDeps(reader, assetId);
var formattedCode = formatter.format(transformedCode, uri: assetPath);
transform.addOutput(new Asset.fromString(assetId, formattedCode));
} catch (ex, stackTrace) {
log.logger.error('Linking ng directives failed.\n'

View File

@ -16,17 +16,13 @@ import 'visitors.dart';
/// If no Angular 2 `Directive`s are found in [code], returns the empty
/// string unless [forceGenerate] is true, in which case an empty ngDeps
/// file is created.
String createNgDeps(String code, String path, {bool forceGenerate: false}) {
String createNgDeps(String code, String path) {
// TODO(kegluneq): Shortcut if we can determine that there are no
// [Directive]s present.
// [Directive]s present, taking into account `export`s.
var writer = new PrintStringWriter();
var visitor = new CreateNgDepsVisitor(writer, path);
parseCompilationUnit(code, name: path).accept(visitor);
if (visitor.foundNgDirectives || forceGenerate) {
return writer.toString();
} else {
return '';
}
return '$writer';
}
/// Visitor responsible for processing [CompilationUnit] and creating an
@ -35,8 +31,8 @@ class CreateNgDepsVisitor extends Object
with SimpleAstVisitor<Object>, VisitorMixin {
final PrintWriter writer;
final _Tester _tester = const _Tester();
bool foundNgDirectives = false;
bool wroteImport = false;
bool _foundNgDirectives = false;
bool _wroteImport = false;
final ToSourceVisitor _copyVisitor;
final FactoryTransformVisitor _factoryVisitor;
final ParameterTransformVisitor _paramsVisitor;
@ -61,33 +57,35 @@ class CreateNgDepsVisitor extends Object
return null;
}
void _writeImport() {
/// Write the import to the file the .ng_deps.dart file is based on if it
/// has not yet been written.
void _maybeWriteImport() {
if (_wroteImport) return;
_wroteImport = true;
writer.print('''import '${path.basename(importPath)}';''');
}
@override
Object visitImportDirective(ImportDirective node) {
if (!wroteImport) {
_writeImport();
wroteImport = true;
}
_maybeWriteImport();
return node.accept(_copyVisitor);
}
@override
Object visitExportDirective(ExportDirective node) {
_maybeWriteImport();
return node.accept(_copyVisitor);
}
void _openFunctionWrapper() {
// TODO(kegluneq): Use a [PrintWriter] with a length getter.
_maybeWriteImport();
writer.print('bool _visited = false;'
'void ${SETUP_METHOD_NAME}(${REFLECTOR_VAR_NAME}) {'
'if (_visited) return; _visited = true;');
}
void _closeFunctionWrapper() {
if (foundNgDirectives) {
if (_foundNgDirectives) {
writer.print(';');
}
writer.print('}');
@ -135,10 +133,10 @@ class CreateNgDepsVisitor extends Object
if (shouldProcess) {
var ctor = _getCtor(node);
if (!foundNgDirectives) {
if (!_foundNgDirectives) {
// The receiver for cascaded calls.
writer.print(REFLECTOR_VAR_NAME);
foundNgDirectives = true;
_foundNgDirectives = true;
}
writer.print('..registerType(');
visitNode(node.name);
@ -168,7 +166,14 @@ class CreateNgDepsVisitor extends Object
}
@override
Object visitLibraryDirective(LibraryDirective node) => _nodeToSource(node);
Object visitLibraryDirective(LibraryDirective node) {
if (node != null && node.name != null) {
writer.print('library ');
_nodeToSource(node.name);
writer.print('$DEPS_EXTENSION;');
}
return null;
}
@override
Object visitPartOfDirective(PartOfDirective node) {
@ -194,6 +199,7 @@ class _Tester {
var metaName = meta.name.toString();
return metaName == 'Component' ||
metaName == 'Decorator' ||
metaName == 'Injectable' ||
metaName == 'Template';
}
}

View File

@ -32,14 +32,13 @@ class DirectiveProcessor extends Transformer {
log.init(transform);
try {
var assetCode = await transform.primaryInput.readAsString();
var ngDepsSrc = createNgDeps(assetCode, transform.primaryInput.id.path,
forceGenerate: transform.primaryInput.id.path == options.entryPoint);
var asset = transform.primaryInput;
var assetCode = await asset.readAsString();
var ngDepsSrc = createNgDeps(assetCode, asset.id.path);
if (ngDepsSrc != null && ngDepsSrc.isNotEmpty) {
var ngDepsAssetId =
transform.primaryInput.id.changeExtension(DEPS_EXTENSION);
var exists = await transform.hasInput(ngDepsAssetId);
if (exists) {
if (await transform.hasInput(ngDepsAssetId)) {
log.logger.error('Clobbering ${ngDepsAssetId}. '
'This probably will not end well');
}

View File

@ -29,8 +29,13 @@ class _CtorTransformVisitor extends ToSourceVisitor with VisitorMixin {
var suffix = type != null ? ', ' : '';
visitNodeListWithSeparatorAndSuffix(metadata, ', ', suffix);
}
if (_withParameterTypes) {
visitNodeWithSuffix(type, ' ');
var needCompileTimeConstants = !_withParameterNames;
if (_withParameterTypes && type != null) {
visitNodeWithSuffix(type.name, ' ');
if (!needCompileTimeConstants) {
// Types with arguments are not compile-time constants.
visitNodeWithSuffix(type.typeArguments, ' ');
}
}
if (_withParameterNames) {
visitNode(name);

View File

@ -81,7 +81,7 @@ class Rewriter {
String _commentedNode(AstNode node) {
// TODO(kegluneq): Return commented code once we generate all needed code.
return _code.substring(node.offset, node.end);
return '/*${_code.substring(node.offset, node.end)}*/';
}
}

View File

@ -9,20 +9,27 @@ import 'bind_generator/transformer.dart';
import 'reflection_remover/transformer.dart';
import 'template_compiler/transformer.dart';
import 'common/formatter.dart' as formatter;
import 'common/names.dart';
import 'common/options.dart';
export 'common/options.dart';
/// Replaces Angular 2 mirror use with generated code.
class AngularTransformerGroup extends TransformerGroup {
AngularTransformerGroup(TransformerOptions options) : super([
[new DirectiveProcessor(options)],
[new DirectiveLinker(options)],
AngularTransformerGroup._(phases) : super(phases) {
formatter.init(new DartFormatter());
}
factory AngularTransformerGroup(TransformerOptions options) {
var phases = [[new DirectiveProcessor(options)], [new DirectiveLinker()]];
if (options.modeName == TRANSFORM_MODE) {
phases.addAll([
[new BindGenerator(options)],
[new TemplateComplier(options)],
[new ReflectionRemover(options)]
]) {
formatter.init(new DartFormatter());
]);
}
return new AngularTransformerGroup._(phases);
}
factory AngularTransformerGroup.asPlugin(BarbackSettings settings) {
@ -33,5 +40,6 @@ class AngularTransformerGroup extends TransformerGroup {
TransformerOptions _parseOptions(BarbackSettings settings) {
var config = settings.configuration;
return new TransformerOptions(config[ENTRY_POINT_PARAM],
reflectionEntryPoint: config[REFLECTION_ENTRY_POINT_PARAM]);
reflectionEntryPoint: config[REFLECTION_ENTRY_POINT_PARAM],
modeName: settings.mode.name);
}

View File

@ -1,4 +1,4 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library dinner.soup;
library dinner.soup.ng_deps.dart;
import 'package:angular2/src/core/annotations/annotations.dart';
import 'soup.dart';

View File

@ -1,4 +1,4 @@
library dinner.soup;
library dinner.soup.ng_deps.dart;
import 'package:angular2/src/core/annotations/annotations.dart';
import 'soup.dart';

View File

@ -1,4 +1,4 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library foo;
library foo.ng_deps.dart;
import 'foo.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library web_foo;
library web_foo.ng_deps.dart;
import 'package:angular2/src/core/application.dart';
import 'package:angular2/src/reflection/reflection_capabilities.dart';

View File

@ -1,4 +1,4 @@
library foo;
library foo.ng_deps.dart;
import 'foo.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library web_foo;
library web_foo.ng_deps.dart;
import 'package:angular2/src/core/application.dart';
import 'package:angular2/src/reflection/reflection_capabilities.dart';

View File

@ -1,4 +1,4 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library foo;
library foo.ng_deps.dart;
import 'foo.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library web_foo;
library web_foo.ng_deps.dart;
import 'package:angular2/src/core/application.dart';
import 'package:angular2/src/reflection/reflection_capabilities.dart';

View File

@ -1,4 +1,4 @@
library foo;
library foo.ng_deps.dart;
import 'foo.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -1,4 +1,4 @@
library web_foo;
library web_foo.ng_deps.dart;
import 'package:angular2/src/core/application.dart';
import 'package:angular2/src/reflection/reflection_capabilities.dart';

View File

@ -1,4 +1,4 @@
library dinner.soup;
library dinner.soup.ng_deps.dart;
import 'soup.dart';
import 'package:angular2/src/core/annotations/annotations.dart';

View File

@ -2,16 +2,17 @@ library angular2.test.transform.integration;
import 'dart:io';
import 'package:angular2/src/dom/html_adapter.dart';
import 'package:angular2/src/transform/common/names.dart';
import 'package:angular2/transformer.dart';
import 'package:code_transformers/tests.dart';
import 'package:dart_style/dart_style.dart';
import 'package:guinness/guinness.dart';
import '../common/read_file.dart';
var formatter = new DartFormatter();
var transform = new AngularTransformerGroup(new TransformerOptions(
'web/index.dart', reflectionEntryPoint: 'web/index.dart'));
'web/index.dart',
reflectionEntryPoint: 'web/index.dart', modeName: TRANSFORM_MODE));
class IntegrationTestConfig {
final String name;

View File

@ -1,8 +1,10 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';
import 'foo.dart';
import 'foo.ng_deps.dart' as i0;
import 'package:angular2/src/core/annotations/annotations.ng_deps.dart' as i1;
bool _visited = false;
void setupReflection(reflector) {
@ -15,4 +17,6 @@ void setupReflection(reflector) {
'annotations':
const [const Component(componentServices: const [MyContext])]
});
i0.setupReflection(reflector);
i1.setupReflection(reflector);
}

View File

@ -1,7 +1,8 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';
import 'package:angular2/src/core/annotations/annotations.ng_deps.dart' as i0;
bool _visited = false;
void setupReflection(reflector) {
@ -13,4 +14,5 @@ void setupReflection(reflector) {
'parameters': const [],
'annotations': const [const Component(selector: '[soup]')]
});
i0.setupReflection(reflector);
}

View File

@ -1,4 +1,4 @@
library web_foo;
library web_foo.ng_deps.dart;
import 'index.dart';
import 'package:angular2/src/core/application.dart';
@ -6,10 +6,15 @@ import 'package:angular2/src/reflection/reflection.dart';
import 'package:angular2/src/reflection/reflection_capabilities.dart';
import 'bar.dart';
import 'bar.ng_deps.dart' as i0;
import 'package:angular2/src/core/application.ng_deps.dart' as i1;
import 'package:angular2/src/reflection/reflection_capabilities.ng_deps.dart'
as i2;
bool _visited = false;
void setupReflection(reflector) {
if (_visited) return;
_visited = true;
i0.setupReflection(reflector);
i1.setupReflection(reflector);
i2.setupReflection(reflector);
}

View File

@ -1,7 +1,8 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';
import 'package:angular2/src/core/annotations/annotations.ng_deps.dart' as i0;
bool _visited = false;
void setupReflection(reflector) {
@ -13,4 +14,5 @@ void setupReflection(reflector) {
'parameters': const [],
'annotations': const [const Component(selector: '[soup]')]
});
i0.setupReflection(reflector);
}

View File

@ -1,8 +1,10 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';
import 'package:angular2/src/core/annotations/template.dart';
import 'package:angular2/src/core/annotations/template.ng_deps.dart' as i0;
import 'package:angular2/src/core/annotations/annotations.ng_deps.dart' as i1;
bool _visited = false;
void setupReflection(reflector) {
@ -17,4 +19,6 @@ void setupReflection(reflector) {
const Template(inline: 'Salad')
]
});
i0.setupReflection(reflector);
i1.setupReflection(reflector);
}

View File

@ -1,8 +1,10 @@
library bar;
library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/core/annotations/annotations.dart';
import 'foo.dart' as prefix;
import 'foo.ng_deps.dart' as i0;
import 'package:angular2/src/core/annotations/annotations.ng_deps.dart' as i1;
bool _visited = false;
void setupReflection(reflector) {
@ -16,4 +18,6 @@ void setupReflection(reflector) {
'annotations':
const [const Component(selector: prefix.preDefinedSelector)]
});
i0.setupReflection(reflector);
i1.setupReflection(reflector);
}

View File

@ -13,10 +13,10 @@ library web_foo;
import 'package:angular2/src/core/application.dart';
import 'package:angular2/src/reflection/reflection.dart';
import 'package:angular2/src/reflection/reflection_capabilities.dart';import 'index.ng_deps.dart' as ngStaticInit;
/*import 'package:angular2/src/reflection/reflection_capabilities.dart';*/import 'index.ng_deps.dart' as ngStaticInit;
void main() {
reflector.reflectionCapabilities = new ReflectionCapabilities();ngStaticInit.setupReflection(reflector);
/*reflector.reflectionCapabilities = new ReflectionCapabilities();*/ngStaticInit.setupReflection(reflector);
bootstrap(MyComponent);
}
""";

View File

@ -1,4 +1,4 @@
library examples.hello_world.index_common_dart;
library examples.hello_world.index_common_dart.ng_deps.dart;
import 'hello.dart';
import 'package:angular2/angular2.dart'

View File

@ -1,4 +1,4 @@
library examples.hello_world.index_common_dart;
library examples.hello_world.index_common_dart.ng_deps.dart;
import 'hello.dart';
import 'package:angular2/angular2.dart'

View File

@ -1,4 +1,4 @@
library examples.hello_world.index_common_dart;
library examples.hello_world.index_common_dart.ng_deps.dart;
import 'hello.dart';
import 'package:angular2/angular2.dart'

View File

@ -1,4 +1,4 @@
library examples.hello_world.index_common_dart;
library examples.hello_world.index_common_dart.ng_deps.dart;
import 'hello.dart';
import 'package:angular2/angular2.dart'