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

Side by Side Diff: pkg/compiler/lib/src/compiler.dart

Issue 1803303002: Move all flags to CompilerOptions (first step to stop passing the compiler to (Closed) Base URL: git@github.com:dart-lang/sdk.git@master
Patch Set: Created 4 years, 9 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
OLDNEW
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2012, 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 library dart2js.compiler_base; 5 library dart2js.compiler_base;
6 6
7 import 'dart:async' show 7 import 'dart:async' show
8 EventSink, 8 EventSink,
9 Future; 9 Future;
10 10
(...skipping 166 matching lines...) Expand 10 before | Expand all | Expand 10 after
177 /** 177 /**
178 * Dependencies that are only included due to mirrors. 178 * Dependencies that are only included due to mirrors.
179 * 179 *
180 * We should get rid of this and ensure that all dependencies are 180 * We should get rid of this and ensure that all dependencies are
181 * associated with a particular element. 181 * associated with a particular element.
182 */ 182 */
183 // TODO(johnniwinther): This should not be a [ResolutionRegistry]. 183 // TODO(johnniwinther): This should not be a [ResolutionRegistry].
184 final Registry mirrorDependencies = 184 final Registry mirrorDependencies =
185 new ResolutionRegistry(null, new TreeElementMapping(null)); 185 new ResolutionRegistry(null, new TreeElementMapping(null));
186 186
187 final bool enableMinification; 187 /// Options provided from command-line arguments.
188 188 final api.CompilerOptions options;
189 final bool useFrequencyNamer;
190
191 /// When `true` emits URIs in the reflection metadata.
192 final bool preserveUris;
193
194 final bool enableTypeAssertions;
195 final bool enableUserAssertions;
196 final bool trustTypeAnnotations;
197 final bool trustPrimitives;
198 final bool trustJSInteropTypeAnnotations;
199 final bool disableTypeInferenceFlag;
200 final Uri deferredMapUri;
201 final bool dumpInfo;
202 final bool useContentSecurityPolicy;
203 final bool enableExperimentalMirrors;
204 final bool enableAssertMessage;
205
206 /**
207 * The maximum size of a concrete type before it widens to dynamic during
208 * concrete type inference.
209 */
210 final int maxConcreteTypeSize;
211 final bool analyzeAllFlag;
212 final bool analyzeOnly;
213
214 /// If true, disable tree-shaking for the main script.
215 final bool analyzeMain;
216
217 /**
218 * If true, skip analysis of method bodies and field initializers. Implies
219 * [analyzeOnly].
220 */
221 final bool analyzeSignaturesOnly;
222 final bool enableNativeLiveTypeAnalysis;
223 189
224 /** 190 /**
225 * If true, stop compilation after type inference is complete. Used for 191 * If true, stop compilation after type inference is complete. Used for
226 * debugging and testing purposes only. 192 * debugging and testing purposes only.
227 */ 193 */
228 bool stopAfterTypeInference = false; 194 bool stopAfterTypeInference = false;
229 195
230 /**
231 * If [:true:], comment tokens are collected in [commentMap] during scanning.
232 */
233 final bool preserveComments;
234
235 /// Use the new CPS based backend end. This flag works for both the Dart and
236 /// JavaScript backend.
237 final bool useCpsIr;
238
239 /**
240 * Is the compiler in verbose mode.
241 */
242 final bool verbose;
243
244 /**
245 * URI of the main source map if the compiler is generating source
246 * maps.
247 */
248 final Uri sourceMapUri;
249
250 /**
251 * URI of the main output if the compiler is generating source maps.
252 */
253 final Uri outputUri;
254
255 /// If `true`, some values are cached for reuse in incremental compilation.
256 /// Incremental compilation is basically calling [run] more than once.
257 final bool hasIncrementalSupport;
258
259 /// If `true` native extension syntax is supported by the frontend.
260 final bool allowNativeExtensions;
261
262 /// Output provider from user of Compiler API. 196 /// Output provider from user of Compiler API.
263 api.CompilerOutput userOutputProvider; 197 api.CompilerOutput userOutputProvider;
264 198
265 /// Generate output even when there are compile-time errors.
266 final bool generateCodeWithCompileTimeErrors;
267
268 /// The compiler is run from the build bot.
269 final bool testMode;
270
271 bool disableInlining = false;
272
273 List<Uri> librariesToAnalyzeWhenRun; 199 List<Uri> librariesToAnalyzeWhenRun;
274 200
275 /// The set of platform libraries reported as unsupported. 201 /// The set of platform libraries reported as unsupported.
276 /// 202 ///
277 /// For instance when importing 'dart:io' without '--categories=Server'. 203 /// For instance when importing 'dart:io' without '--categories=Server'.
278 Set<Uri> disallowedLibraryUris = new Setlet<Uri>(); 204 Set<Uri> disallowedLibraryUris = new Setlet<Uri>();
279 205
280 Tracer tracer; 206 Tracer tracer;
281 207
282 CompilerTask measuredTask; 208 CompilerTask measuredTask;
(...skipping 90 matching lines...) Expand 10 before | Expand all | Expand 10 after
373 GenericTask reuseLibraryTask; 299 GenericTask reuseLibraryTask;
374 300
375 /// The constant environment for the frontend interpretation of compile-time 301 /// The constant environment for the frontend interpretation of compile-time
376 /// constants. 302 /// constants.
377 ConstantEnvironment constants; 303 ConstantEnvironment constants;
378 304
379 EnqueueTask enqueuer; 305 EnqueueTask enqueuer;
380 DeferredLoadTask deferredLoadTask; 306 DeferredLoadTask deferredLoadTask;
381 MirrorUsageAnalyzerTask mirrorUsageAnalyzerTask; 307 MirrorUsageAnalyzerTask mirrorUsageAnalyzerTask;
382 DumpInfoTask dumpInfoTask; 308 DumpInfoTask dumpInfoTask;
383 String buildId;
384 309
385 /// A customizable filter that is applied to enqueued work items. 310 /// A customizable filter that is applied to enqueued work items.
386 QueueFilter enqueuerFilter = new QueueFilter(); 311 QueueFilter enqueuerFilter = new QueueFilter();
387 312
388 final Selector symbolValidatedConstructorSelector = new Selector.call( 313 final Selector symbolValidatedConstructorSelector = new Selector.call(
389 const PublicName('validated'), CallStructure.ONE_ARG); 314 const PublicName('validated'), CallStructure.ONE_ARG);
390 315
391 static const String CREATE_INVOCATION_MIRROR = 316 static const String CREATE_INVOCATION_MIRROR =
392 'createInvocationMirror'; 317 'createInvocationMirror';
393 318
394 static const String UNDETERMINED_BUILD_ID =
395 "build number could not be determined";
396
397 bool enabledRuntimeType = false; 319 bool enabledRuntimeType = false;
398 bool enabledFunctionApply = false; 320 bool enabledFunctionApply = false;
399 bool enabledInvokeOn = false; 321 bool enabledInvokeOn = false;
400 bool hasIsolateSupport = false; 322 bool hasIsolateSupport = false;
401 323
402 bool get hasCrashed => _reporter.hasCrashed; 324 bool get hasCrashed => _reporter.hasCrashed;
403 325
404 Stopwatch progress; 326 Stopwatch progress;
405 327
406 bool get shouldPrintProgress { 328 bool get shouldPrintProgress {
407 return verbose && progress.elapsedMilliseconds > 500; 329 return options.verbose && progress.elapsedMilliseconds > 500;
408 } 330 }
409 331
410 static const int PHASE_SCANNING = 0; 332 static const int PHASE_SCANNING = 0;
411 static const int PHASE_RESOLVING = 1; 333 static const int PHASE_RESOLVING = 1;
412 static const int PHASE_DONE_RESOLVING = 2; 334 static const int PHASE_DONE_RESOLVING = 2;
413 static const int PHASE_COMPILING = 3; 335 static const int PHASE_COMPILING = 3;
414 int phase; 336 int phase;
415 337
416 bool compilationFailedInternal = false; 338 bool compilationFailedInternal = false;
417 339
418 bool get compilationFailed => compilationFailedInternal; 340 bool get compilationFailed => compilationFailedInternal;
419 341
420 void set compilationFailed(bool value) { 342 void set compilationFailed(bool value) {
421 if (value) { 343 if (value) {
422 elementsWithCompileTimeErrors.add(currentElement); 344 elementsWithCompileTimeErrors.add(currentElement);
423 } 345 }
424 compilationFailedInternal = value; 346 compilationFailedInternal = value;
425 } 347 }
426 348
427 /// Set by the backend if real reflection is detected in use of dart:mirrors. 349 Compiler({api.CompilerOptions options,
428 bool disableTypeInferenceForMirrors = false; 350 api.CompilerOutput outputProvider})
429 351 : this.options = options,
430 Compiler({this.enableTypeAssertions: false, 352 this.cacheStrategy = new CacheStrategy(options.hasIncrementalSupport),
431 this.enableUserAssertions: false,
432 this.trustTypeAnnotations: false,
433 this.trustPrimitives: false,
434 this.trustJSInteropTypeAnnotations: false,
435 bool disableTypeInferenceFlag: false,
436 this.maxConcreteTypeSize: 5,
437 this.enableMinification: false,
438 this.preserveUris: false,
439 this.enableNativeLiveTypeAnalysis: false,
440 bool emitJavaScript: true,
441 bool dart2dartMultiFile: false,
442 bool generateSourceMap: true,
443 bool analyzeAllFlag: false,
444 bool analyzeOnly: false,
445 this.analyzeMain: false,
446 bool analyzeSignaturesOnly: false,
447 this.preserveComments: false,
448 this.useCpsIr: false,
449 this.useFrequencyNamer: false,
450 this.verbose: false,
451 this.sourceMapUri: null,
452 this.outputUri: null,
453 this.buildId: UNDETERMINED_BUILD_ID,
454 this.deferredMapUri: null,
455 this.dumpInfo: false,
456 bool useStartupEmitter: false,
457 bool enableConditionalDirectives: false,
458 bool useNewSourceInfo: false,
459 this.useContentSecurityPolicy: false,
460 bool hasIncrementalSupport: false,
461 this.enableExperimentalMirrors: false,
462 this.enableAssertMessage: false,
463 this.allowNativeExtensions: false,
464 this.generateCodeWithCompileTimeErrors: false,
465 this.testMode: false,
466 DiagnosticOptions diagnosticOptions,
467 api.CompilerOutput outputProvider,
468 List<String> strips: const []})
469 : this.disableTypeInferenceFlag =
470 disableTypeInferenceFlag || !emitJavaScript,
471 this.analyzeOnly =
472 analyzeOnly || analyzeSignaturesOnly || analyzeAllFlag,
473 this.analyzeSignaturesOnly = analyzeSignaturesOnly,
474 this.analyzeAllFlag = analyzeAllFlag,
475 this.hasIncrementalSupport = hasIncrementalSupport,
476 cacheStrategy = new CacheStrategy(hasIncrementalSupport),
477 this.userOutputProvider = outputProvider == null 353 this.userOutputProvider = outputProvider == null
478 ? const NullCompilerOutput() : outputProvider { 354 ? const NullCompilerOutput() : outputProvider {
479 if (hasIncrementalSupport) { 355
480 // TODO(ahe): This is too much. Any method from platform and package
481 // libraries can be inlined.
482 disableInlining = true;
483 }
484 world = new World(this); 356 world = new World(this);
485 // TODO(johnniwinther): Initialize core types in [initializeCoreClasses] and 357 // TODO(johnniwinther): Initialize core types in [initializeCoreClasses] and
486 // make its field final. 358 // make its field final.
487 _reporter = new _CompilerDiagnosticReporter(this, diagnosticOptions); 359 _reporter = new _CompilerDiagnosticReporter(
360 this, options.diagnosticOptions);
488 _parsing = new _CompilerParsing(this); 361 _parsing = new _CompilerParsing(this);
489 _resolution = new _CompilerResolution(this); 362 _resolution = new _CompilerResolution(this);
490 _coreTypes = new _CompilerCoreTypes(_resolution); 363 _coreTypes = new _CompilerCoreTypes(_resolution);
491 types = new Types(_resolution); 364 types = new Types(_resolution);
492 tracer = new Tracer(this, this.outputProvider); 365 tracer = new Tracer(this, this.outputProvider);
493 366
494 if (verbose) { 367 if (options.verbose) {
495 progress = new Stopwatch()..start(); 368 progress = new Stopwatch()..start();
496 } 369 }
497 370
498 // TODO(johnniwinther): Separate the dependency tracking from the enqueuing 371 // TODO(johnniwinther): Separate the dependency tracking from the enqueuing
499 // for global dependencies. 372 // for global dependencies.
500 globalDependencies = new GlobalDependencyRegistry(this); 373 globalDependencies = new GlobalDependencyRegistry(this);
501 374
502 if (emitJavaScript) { 375 if (options.emitJavaScript) {
503 js_backend.JavaScriptBackend jsBackend = 376 js_backend.JavaScriptBackend jsBackend =
504 new js_backend.JavaScriptBackend( 377 new js_backend.JavaScriptBackend(
505 this, generateSourceMap: generateSourceMap, 378 this, generateSourceMap: options.generateSourceMap,
506 useStartupEmitter: useStartupEmitter, 379 useStartupEmitter: options.useStartupEmitter,
507 useNewSourceInfo: useNewSourceInfo); 380 useNewSourceInfo: options.useNewSourceInfo);
508 backend = jsBackend; 381 backend = jsBackend;
509 } else { 382 } else {
510 backend = new dart_backend.DartBackend(this, strips, 383 backend = new dart_backend.DartBackend(this, options.strips,
511 multiFile: dart2dartMultiFile); 384 multiFile: options.dart2dartMultiFile);
512 if (dumpInfo) { 385 if (options.dumpInfo) {
513 throw new ArgumentError('--dump-info is not supported for dart2dart.'); 386 throw new ArgumentError('--dump-info is not supported for dart2dart.');
514 } 387 }
515 } 388 }
516 389
517 tasks = [ 390 tasks = [
518 libraryLoader = new LibraryLoaderTask(this), 391 libraryLoader = new LibraryLoaderTask(this),
519 serialization = new SerializationTask(this), 392 serialization = new SerializationTask(this),
520 scanner = new ScannerTask(this), 393 scanner = new ScannerTask(this),
521 dietParser = new DietParserTask( 394 dietParser = new DietParserTask(
522 this, enableConditionalDirectives: enableConditionalDirectives), 395 this, enableConditionalDirectives: options.enableConditionalDirectives ),
523 parser = new ParserTask( 396 parser = new ParserTask(
524 this, enableConditionalDirectives: enableConditionalDirectives), 397 this, enableConditionalDirectives: options.enableConditionalDirectives ),
525 patchParser = new PatchParserTask( 398 patchParser = new PatchParserTask(
526 this, enableConditionalDirectives: enableConditionalDirectives), 399 this, enableConditionalDirectives: options.enableConditionalDirectives ),
527 resolver = new ResolverTask(this, backend.constantCompilerTask), 400 resolver = new ResolverTask(this, backend.constantCompilerTask),
528 closureToClassMapper = new closureMapping.ClosureTask(this), 401 closureToClassMapper = new closureMapping.ClosureTask(this),
529 checker = new TypeCheckerTask(this), 402 checker = new TypeCheckerTask(this),
530 typesTask = new ti.TypesTask(this), 403 typesTask = new ti.TypesTask(this),
531 constants = backend.constantCompilerTask, 404 constants = backend.constantCompilerTask,
532 deferredLoadTask = new DeferredLoadTask(this), 405 deferredLoadTask = new DeferredLoadTask(this),
533 mirrorUsageAnalyzerTask = new MirrorUsageAnalyzerTask(this), 406 mirrorUsageAnalyzerTask = new MirrorUsageAnalyzerTask(this),
534 enqueuer = new EnqueueTask(this), 407 enqueuer = new EnqueueTask(this),
535 dumpInfoTask = new DumpInfoTask(this), 408 dumpInfoTask = new DumpInfoTask(this),
536 reuseLibraryTask = new GenericTask('Reuse library', this), 409 reuseLibraryTask = new GenericTask('Reuse library', this),
537 ]; 410 ];
538 411
539 tasks.addAll(backend.tasks); 412 tasks.addAll(backend.tasks);
540 } 413 }
541 414
542 Universe get resolverWorld => enqueuer.resolution.universe; 415 Universe get resolverWorld => enqueuer.resolution.universe;
543 Universe get codegenWorld => enqueuer.codegen.universe; 416 Universe get codegenWorld => enqueuer.codegen.universe;
544 417
545 bool get hasBuildId => buildId != UNDETERMINED_BUILD_ID; 418 bool get analyzeAll => options.analyzeAll || compileAll;
546
547 bool get analyzeAll => analyzeAllFlag || compileAll;
548 419
549 bool get compileAll => false; 420 bool get compileAll => false;
550 421
551 bool get disableTypeInference { 422 bool get disableTypeInference =>
552 return disableTypeInferenceFlag || compilationFailed; 423 options.disableTypeInference || compilationFailed;
553 }
554 424
555 int getNextFreeClassId() => nextFreeClassId++; 425 int getNextFreeClassId() => nextFreeClassId++;
556 426
557 void unimplemented(Spannable spannable, String methodName) { 427 void unimplemented(Spannable spannable, String methodName) {
558 reporter.internalError(spannable, "$methodName not implemented."); 428 reporter.internalError(spannable, "$methodName not implemented.");
559 } 429 }
560 430
561 // Compiles the dart script at [uri]. 431 // Compiles the dart script at [uri].
562 // 432 //
563 // The resulting future will complete with true if the compilation 433 // The resulting future will complete with true if the compilation
(...skipping 70 matching lines...) Expand 10 before | Expand all | Expand 10 after
634 /// <main-uri> => <intermediate-uri1> => <intermediate-uri2> => <uri> 504 /// <main-uri> => <intermediate-uri1> => <intermediate-uri2> => <uri>
635 /// 505 ///
636 Set<String> computeImportChainsFor(LoadedLibraries loadedLibraries, Uri uri) { 506 Set<String> computeImportChainsFor(LoadedLibraries loadedLibraries, Uri uri) {
637 // TODO(johnniwinther): Move computation of dependencies to the library 507 // TODO(johnniwinther): Move computation of dependencies to the library
638 // loader. 508 // loader.
639 Uri rootUri = loadedLibraries.rootUri; 509 Uri rootUri = loadedLibraries.rootUri;
640 Set<String> importChains = new Set<String>(); 510 Set<String> importChains = new Set<String>();
641 // The maximum number of full imports chains to process. 511 // The maximum number of full imports chains to process.
642 final int chainLimit = 10000; 512 final int chainLimit = 10000;
643 // The maximum number of imports chains to show. 513 // The maximum number of imports chains to show.
644 final int compactChainLimit = verbose ? 20 : 10; 514 final int compactChainLimit = options.verbose ? 20 : 10;
645 int chainCount = 0; 515 int chainCount = 0;
646 loadedLibraries.forEachImportChain(uri, 516 loadedLibraries.forEachImportChain(uri,
647 callback: (Link<Uri> importChainReversed) { 517 callback: (Link<Uri> importChainReversed) {
648 Link<CodeLocation> compactImportChain = const Link<CodeLocation>(); 518 Link<CodeLocation> compactImportChain = const Link<CodeLocation>();
649 CodeLocation currentCodeLocation = 519 CodeLocation currentCodeLocation =
650 new UriLocation(importChainReversed.head); 520 new UriLocation(importChainReversed.head);
651 compactImportChain = compactImportChain.prepend(currentCodeLocation); 521 compactImportChain = compactImportChain.prepend(currentCodeLocation);
652 for (Link<Uri> link = importChainReversed.tail; 522 for (Link<Uri> link = importChainReversed.tail;
653 !link.isEmpty; 523 !link.isEmpty;
654 link = link.tail) { 524 link = link.tail) {
655 Uri uri = link.head; 525 Uri uri = link.head;
656 if (!currentCodeLocation.inSameLocation(uri)) { 526 if (!currentCodeLocation.inSameLocation(uri)) {
657 currentCodeLocation = 527 currentCodeLocation =
658 verbose ? new UriLocation(uri) : new CodeLocation(uri); 528 options.verbose ? new UriLocation(uri) : new CodeLocation(uri);
659 compactImportChain = 529 compactImportChain =
660 compactImportChain.prepend(currentCodeLocation); 530 compactImportChain.prepend(currentCodeLocation);
661 } 531 }
662 } 532 }
663 String importChain = 533 String importChain =
664 compactImportChain.map((CodeLocation codeLocation) { 534 compactImportChain.map((CodeLocation codeLocation) {
665 return codeLocation.relativize(rootUri); 535 return codeLocation.relativize(rootUri);
666 }).join(' => '); 536 }).join(' => ');
667 537
668 if (!importChains.contains(importChain)) { 538 if (!importChains.contains(importChain)) {
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
721 bool importsMirrorsLibrary = 591 bool importsMirrorsLibrary =
722 loadedLibraries.containsLibrary(Uris.dart_mirrors); 592 loadedLibraries.containsLibrary(Uris.dart_mirrors);
723 if (importsMirrorsLibrary && !backend.supportsReflection) { 593 if (importsMirrorsLibrary && !backend.supportsReflection) {
724 Set<String> importChains = 594 Set<String> importChains =
725 computeImportChainsFor(loadedLibraries, Uris.dart_mirrors); 595 computeImportChainsFor(loadedLibraries, Uris.dart_mirrors);
726 reporter.reportErrorMessage( 596 reporter.reportErrorMessage(
727 NO_LOCATION_SPANNABLE, 597 NO_LOCATION_SPANNABLE,
728 MessageKind.MIRRORS_LIBRARY_NOT_SUPPORT_BY_BACKEND, 598 MessageKind.MIRRORS_LIBRARY_NOT_SUPPORT_BY_BACKEND,
729 {'importChain': importChains.join( 599 {'importChain': importChains.join(
730 MessageTemplate.MIRRORS_NOT_SUPPORTED_BY_BACKEND_PADDING)}); 600 MessageTemplate.MIRRORS_NOT_SUPPORTED_BY_BACKEND_PADDING)});
731 } else if (importsMirrorsLibrary && !enableExperimentalMirrors) { 601 } else if (importsMirrorsLibrary && !options.enableExperimentalMirrors) {
732 Set<String> importChains = 602 Set<String> importChains =
733 computeImportChainsFor(loadedLibraries, Uris.dart_mirrors); 603 computeImportChainsFor(loadedLibraries, Uris.dart_mirrors);
734 reporter.reportWarningMessage( 604 reporter.reportWarningMessage(
735 NO_LOCATION_SPANNABLE, 605 NO_LOCATION_SPANNABLE,
736 MessageKind.IMPORT_EXPERIMENTAL_MIRRORS, 606 MessageKind.IMPORT_EXPERIMENTAL_MIRRORS,
737 {'importChain': importChains.join( 607 {'importChain': importChains.join(
738 MessageTemplate.IMPORT_EXPERIMENTAL_MIRRORS_PADDING)}); 608 MessageTemplate.IMPORT_EXPERIMENTAL_MIRRORS_PADDING)});
739 } 609 }
740 610
741 coreClasses.functionClass.ensureResolved(resolution); 611 coreClasses.functionClass.ensureResolved(resolution);
742 functionApplyMethod = 612 functionApplyMethod =
743 coreClasses.functionClass.lookupLocalMember('apply'); 613 coreClasses.functionClass.lookupLocalMember('apply');
744 614
745 if (preserveComments) { 615 if (options.preserveComments) {
746 return libraryLoader.loadLibrary(Uris.dart_mirrors) 616 return libraryLoader.loadLibrary(Uris.dart_mirrors)
747 .then((LibraryElement libraryElement) { 617 .then((LibraryElement libraryElement) {
748 documentClass = libraryElement.find('Comment'); 618 documentClass = libraryElement.find('Comment');
749 }); 619 });
750 } 620 }
751 }).then((_) => backend.onLibrariesLoaded(loadedLibraries)); 621 }).then((_) => backend.onLibrariesLoaded(loadedLibraries));
752 } 622 }
753 623
754 bool isProxyConstant(ConstantValue value) { 624 bool isProxyConstant(ConstantValue value) {
755 FieldElement field = coreLibrary.find('proxy'); 625 FieldElement field = coreLibrary.find('proxy');
(...skipping 100 matching lines...) Expand 10 before | Expand all | Expand 10 after
856 StringToken.canonicalizedSubstrings.clear(); 726 StringToken.canonicalizedSubstrings.clear();
857 Selector.canonicalizedValues.clear(); 727 Selector.canonicalizedValues.clear();
858 728
859 // The selector objects held in static fields must remain canonical. 729 // The selector objects held in static fields must remain canonical.
860 for (Selector selector in Selectors.ALL) { 730 for (Selector selector in Selectors.ALL) {
861 Selector.canonicalizedValues 731 Selector.canonicalizedValues
862 .putIfAbsent(selector.hashCode, () => <Selector>[]) 732 .putIfAbsent(selector.hashCode, () => <Selector>[])
863 .add(selector); 733 .add(selector);
864 } 734 }
865 735
866 assert(uri != null || analyzeOnly || hasIncrementalSupport); 736 assert(uri != null || options.analyzeOnly || options.hasIncrementalSupport);
867 return new Future.sync(() { 737 return new Future.sync(() {
868 if (librariesToAnalyzeWhenRun != null) { 738 if (librariesToAnalyzeWhenRun != null) {
869 return Future.forEach(librariesToAnalyzeWhenRun, (libraryUri) { 739 return Future.forEach(librariesToAnalyzeWhenRun, (libraryUri) {
870 reporter.log('Analyzing $libraryUri ($buildId)'); 740 reporter.log('Analyzing $libraryUri (${options.buildId})');
871 return libraryLoader.loadLibrary(libraryUri); 741 return libraryLoader.loadLibrary(libraryUri);
872 }); 742 });
873 } 743 }
874 }).then((_) { 744 }).then((_) {
875 if (uri != null) { 745 if (uri != null) {
876 if (analyzeOnly) { 746 if (options.analyzeOnly) {
877 reporter.log('Analyzing $uri ($buildId)'); 747 reporter.log('Analyzing $uri (${options.buildId})');
878 } else { 748 } else {
879 reporter.log('Compiling $uri ($buildId)'); 749 reporter.log('Compiling $uri (${options.buildId})');
880 } 750 }
881 return libraryLoader.loadLibrary(uri).then((LibraryElement library) { 751 return libraryLoader.loadLibrary(uri).then((LibraryElement library) {
882 mainApp = library; 752 mainApp = library;
883 }); 753 });
884 } 754 }
885 }).then((_) { 755 }).then((_) {
886 compileLoadedLibraries(); 756 compileLoadedLibraries();
887 }); 757 });
888 } 758 }
889 759
890 void computeMain() { 760 void computeMain() {
891 if (mainApp == null) return; 761 if (mainApp == null) return;
892 762
893 Element main = mainApp.findExported(Identifiers.main); 763 Element main = mainApp.findExported(Identifiers.main);
894 ErroneousElement errorElement = null; 764 ErroneousElement errorElement = null;
895 if (main == null) { 765 if (main == null) {
896 if (analyzeOnly) { 766 if (options.analyzeOnly) {
897 if (!analyzeAll) { 767 if (!analyzeAll) {
898 errorElement = new ErroneousElementX( 768 errorElement = new ErroneousElementX(
899 MessageKind.CONSIDER_ANALYZE_ALL, {'main': Identifiers.main}, 769 MessageKind.CONSIDER_ANALYZE_ALL, {'main': Identifiers.main},
900 Identifiers.main, mainApp); 770 Identifiers.main, mainApp);
901 } 771 }
902 } else { 772 } else {
903 // Compilation requires a main method. 773 // Compilation requires a main method.
904 errorElement = new ErroneousElementX( 774 errorElement = new ErroneousElementX(
905 MessageKind.MISSING_MAIN, {'main': Identifiers.main}, 775 MessageKind.MISSING_MAIN, {'main': Identifiers.main},
906 Identifiers.main, mainApp); 776 Identifiers.main, mainApp);
(...skipping 23 matching lines...) Expand all
930 MessageKind.MAIN_WITH_EXTRA_PARAMETER, {'main': Identifiers.main}, 800 MessageKind.MAIN_WITH_EXTRA_PARAMETER, {'main': Identifiers.main},
931 Identifiers.main, 801 Identifiers.main,
932 parameter); 802 parameter);
933 mainFunction = backend.helperForMainArity(); 803 mainFunction = backend.helperForMainArity();
934 // Don't warn about main not being used: 804 // Don't warn about main not being used:
935 enqueuer.resolution.registerStaticUse(new StaticUse.foreignUse(main)); 805 enqueuer.resolution.registerStaticUse(new StaticUse.foreignUse(main));
936 }); 806 });
937 } 807 }
938 } 808 }
939 if (mainFunction == null) { 809 if (mainFunction == null) {
940 if (errorElement == null && !analyzeOnly && !analyzeAll) { 810 if (errorElement == null && !options.analyzeOnly && !analyzeAll) {
941 reporter.internalError(mainApp, "Problem with '${Identifiers.main}'."); 811 reporter.internalError(mainApp, "Problem with '${Identifiers.main}'.");
942 } else { 812 } else {
943 mainFunction = errorElement; 813 mainFunction = errorElement;
944 } 814 }
945 } 815 }
946 if (errorElement != null && 816 if (errorElement != null &&
947 errorElement.isSynthesized && 817 errorElement.isSynthesized &&
948 !mainApp.isSynthesized) { 818 !mainApp.isSynthesized) {
949 reporter.reportWarningMessage( 819 reporter.reportWarningMessage(
950 errorElement, errorElement.messageKind, 820 errorElement, errorElement.messageKind,
951 errorElement.messageArguments); 821 errorElement.messageArguments);
952 } 822 }
953 } 823 }
954 824
955 /// Analyze all members of the library in [libraryUri]. 825 /// Analyze all members of the library in [libraryUri].
956 /// 826 ///
957 /// If [skipLibraryWithPartOfTag] is `true`, member analysis is skipped if the 827 /// If [skipLibraryWithPartOfTag] is `true`, member analysis is skipped if the
958 /// library has a `part of` tag, assuming it is a part and not a library. 828 /// library has a `part of` tag, assuming it is a part and not a library.
959 /// 829 ///
960 /// This operation assumes an unclosed resolution queue and is only supported 830 /// This operation assumes an unclosed resolution queue and is only supported
961 /// when the '--analyze-main' option is used. 831 /// when the '--analyze-main' option is used.
962 Future<LibraryElement> analyzeUri( 832 Future<LibraryElement> analyzeUri(
963 Uri libraryUri, 833 Uri libraryUri,
964 {bool skipLibraryWithPartOfTag: true}) { 834 {bool skipLibraryWithPartOfTag: true}) {
965 assert(analyzeMain); 835 assert(options.analyzeMain);
966 reporter.log('Analyzing $libraryUri ($buildId)'); 836 reporter.log('Analyzing $libraryUri (${options.buildId})');
967 return libraryLoader.loadLibrary( 837 return libraryLoader.loadLibrary(
968 libraryUri, skipFileWithPartOfTag: true).then( 838 libraryUri, skipFileWithPartOfTag: true).then(
969 (LibraryElement library) { 839 (LibraryElement library) {
970 if (library == null) return null; 840 if (library == null) return null;
971 fullyEnqueueLibrary(library, enqueuer.resolution); 841 fullyEnqueueLibrary(library, enqueuer.resolution);
972 emptyQueue(enqueuer.resolution); 842 emptyQueue(enqueuer.resolution);
973 enqueuer.resolution.logSummary(reporter.log); 843 enqueuer.resolution.logSummary(reporter.log);
974 return library; 844 return library;
975 }); 845 });
976 } 846 }
977 847
978 /// Performs the compilation when all libraries have been loaded. 848 /// Performs the compilation when all libraries have been loaded.
979 void compileLoadedLibraries() { 849 void compileLoadedLibraries() {
980 computeMain(); 850 computeMain();
981 851
982 mirrorUsageAnalyzerTask.analyzeUsage(mainApp); 852 mirrorUsageAnalyzerTask.analyzeUsage(mainApp);
983 853
984 // In order to see if a library is deferred, we must compute the 854 // In order to see if a library is deferred, we must compute the
985 // compile-time constants that are metadata. This means adding 855 // compile-time constants that are metadata. This means adding
986 // something to the resolution queue. So we cannot wait with 856 // something to the resolution queue. So we cannot wait with
987 // this until after the resolution queue is processed. 857 // this until after the resolution queue is processed.
988 deferredLoadTask.beforeResolution(this); 858 deferredLoadTask.beforeResolution(this);
989 impactStrategy = backend.createImpactStrategy( 859 impactStrategy = backend.createImpactStrategy(
990 supportDeferredLoad: deferredLoadTask.isProgramSplit, 860 supportDeferredLoad: deferredLoadTask.isProgramSplit,
991 supportDumpInfo: dumpInfo); 861 supportDumpInfo: options.dumpInfo);
992 862
993 phase = PHASE_RESOLVING; 863 phase = PHASE_RESOLVING;
994 if (analyzeAll) { 864 if (analyzeAll) {
995 libraryLoader.libraries.forEach((LibraryElement library) { 865 libraryLoader.libraries.forEach((LibraryElement library) {
996 reporter.log('Enqueuing ${library.canonicalUri}'); 866 reporter.log('Enqueuing ${library.canonicalUri}');
997 fullyEnqueueLibrary(library, enqueuer.resolution); 867 fullyEnqueueLibrary(library, enqueuer.resolution);
998 }); 868 });
999 } else if (analyzeMain) { 869 } else if (options.analyzeMain) {
1000 if (mainApp != null) { 870 if (mainApp != null) {
1001 fullyEnqueueLibrary(mainApp, enqueuer.resolution); 871 fullyEnqueueLibrary(mainApp, enqueuer.resolution);
1002 } 872 }
1003 if (librariesToAnalyzeWhenRun != null) { 873 if (librariesToAnalyzeWhenRun != null) {
1004 for (Uri libraryUri in librariesToAnalyzeWhenRun) { 874 for (Uri libraryUri in librariesToAnalyzeWhenRun) {
1005 fullyEnqueueLibrary(libraryLoader.lookupLibrary(libraryUri), 875 fullyEnqueueLibrary(libraryLoader.lookupLibrary(libraryUri),
1006 enqueuer.resolution); 876 enqueuer.resolution);
1007 } 877 }
1008 } 878 }
1009 } 879 }
1010 // Elements required by enqueueHelpers are global dependencies 880 // Elements required by enqueueHelpers are global dependencies
1011 // that are not pulled in by a particular element. 881 // that are not pulled in by a particular element.
1012 backend.enqueueHelpers(enqueuer.resolution, globalDependencies); 882 backend.enqueueHelpers(enqueuer.resolution, globalDependencies);
1013 resolveLibraryMetadata(); 883 resolveLibraryMetadata();
1014 reporter.log('Resolving...'); 884 reporter.log('Resolving...');
1015 processQueue(enqueuer.resolution, mainFunction); 885 processQueue(enqueuer.resolution, mainFunction);
1016 enqueuer.resolution.logSummary(reporter.log); 886 enqueuer.resolution.logSummary(reporter.log);
1017 887
1018 _reporter.reportSuppressedMessagesSummary(); 888 _reporter.reportSuppressedMessagesSummary();
1019 889
1020 if (compilationFailed){ 890 if (compilationFailed){
1021 if (!generateCodeWithCompileTimeErrors) return; 891 if (!options.generateCodeWithCompileTimeErrors) return;
1022 if (!backend.enableCodegenWithErrorsIfSupported(NO_LOCATION_SPANNABLE)) { 892 if (!backend.enableCodegenWithErrorsIfSupported(NO_LOCATION_SPANNABLE)) {
1023 return; 893 return;
1024 } 894 }
1025 } 895 }
1026 896
1027 if (analyzeOnly) { 897 if (options.analyzeOnly) {
1028 if (!analyzeAll && !compilationFailed) { 898 if (!analyzeAll && !compilationFailed) {
1029 // No point in reporting unused code when [analyzeAll] is true: all 899 // No point in reporting unused code when [analyzeAll] is true: all
1030 // code is artificially used. 900 // code is artificially used.
1031 // If compilation failed, it is possible that the error prevents the 901 // If compilation failed, it is possible that the error prevents the
1032 // compiler from analyzing all the code. 902 // compiler from analyzing all the code.
1033 // TODO(johnniwinther): Reenable this when the reporting is more 903 // TODO(johnniwinther): Reenable this when the reporting is more
1034 // precise. 904 // precise.
1035 //reportUnusedCode(); 905 //reportUnusedCode();
1036 } 906 }
1037 return; 907 return;
(...skipping 25 matching lines...) Expand all
1063 if (compileAll) { 933 if (compileAll) {
1064 libraryLoader.libraries.forEach((LibraryElement library) { 934 libraryLoader.libraries.forEach((LibraryElement library) {
1065 fullyEnqueueLibrary(library, enqueuer.codegen); 935 fullyEnqueueLibrary(library, enqueuer.codegen);
1066 }); 936 });
1067 } 937 }
1068 processQueue(enqueuer.codegen, mainFunction); 938 processQueue(enqueuer.codegen, mainFunction);
1069 enqueuer.codegen.logSummary(reporter.log); 939 enqueuer.codegen.logSummary(reporter.log);
1070 940
1071 int programSize = backend.assembleProgram(); 941 int programSize = backend.assembleProgram();
1072 942
1073 if (dumpInfo) { 943 if (options.dumpInfo) {
1074 dumpInfoTask.reportSize(programSize); 944 dumpInfoTask.reportSize(programSize);
1075 dumpInfoTask.dumpInfo(); 945 dumpInfoTask.dumpInfo();
1076 } 946 }
1077 947
1078 backend.sourceInformationStrategy.onComplete(); 948 backend.sourceInformationStrategy.onComplete();
1079 949
1080 checkQueues(); 950 checkQueues();
1081 } 951 }
1082 952
1083 void fullyEnqueueLibrary(LibraryElement library, Enqueuer world) { 953 void fullyEnqueueLibrary(LibraryElement library, Enqueuer world) {
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
1134 backend.registerInstantiatedType( 1004 backend.registerInstantiatedType(
1135 backend.listImplementation.rawType, world, globalDependencies); 1005 backend.listImplementation.rawType, world, globalDependencies);
1136 backend.stringImplementation.ensureResolved(resolution); 1006 backend.stringImplementation.ensureResolved(resolution);
1137 backend.registerInstantiatedType( 1007 backend.registerInstantiatedType(
1138 backend.stringImplementation.rawType, world, globalDependencies); 1008 backend.stringImplementation.rawType, world, globalDependencies);
1139 1009
1140 backend.registerMainHasArguments(world); 1010 backend.registerMainHasArguments(world);
1141 } 1011 }
1142 world.addToWorkList(main); 1012 world.addToWorkList(main);
1143 } 1013 }
1144 if (verbose) { 1014 if (options.verbose) {
1145 progress.reset(); 1015 progress.reset();
1146 } 1016 }
1147 emptyQueue(world); 1017 emptyQueue(world);
1148 world.queueIsClosed = true; 1018 world.queueIsClosed = true;
1149 // Notify the impact strategy impacts are no longer needed for this 1019 // Notify the impact strategy impacts are no longer needed for this
1150 // enqueuer. 1020 // enqueuer.
1151 impactStrategy.onImpactUsed(world.impactUse); 1021 impactStrategy.onImpactUsed(world.impactUse);
1152 backend.onQueueClosed(); 1022 backend.onQueueClosed();
1153 assert(compilationFailed || world.checkNoEnqueuedInvokedInstanceMethods()); 1023 assert(compilationFailed || world.checkNoEnqueuedInvokedInstanceMethods());
1154 } 1024 }
(...skipping 99 matching lines...) Expand 10 before | Expand all | Expand 10 after
1254 } 1124 }
1255 1125
1256 /// Messages for which compile-time errors are reported but compilation 1126 /// Messages for which compile-time errors are reported but compilation
1257 /// continues regardless. 1127 /// continues regardless.
1258 static const List<MessageKind> BENIGN_ERRORS = const <MessageKind>[ 1128 static const List<MessageKind> BENIGN_ERRORS = const <MessageKind>[
1259 MessageKind.INVALID_METADATA, 1129 MessageKind.INVALID_METADATA,
1260 MessageKind.INVALID_METADATA_GENERIC, 1130 MessageKind.INVALID_METADATA_GENERIC,
1261 ]; 1131 ];
1262 1132
1263 bool markCompilationAsFailed(DiagnosticMessage message, api.Diagnostic kind) { 1133 bool markCompilationAsFailed(DiagnosticMessage message, api.Diagnostic kind) {
1264 if (testMode) { 1134 if (options.testMode) {
1265 // When in test mode, i.e. on the build-bot, we always stop compilation. 1135 // When in test mode, i.e. on the build-bot, we always stop compilation.
1266 return true; 1136 return true;
1267 } 1137 }
1268 if (reporter.options.fatalWarnings) { 1138 if (reporter.options.fatalWarnings) {
1269 return true; 1139 return true;
1270 } 1140 }
1271 return !BENIGN_ERRORS.contains(message.message.kind); 1141 return !BENIGN_ERRORS.contains(message.message.kind);
1272 } 1142 }
1273 1143
1274 void fatalDiagnosticReported(DiagnosticMessage message, 1144 void fatalDiagnosticReported(DiagnosticMessage message,
(...skipping 188 matching lines...) Expand 10 before | Expand all | Expand 10 after
1463 } 1333 }
1464 backend.forgetElement(element); 1334 backend.forgetElement(element);
1465 } 1335 }
1466 1336
1467 bool elementHasCompileTimeError(Element element) { 1337 bool elementHasCompileTimeError(Element element) {
1468 return elementsWithCompileTimeErrors.contains(element); 1338 return elementsWithCompileTimeErrors.contains(element);
1469 } 1339 }
1470 1340
1471 EventSink<String> outputProvider(String name, String extension) { 1341 EventSink<String> outputProvider(String name, String extension) {
1472 if (compilationFailed) { 1342 if (compilationFailed) {
1473 if (!generateCodeWithCompileTimeErrors || testMode) { 1343 if (!options.generateCodeWithCompileTimeErrors || options.testMode) {
1474 // Disable output in test mode: The build bot currently uses the time 1344 // Disable output in test mode: The build bot currently uses the time
1475 // stamp of the generated file to determine whether the output is 1345 // stamp of the generated file to determine whether the output is
1476 // up-to-date. 1346 // up-to-date.
1477 return new NullSink('$name.$extension'); 1347 return new NullSink('$name.$extension');
1478 } 1348 }
1479 } 1349 }
1480 return userOutputProvider.createEventSink(name, extension); 1350 return userOutputProvider.createEventSink(name, extension);
1481 } 1351 }
1482 } 1352 }
1483 1353
(...skipping 487 matching lines...) Expand 10 before | Expand all | Expand 10 after
1971 reportDiagnostic( 1841 reportDiagnostic(
1972 createMessage(element, MessageKind.COMPILER_CRASHED), 1842 createMessage(element, MessageKind.COMPILER_CRASHED),
1973 const <DiagnosticMessage>[], 1843 const <DiagnosticMessage>[],
1974 api.Diagnostic.CRASH); 1844 api.Diagnostic.CRASH);
1975 pleaseReportCrash(); 1845 pleaseReportCrash();
1976 } 1846 }
1977 1847
1978 void pleaseReportCrash() { 1848 void pleaseReportCrash() {
1979 print( 1849 print(
1980 MessageTemplate.TEMPLATES[MessageKind.PLEASE_REPORT_THE_CRASH] 1850 MessageTemplate.TEMPLATES[MessageKind.PLEASE_REPORT_THE_CRASH]
1981 .message({'buildId': compiler.buildId})); 1851 .message({'buildId': compiler.options.buildId}));
1982 } 1852 }
1983 1853
1984 /// Finds the approximate [Element] for [node]. [currentElement] is used as 1854 /// Finds the approximate [Element] for [node]. [currentElement] is used as
1985 /// the default value. 1855 /// the default value.
1986 Element elementFromSpannable(Spannable node) { 1856 Element elementFromSpannable(Spannable node) {
1987 Element element; 1857 Element element;
1988 if (node is Element) { 1858 if (node is Element) {
1989 element = node; 1859 element = node;
1990 } else if (node is HInstruction) { 1860 } else if (node is HInstruction) {
1991 element = _elementFromHInstruction(node); 1861 element = _elementFromHInstruction(node);
(...skipping 127 matching lines...) Expand 10 before | Expand all | Expand 10 after
2119 } 1989 }
2120 1990
2121 @override 1991 @override
2122 WorldImpact computeWorldImpact(Element element) { 1992 WorldImpact computeWorldImpact(Element element) {
2123 return _worldImpactCache.putIfAbsent(element, () { 1993 return _worldImpactCache.putIfAbsent(element, () {
2124 assert(compiler.parser != null); 1994 assert(compiler.parser != null);
2125 Node tree = compiler.parser.parse(element); 1995 Node tree = compiler.parser.parse(element);
2126 assert(invariant(element, !element.isSynthesized || tree == null)); 1996 assert(invariant(element, !element.isSynthesized || tree == null));
2127 ResolutionImpact resolutionImpact = 1997 ResolutionImpact resolutionImpact =
2128 compiler.resolver.resolve(element); 1998 compiler.resolver.resolve(element);
2129 if (tree != null && !compiler.analyzeSignaturesOnly) { 1999 if (tree != null && !compiler.options.analyzeSignaturesOnly) {
2130 // TODO(het): don't do this if suppressWarnings is on, currently we have 2000 // TODO(het): don't do this if suppressWarnings is on, currently we have
2131 // to do it because the typechecker also sets types 2001 // to do it because the typechecker also sets types
2132 // Only analyze nodes with a corresponding [TreeElements]. 2002 // Only analyze nodes with a corresponding [TreeElements].
2133 compiler.checker.check(element); 2003 compiler.checker.check(element);
2134 } 2004 }
2135 WorldImpact worldImpact = 2005 WorldImpact worldImpact =
2136 compiler.backend.impactTransformer.transformResolutionImpact( 2006 compiler.backend.impactTransformer.transformResolutionImpact(
2137 resolutionImpact); 2007 resolutionImpact);
2138 return worldImpact; 2008 return worldImpact;
2139 }); 2009 });
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
2203 if (_otherDependencies == null) { 2073 if (_otherDependencies == null) {
2204 _otherDependencies = new Setlet<Element>(); 2074 _otherDependencies = new Setlet<Element>();
2205 } 2075 }
2206 _otherDependencies.add(element.implementation); 2076 _otherDependencies.add(element.implementation);
2207 } 2077 }
2208 2078
2209 Iterable<Element> get otherDependencies { 2079 Iterable<Element> get otherDependencies {
2210 return _otherDependencies != null ? _otherDependencies : const <Element>[]; 2080 return _otherDependencies != null ? _otherDependencies : const <Element>[];
2211 } 2081 }
2212 } 2082 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698