OLD | NEW |
| (Empty) |
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 | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 /// Logic to validate that developers are correctly using Polymer constructs. | |
6 /// This is mainly used to produce warnings for feedback in the editor. | |
7 library polymer.src.build.linter; | |
8 | |
9 import 'dart:async'; | |
10 import 'dart:convert'; | |
11 | |
12 import 'package:barback/barback.dart'; | |
13 import 'package:code_transformers/assets.dart'; | |
14 import 'package:code_transformers/messages/build_logger.dart'; | |
15 import 'package:code_transformers/messages/messages.dart' show Message; | |
16 import 'package:html/dom.dart'; | |
17 import 'package:html/dom_parsing.dart'; | |
18 import 'package:path/path.dart' as path; | |
19 import 'package:source_span/source_span.dart'; | |
20 | |
21 import 'common.dart'; | |
22 import 'utils.dart'; | |
23 import 'messages.dart'; | |
24 | |
25 /// A linter that checks for common Polymer errors and produces warnings to | |
26 /// show on the editor or the command line. Leaves sources unchanged, but | |
27 /// creates a new asset containing all the warnings. | |
28 class Linter extends Transformer with PolymerTransformer { | |
29 final TransformOptions options; | |
30 final bool skipMissingElementWarning; | |
31 | |
32 Linter(this.options, {this.skipMissingElementWarning: false}); | |
33 | |
34 isPrimary(AssetId id) => | |
35 id.extension == '.html' && options.lint.shouldLint(id.path); | |
36 | |
37 Future apply(Transform transform) { | |
38 var seen = new Set<AssetId>(); | |
39 var primary = transform.primaryInput; | |
40 var id = primary.id; | |
41 transform.addOutput(primary); // this phase is analysis only | |
42 seen.add(id); | |
43 bool isEntryPoint = options.isHtmlEntryPoint(id); | |
44 | |
45 var logger = new BuildLogger(transform, | |
46 convertErrorsToWarnings: !options.releaseMode, | |
47 detailsUri: 'http://goo.gl/5HPeuP'); | |
48 | |
49 return readPrimaryAsHtml(transform, logger).then((document) { | |
50 return _collectElements(document, id, transform, logger, seen) | |
51 .then((elements) { | |
52 new _LinterVisitor(id, logger, elements, isEntryPoint, | |
53 skipMissingElementWarning || !isEntryPoint).run(document); | |
54 | |
55 // Write out the logs collected by our [BuildLogger]. | |
56 if (options.injectBuildLogsInOutput && logger is BuildLogger) { | |
57 return (logger as BuildLogger).writeOutput(); | |
58 } | |
59 }); | |
60 }); | |
61 } | |
62 | |
63 /// Collect into [elements] any data about each polymer-element defined in | |
64 /// [document] or any of it's imports, unless they have already been [seen]. | |
65 /// Elements are added in the order they appear, transitive imports are added | |
66 /// first. | |
67 Future<Map<String, _ElementSummary>> _collectElements(Document document, | |
68 AssetId sourceId, Transform transform, BuildLogger logger, | |
69 Set<AssetId> seen, [Map<String, _ElementSummary> elements]) { | |
70 if (elements == null) elements = <String, _ElementSummary>{}; | |
71 return _getImportedIds(document, sourceId, transform, logger) | |
72 // Note: the import order is relevant, so we visit in that order. | |
73 .then((ids) => Future.forEach(ids, (id) => | |
74 _readAndCollectElements(id, transform, logger, seen, elements))) | |
75 .then((_) { | |
76 if (sourceId.package == 'polymer_interop' && | |
77 sourceId.path == 'lib/src/js/polymer.html' && | |
78 elements['polymer-element'] == null) { | |
79 elements['polymer-element'] = | |
80 new _ElementSummary('polymer-element', null, null); | |
81 } | |
82 return _addElements(document, logger, elements); | |
83 }).then((_) => elements); | |
84 } | |
85 | |
86 Future _readAndCollectElements(AssetId id, Transform transform, | |
87 BuildLogger logger, Set<AssetId> seen, | |
88 Map<String, _ElementSummary> elements) { | |
89 if (id == null || seen.contains(id)) return new Future.value(null); | |
90 seen.add(id); | |
91 return readAsHtml(id, transform, logger, showWarnings: false).then( | |
92 (doc) => _collectElements(doc, id, transform, logger, seen, elements)); | |
93 } | |
94 | |
95 Future<List<AssetId>> _getImportedIds(Document document, AssetId sourceId, | |
96 Transform transform, BuildLogger logger) { | |
97 var importIds = []; | |
98 for (var tag in document.querySelectorAll('link')) { | |
99 if (tag.attributes['rel'] != 'import') continue; | |
100 var href = tag.attributes['href']; | |
101 var span = tag.sourceSpan; | |
102 var id = uriToAssetId(sourceId, href, logger, span); | |
103 if (id == null) continue; | |
104 importIds.add(assetExists(id, transform).then((exists) { | |
105 if (exists) return id; | |
106 if (sourceId == transform.primaryInput.id) { | |
107 logger.warning( | |
108 IMPORT_NOT_FOUND.create({'path': id.path, 'package': id.package}), | |
109 span: span); | |
110 } | |
111 })); | |
112 } | |
113 return Future.wait(importIds); | |
114 } | |
115 | |
116 void _addElements(Document document, BuildLogger logger, | |
117 Map<String, _ElementSummary> elements) { | |
118 for (var tag in document.querySelectorAll('polymer-element')) { | |
119 var name = tag.attributes['name']; | |
120 if (name == null) continue; | |
121 var extendsTag = tag.attributes['extends']; | |
122 var span = tag.sourceSpan; | |
123 var existing = elements[name]; | |
124 if (existing != null) { | |
125 | |
126 // Report warning only once. | |
127 if (existing.hasConflict) continue; | |
128 existing.hasConflict = true; | |
129 logger.warning( | |
130 DUPLICATE_DEFINITION.create({'name': name, 'second': ''}), | |
131 span: existing.span); | |
132 logger.warning(DUPLICATE_DEFINITION | |
133 .create({'name': name, 'second': ' (second definition).'}), | |
134 span: span); | |
135 continue; | |
136 } | |
137 | |
138 elements[name] = new _ElementSummary(name, extendsTag, tag.sourceSpan); | |
139 } | |
140 } | |
141 } | |
142 | |
143 /// Information needed about other polymer-element tags in order to validate | |
144 /// how they are used and extended. | |
145 /// | |
146 /// Note: these are only created for polymer-element, because pure custom | |
147 /// elements don't have a declarative form. | |
148 class _ElementSummary { | |
149 final String tagName; | |
150 final String extendsTag; | |
151 final SourceSpan span; | |
152 | |
153 _ElementSummary extendsType; | |
154 bool hasConflict = false; | |
155 | |
156 String get baseExtendsTag { | |
157 if (extendsType != null) return extendsType.baseExtendsTag; | |
158 if (extendsTag != null && !extendsTag.contains('-')) return extendsTag; | |
159 return null; | |
160 } | |
161 | |
162 _ElementSummary(this.tagName, this.extendsTag, this.span); | |
163 | |
164 String toString() => "($tagName <: $extendsTag)"; | |
165 } | |
166 | |
167 class _LinterVisitor extends TreeVisitor { | |
168 BuildLogger _logger; | |
169 AssetId _sourceId; | |
170 bool _inPolymerElement = false; | |
171 bool _inAutoBindingElement = false; | |
172 bool _dartTagSeen = false; | |
173 bool _polymerHtmlSeen = false; | |
174 bool _polymerExperimentalHtmlSeen = false; | |
175 bool _isEntryPoint; | |
176 Map<String, _ElementSummary> _elements; | |
177 bool _skipMissingElementWarning; | |
178 | |
179 _LinterVisitor(this._sourceId, this._logger, this._elements, | |
180 this._isEntryPoint, this._skipMissingElementWarning) { | |
181 // We normalize the map, so each element has a direct reference to any | |
182 // element it extends from. | |
183 for (var tag in _elements.values) { | |
184 var extendsTag = tag.extendsTag; | |
185 if (extendsTag == null) continue; | |
186 tag.extendsType = _elements[extendsTag]; | |
187 } | |
188 } | |
189 | |
190 void visitElement(Element node) { | |
191 switch (node.localName) { | |
192 case 'link': | |
193 _validateLinkElement(node); | |
194 break; | |
195 case 'element': | |
196 _validateElementElement(node); | |
197 break; | |
198 case 'polymer-element': | |
199 _validatePolymerElement(node); | |
200 break; | |
201 case 'script': | |
202 _validateScriptElement(node); | |
203 break; | |
204 case 'template': | |
205 var isTag = node.attributes['is']; | |
206 var oldInAutoBindingElement = _inAutoBindingElement; | |
207 if (isTag != null && AUTO_BINDING_ELEMENTS.contains(isTag)) { | |
208 _inAutoBindingElement = true; | |
209 } | |
210 _validateNormalElement(node); | |
211 super.visitElement(node); | |
212 _inAutoBindingElement = oldInAutoBindingElement; | |
213 break; | |
214 default: | |
215 _validateNormalElement(node); | |
216 super.visitElement(node); | |
217 break; | |
218 } | |
219 } | |
220 | |
221 void run(Document doc) { | |
222 visit(doc); | |
223 | |
224 if (_isEntryPoint && !_dartTagSeen && !_polymerExperimentalHtmlSeen) { | |
225 _logger.warning(MISSING_INIT_POLYMER, span: doc.body.sourceSpan); | |
226 } | |
227 } | |
228 | |
229 /// Produce warnings for invalid link-rel tags. | |
230 void _validateLinkElement(Element node) { | |
231 var rel = node.attributes['rel']; | |
232 if (rel != 'import' && rel != 'stylesheet') return; | |
233 | |
234 if (rel == 'import' && _dartTagSeen) { | |
235 _logger.warning(MOVE_IMPORTS_UP, span: node.sourceSpan); | |
236 } | |
237 | |
238 var href = node.attributes['href']; | |
239 if (href == null || href == '') { | |
240 _logger.warning(MISSING_HREF.create({'rel': rel}), span: node.sourceSpan); | |
241 return; | |
242 } | |
243 | |
244 if (rel != 'import') return; | |
245 | |
246 if (_inPolymerElement) { | |
247 _logger.error(NO_IMPORT_WITHIN_ELEMENT, span: node.sourceSpan); | |
248 return; | |
249 } | |
250 | |
251 if (href == POLYMER_EXPERIMENTAL_HTML) { | |
252 _polymerExperimentalHtmlSeen = true; | |
253 } | |
254 // TODO(sigmund): warn also if href can't be resolved. | |
255 } | |
256 | |
257 /// Produce warnings if using `<element>` instead of `<polymer-element>`. | |
258 void _validateElementElement(Element node) { | |
259 _logger.warning(ELEMENT_DEPRECATED_EONS_AGO, span: node.sourceSpan); | |
260 } | |
261 | |
262 /// Produce warnings if using `<polymer-element>` in the wrong place or if the | |
263 /// definition is not complete. | |
264 void _validatePolymerElement(Element node) { | |
265 if (!_skipMissingElementWarning && | |
266 !_elements.containsKey('polymer-element')) { | |
267 _logger.warning(usePolymerHtmlMessageFrom(_sourceId), | |
268 span: node.sourceSpan); | |
269 } | |
270 | |
271 if (_inPolymerElement) { | |
272 _logger.error(NESTED_POLYMER_ELEMENT, span: node.sourceSpan); | |
273 return; | |
274 } | |
275 | |
276 var tagName = node.attributes['name']; | |
277 var extendsTag = node.attributes['extends']; | |
278 | |
279 if (tagName == null) { | |
280 _logger.error(MISSING_TAG_NAME, span: node.sourceSpan); | |
281 } else if (!isCustomTagName(tagName)) { | |
282 _logger.error(INVALID_TAG_NAME.create({'name': tagName}), | |
283 span: node.sourceSpan); | |
284 } | |
285 | |
286 if (!_skipMissingElementWarning && | |
287 _elements[extendsTag] == null && | |
288 isCustomTagName(extendsTag)) { | |
289 _logger.warning(CUSTOM_ELEMENT_NOT_FOUND.create({'tag': extendsTag}), | |
290 span: node.sourceSpan); | |
291 } | |
292 | |
293 var attrs = node.attributes['attributes']; | |
294 if (attrs != null) { | |
295 var attrsSpan = node.attributeSpans['attributes']; | |
296 | |
297 // names='a b c' or names='a,b,c' | |
298 // record each name for publishing | |
299 for (var attr in attrs.split(ATTRIBUTES_REGEX)) { | |
300 if (!_validateCustomAttributeName(attr.trim(), attrsSpan)) break; | |
301 } | |
302 } | |
303 | |
304 var oldValue = _inPolymerElement; | |
305 _inPolymerElement = true; | |
306 super.visitElement(node); | |
307 _inPolymerElement = oldValue; | |
308 } | |
309 | |
310 /// Checks for multiple Dart script tags in the same page, which is invalid. | |
311 void _validateScriptElement(Element node) { | |
312 var scriptType = node.attributes['type']; | |
313 var isDart = scriptType == 'application/dart'; | |
314 var src = node.attributes['src']; | |
315 | |
316 if (isDart) { | |
317 if (_dartTagSeen) _logger.warning(ONLY_ONE_TAG, span: node.sourceSpan); | |
318 if (_isEntryPoint && _polymerExperimentalHtmlSeen) { | |
319 _logger.warning(NO_DART_SCRIPT_AND_EXPERIMENTAL, span: node.sourceSpan); | |
320 } | |
321 _dartTagSeen = true; | |
322 } | |
323 | |
324 if (src != null && src.endsWith('web_components/dart_support.js')) { | |
325 _logger.warning(DART_SUPPORT_NO_LONGER_REQUIRED, span: node.sourceSpan); | |
326 } | |
327 | |
328 if (src != null && src.contains('web_components/webcomponents.')) { | |
329 _logger.warning(WEB_COMPONENTS_NO_LONGER_REQUIRED, span: node.sourceSpan); | |
330 } | |
331 | |
332 if (src != null && src.contains('web_components/platform.')) { | |
333 _logger.warning(PLATFORM_JS_RENAMED, span: node.sourceSpan); | |
334 } | |
335 | |
336 var isEmpty = node.innerHtml.trim() == ''; | |
337 | |
338 if (src == null) { | |
339 if (isDart && isEmpty) { | |
340 _logger.warning(SCRIPT_TAG_SEEMS_EMPTY, span: node.sourceSpan); | |
341 } | |
342 return; | |
343 } | |
344 | |
345 if (src.endsWith('.dart') && !isDart) { | |
346 _logger.warning(EXPECTED_DART_MIME_TYPE, span: node.sourceSpan); | |
347 return; | |
348 } | |
349 | |
350 if (!src.endsWith('.dart') && isDart) { | |
351 _logger.warning(EXPECTED_DART_EXTENSION, span: node.sourceSpan); | |
352 return; | |
353 } | |
354 | |
355 if (!isEmpty) { | |
356 _logger.warning(FOUND_BOTH_SCRIPT_SRC_AND_TEXT, span: node.sourceSpan); | |
357 } | |
358 } | |
359 | |
360 /// Produces warnings for misuses of on-foo event handlers, and for instanting | |
361 /// custom tags incorrectly. | |
362 void _validateNormalElement(Element node) { | |
363 // Event handlers only allowed inside polymer-elements | |
364 node.attributes.forEach((name, value) { | |
365 if (name is String && name.startsWith('on')) { | |
366 _validateEventHandler(node, name, value); | |
367 } | |
368 }); | |
369 | |
370 // Validate uses of custom-tags | |
371 var nodeTag = node.localName; | |
372 var hasIsAttribute; | |
373 var customTagName; | |
374 if (isCustomTagName(nodeTag)) { | |
375 // <fancy-button> | |
376 customTagName = nodeTag; | |
377 hasIsAttribute = false; | |
378 } else { | |
379 // <button is="fancy-button"> | |
380 customTagName = node.attributes['is']; | |
381 hasIsAttribute = true; | |
382 } | |
383 | |
384 if (customTagName == null || | |
385 INTERNALLY_DEFINED_ELEMENTS.contains(customTagName)) { | |
386 return; | |
387 } | |
388 | |
389 var info = _elements[customTagName]; | |
390 if (info == null) { | |
391 if (!_skipMissingElementWarning && _isEntryPoint) { | |
392 _logger.warning(CUSTOM_ELEMENT_NOT_FOUND.create({'tag': customTagName}), | |
393 span: node.sourceSpan); | |
394 } | |
395 return; | |
396 } | |
397 | |
398 var baseTag = info.baseExtendsTag; | |
399 if (baseTag != null && !hasIsAttribute) { | |
400 _logger.warning(BAD_INSTANTIATION_MISSING_BASE_TAG | |
401 .create({'tag': customTagName, 'base': baseTag}), | |
402 span: node.sourceSpan); | |
403 return; | |
404 } | |
405 | |
406 if (hasIsAttribute && baseTag == null) { | |
407 _logger.warning(BAD_INSTANTIATION_BOGUS_BASE_TAG | |
408 .create({'tag': customTagName, 'base': nodeTag}), | |
409 span: node.sourceSpan); | |
410 return; | |
411 } | |
412 | |
413 if (hasIsAttribute && baseTag != nodeTag) { | |
414 _logger.warning(BAD_INSTANTIATION_WRONG_BASE_TAG | |
415 .create({'tag': customTagName, 'base': baseTag}), | |
416 span: node.sourceSpan); | |
417 } | |
418 | |
419 // FOUC check, if content is supplied | |
420 if (_isEntryPoint && !node.innerHtml.isEmpty) { | |
421 var parent = node; | |
422 var hasFoucFix = false; | |
423 while (parent != null && !hasFoucFix) { | |
424 if (parent.localName == 'polymer-element' || | |
425 parent.attributes['unresolved'] != null) { | |
426 hasFoucFix = true; | |
427 } | |
428 if (parent.localName == 'body') break; | |
429 parent = parent.parent; | |
430 } | |
431 if (!hasFoucFix) _logger.warning(POSSIBLE_FUOC, span: node.sourceSpan); | |
432 } | |
433 } | |
434 | |
435 /// Validate an attribute on a custom-element. Returns true if valid. | |
436 bool _validateCustomAttributeName(String name, FileSpan span) { | |
437 if (name.contains('-')) { | |
438 var newName = toCamelCase(name); | |
439 var alternative = '"$newName" or "${newName.toLowerCase()}"'; | |
440 _logger.warning(NO_DASHES_IN_CUSTOM_ATTRIBUTES | |
441 .create({'name': name, 'alternative': alternative}), span: span); | |
442 return false; | |
443 } | |
444 return true; | |
445 } | |
446 | |
447 /// Validate event handlers are used correctly. | |
448 void _validateEventHandler(Element node, String name, String value) { | |
449 if (!name.startsWith('on-')) return; | |
450 | |
451 if (!_inPolymerElement && !_inAutoBindingElement) { | |
452 _logger.warning(EVENT_HANDLERS_ONLY_WITHIN_POLYMER, | |
453 span: node.attributeSpans[name]); | |
454 return; | |
455 } | |
456 | |
457 // Valid bindings have {{ }}, don't look like method calls foo(bar), and are | |
458 // non empty. | |
459 if (!value.startsWith("{{") || | |
460 !value.endsWith("}}") || | |
461 value.contains('(') || | |
462 value.substring(2, value.length - 2).trim() == '') { | |
463 _logger.warning( | |
464 INVALID_EVENT_HANDLER_BODY.create({'value': value, 'name': name}), | |
465 span: node.attributeSpans[name]); | |
466 } | |
467 } | |
468 } | |
469 | |
470 Message usePolymerHtmlMessageFrom(AssetId id) { | |
471 var segments = path.url.split(id.path); | |
472 var upDirCount = 0; | |
473 if (segments[0] == 'lib') { | |
474 // lib/foo.html => ../../packages/ | |
475 upDirCount = segments.length; | |
476 } else if (segments.length > 2) { | |
477 // web/a/foo.html => ../packages/ | |
478 upDirCount = segments.length - 2; | |
479 } | |
480 var reachOutPrefix = '../' * upDirCount; | |
481 return USE_POLYMER_HTML.create({'reachOutPrefix': reachOutPrefix}); | |
482 } | |
483 | |
484 const List<String> INTERNALLY_DEFINED_ELEMENTS = const [ | |
485 'auto-binding-dart', | |
486 'polymer-element' | |
487 ]; | |
488 const List<String> AUTO_BINDING_ELEMENTS = const [ | |
489 'auto-binding-dart', | |
490 'auto-binding' | |
491 ]; | |
OLD | NEW |