Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(72)

Side by Side Diff: observatory_pub_packages/polymer/src/build/linter.dart

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

Powered by Google App Engine
This is Rietveld 408576698