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

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

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

Powered by Google App Engine
This is Rietveld 408576698