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

Side by Side Diff: pkg/analyzer/test/src/task/strong/strong_test_helper.dart

Issue 1402783004: port DDC checker code to analyzer (Closed) Base URL: git@github.com:dart-lang/sdk.git@master
Patch Set: Created 5 years, 2 months 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
« no previous file with comments | « pkg/analyzer/test/src/task/strong/inferred_type_test.dart ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2015, 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 // TODO(jmesserly): this file needs to be refactored, it's a port from
6 // package:dev_compiler's tests
7 library test.src.task.strong.strong_test_helper;
8
9 import 'package:analyzer/file_system/file_system.dart';
10 import 'package:analyzer/file_system/memory_file_system.dart';
11 import 'package:analyzer/src/context/context.dart' show SdkAnalysisContext;
12 import 'package:analyzer/src/generated/ast.dart';
13 import 'package:analyzer/src/generated/element.dart';
14 import 'package:analyzer/src/generated/engine.dart' hide SdkAnalysisContext;
15 import 'package:analyzer/src/generated/error.dart';
16 import 'package:analyzer/src/generated/sdk.dart';
17 import 'package:analyzer/src/generated/source.dart';
18 import 'package:analyzer/src/task/strong/checker.dart';
19 import 'package:analyzer/src/task/strong/rules.dart';
20 import 'package:logging/logging.dart'; // TODO(jmesserly): remove
21 import 'package:source_span/source_span.dart'; // TODO(jmesserly): remove
22 import 'package:unittest/unittest.dart';
23
24
25 /// Run the checker on a program with files contents as indicated in
26 /// [testFiles].
27 ///
28 /// This function makes several assumptions to make it easier to describe error
29 /// expectations:
30 ///
31 /// * a file named `/main.dart` exists in [testFiles].
32 /// * all expected failures are listed in the source code using comments
33 /// immediately in front of the AST node that should contain the error.
34 /// * errors are formatted as a token `level:Type`, where `level` is the
35 /// logging level were the error would be reported at, and `Type` is the
36 /// concrete subclass of [StaticInfo] that denotes the error.
37 ///
38 /// For example, to check that an assignment produces a warning about a boxing
39 /// conversion, you can describe the test as follows:
40 ///
41 /// testChecker({
42 /// '/main.dart': '''
43 /// testMethod() {
44 /// dynamic x = /*warning:Box*/3;
45 /// }
46 /// '''
47 /// });
48 ///
49 void testChecker(String name, Map<String, String> testFiles) {
50 test(name, () {
51 expect(testFiles.containsKey('/main.dart'), isTrue,
52 reason: '`/main.dart` is missing in testFiles');
53
54 var provider = new MemoryResourceProvider();
55 testFiles.forEach((key, value) {
56 var scheme = 'package:';
57 if (key.startsWith(scheme)) {
58 key = '/packages/${key.substring(scheme.length)}';
59 }
60 provider.newFile(key, value);
61 });
62 var uriResolver = new TestUriResolver(provider);
63 // Enable task model strong mode
64 AnalysisEngine.instance.useTaskModel = true;
65 var context = AnalysisEngine.instance.createAnalysisContext();
66 context.analysisOptions.strongMode = true;
67
68 context.sourceFactory = new SourceFactory([
69 new MockDartSdk(mockSdkSources, reportMissing: true).resolver,
70 uriResolver
71 ]);
72
73 // Run the checker on /main.dart.
74 Source mainSource = uriResolver.resolveAbsolute(new Uri.file('/main.dart'));
75 var initialLibrary =
76 context.resolveCompilationUnit2(mainSource, mainSource);
77
78 var collector = new _ErrorCollector();
79 var errorReporter = new ErrorReporter(collector, mainSource);
80 var checker = new CodeChecker(new TypeRules(context.typeProvider),
81 errorReporter);
82
83 // Extract expectations from the comments in the test files, and
84 // check that all errors we emit are included in the expected map.
85 var allLibraries = reachableLibraries(initialLibrary.element.library);
86 for (var lib in allLibraries) {
87 for (var unit in lib.units) {
88 var errors = <AnalysisError>[];
89 collector.errors = errors;
90
91 var source = unit.source;
92 if (source.uri.scheme == 'dart') continue;
93 errorReporter.source = unit.source;
94
95 var librarySource = context.getLibrariesContaining(source).single;
96 var resolved = context.resolveCompilationUnit2(source, librarySource);
97 checker.visitCompilationUnit(resolved);
98
99 new _ExpectedErrorVisitor(errors).validate(resolved);
100 }
101 }
102 });
103 }
104
105 class _ErrorCollector implements AnalysisErrorListener {
106 List<AnalysisError> errors;
107 final bool hints;
108 _ErrorCollector({this.hints: true});
109
110 void onError(AnalysisError error) {
111 // Unless DDC hints are requested, filter them out.
112 var HINT = ErrorSeverity.INFO.ordinal;
113 if (hints || error.errorCode.errorSeverity.ordinal > HINT) {
114 errors.add(error);
115 }
116 }
117 }
118
119 class TestUriResolver extends ResourceUriResolver {
120 final MemoryResourceProvider provider;
121 TestUriResolver(provider)
122 : provider = provider,
123 super(provider);
124
125 @override
126 Source resolveAbsolute(Uri uri, [Uri actualUri]) {
127 if (uri.scheme == 'package') {
128 return (provider.getResource('/packages/' + uri.path) as File)
129 .createSource(uri);
130 }
131 return super.resolveAbsolute(uri, actualUri);
132 }
133 }
134
135 class _ExpectedErrorVisitor extends UnifyingAstVisitor {
136 final Set<AnalysisError> _actualErrors;
137 CompilationUnit _unit;
138 String _unitSourceCode;
139
140 _ExpectedErrorVisitor(List<AnalysisError> actualErrors)
141 : _actualErrors = new Set.from(actualErrors);
142
143 validate(CompilationUnit unit) {
144 _unit = unit;
145 // This reads the file. Only safe because tests use MemoryFileSystem.
146 _unitSourceCode = unit.element.source.contents.data;
147
148 // Visit the compilation unit.
149 unit.accept(this);
150
151 if (_actualErrors.isNotEmpty) {
152 var actualMsgs = _actualErrors.map(_formatActualError).join('\n');
153 fail('Unexpected errors reported by checker:\n\n$actualMsgs');
154 }
155 }
156
157 visitNode(AstNode node) {
158 var token = node.beginToken;
159 var comment = token.precedingComments;
160 // Use error marker found in an immediately preceding comment,
161 // and attach it to the outermost expression that starts at that token.
162 if (comment != null) {
163 while (comment.next != null) {
164 comment = comment.next;
165 }
166 if (comment.end == token.offset && node.parent.beginToken != token) {
167 var commentText = '$comment';
168 var start = commentText.lastIndexOf('/*');
169 var end = commentText.lastIndexOf('*/');
170 if (start != -1 && end != -1) {
171 expect(start, lessThan(end));
172 var errors = commentText.substring(start + 2, end).split(',');
173 var expectations =
174 errors.map(_ErrorExpectation.parse).where((x) => x != null);
175
176 for (var e in expectations) _expectError(node, e);
177 }
178 }
179 }
180 return super.visitNode(node);
181 }
182
183 void _expectError(AstNode node, _ErrorExpectation expected) {
184 // See if we can find the expected error in our actual errors
185 for (var actual in _actualErrors) {
186 if (actual.offset == node.offset && actual.length == node.length) {
187 var actualMsg = _formatActualError(actual);
188 expect(_actualErrorLevel(actual), expected.level,
189 reason: 'expected different error code at:\n\n$actualMsg');
190 expect(errorCodeName(actual.errorCode), expected.typeName,
191 reason: 'expected different error type at:\n\n$actualMsg');
192
193 // We found it. Stop the search.
194 _actualErrors.remove(actual);
195 return;
196 }
197 }
198
199 var span = _createSpan(node.offset, node.length);
200 var levelName = expected.level.name.toLowerCase();
201 var msg = span.message(expected.typeName, color: colorOf(levelName));
202 fail('expected error was not reported at:\n\n$levelName: $msg');
203 }
204
205 Level _actualErrorLevel(AnalysisError actual) {
206 return const <ErrorSeverity, Level>{
207 ErrorSeverity.ERROR: Level.SEVERE,
208 ErrorSeverity.WARNING: Level.WARNING,
209 ErrorSeverity.INFO: Level.INFO
210 }[actual.errorCode.errorSeverity];
211 }
212
213 String _formatActualError(AnalysisError actual) {
214 var span = _createSpan(actual.offset, actual.length);
215 var levelName = _actualErrorLevel(actual).name.toLowerCase();
216 var msg = span.message(actual.message, color: colorOf(levelName));
217 return '$levelName: [${errorCodeName(actual.errorCode)}] $msg';
218 }
219
220 SourceSpan _createSpan(int offset, int len) {
221 return createSpanHelper(_unit.lineInfo, offset, offset + len,
222 _unit.element.source, _unitSourceCode);
223 }
224 }
225
226 SourceLocation locationForOffset(LineInfo lineInfo, Uri uri, int offset) {
227 var loc = lineInfo.getLocation(offset);
228 return new SourceLocation(offset,
229 sourceUrl: uri, line: loc.lineNumber - 1, column: loc.columnNumber - 1);
230 }
231
232 SourceSpanWithContext createSpanHelper(
233 LineInfo lineInfo, int start, int end, Source source, String content) {
234 var startLoc = locationForOffset(lineInfo, source.uri, start);
235 var endLoc = locationForOffset(lineInfo, source.uri, end);
236
237 var lineStart = startLoc.offset - startLoc.column;
238 // Find the end of the line. This is not exposed directly on LineInfo, but
239 // we can find it pretty easily.
240 // TODO(jmesserly): for now we do the simple linear scan. Ideally we can get
241 // some help from the LineInfo API.
242 int lineEnd = endLoc.offset;
243 int lineNum = lineInfo.getLocation(lineEnd).lineNumber;
244 while (lineEnd < content.length &&
245 lineInfo.getLocation(++lineEnd).lineNumber == lineNum);
246
247 var text = content.substring(start, end);
248 var lineText = content.substring(lineStart, lineEnd);
249 return new SourceSpanWithContext(startLoc, endLoc, text, lineText);
250 }
251
252 /// Describes an expected message that should be produced by the checker.
253 class _ErrorExpectation {
254 final Level level;
255 final String typeName;
256 _ErrorExpectation(this.level, this.typeName);
257
258 static _ErrorExpectation _parse(String descriptor) {
259 var tokens = descriptor.split(':');
260 expect(tokens.length, 2, reason: 'invalid error descriptor');
261 var name = tokens[0].toUpperCase();
262 var typeName = tokens[1];
263
264 var level =
265 Level.LEVELS.firstWhere((l) => l.name == name, orElse: () => null);
266 expect(level, isNotNull,
267 reason: 'invalid level in error descriptor: `${tokens[0]}`');
268 expect(typeName, isNotNull,
269 reason: 'invalid type in error descriptor: ${tokens[1]}');
270 return new _ErrorExpectation(level, typeName);
271 }
272
273 static _ErrorExpectation parse(String descriptor) {
274 descriptor = descriptor.trim();
275 var tokens = descriptor.split(' ');
276 if (tokens.length == 1) return _parse(tokens[0]);
277 expect(tokens.length, 4, reason: 'invalid error descriptor');
278 expect(tokens[1], "should", reason: 'invalid error descriptor');
279 expect(tokens[2], "be", reason: 'invalid error descriptor');
280 if (tokens[0] == "pass") return null;
281 // TODO(leafp) For now, we just use whatever the current expectation is,
282 // eventually we could do more automated reporting here.
283 return _parse(tokens[0]);
284 }
285
286 String toString() => '$level $typeName';
287 }
288
289
290 /// Dart SDK which contains a mock implementation of the SDK libraries. May be
291 /// used to speed up execution when most of the core libraries is not needed.
292 class MockDartSdk implements DartSdk {
293 final Map<Uri, _MockSdkSource> _sources = {};
294 final bool reportMissing;
295 final Map<String, SdkLibrary> _libs = {};
296 final String sdkVersion = '0';
297 List<String> get uris => _sources.keys.map((uri) => '$uri').toList();
298 final AnalysisContext context = new SdkAnalysisContext();
299 DartUriResolver _resolver;
300 DartUriResolver get resolver => _resolver;
301
302 MockDartSdk(Map<String, String> sources, {this.reportMissing}) {
303 sources.forEach((uriString, contents) {
304 var uri = Uri.parse(uriString);
305 _sources[uri] = new _MockSdkSource(uri, contents);
306 _libs[uriString] = new SdkLibraryImpl(uri.path)
307 ..setDart2JsLibrary()
308 ..setVmLibrary();
309 });
310 _resolver = new DartUriResolver(this);
311 context.sourceFactory = new SourceFactory([_resolver]);
312 }
313
314 List<SdkLibrary> get sdkLibraries => _libs.values.toList();
315 SdkLibrary getSdkLibrary(String dartUri) => _libs[dartUri];
316 Source mapDartUri(String dartUri) => _getSource(Uri.parse(dartUri));
317
318 Source fromEncoding(UriKind kind, Uri uri) {
319 if (kind != UriKind.DART_URI) {
320 throw new UnsupportedError('expected dart: uri kind, got $kind.');
321 }
322 return _getSource(uri);
323 }
324
325 Source _getSource(Uri uri) {
326 var src = _sources[uri];
327 if (src == null) {
328 if (reportMissing) print('warning: missing mock for $uri.');
329 _sources[uri] =
330 src = new _MockSdkSource(uri, 'library dart.${uri.path};');
331 }
332 return src;
333 }
334
335 @override
336 Source fromFileUri(Uri uri) {
337 throw new UnsupportedError('MockDartSdk.fromFileUri');
338 }
339 }
340
341 class _MockSdkSource implements Source {
342 /// Absolute URI which this source can be imported from.
343 final Uri uri;
344 final String _contents;
345
346 _MockSdkSource(this.uri, this._contents);
347
348 bool exists() => true;
349
350 int get hashCode => uri.hashCode;
351
352 final int modificationStamp = 1;
353
354 TimestampedData<String> get contents =>
355 new TimestampedData(modificationStamp, _contents);
356
357 String get encoding => "${uriKind.encoding}$uri";
358
359 Source get source => this;
360
361 String get fullName => shortName;
362
363 String get shortName => uri.path;
364
365 UriKind get uriKind => UriKind.DART_URI;
366
367 bool get isInSystemLibrary => true;
368
369 Source resolveRelative(Uri relativeUri) =>
370 throw new UnsupportedError('not expecting relative urls in dart: mocks');
371
372 Uri resolveRelativeUri(Uri relativeUri) =>
373 throw new UnsupportedError('not expecting relative urls in dart: mocks');
374 }
375
376 /// Sample mock SDK sources.
377 final Map<String, String> mockSdkSources = {
378 // The list of types below is derived from:
379 // * types we use via our smoke queries, including HtmlElement and
380 // types from `_typeHandlers` (deserialize.dart)
381 // * types that are used internally by the resolver (see
382 // _initializeFrom in resolver.dart).
383 'dart:core': '''
384 library dart.core;
385
386 void print(Object o) {}
387
388 class Object {
389 int get hashCode {}
390 Type get runtimeType {}
391 String toString(){}
392 bool ==(other){}
393 }
394 class Function {}
395 class StackTrace {}
396 class Symbol {}
397 class Type {}
398
399 class String {
400 String operator +(String other) {}
401 }
402 class bool {}
403 class num {
404 num operator +(num other) {}
405 }
406 class int extends num {
407 bool operator<(num other) {}
408 int operator-() {}
409 }
410 class double extends num {}
411 class DateTime {}
412 class Null {}
413
414 class Deprecated {
415 final String expires;
416 const Deprecated(this.expires);
417 }
418 const Object deprecated = const Deprecated("next release");
419 class _Override { const _Override(); }
420 const Object override = const _Override();
421 class _Proxy { const _Proxy(); }
422 const Object proxy = const _Proxy();
423
424 class Iterable<E> {
425 fold(initialValue, combine(previousValue, E element)) {}
426 Iterable map(f(E element)) {}
427 }
428 class List<E> implements Iterable<E> {
429 List([int length]);
430 List.filled(int length, E fill);
431 }
432 class Map<K, V> {
433 Iterable<K> get keys {}
434 }
435 ''',
436 'dart:async': '''
437 class Future<T> {
438 Future(computation()) {}
439 Future.value(T t) {}
440 Future then(onValue(T value)) {}
441 static Future<List> wait(Iterable<Future> futures) {}
442 }
443 class Stream<T> {}
444 ''',
445 'dart:html': '''
446 library dart.html;
447 class HtmlElement {}
448 ''',
449 'dart:math': '''
450 library dart.math;
451 class Random {
452 bool nextBool() {}
453 }
454 num min(num x, num y) {}
455 num max(num x, num y) {}
456 ''',
457 };
458
459
460 /// Returns all libraries transitively imported or exported from [start].
461 List<LibraryElement> reachableLibraries(LibraryElement start) {
462 var results = <LibraryElement>[];
463 var seen = new Set();
464 void find(LibraryElement lib) {
465 if (seen.contains(lib)) return;
466 seen.add(lib);
467 results.add(lib);
468 lib.importedLibraries.forEach(find);
469 lib.exportedLibraries.forEach(find);
470 }
471 find(start);
472 return results;
473 }
474
475 String errorCodeName(ErrorCode errorCode) {
476 var name = errorCode.name;
477 final prefix = 'dev_compiler.';
478 if (name.startsWith(prefix)) {
479 return name.substring(prefix.length);
480 } else {
481 // TODO(jmesserly): this is for backwards compat, but not sure it's very
482 // useful to log this.
483 return 'AnalyzerMessage';
484 }
485 }
486
487 /// Returns an ANSII color escape sequence corresponding to [levelName]. Colors
488 /// are defined for: severe, error, warning, or info. Returns null if the level
489 /// name is not recognized.
490 String colorOf(String levelName) {
491 levelName = levelName.toLowerCase();
492 if (levelName == 'shout' || levelName == 'severe' || levelName == 'error') {
493 return _RED_COLOR;
494 }
495 if (levelName == 'warning') return _MAGENTA_COLOR;
496 if (levelName == 'info') return _CYAN_COLOR;
497 return null;
498 }
499
500 const String _RED_COLOR = '\u001b[31m';
501 const String _MAGENTA_COLOR = '\u001b[35m';
502 const String _CYAN_COLOR = '\u001b[36m';
503 const String GREEN_COLOR = '\u001b[32m';
504 const String NO_COLOR = '\u001b[0m';
OLDNEW
« no previous file with comments | « pkg/analyzer/test/src/task/strong/inferred_type_test.dart ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698