Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
| 4 | 4 |
| 5 /// Transfomer that combines multiple dart script tags into a single one. | 5 /// Transfomer that combines multiple dart script tags into a single one. |
| 6 library polymer.src.build.script_compactor; | 6 library polymer.src.build.script_compactor; |
| 7 | 7 |
| 8 import 'dart:async'; | 8 import 'dart:async'; |
| 9 import 'dart:convert'; | 9 import 'dart:convert'; |
| 10 | 10 |
| 11 import 'package:html5lib/dom.dart' show Document, Element; | 11 import 'package:html5lib/dom.dart' show Document, Element, Text; |
| 12 import 'package:html5lib/dom_parsing.dart'; | |
| 12 import 'package:analyzer/src/generated/ast.dart'; | 13 import 'package:analyzer/src/generated/ast.dart'; |
| 14 import 'package:analyzer/src/generated/element.dart' hide Element; | |
| 15 import 'package:analyzer/src/generated/element.dart' as analyzer show Element; | |
| 13 import 'package:barback/barback.dart'; | 16 import 'package:barback/barback.dart'; |
| 14 import 'package:code_transformers/assets.dart'; | 17 import 'package:code_transformers/assets.dart'; |
| 15 import 'package:path/path.dart' as path; | 18 import 'package:path/path.dart' as path; |
| 16 import 'package:source_maps/span.dart' show SourceFile; | 19 import 'package:source_maps/span.dart' show SourceFile; |
| 20 import 'package:smoke/codegen/generator.dart'; | |
| 21 import 'package:smoke/codegen/recorder.dart'; | |
| 22 import 'package:code_transformers/resolver.dart'; | |
| 23 import 'package:code_transformers/src/dart_sdk.dart'; | |
| 24 | |
| 25 import 'package:polymer_expressions/expression.dart' as pe; | |
| 26 import 'package:polymer_expressions/parser.dart' as pe; | |
| 27 import 'package:polymer_expressions/visitor.dart' as pe; | |
| 17 | 28 |
| 18 import 'import_inliner.dart' show ImportInliner; // just for docs. | 29 import 'import_inliner.dart' show ImportInliner; // just for docs. |
| 19 import 'common.dart'; | 30 import 'common.dart'; |
| 20 | 31 |
| 21 /// Combines Dart script tags into a single script tag, and creates a new Dart | 32 /// Combines Dart script tags into a single script tag, and creates a new Dart |
| 22 /// file that calls the main function of each of the original script tags. | 33 /// file that calls the main function of each of the original script tags. |
| 23 /// | 34 /// |
| 24 /// This transformer assumes that all script tags point to external files. To | 35 /// This transformer assumes that all script tags point to external files. To |
| 25 /// support script tags with inlined code, use this transformer after running | 36 /// support script tags with inlined code, use this transformer after running |
| 26 /// [ImportInliner] on an earlier phase. | 37 /// [ImportInliner] on an earlier phase. |
| 27 /// | 38 /// |
| 28 /// Internally, this transformer will convert each script tag into an import | 39 /// Internally, this transformer will convert each script tag into an import |
| 29 /// statement to a library, and then uses `initPolymer` (see polymer.dart) to | 40 /// statement to a library, and then uses `initPolymer` (see polymer.dart) to |
| 30 /// process `@initMethod` and `@CustomTag` annotations in those libraries. | 41 /// process `@initMethod` and `@CustomTag` annotations in those libraries. |
| 31 class ScriptCompactor extends Transformer { | 42 class ScriptCompactor extends Transformer { |
| 43 final Resolvers resolvers; | |
| 32 final TransformOptions options; | 44 final TransformOptions options; |
| 33 | 45 |
| 34 ScriptCompactor(this.options); | 46 ScriptCompactor(this.options, {String sdkDir}) |
| 47 : resolvers = new Resolvers(sdkDir != null ? sdkDir : dartSdkDirectory); | |
| 35 | 48 |
| 36 /// Only run on entry point .html files. | 49 /// Only run on entry point .html files. |
| 37 Future<bool> isPrimary(Asset input) => | 50 Future<bool> isPrimary(Asset input) => |
| 38 new Future.value(options.isHtmlEntryPoint(input.id)); | 51 new Future.value(options.isHtmlEntryPoint(input.id)); |
| 39 | 52 |
| 40 Future apply(Transform transform) => | 53 Future apply(Transform transform) => |
| 41 new _ScriptCompactor(transform, options).apply(); | 54 new _ScriptCompactor(transform, options, resolvers).apply(); |
| 42 } | 55 } |
| 43 | 56 |
| 44 /// Helper class mainly use to flatten the async code. | 57 /// Helper class mainly use to flatten the async code. |
| 45 class _ScriptCompactor extends PolymerTransformer { | 58 class _ScriptCompactor extends PolymerTransformer { |
| 46 final TransformOptions options; | 59 final TransformOptions options; |
| 47 final Transform transform; | 60 final Transform transform; |
| 48 final TransformLogger logger; | 61 final TransformLogger logger; |
| 49 final AssetId docId; | 62 final AssetId docId; |
| 50 final AssetId bootstrapId; | 63 final AssetId bootstrapId; |
| 51 | 64 |
| 65 /// HTML document parsed from [docId]. | |
| 52 Document document; | 66 Document document; |
| 67 | |
| 68 /// List of ids for each Dart entry script tag (the main tag and any tag | |
| 69 /// included on each custom element definition). | |
| 53 List<AssetId> entryLibraries; | 70 List<AssetId> entryLibraries; |
| 71 | |
| 72 /// The id of the main Dart program. | |
| 54 AssetId mainLibraryId; | 73 AssetId mainLibraryId; |
| 74 | |
| 75 /// Script tag that loads the Dart entry point. | |
| 55 Element mainScriptTag; | 76 Element mainScriptTag; |
| 56 final Map<AssetId, List<_Initializer>> initializers = {}; | |
| 57 | 77 |
| 58 _ScriptCompactor(Transform transform, this.options) | 78 /// Initializers that will register custom tags or invoke `initMethod`s. |
| 79 final List<_Initializer> initializers = []; | |
| 80 | |
| 81 /// Attributes published on a custom-tag. We make these available via | |
| 82 /// reflection even if @published was not used. | |
| 83 final Map<String, List<String>> publishedAttributes = {}; | |
| 84 | |
| 85 /// Those custom-tags for which we have found a corresponding class in code. | |
| 86 final Set<String> tagsWithClasses = new Set(); | |
| 87 | |
| 88 /// Hook needed to access the analyzer within barback transformers. | |
| 89 final Resolvers resolvers; | |
| 90 | |
| 91 /// The resolver instance associated with a single run of this transformer. | |
| 92 Resolver resolver; | |
| 93 | |
| 94 /// Element representing `HtmlElement`. | |
| 95 ClassElement _htmlElementElement; | |
| 96 | |
| 97 /// Element representing the type of `@CustomTag`. | |
| 98 ClassElement _customTagElement; | |
| 99 | |
| 100 /// Element representing the type of `@published`. | |
| 101 ClassElement _publishedElement; | |
| 102 | |
| 103 /// Element representing the type of `@observable`. | |
| 104 ClassElement _observableElement; | |
| 105 | |
| 106 /// Element representing the type of `@ObserveProperty`. | |
| 107 ClassElement _observePropertyElement; | |
| 108 | |
| 109 /// Element representing the `@initMethod` annotation. | |
| 110 TopLevelVariableElement _initMethodElement; | |
| 111 | |
| 112 /// Code generator used to create the static initialization for smoke. | |
| 113 final SmokeCodeGenerator generator = new SmokeCodeGenerator(); | |
| 114 | |
| 115 /// Recorder that uses analyzer data to feed data to [generator]. | |
| 116 Recorder recorder; | |
| 117 | |
| 118 _ScriptCompactor(Transform transform, this.options, this.resolvers) | |
| 59 : transform = transform, | 119 : transform = transform, |
| 60 logger = transform.logger, | 120 logger = transform.logger, |
| 61 docId = transform.primaryInput.id, | 121 docId = transform.primaryInput.id, |
| 62 bootstrapId = transform.primaryInput.id.addExtension('_bootstrap.dart'); | 122 bootstrapId = transform.primaryInput.id.addExtension('_bootstrap.dart'); |
| 63 | 123 |
| 64 Future apply() => | 124 Future apply() => |
| 65 _loadDocument() | 125 _loadDocument() |
| 66 .then(_loadEntryLibraries) | 126 .then(_loadEntryLibraries) |
| 67 .then(_processHtml) | 127 .then(_processHtml) |
| 68 .then(_emitNewEntrypoint); | 128 .then(_emitNewEntrypoint); |
| (...skipping 44 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 113 Future _emitNewEntrypoint(_) { | 173 Future _emitNewEntrypoint(_) { |
| 114 if (mainScriptTag == null) { | 174 if (mainScriptTag == null) { |
| 115 // We didn't find any main library, nothing to do. | 175 // We didn't find any main library, nothing to do. |
| 116 transform.addOutput(transform.primaryInput); | 176 transform.addOutput(transform.primaryInput); |
| 117 return null; | 177 return null; |
| 118 } | 178 } |
| 119 | 179 |
| 120 // Emit the bootstrap .dart file | 180 // Emit the bootstrap .dart file |
| 121 mainScriptTag.attributes['src'] = path.url.basename(bootstrapId.path); | 181 mainScriptTag.attributes['src'] = path.url.basename(bootstrapId.path); |
| 122 entryLibraries.add(mainLibraryId); | 182 entryLibraries.add(mainLibraryId); |
| 123 return _computeInitializers().then(_createBootstrapCode).then((code) { | 183 |
| 124 transform.addOutput(new Asset.fromString(bootstrapId, code)); | 184 return _initResolver() |
| 125 transform.addOutput(new Asset.fromString(docId, document.outerHtml)); | 185 .then(_extractUsesOfMirrors) |
| 186 .then(_emitFiles) | |
| 187 .then((_) => resolver.release()); | |
| 188 } | |
| 189 | |
| 190 /// Load a resolver that computes information for every library in | |
| 191 /// [entryLibraries], then use it to initialize the [recorder] (for import | |
| 192 /// resolution) and to resolve specific elements (for analyzing the user's | |
| 193 /// code). | |
| 194 Future _initResolver() => resolvers.get(transform, entryLibraries).then((r) { | |
| 195 resolver = r; | |
| 196 recorder = new Recorder(generator, | |
| 197 (lib) => resolver.getImportUri(lib, from: bootstrapId).toString()); | |
| 198 | |
| 199 // Load class elements that are used in queries for codegen. | |
| 200 var polymerLib = r.getLibrary(new AssetId('polymer', 'lib/polymer.dart')); | |
| 201 if (polymerLib == null) _definitionError('the polymer library'); | |
| 202 var htmlLib = r.getLibraryByUri(Uri.parse('dart:html')); | |
| 203 if (htmlLib == null) _definitionError('the "dart:html" library'); | |
| 204 var observeLib = r.getLibrary( | |
| 205 new AssetId('observe', 'lib/src/metadata.dart')); | |
| 206 if (observeLib == null) _definitionError('the observe library'); | |
| 207 | |
| 208 for (var unit in polymerLib.parts) { | |
| 209 if (unit.uri == 'src/loader.dart') { | |
| 210 _initMethodElement = unit.topLevelVariables.firstWhere( | |
| 211 (t) => t.displayName == 'initMethod'); | |
| 212 break; | |
| 213 } | |
| 214 } | |
| 215 _customTagElement = _lookupType(polymerLib, 'CustomTag'); | |
|
blois
2014/03/26 16:02:33
If you change this to be the constructor then can
Siggi Cherem (dart-lang)
2014/03/26 17:56:34
Nice idea. Done.
| |
| 216 _publishedElement = _lookupType(polymerLib, 'PublishedProperty'); | |
| 217 _observableElement = _lookupType(observeLib, 'ObservableProperty'); | |
|
blois
2014/03/26 16:02:33
Why not use the const TopLevelVariable?
Siggi Cherem (dart-lang)
2014/03/26 17:56:34
good question. I'm on the fence on this.
I mainly
| |
| 218 _observePropertyElement = _lookupType(polymerLib, 'ObserveProperty'); | |
| 219 _htmlElementElement = _lookupType(htmlLib, 'HtmlElement'); | |
| 220 if (_initMethodElement == null) _definitionError('@initMethod'); | |
| 221 }); | |
| 222 | |
| 223 _lookupType(LibraryElement lib, String typeName) { | |
| 224 var result = lib.getType(typeName); | |
| 225 if (result == null) _definitionError(typeName); | |
| 226 return result; | |
| 227 } | |
| 228 | |
| 229 _definitionError(name) { | |
| 230 throw new StateError("Internal error in polymer-builder: couldn't find " | |
| 231 "definition of $name."); | |
| 232 } | |
| 233 | |
| 234 /// Inspects the entire program to find out anything that polymer accesses | |
| 235 /// using mirrors and produces static information that can be used to replace | |
| 236 /// the mirror-based loader and the uses of mirrors through the `smoke` | |
| 237 /// package. This includes: | |
| 238 /// | |
| 239 /// * visiting entry-libraries to extract initializers, | |
| 240 /// * visiting polymer-expressions to extract getters and setters, | |
| 241 /// * looking for published fields of custom elements, and | |
| 242 /// * looking for event handlers and callbacks of change notifications. | |
| 243 /// | |
| 244 void _extractUsesOfMirrors(_) { | |
| 245 // Generate getters and setters needed to evaluate polymer expressions, and | |
| 246 // extract information about published attributes. | |
| 247 new _HtmlExtractor(generator, publishedAttributes).visit(document); | |
| 248 | |
| 249 // Process all classes and top-level functions to include initializers, | |
| 250 // register custom elements, and include special fields and methods in | |
| 251 // custom element classes. | |
| 252 for (var id in entryLibraries) { | |
| 253 var lib = resolver.getLibrary(id); | |
| 254 for (var cls in _visibleClassesOf(lib)) { | |
| 255 _processClass(cls, id); | |
| 256 } | |
| 257 | |
| 258 for (var fun in _visibleTopLevelMethodsOf(lib)) { | |
| 259 _processFunction(fun, id); | |
| 260 } | |
| 261 } | |
| 262 | |
| 263 // Warn about tagNames with no corresponding Dart class | |
| 264 // TODO(sigmund): is there a way to exclude polymer.js elements? should we | |
| 265 // remove the warning below? | |
| 266 publishedAttributes.forEach((tagName, attrs) { | |
| 267 if (tagsWithClasses.contains(tagName)) return; | |
| 268 logger.warning('Class for custom-element "$tagName" not found. ' | |
| 269 'Code-generation might be incomplete.'); | |
| 270 // We include accessors for the missing attributes because they help get | |
| 271 // better warning messages at runtime. | |
| 272 for (var attr in attrs) { | |
| 273 generator.addGetter(attr); | |
| 274 generator.addSetter(attr); | |
| 275 generator.addSymbol(attr); | |
| 276 } | |
| 126 }); | 277 }); |
| 127 } | 278 } |
| 128 | 279 |
| 129 /// Emits the actual bootstrap code. | 280 /// Retrieves all classses that are visible if you were to import [lib]. This |
| 130 String _createBootstrapCode(_) { | 281 /// includes exported classes from other libraries. |
| 282 List<ClassElement> _visibleClassesOf(LibraryElement lib) { | |
| 283 var result = []; | |
| 284 result.addAll(lib.units.expand((u) => u.types)); | |
| 285 for (var e in lib.exports) { | |
| 286 var exported = e.exportedLibrary.units.expand((u) => u.types).toList(); | |
| 287 _filter(exported, e.combinators); | |
| 288 result.addAll(exported); | |
| 289 } | |
| 290 return result; | |
| 291 } | |
| 292 | |
| 293 /// Retrieves all top-level methods that are visible if you were to import | |
| 294 /// [lib]. This includes exported methods from other libraries too. | |
| 295 List<ClassElement> _visibleTopLevelMethodsOf(LibraryElement lib) { | |
| 296 var result = []; | |
| 297 result.addAll(lib.units.expand((u) => u.functions)); | |
| 298 for (var e in lib.exports) { | |
| 299 var exported = e.exportedLibrary.units | |
| 300 .expand((u) => u.functions).toList(); | |
| 301 _filter(exported, e.combinators); | |
| 302 result.addAll(exported); | |
| 303 } | |
| 304 return result; | |
| 305 } | |
| 306 | |
| 307 /// Filters [elements] that come from an export, according to its show/hide | |
| 308 /// combinators. This modifies [elements] in place. | |
| 309 void _filter(List<analyzer.Element> elements, | |
| 310 List<NamespaceCombinator> combinators) { | |
| 311 for (var c in combinators) { | |
| 312 if (c is ShowElementCombinator) { | |
| 313 var show = c.shownNames.toSet(); | |
| 314 elements.retainWhere((e) => show.contains(e.displayName)); | |
| 315 } else if (c is HideElementCombinator) { | |
| 316 var hide = c.hiddenNames.toSet(); | |
| 317 elements.removeWhere((e) => hide.contains(e.displayName)); | |
| 318 } | |
| 319 } | |
| 320 } | |
| 321 | |
| 322 /// Process a class ([cls]). If it contains an appropriate [CustomTag] | |
| 323 /// annotation, we include an initializer to register this class, and make | |
| 324 /// sure to include everything that might be accessed or queried from them | |
| 325 /// using the smoke package. In particular, polymer uses smoke for the | |
| 326 /// following: | |
| 327 /// * invoke #registerCallback on custom elements classes, if present. | |
| 328 /// * query for methods ending in `*Changed`. | |
| 329 /// * query for methods with the `@ObserveProperty` annotation. | |
| 330 /// * query for non-final properties labeled with `@published`. | |
| 331 /// * read declarations of properties named in the `attributes` attribute. | |
| 332 /// * read/write the value of published properties . | |
| 333 /// * invoke methods in event handlers. | |
| 334 _processClass(ClassElement cls, AssetId id) { | |
| 335 // Check whether the class has a @CustomTag annotation. Typically we expect | |
| 336 // a single @CustomTag, but it's possible to have several. | |
| 337 var tagNames = []; | |
| 338 for (var meta in cls.node.metadata) { | |
| 339 var tagName = _extractTagName(meta, cls); | |
| 340 if (tagName != null) tagNames.add(tagName); | |
| 341 } | |
| 342 if (tagNames.isEmpty) return; | |
| 343 | |
| 344 if (cls.isPrivate) { | |
| 345 logger.error('@CustomTag is no longer supported on private classes:' | |
| 346 ' ${tagNames.first}', span: _spanForNode(cls, cls.node.name)); | |
| 347 return; | |
| 348 } | |
| 349 | |
| 350 // Include #registerCallback if it exists. Note that by default lookupMember | |
| 351 // and query will also add the corresponding getters and setters. | |
| 352 recorder.lookupMember(cls, 'registerCallback'); | |
| 353 | |
| 354 // Include methods that end with *Changed. | |
| 355 recorder.runQuery(cls, new QueryOptions( | |
| 356 includeFields: false, includeProperties: false, | |
| 357 includeInherited: true, includeMethods: true, | |
| 358 includeUpTo: _htmlElementElement, | |
| 359 matches: (n) => n.endsWith('Changed') && n != 'attributeChanged')); | |
| 360 | |
| 361 // Include methods marked with @ObserveProperty. | |
| 362 recorder.runQuery(cls, new QueryOptions( | |
| 363 includeFields: false, includeProperties: false, | |
| 364 includeInherited: true, includeMethods: true, | |
| 365 includeUpTo: _htmlElementElement, | |
| 366 withAnnotations: [_observePropertyElement])); | |
| 367 | |
| 368 // Include @published and @observable properties. | |
| 369 // Symbols in @published are used when resolving bindings on published | |
| 370 // attributes, symbols for @observable are used via path observers when | |
| 371 // implementing *Changed an @ObserveProperty. | |
| 372 // TODO(sigmund): consider including only those symbols mentioned in | |
| 373 // *Changed and @ObserveProperty instead. | |
| 374 recorder.runQuery(cls, new QueryOptions(includeUpTo: _htmlElementElement, | |
| 375 withAnnotations: [_publishedElement, _observableElement])); | |
| 376 | |
| 377 for (var tagName in tagNames) { | |
| 378 tagsWithClasses.add(tagName); | |
| 379 // Include an initializer that will call Polymer.register | |
| 380 initializers.add(new _CustomTagInitializer(id, tagName, cls.displayName)); | |
| 381 | |
| 382 // Include also properties published via the `attributes` attribute. | |
| 383 var attrs = publishedAttributes[tagName]; | |
| 384 if (attrs == null) continue; | |
| 385 for (var attr in attrs) { | |
| 386 recorder.lookupMember(cls, attr, recursive: true); | |
| 387 } | |
| 388 } | |
| 389 } | |
| 390 | |
| 391 /// If [meta] is [CustomTag], extract the name associated with the tag. | |
| 392 String _extractTagName(Annotation meta, ClassElement cls) { | |
| 393 if (meta.element is! ConstructorElement || | |
| 394 meta.element.enclosingElement != _customTagElement) { | |
| 395 return null; | |
| 396 } | |
| 397 var args = meta.arguments.arguments; | |
| 398 if (args == null || args.length == 0) { | |
| 399 logger.error('Missing argument in @CustomTag annotation', | |
| 400 span: _spanForNode(cls, meta)); | |
| 401 return null; | |
| 402 } | |
| 403 return args[0].stringValue; | |
|
blois
2014/03/26 16:02:33
Might want to check that this is a StringLiteral-
Siggi Cherem (dart-lang)
2014/03/26 17:56:34
Done.
| |
| 404 } | |
| 405 | |
| 406 /// Adds the top-level [function] as an initalizer if it's marked with | |
| 407 /// `@initMethod`. | |
| 408 _processFunction(FunctionElement function, AssetId id) { | |
| 409 bool initMethodFound = false; | |
| 410 for (var meta in function.metadata) { | |
| 411 var e = meta.element; | |
| 412 if (e is PropertyAccessorElement && e.variable == _initMethodElement) { | |
| 413 initMethodFound = true; | |
| 414 break; | |
| 415 } | |
| 416 } | |
| 417 if (!initMethodFound) return; | |
| 418 if (function.isPrivate) { | |
| 419 logger.error('@initMethod is no longer supported on private ' | |
| 420 'functions: ${function.displayName}', | |
| 421 span: _spanForNode(function, function.node.name)); | |
| 422 return; | |
| 423 } | |
| 424 initializers.add(new _InitMethodInitializer(id, function.displayName)); | |
| 425 } | |
| 426 | |
| 427 /// Writes the final output for the bootstrap Dart file and entrypoint HTML | |
| 428 /// file. | |
| 429 void _emitFiles(_) { | |
| 131 StringBuffer code = new StringBuffer()..writeln(MAIN_HEADER); | 430 StringBuffer code = new StringBuffer()..writeln(MAIN_HEADER); |
| 132 for (int i = 0; i < entryLibraries.length; i++) { | 431 Map<AssetId, String> prefixes = {}; |
| 133 var url = assetUrlFor(entryLibraries[i], bootstrapId, logger); | 432 int i = 0; |
| 134 if (url != null) code.writeln("import '$url' as i$i;"); | 433 for (var id in entryLibraries) { |
| 135 } | 434 var url = assetUrlFor(id, bootstrapId, logger); |
| 136 | 435 if (url == null) continue; |
| 137 code..write('\n') | 436 code.writeln("import '$url' as i$i;"); |
| 138 ..writeln('void main() {') | 437 prefixes[id] = 'i$i'; |
| 139 ..writeln(' configureForDeployment(['); | 438 i++; |
| 140 | 439 } |
| 141 // Inject @CustomTag and @initMethod initializations for each library | 440 |
| 142 // that is sourced in a script tag. | 441 // Include smoke initialization. |
| 143 for (int i = 0; i < entryLibraries.length; i++) { | 442 generator.writeImports(code); |
| 144 for (var init in initializers[entryLibraries[i]]) { | 443 generator.writeTopLevelDeclarations(code); |
| 145 var initCode = init.asCode('i$i'); | 444 code.writeln('\nvoid main() {'); |
| 146 code.write(" $initCode,\n"); | 445 generator.writeInitCall(code); |
| 147 } | 446 code.writeln(' configureForDeployment(['); |
| 447 | |
| 448 // Include initializers to switch from mirrors_loader to static_loader. | |
| 449 // TODO(sigmund): do we need to sort out initializers to ensure that parent | |
| 450 // classes are initialized first? | |
| 451 for (var init in initializers) { | |
| 452 var initCode = init.asCode(prefixes[init.assetId]); | |
| 453 code.write(" $initCode,\n"); | |
| 148 } | 454 } |
| 149 code..writeln(' ]);') | 455 code..writeln(' ]);') |
| 150 ..writeln(' i${entryLibraries.length - 1}.main();') | 456 ..writeln(' i${entryLibraries.length - 1}.main();') |
| 151 ..writeln('}'); | 457 ..writeln('}'); |
| 152 return code.toString(); | 458 transform.addOutput(new Asset.fromString(bootstrapId, code.toString())); |
| 153 } | 459 transform.addOutput(new Asset.fromString(docId, document.outerHtml)); |
| 154 | 460 } |
| 155 /// Computes initializers needed for each library in [entryLibraries]. Results | 461 |
| 156 /// are available afterwards in [initializers]. | 462 _spanForNode(analyzer.Element context, AstNode node) { |
| 157 Future _computeInitializers() => Future.forEach(entryLibraries, (lib) { | 463 var file = resolver.getSourceFile(context); |
| 158 return _initializersOf(lib).then((res) { | 464 return file.span(node.offset, node.end); |
| 159 initializers[lib] = res; | |
| 160 }); | |
| 161 }); | |
| 162 | |
| 163 /// Computes the initializers of [dartLibrary]. That is, a closure that calls | |
| 164 /// Polymer.register for each @CustomTag, and any public top-level methods | |
| 165 /// labeled with @initMethod. | |
| 166 Future<List<_Initializer>> _initializersOf(AssetId dartLibrary) { | |
|
Siggi Cherem (dart-lang)
2014/03/26 01:18:09
now that I had to use the resolver, I rewrote this
| |
| 167 var result = []; | |
| 168 return transform.readInputAsString(dartLibrary).then((code) { | |
| 169 var file = new SourceFile.text(_simpleUriForSource(dartLibrary), code); | |
| 170 var unit = parseCompilationUnit(code); | |
| 171 | |
| 172 return Future.forEach(unit.directives, (directive) { | |
| 173 // Include anything from parts. | |
| 174 if (directive is PartDirective) { | |
| 175 var targetId = uriToAssetId(dartLibrary, directive.uri.stringValue, | |
| 176 logger, _getSpan(file, directive)); | |
| 177 return _initializersOf(targetId).then(result.addAll); | |
| 178 } | |
| 179 | |
| 180 // Similarly, include anything from exports except what's filtered by | |
| 181 // the show/hide combinators. | |
| 182 if (directive is ExportDirective) { | |
| 183 var targetId = uriToAssetId(dartLibrary, directive.uri.stringValue, | |
| 184 logger, _getSpan(file, directive)); | |
| 185 return _initializersOf(targetId).then( | |
| 186 (r) => _processExportDirective(directive, r, result)); | |
| 187 } | |
| 188 }).then((_) { | |
| 189 // Scan the code for classes and top-level functions. | |
| 190 for (var node in unit.declarations) { | |
| 191 if (node is ClassDeclaration) { | |
| 192 _processClassDeclaration(node, result, file, logger); | |
| 193 } else if (node is FunctionDeclaration && | |
| 194 node.metadata.any(_isInitMethodAnnotation)) { | |
| 195 _processFunctionDeclaration(node, result, file, logger); | |
| 196 } | |
| 197 } | |
| 198 return result; | |
| 199 }); | |
| 200 }); | |
| 201 } | |
| 202 | |
| 203 static String _simpleUriForSource(AssetId source) => | |
| 204 source.path.startsWith('lib/') | |
| 205 ? 'package:${source.package}/${source.path.substring(4)}' : source.path; | |
| 206 | |
| 207 /// Filter [exportedInitializers] according to [directive]'s show/hide | |
| 208 /// combinators and add the result to [result]. | |
| 209 // TODO(sigmund): call the analyzer's resolver instead? | |
| 210 static _processExportDirective(ExportDirective directive, | |
| 211 List<_Initializer> exportedInitializers, | |
| 212 List<_Initializer> result) { | |
| 213 for (var combinator in directive.combinators) { | |
| 214 if (combinator is ShowCombinator) { | |
| 215 var show = combinator.shownNames.map((n) => n.name).toSet(); | |
| 216 exportedInitializers.retainWhere((e) => show.contains(e.symbolName)); | |
| 217 } else if (combinator is HideCombinator) { | |
| 218 var hide = combinator.hiddenNames.map((n) => n.name).toSet(); | |
| 219 exportedInitializers.removeWhere((e) => hide.contains(e.symbolName)); | |
| 220 } | |
| 221 } | |
| 222 result.addAll(exportedInitializers); | |
| 223 } | |
| 224 | |
| 225 /// Add an initializer to register [node] as a polymer element if it contains | |
| 226 /// an appropriate [CustomTag] annotation. | |
| 227 static _processClassDeclaration(ClassDeclaration node, | |
| 228 List<_Initializer> result, SourceFile file, | |
| 229 TransformLogger logger) { | |
| 230 for (var meta in node.metadata) { | |
| 231 if (!_isCustomTagAnnotation(meta)) continue; | |
| 232 var args = meta.arguments.arguments; | |
| 233 if (args == null || args.length == 0) { | |
| 234 logger.error('Missing argument in @CustomTag annotation', | |
| 235 span: _getSpan(file, meta)); | |
| 236 continue; | |
| 237 } | |
| 238 | |
| 239 var tagName = args[0].stringValue; | |
| 240 var typeName = node.name.name; | |
| 241 if (typeName.startsWith('_')) { | |
| 242 logger.error('@CustomTag is no longer supported on private ' | |
| 243 'classes: $tagName', span: _getSpan(file, node.name)); | |
| 244 continue; | |
| 245 } | |
| 246 result.add(new _CustomTagInitializer(tagName, typeName)); | |
| 247 } | |
| 248 } | |
| 249 | |
| 250 /// Add a method initializer for [function]. | |
| 251 static _processFunctionDeclaration(FunctionDeclaration function, | |
| 252 List<_Initializer> result, SourceFile file, | |
| 253 TransformLogger logger) { | |
| 254 var name = function.name.name; | |
| 255 if (name.startsWith('_')) { | |
| 256 logger.error('@initMethod is no longer supported on private ' | |
| 257 'functions: $name', span: _getSpan(file, function.name)); | |
| 258 return; | |
| 259 } | |
| 260 result.add(new _InitMethodInitializer(name)); | |
| 261 } | 465 } |
| 262 } | 466 } |
| 263 | 467 |
| 264 // TODO(sigmund): consider support for importing annotations with prefixes. | |
| 265 bool _isInitMethodAnnotation(Annotation node) => | |
| 266 node.name.name == 'initMethod' && node.constructorName == null && | |
| 267 node.arguments == null; | |
| 268 bool _isCustomTagAnnotation(Annotation node) => node.name.name == 'CustomTag'; | |
| 269 | |
| 270 abstract class _Initializer { | 468 abstract class _Initializer { |
| 469 AssetId get assetId; | |
| 271 String get symbolName; | 470 String get symbolName; |
| 272 String asCode(String prefix); | 471 String asCode(String prefix); |
| 273 } | 472 } |
| 274 | 473 |
| 275 class _InitMethodInitializer implements _Initializer { | 474 class _InitMethodInitializer implements _Initializer { |
| 276 String methodName; | 475 final AssetId assetId; |
| 476 final String methodName; | |
| 277 String get symbolName => methodName; | 477 String get symbolName => methodName; |
| 278 _InitMethodInitializer(this.methodName); | 478 _InitMethodInitializer(this.assetId, this.methodName); |
| 279 | 479 |
| 280 String asCode(String prefix) => "$prefix.$methodName"; | 480 String asCode(String prefix) => "$prefix.$methodName"; |
| 281 } | 481 } |
| 282 | 482 |
| 283 class _CustomTagInitializer implements _Initializer { | 483 class _CustomTagInitializer implements _Initializer { |
| 284 String tagName; | 484 final AssetId assetId; |
| 285 String typeName; | 485 final String tagName; |
| 486 final String typeName; | |
| 286 String get symbolName => typeName; | 487 String get symbolName => typeName; |
| 287 _CustomTagInitializer(this.tagName, this.typeName); | 488 _CustomTagInitializer(this.assetId, this.tagName, this.typeName); |
| 288 | 489 |
| 289 String asCode(String prefix) => | 490 String asCode(String prefix) => |
| 290 "() => Polymer.register('$tagName', $prefix.$typeName)"; | 491 "() => Polymer.register('$tagName', $prefix.$typeName)"; |
| 291 } | 492 } |
| 292 | 493 |
| 293 _getSpan(SourceFile file, AstNode node) => file.span(node.offset, node.end); | 494 _getSpan(SourceFile file, AstNode node) => file.span(node.offset, node.end); |
| 294 | 495 |
| 295 const MAIN_HEADER = """ | 496 const MAIN_HEADER = """ |
| 296 library app_bootstrap; | 497 library app_bootstrap; |
| 297 | 498 |
| 298 import 'package:polymer/polymer.dart'; | 499 import 'package:polymer/polymer.dart'; |
| 299 import 'package:smoke/static.dart' as smoke; | |
| 300 """; | 500 """; |
| 501 | |
| 502 /// An html visitor that: | |
| 503 /// * finds all polymer expressions and records the getters and setters that | |
| 504 /// will be needed to evaluate them at runtime. | |
| 505 /// * extracts all attributes declared in the `attribute` attributes of | |
| 506 /// polymer elements. | |
| 507 class _HtmlExtractor extends TreeVisitor { | |
| 508 final Map<String, List<String>> publishedAttributes; | |
| 509 final SmokeCodeGenerator generator; | |
| 510 final _SubExpressionVisitor visitor; | |
| 511 bool _inTemplate = false; | |
| 512 | |
| 513 _HtmlExtractor(SmokeCodeGenerator generator, this.publishedAttributes) | |
| 514 : generator = generator, | |
| 515 visitor = new _SubExpressionVisitor(generator); | |
| 516 | |
| 517 void visitElement(Element node) { | |
| 518 if (_inTemplate) _processNormalElement(node); | |
| 519 if (node.localName == 'polymer-element') { | |
| 520 _processPolymerElement(node); | |
| 521 _processNormalElement(node); | |
| 522 } | |
| 523 | |
| 524 if (node.localName == 'template') { | |
| 525 var last = _inTemplate; | |
| 526 _inTemplate = true; | |
| 527 super.visitElement(node); | |
| 528 _inTemplate = last; | |
| 529 } else { | |
| 530 super.visitElement(node); | |
| 531 } | |
| 532 } | |
| 533 | |
| 534 void visitText(Text node) { | |
| 535 if (!_inTemplate) return; | |
| 536 var bindings = _parseMustaches(node.data); | |
| 537 if (bindings == null) return; | |
| 538 for (var e in bindings.expressions) { | |
| 539 _addExpression(e, false, false); | |
| 540 } | |
| 541 } | |
| 542 | |
| 543 /// Registers getters and setters for all published attributes. | |
| 544 void _processPolymerElement(Element node) { | |
| 545 var tagName = node.attributes['name']; | |
| 546 var value = node.attributes['attributes']; | |
| 547 if (value != null) { | |
| 548 // value may be 'a b c' or 'a,b,c' | |
|
blois
2014/03/26 16:02:33
how about a, b c (I believe that polymer.js suppor
Siggi Cherem (dart-lang)
2014/03/26 17:56:34
good catch. I had copied this from the linter, wit
| |
| 549 var attrs = value.split(value.contains(',') ? ',' : ' '); | |
| 550 publishedAttributes[tagName] = attrs.map((a) => a.trim()).toList(); | |
| 551 } | |
| 552 } | |
| 553 | |
| 554 /// Produces warnings for misuses of on-foo event handlers, and for instanting | |
| 555 /// custom tags incorrectly. | |
| 556 void _processNormalElement(Element node) { | |
| 557 var tag = node.localName; | |
| 558 var isCustomTag = isCustomTagName(tag) || node.attributes['is'] != null; | |
| 559 | |
| 560 // Event handlers only allowed inside polymer-elements | |
| 561 node.attributes.forEach((name, value) { | |
| 562 var bindings = _parseMustaches(value); | |
| 563 if (bindings == null) return; | |
| 564 var isEvent = false; | |
| 565 var isTwoWay = false; | |
| 566 if (name is String) { | |
| 567 name = name.toLowerCase(); | |
| 568 isEvent = name.startsWith('on-'); | |
| 569 isTwoWay = !isEvent && bindings.isWhole && (isCustomTag || | |
| 570 tag == 'input' && (name == 'value' || name =='checked') || | |
| 571 tag == 'select' && (name == 'selectedindex' || name == 'value') || | |
| 572 tag == 'textarea' && name == 'value'); | |
| 573 } | |
| 574 for (var exp in bindings.expressions) { | |
| 575 _addExpression(exp, isEvent, isTwoWay); | |
| 576 } | |
| 577 }); | |
| 578 } | |
| 579 | |
| 580 void _addExpression(String stringExpression, bool inEvent, bool isTwoWay) { | |
| 581 if (inEvent) { | |
| 582 if (!stringExpression.startsWith("@")) { | |
| 583 generator.addGetter(stringExpression); | |
| 584 generator.addSymbol(stringExpression); | |
| 585 return; | |
| 586 } | |
| 587 stringExpression = stringExpression.substring(1); | |
| 588 } | |
| 589 visitor.run(pe.parse(stringExpression), isTwoWay); | |
| 590 } | |
| 591 } | |
| 592 | |
| 593 /// A polymer-expression visitor that records every getter and setter that will | |
| 594 /// be needed to evaluate a single expression at runtime. | |
| 595 class _SubExpressionVisitor extends pe.RecursiveVisitor { | |
| 596 final SmokeCodeGenerator generator; | |
| 597 bool _includeSetter; | |
| 598 | |
| 599 _SubExpressionVisitor(this.generator); | |
| 600 | |
| 601 /// Visit [exp], and record getters and setters that are needed in order to | |
| 602 /// evaluate it at runtime. [includeSetter] is only true if this expression | |
| 603 /// occured in a context where it could be updated, for example in two-way | |
| 604 /// bindings such as `<input value={{exp}}>`. | |
| 605 void run(pe.Expression exp, bool includeSetter) { | |
| 606 _includeSetter = includeSetter; | |
| 607 visit(exp); | |
| 608 } | |
| 609 | |
| 610 /// Adds a getter and symbol for [name], and optionally a setter. | |
| 611 _add(String name) { | |
| 612 generator.addGetter(name); | |
| 613 generator.addSymbol(name); | |
| 614 if (_includeSetter) generator.addSetter(name); | |
| 615 } | |
| 616 | |
| 617 void preVisitExpression(e) { | |
| 618 // For two-way bindings the outermost expression may be updated, so we need | |
| 619 // both the getter and the setter, but subexpressions only need the getter. | |
| 620 // So we exclude setters as soon as we go deeper in the tree. | |
| 621 _includeSetter = false; | |
| 622 } | |
| 623 | |
| 624 visitIdentifier(pe.Identifier e) { | |
| 625 if (e.value != 'this') _add(e.value); | |
| 626 super.visitIdentifier(e); | |
| 627 } | |
| 628 | |
| 629 visitGetter(pe.Getter e) { | |
| 630 _add(e.name); | |
| 631 super.visitGetter(e); | |
| 632 } | |
| 633 | |
| 634 visitInvoke(pe.Invoke e) { | |
| 635 _includeSetter = false; // Invoke is only valid as an r-value. | |
| 636 _add(e.method); | |
| 637 super.visitInvoke(e); | |
| 638 } | |
| 639 } | |
| 640 | |
| 641 class _Mustaches { | |
| 642 /// Each expression that appears within `{{...}}` and `[[...]]`. | |
| 643 List<String> expressions = []; | |
| 644 | |
| 645 /// Whether the whole text returned by [_parseMustaches] was a single mustache | |
| 646 /// expression. | |
| 647 bool isWhole; | |
| 648 | |
| 649 _Mustaches(this.isWhole); | |
| 650 } | |
| 651 | |
| 652 // TODO(sigmund): this is a simplification of what template-binding does. Could | |
| 653 // we share some code here and in template_binding/src/mustache_tokens.dart? | |
| 654 _Mustaches _parseMustaches(String text) { | |
| 655 if (text == null || text.isEmpty) return null; | |
| 656 var bindings = null; | |
| 657 var length = text.length; | |
| 658 var lastIndex = 0; | |
| 659 while (lastIndex < length) { | |
| 660 var startIndex = text.indexOf('{{', lastIndex); | |
| 661 var oneTimeStart = text.indexOf('[[', lastIndex); | |
| 662 var oneTime = false; | |
| 663 var terminator = '}}'; | |
| 664 | |
| 665 if (oneTimeStart >= 0 && | |
| 666 (startIndex < 0 || oneTimeStart < startIndex)) { | |
| 667 startIndex = oneTimeStart; | |
| 668 oneTime = true; | |
| 669 terminator = ']]'; | |
| 670 } | |
| 671 | |
| 672 var endIndex = -1; | |
| 673 if (startIndex >= 0) { | |
| 674 endIndex = text.indexOf(terminator, startIndex + 2); | |
| 675 } | |
| 676 | |
| 677 if (endIndex < 0) return bindings; | |
| 678 | |
| 679 if (bindings == null) { | |
| 680 bindings = new _Mustaches(startIndex == 0 && endIndex == length - 2); | |
| 681 } | |
| 682 var pathString = text.substring(startIndex + 2, endIndex).trim(); | |
| 683 bindings.expressions.add(pathString); | |
| 684 lastIndex = endIndex + 2; | |
| 685 } | |
| 686 return bindings; | |
| 687 } | |
| OLD | NEW |