OLD | NEW |
1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 |
2 // for details. All rights reserved. Use of this source code is governed by a | 3 // 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 // BSD-style license that can be found in the LICENSE file. |
4 | 5 |
5 // TODO(jmesserly): this file needs to be refactored, it's a port from | 6 // TODO(jmesserly): this file needs to be refactored, it's a port from |
6 // package:dev_compiler's tests | 7 // package:dev_compiler's tests |
7 library analyzer.test.src.task.strong.strong_test_helper; | 8 library analyzer.test.src.task.strong.strong_test_helper; |
8 | 9 |
9 import 'package:analyzer/dart/ast/ast.dart'; | 10 import 'package:analyzer/dart/ast/ast.dart'; |
10 import 'package:analyzer/dart/ast/visitor.dart'; | |
11 import 'package:analyzer/dart/element/element.dart'; | 11 import 'package:analyzer/dart/element/element.dart'; |
12 import 'package:analyzer/file_system/file_system.dart'; | 12 import 'package:analyzer/file_system/file_system.dart'; |
13 import 'package:analyzer/file_system/memory_file_system.dart'; | 13 import 'package:analyzer/file_system/memory_file_system.dart'; |
14 import 'package:analyzer/src/context/context.dart' show SdkAnalysisContext; | 14 import 'package:analyzer/src/context/context.dart' show SdkAnalysisContext; |
15 import 'package:analyzer/src/generated/engine.dart'; | 15 import 'package:analyzer/src/generated/engine.dart'; |
16 import 'package:analyzer/src/generated/error.dart'; | 16 import 'package:analyzer/src/generated/error.dart'; |
| 17 import 'package:analyzer/src/generated/scanner.dart'; |
17 import 'package:analyzer/src/generated/sdk.dart'; | 18 import 'package:analyzer/src/generated/sdk.dart'; |
18 import 'package:analyzer/src/generated/source.dart'; | 19 import 'package:analyzer/src/generated/source.dart'; |
19 import 'package:analyzer/src/generated/type_system.dart'; | 20 import 'package:analyzer/src/generated/type_system.dart'; |
20 import 'package:analyzer/src/task/strong/checker.dart'; | 21 import 'package:analyzer/src/task/strong/checker.dart'; |
21 import 'package:logging/logging.dart'; | 22 import 'package:logging/logging.dart'; |
22 import 'package:source_span/source_span.dart'; | 23 import 'package:source_span/source_span.dart'; |
23 import 'package:unittest/unittest.dart'; | 24 import 'package:unittest/unittest.dart'; |
24 | 25 |
25 | |
26 MemoryResourceProvider files; | 26 MemoryResourceProvider files; |
27 bool _checkCalled; | 27 bool _checkCalled; |
28 | 28 |
29 initStrongModeTests() { | 29 initStrongModeTests() { |
30 setUp(() { | 30 setUp(() { |
31 AnalysisEngine.instance.processRequiredPlugins(); | 31 AnalysisEngine.instance.processRequiredPlugins(); |
32 files = new MemoryResourceProvider(); | 32 files = new MemoryResourceProvider(); |
33 _checkCalled = false; | 33 _checkCalled = false; |
34 }); | 34 }); |
35 | 35 |
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
85 var context = AnalysisEngine.instance.createAnalysisContext(); | 85 var context = AnalysisEngine.instance.createAnalysisContext(); |
86 context.analysisOptions.strongMode = true; | 86 context.analysisOptions.strongMode = true; |
87 context.analysisOptions.strongModeHints = true; | 87 context.analysisOptions.strongModeHints = true; |
88 context.sourceFactory = new SourceFactory([ | 88 context.sourceFactory = new SourceFactory([ |
89 new MockDartSdk(_mockSdkSources, reportMissing: true).resolver, | 89 new MockDartSdk(_mockSdkSources, reportMissing: true).resolver, |
90 uriResolver | 90 uriResolver |
91 ]); | 91 ]); |
92 | 92 |
93 // Run the checker on /main.dart. | 93 // Run the checker on /main.dart. |
94 Source mainSource = uriResolver.resolveAbsolute(new Uri.file('/main.dart')); | 94 Source mainSource = uriResolver.resolveAbsolute(new Uri.file('/main.dart')); |
95 var initialLibrary = | 95 var initialLibrary = context.resolveCompilationUnit2(mainSource, mainSource); |
96 context.resolveCompilationUnit2(mainSource, mainSource); | |
97 | 96 |
98 var collector = new _ErrorCollector(); | 97 var collector = new _ErrorCollector(); |
99 var checker = new CodeChecker( | 98 var checker = new CodeChecker( |
100 context.typeProvider, new StrongTypeSystemImpl(), collector, | 99 context.typeProvider, new StrongTypeSystemImpl(), collector, |
101 hints: true); | 100 hints: true); |
102 | 101 |
103 // Extract expectations from the comments in the test files, and | 102 // Extract expectations from the comments in the test files, and |
104 // check that all errors we emit are included in the expected map. | 103 // check that all errors we emit are included in the expected map. |
105 var allLibraries = reachableLibraries(initialLibrary.element.library); | 104 var allLibraries = reachableLibraries(initialLibrary.element.library); |
106 for (var lib in allLibraries) { | 105 for (var lib in allLibraries) { |
107 for (var unit in lib.units) { | 106 for (var unit in lib.units) { |
108 var errors = <AnalysisError>[]; | 107 var errors = <AnalysisError>[]; |
109 collector.errors = errors; | 108 collector.errors = errors; |
110 | 109 |
111 var source = unit.source; | 110 var source = unit.source; |
112 if (source.uri.scheme == 'dart') continue; | 111 if (source.uri.scheme == 'dart') continue; |
113 | 112 |
114 var librarySource = context.getLibrariesContaining(source).single; | 113 var librarySource = context.getLibrariesContaining(source).single; |
115 var resolved = context.resolveCompilationUnit2(source, librarySource); | 114 var resolved = context.resolveCompilationUnit2(source, librarySource); |
116 var analyzerErrors = context | 115 errors.addAll(context.getErrors(source).errors.where((error) => |
117 .getErrors(source) | 116 error.errorCode.name.startsWith('STRONG_MODE_INFERRED_TYPE'))); |
118 .errors | |
119 .where((error) => | |
120 error.errorCode.name.startsWith('STRONG_MODE_INFERRED_TYPE')) | |
121 .toList(); | |
122 errors.addAll(analyzerErrors); | |
123 checker.visitCompilationUnit(resolved); | 117 checker.visitCompilationUnit(resolved); |
124 | 118 |
125 new _ExpectedErrorVisitor(errors).validate(resolved); | 119 _expectErrors(resolved, errors); |
126 } | 120 } |
127 } | 121 } |
128 } | 122 } |
129 | 123 |
130 /// Sample mock SDK sources. | 124 /// Sample mock SDK sources. |
131 final Map<String, String> _mockSdkSources = { | 125 final Map<String, String> _mockSdkSources = { |
132 // The list of types below is derived from: | 126 // The list of types below is derived from: |
133 // * types we use via our smoke queries, including HtmlElement and | 127 // * types we use via our smoke queries, including HtmlElement and |
134 // types from `_typeHandlers` (deserialize.dart) | 128 // types from `_typeHandlers` (deserialize.dart) |
135 // * types that are used internally by the resolver (see | 129 // * types that are used internally by the resolver (see |
(...skipping 81 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
217 'dart:_foreign_helper': ''' | 211 'dart:_foreign_helper': ''' |
218 library dart._foreign_helper; | 212 library dart._foreign_helper; |
219 | 213 |
220 JS(String typeDescription, String codeTemplate, | 214 JS(String typeDescription, String codeTemplate, |
221 [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11]) | 215 [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11]) |
222 {} | 216 {} |
223 ''' | 217 ''' |
224 }; | 218 }; |
225 | 219 |
226 SourceSpanWithContext createSpanHelper( | 220 SourceSpanWithContext createSpanHelper( |
227 LineInfo lineInfo, int start, int end, Source source, String content) { | 221 LineInfo lineInfo, int start, Source source, String content, |
| 222 {int end}) { |
228 var startLoc = locationForOffset(lineInfo, source.uri, start); | 223 var startLoc = locationForOffset(lineInfo, source.uri, start); |
229 var endLoc = locationForOffset(lineInfo, source.uri, end); | 224 var endLoc = locationForOffset(lineInfo, source.uri, end ?? start); |
230 | 225 |
231 var lineStart = startLoc.offset - startLoc.column; | 226 var lineStart = startLoc.offset - startLoc.column; |
232 // Find the end of the line. This is not exposed directly on LineInfo, but | 227 // Find the end of the line. This is not exposed directly on LineInfo, but |
233 // we can find it pretty easily. | 228 // we can find it pretty easily. |
234 // TODO(jmesserly): for now we do the simple linear scan. Ideally we can get | 229 // TODO(jmesserly): for now we do the simple linear scan. Ideally we can get |
235 // some help from the LineInfo API. | 230 // some help from the LineInfo API. |
236 int lineEnd = endLoc.offset; | 231 int lineEnd = endLoc.offset; |
237 int lineNum = lineInfo.getLocation(lineEnd).lineNumber; | 232 int lineNum = lineInfo.getLocation(lineEnd).lineNumber; |
238 while (lineEnd < content.length && | 233 while (lineEnd < content.length && |
239 lineInfo.getLocation(++lineEnd).lineNumber == lineNum); | 234 lineInfo.getLocation(++lineEnd).lineNumber == lineNum); |
240 | 235 |
| 236 if (end == null) { |
| 237 end = lineEnd; |
| 238 endLoc = locationForOffset(lineInfo, source.uri, lineEnd); |
| 239 } |
| 240 |
241 var text = content.substring(start, end); | 241 var text = content.substring(start, end); |
242 var lineText = content.substring(lineStart, lineEnd); | 242 var lineText = content.substring(lineStart, lineEnd); |
243 return new SourceSpanWithContext(startLoc, endLoc, text, lineText); | 243 return new SourceSpanWithContext(startLoc, endLoc, text, lineText); |
244 } | 244 } |
245 | 245 |
246 String errorCodeName(ErrorCode errorCode) { | 246 String errorCodeName(ErrorCode errorCode) { |
247 var name = errorCode.name; | 247 var name = errorCode.name; |
248 final prefix = 'STRONG_MODE_'; | 248 final prefix = 'STRONG_MODE_'; |
249 if (name.startsWith(prefix)) { | 249 if (name.startsWith(prefix)) { |
250 return name.substring(prefix.length); | 250 return name.substring(prefix.length); |
(...skipping 28 matching lines...) Expand all Loading... |
279 | 279 |
280 /// Dart SDK which contains a mock implementation of the SDK libraries. May be | 280 /// Dart SDK which contains a mock implementation of the SDK libraries. May be |
281 /// used to speed up execution when most of the core libraries is not needed. | 281 /// used to speed up execution when most of the core libraries is not needed. |
282 class MockDartSdk implements DartSdk { | 282 class MockDartSdk implements DartSdk { |
283 final Map<Uri, _MockSdkSource> _sources = {}; | 283 final Map<Uri, _MockSdkSource> _sources = {}; |
284 final bool reportMissing; | 284 final bool reportMissing; |
285 final Map<String, SdkLibrary> _libs = {}; | 285 final Map<String, SdkLibrary> _libs = {}; |
286 final String sdkVersion = '0'; | 286 final String sdkVersion = '0'; |
287 final AnalysisContext context = new SdkAnalysisContext(); | 287 final AnalysisContext context = new SdkAnalysisContext(); |
288 DartUriResolver _resolver; | 288 DartUriResolver _resolver; |
| 289 |
289 MockDartSdk(Map<String, String> sources, {this.reportMissing}) { | 290 MockDartSdk(Map<String, String> sources, {this.reportMissing}) { |
290 sources.forEach((uriString, contents) { | 291 sources.forEach((uriString, contents) { |
291 var uri = Uri.parse(uriString); | 292 var uri = Uri.parse(uriString); |
292 _sources[uri] = new _MockSdkSource(uri, contents); | 293 _sources[uri] = new _MockSdkSource(uri, contents); |
293 _libs[uriString] = new SdkLibraryImpl(uri.path) | 294 _libs[uriString] = new SdkLibraryImpl(uri.path) |
294 ..setDart2JsLibrary() | 295 ..setDart2JsLibrary() |
295 ..setVmLibrary(); | 296 ..setVmLibrary(); |
296 }); | 297 }); |
297 _resolver = new DartUriResolver(this); | 298 _resolver = new DartUriResolver(this); |
298 context.sourceFactory = new SourceFactory([_resolver]); | 299 context.sourceFactory = new SourceFactory([_resolver]); |
299 } | 300 } |
| 301 |
300 DartUriResolver get resolver => _resolver; | 302 DartUriResolver get resolver => _resolver; |
301 | 303 |
302 List<SdkLibrary> get sdkLibraries => _libs.values.toList(); | 304 List<SdkLibrary> get sdkLibraries => _libs.values.toList(); |
303 | 305 |
304 List<String> get uris => _sources.keys.map((uri) => '$uri').toList(); | 306 List<String> get uris => _sources.keys.map((uri) => '$uri').toList(); |
| 307 |
305 Source fromEncoding(UriKind kind, Uri uri) { | 308 Source fromEncoding(UriKind kind, Uri uri) { |
306 if (kind != UriKind.DART_URI) { | 309 if (kind != UriKind.DART_URI) { |
307 throw new UnsupportedError('expected dart: uri kind, got $kind.'); | 310 throw new UnsupportedError('expected dart: uri kind, got $kind.'); |
308 } | 311 } |
309 return _getSource(uri); | 312 return _getSource(uri); |
310 } | 313 } |
311 | 314 |
312 @override | 315 @override |
313 Source fromFileUri(Uri uri) { | 316 Source fromFileUri(Uri uri) { |
314 throw new UnsupportedError('MockDartSdk.fromFileUri'); | 317 throw new UnsupportedError('MockDartSdk.fromFileUri'); |
315 } | 318 } |
316 | 319 |
317 SdkLibrary getSdkLibrary(String dartUri) => _libs[dartUri]; | 320 SdkLibrary getSdkLibrary(String dartUri) => _libs[dartUri]; |
318 | 321 |
319 Source mapDartUri(String dartUri) => _getSource(Uri.parse(dartUri)); | 322 Source mapDartUri(String dartUri) => _getSource(Uri.parse(dartUri)); |
320 | 323 |
321 Source _getSource(Uri uri) { | 324 Source _getSource(Uri uri) { |
322 var src = _sources[uri]; | 325 var src = _sources[uri]; |
323 if (src == null) { | 326 if (src == null) { |
324 if (reportMissing) print('warning: missing mock for $uri.'); | 327 if (reportMissing) print('warning: missing mock for $uri.'); |
325 _sources[uri] = | 328 _sources[uri] = |
326 src = new _MockSdkSource(uri, 'library dart.${uri.path};'); | 329 src = new _MockSdkSource(uri, 'library dart.${uri.path};'); |
327 } | 330 } |
328 return src; | 331 return src; |
329 } | 332 } |
330 } | 333 } |
331 | 334 |
332 class TestUriResolver extends ResourceUriResolver { | 335 class TestUriResolver extends ResourceUriResolver { |
333 final MemoryResourceProvider provider; | 336 final MemoryResourceProvider provider; |
| 337 |
334 TestUriResolver(provider) | 338 TestUriResolver(provider) |
335 : provider = provider, | 339 : provider = provider, |
336 super(provider); | 340 super(provider); |
337 | 341 |
338 @override | 342 @override |
339 Source resolveAbsolute(Uri uri, [Uri actualUri]) { | 343 Source resolveAbsolute(Uri uri, [Uri actualUri]) { |
340 if (uri.scheme == 'package') { | 344 if (uri.scheme == 'package') { |
341 return (provider.getResource('/packages/' + uri.path) as File) | 345 return (provider.getResource('/packages/' + uri.path) as File) |
342 .createSource(uri); | 346 .createSource(uri); |
343 } | 347 } |
344 return super.resolveAbsolute(uri, actualUri); | 348 return super.resolveAbsolute(uri, actualUri); |
345 } | 349 } |
346 } | 350 } |
347 | 351 |
348 class _ErrorCollector implements AnalysisErrorListener { | 352 class _ErrorCollector implements AnalysisErrorListener { |
349 List<AnalysisError> errors; | 353 List<AnalysisError> errors; |
350 final bool hints; | 354 final bool hints; |
| 355 |
351 _ErrorCollector({this.hints: true}); | 356 _ErrorCollector({this.hints: true}); |
352 | 357 |
353 void onError(AnalysisError error) { | 358 void onError(AnalysisError error) { |
354 // Unless DDC hints are requested, filter them out. | 359 // Unless DDC hints are requested, filter them out. |
355 var HINT = ErrorSeverity.INFO.ordinal; | 360 var HINT = ErrorSeverity.INFO.ordinal; |
356 if (hints || error.errorCode.errorSeverity.ordinal > HINT) { | 361 if (hints || error.errorCode.errorSeverity.ordinal > HINT) { |
357 errors.add(error); | 362 errors.add(error); |
358 } | 363 } |
359 } | 364 } |
360 } | 365 } |
361 | 366 |
362 /// Describes an expected message that should be produced by the checker. | 367 /// Describes an expected message that should be produced by the checker. |
363 class _ErrorExpectation { | 368 class _ErrorExpectation { |
| 369 final int offset; |
364 final Level level; | 370 final Level level; |
365 final String typeName; | 371 final String typeName; |
366 _ErrorExpectation(this.level, this.typeName); | |
367 | 372 |
368 String toString() => '$level $typeName'; | 373 _ErrorExpectation(this.offset, this.level, this.typeName); |
369 | 374 |
370 static _ErrorExpectation parse(String descriptor) { | 375 String toString() => |
| 376 '@$offset ${level.toString().toLowerCase()}: [$typeName]'; |
| 377 |
| 378 static _ErrorExpectation parse(int offset, String descriptor) { |
371 descriptor = descriptor.trim(); | 379 descriptor = descriptor.trim(); |
372 var tokens = descriptor.split(' '); | 380 var tokens = descriptor.split(' '); |
373 if (tokens.length == 1) return _parse(tokens[0]); | 381 if (tokens.length == 1) return _parse(offset, tokens[0]); |
374 expect(tokens.length, 4, reason: 'invalid error descriptor'); | 382 expect(tokens.length, 4, reason: 'invalid error descriptor'); |
375 expect(tokens[1], "should", reason: 'invalid error descriptor'); | 383 expect(tokens[1], "should", reason: 'invalid error descriptor'); |
376 expect(tokens[2], "be", reason: 'invalid error descriptor'); | 384 expect(tokens[2], "be", reason: 'invalid error descriptor'); |
377 if (tokens[0] == "pass") return null; | 385 if (tokens[0] == "pass") return null; |
378 // TODO(leafp) For now, we just use whatever the current expectation is, | 386 // TODO(leafp) For now, we just use whatever the current expectation is, |
379 // eventually we could do more automated reporting here. | 387 // eventually we could do more automated reporting here. |
380 return _parse(tokens[0]); | 388 return _parse(offset, tokens[0]); |
381 } | 389 } |
382 | 390 |
383 static _ErrorExpectation _parse(String descriptor) { | 391 static _ErrorExpectation _parse(offset, String descriptor) { |
384 var tokens = descriptor.split(':'); | 392 var tokens = descriptor.split(':'); |
385 expect(tokens.length, 2, reason: 'invalid error descriptor'); | 393 expect(tokens.length, 2, reason: 'invalid error descriptor'); |
386 var name = tokens[0].toUpperCase(); | 394 var name = tokens[0].toUpperCase(); |
387 var typeName = tokens[1]; | 395 var typeName = tokens[1]; |
388 | 396 |
389 var level = | 397 var level = |
390 Level.LEVELS.firstWhere((l) => l.name == name, orElse: () => null); | 398 Level.LEVELS.firstWhere((l) => l.name == name, orElse: () => null); |
391 expect(level, isNotNull, | 399 expect(level, isNotNull, |
392 reason: 'invalid level in error descriptor: `${tokens[0]}`'); | 400 reason: 'invalid level in error descriptor: `${tokens[0]}`'); |
393 expect(typeName, isNotNull, | 401 expect(typeName, isNotNull, |
394 reason: 'invalid type in error descriptor: ${tokens[1]}'); | 402 reason: 'invalid type in error descriptor: ${tokens[1]}'); |
395 return new _ErrorExpectation(level, typeName); | 403 return new _ErrorExpectation(offset, level, typeName); |
| 404 } |
| 405 |
| 406 AnalysisError _removeMatchingActual(List<AnalysisError> actualErrors) { |
| 407 for (var actual in actualErrors) { |
| 408 if (actual.offset == offset) { |
| 409 actualErrors.remove(actual); |
| 410 return actual; |
| 411 } |
| 412 } |
| 413 return null; |
396 } | 414 } |
397 } | 415 } |
398 | 416 |
399 class _ExpectedErrorVisitor extends UnifyingAstVisitor { | 417 void _expectErrors(CompilationUnit unit, List<AnalysisError> actualErrors) { |
400 final Set<AnalysisError> _actualErrors; | 418 var expectedErrors = _findExpectedErrors(unit.beginToken); |
401 CompilationUnit _unit; | |
402 String _unitSourceCode; | |
403 | 419 |
404 _ExpectedErrorVisitor(List<AnalysisError> actualErrors) | 420 // Categorize the differences, if any. |
405 : _actualErrors = new Set.from(actualErrors); | 421 var unreported = <_ErrorExpectation>[]; |
| 422 var different = <_ErrorExpectation, AnalysisError>{}; |
406 | 423 |
407 validate(CompilationUnit unit) { | 424 for (var expected in expectedErrors) { |
408 _unit = unit; | 425 AnalysisError actual = expected._removeMatchingActual(actualErrors); |
409 // This reads the file. Only safe because tests use MemoryFileSystem. | 426 if (actual != null) { |
410 _unitSourceCode = unit.element.source.contents.data; | 427 if (_actualErrorLevel(actual) != expected.level || |
411 | 428 errorCodeName(actual.errorCode) != expected.typeName) { |
412 // Visit the compilation unit. | 429 different[expected] = actual; |
413 unit.accept(this); | 430 } |
414 | 431 } else { |
415 if (_actualErrors.isNotEmpty) { | 432 unreported.add(expected); |
416 var actualMsgs = _actualErrors.map(_formatActualError).join('\n'); | |
417 fail('Unexpected errors reported by checker:\n\n$actualMsgs'); | |
418 } | 433 } |
419 } | 434 } |
420 | 435 |
421 visitNode(AstNode node) { | 436 // Whatever is left was an unexpected error. |
422 var token = node.beginToken; | 437 List<AnalysisError> unexpected = actualErrors; |
423 var comment = token.precedingComments; | |
424 // Use error marker found in an immediately preceding comment, | |
425 // and attach it to the outermost expression that starts at that token. | |
426 if (comment != null) { | |
427 while (comment.next != null) { | |
428 comment = comment.next; | |
429 } | |
430 if (comment.end == token.offset && node.parent.beginToken != token) { | |
431 var commentText = '$comment'; | |
432 var start = commentText.lastIndexOf('/*'); | |
433 var end = commentText.lastIndexOf('*/'); | |
434 if (start != -1 && | |
435 end != -1 && | |
436 !commentText.startsWith('/*<', start) && | |
437 !commentText.startsWith('/*=', start)) { | |
438 expect(start, lessThan(end)); | |
439 var errors = commentText.substring(start + 2, end).split(','); | |
440 var expectations = | |
441 errors.map(_ErrorExpectation.parse).where((x) => x != null); | |
442 | 438 |
443 for (var e in expectations) { | 439 if (unreported.isNotEmpty || unexpected.isNotEmpty || different.isNotEmpty) { |
444 _expectError(node, e); | 440 _reportFailure(unit, unreported, unexpected, different); |
| 441 } |
| 442 } |
| 443 |
| 444 void _reportFailure( |
| 445 CompilationUnit unit, |
| 446 List<_ErrorExpectation> unreported, |
| 447 List<AnalysisError> unexpected, |
| 448 Map<_ErrorExpectation, AnalysisError> different) { |
| 449 |
| 450 // Get the source code. This reads the data again, but it's safe because |
| 451 // all tests use memory file system. |
| 452 var sourceCode = unit.element.source.contents.data; |
| 453 |
| 454 String formatActualError(AnalysisError error) { |
| 455 int offset = error.offset; |
| 456 int length = error.length; |
| 457 var span = createSpanHelper( |
| 458 unit.lineInfo, offset, unit.element.source, sourceCode, |
| 459 end: offset + length); |
| 460 var levelName = _actualErrorLevel(error).name.toLowerCase(); |
| 461 return '@$offset $levelName: [${errorCodeName(error.errorCode)}]\n' + |
| 462 span.message(error.message); |
| 463 } |
| 464 |
| 465 String formatExpectedError(_ErrorExpectation error) { |
| 466 int offset = error.offset; |
| 467 var span = createSpanHelper( |
| 468 unit.lineInfo, offset, unit.element.source, sourceCode); |
| 469 var levelName = error.level.toString().toLowerCase(); |
| 470 return '@$offset $levelName: [${error.typeName}]\n' + span.message(''); |
| 471 } |
| 472 |
| 473 var message = new StringBuffer(); |
| 474 if (unreported.isNotEmpty) { |
| 475 message.writeln('Expected errors that were not reported:'); |
| 476 unreported.map(formatExpectedError).forEach(message.writeln); |
| 477 message.writeln(); |
| 478 } |
| 479 if (unexpected.isNotEmpty) { |
| 480 message.writeln('Errors that were not expected:'); |
| 481 unexpected.map(formatActualError).forEach(message.writeln); |
| 482 message.writeln(); |
| 483 } |
| 484 if (different.isNotEmpty) { |
| 485 message.writeln('Errors that were reported, but different than expected:'); |
| 486 different.forEach((expected, actual) { |
| 487 message.writeln('Expected: ' + formatExpectedError(expected)); |
| 488 message.writeln('Actual: ' + formatActualError(actual)); |
| 489 }); |
| 490 message.writeln(); |
| 491 } |
| 492 fail('Checker errors do not match expected errors:\n\n$message'); |
| 493 } |
| 494 |
| 495 List<_ErrorExpectation> _findExpectedErrors(Token beginToken) { |
| 496 var expectedErrors = <_ErrorExpectation>[]; |
| 497 |
| 498 // Collect expectations like "severe:STATIC_TYPE_ERROR" from comment tokens. |
| 499 for (Token t = beginToken; t.type != TokenType.EOF; t = t.next) { |
| 500 for (CommentToken c = t.precedingComments; c != null; c = c.next) { |
| 501 if (c.type == TokenType.MULTI_LINE_COMMENT) { |
| 502 String value = c.lexeme.substring(2, c.lexeme.length - 2); |
| 503 if (value.contains(':')) { |
| 504 var offset = c.end; |
| 505 if (c.next?.type == TokenType.GENERIC_METHOD_TYPE_LIST) { |
| 506 offset += 2; |
| 507 } |
| 508 for (var expectCode in value.split(',')) { |
| 509 var expected = _ErrorExpectation.parse(offset, expectCode); |
| 510 if (expected != null) { |
| 511 expectedErrors.add(expected); |
| 512 } |
445 } | 513 } |
446 } | 514 } |
447 } | 515 } |
448 } | 516 } |
449 return super.visitNode(node); | |
450 } | 517 } |
| 518 return expectedErrors; |
| 519 } |
451 | 520 |
452 Level _actualErrorLevel(AnalysisError actual) { | 521 Level _actualErrorLevel(AnalysisError actual) { |
453 return const <ErrorSeverity, Level>{ | 522 return const <ErrorSeverity, Level>{ |
454 ErrorSeverity.ERROR: Level.SEVERE, | 523 ErrorSeverity.ERROR: Level.SEVERE, |
455 ErrorSeverity.WARNING: Level.WARNING, | 524 ErrorSeverity.WARNING: Level.WARNING, |
456 ErrorSeverity.INFO: Level.INFO | 525 ErrorSeverity.INFO: Level.INFO |
457 }[actual.errorCode.errorSeverity]; | 526 }[actual.errorCode.errorSeverity]; |
458 } | |
459 | |
460 SourceSpan _createSpan(int offset, int len) { | |
461 return createSpanHelper(_unit.lineInfo, offset, offset + len, | |
462 _unit.element.source, _unitSourceCode); | |
463 } | |
464 | |
465 void _expectError(AstNode node, _ErrorExpectation expected) { | |
466 // See if we can find the expected error in our actual errors | |
467 for (var actual in _actualErrors) { | |
468 if (actual.offset == node.offset && actual.length == node.length) { | |
469 var actualMsg = _formatActualError(actual); | |
470 expect(_actualErrorLevel(actual), expected.level, | |
471 reason: 'expected different error code at:\n\n$actualMsg'); | |
472 expect(errorCodeName(actual.errorCode), expected.typeName, | |
473 reason: 'expected different error type at:\n\n$actualMsg'); | |
474 | |
475 // We found it. Stop the search. | |
476 _actualErrors.remove(actual); | |
477 return; | |
478 } | |
479 } | |
480 | |
481 var span = _createSpan(node.offset, node.length); | |
482 var levelName = expected.level.name.toLowerCase(); | |
483 var msg = span.message(expected.typeName, color: _colorOf(levelName)); | |
484 fail('expected error was not reported at:\n\n$levelName: $msg'); | |
485 } | |
486 | |
487 String _formatActualError(AnalysisError actual) { | |
488 var span = _createSpan(actual.offset, actual.length); | |
489 var levelName = _actualErrorLevel(actual).name.toLowerCase(); | |
490 var msg = span.message(actual.message, color: _colorOf(levelName)); | |
491 return '$levelName: [${errorCodeName(actual.errorCode)}] $msg'; | |
492 } | |
493 | |
494 /// Returns an ANSII color escape sequence corresponding to [levelName]. | |
495 /// | |
496 /// Colors are defined for: severe, error, warning, or info. | |
497 /// Returns null if the level name is not recognized. | |
498 String _colorOf(String levelName) { | |
499 const String CYAN_COLOR = '\u001b[36m'; | |
500 const String MAGENTA_COLOR = '\u001b[35m'; | |
501 const String RED_COLOR = '\u001b[31m'; | |
502 | |
503 levelName = levelName.toLowerCase(); | |
504 if (levelName == 'shout' || levelName == 'severe' || levelName == 'error') { | |
505 return RED_COLOR; | |
506 } | |
507 if (levelName == 'warning') return MAGENTA_COLOR; | |
508 if (levelName == 'info') return CYAN_COLOR; | |
509 return null; | |
510 } | |
511 } | 527 } |
512 | 528 |
513 class _MockSdkSource implements Source { | 529 class _MockSdkSource implements Source { |
514 /// Absolute URI which this source can be imported from. | 530 /// Absolute URI which this source can be imported from. |
515 final Uri uri; | 531 final Uri uri; |
516 final String _contents; | 532 final String _contents; |
517 | 533 |
518 final int modificationStamp = 1; | 534 final int modificationStamp = 1; |
519 | 535 |
520 _MockSdkSource(this.uri, this._contents); | 536 _MockSdkSource(this.uri, this._contents); |
(...skipping 16 matching lines...) Expand all Loading... |
537 UriKind get uriKind => UriKind.DART_URI; | 553 UriKind get uriKind => UriKind.DART_URI; |
538 | 554 |
539 bool exists() => true; | 555 bool exists() => true; |
540 | 556 |
541 Source resolveRelative(Uri relativeUri) => | 557 Source resolveRelative(Uri relativeUri) => |
542 throw new UnsupportedError('not expecting relative urls in dart: mocks'); | 558 throw new UnsupportedError('not expecting relative urls in dart: mocks'); |
543 | 559 |
544 Uri resolveRelativeUri(Uri relativeUri) => | 560 Uri resolveRelativeUri(Uri relativeUri) => |
545 throw new UnsupportedError('not expecting relative urls in dart: mocks'); | 561 throw new UnsupportedError('not expecting relative urls in dart: mocks'); |
546 } | 562 } |
OLD | NEW |