analysis.dart 8.39 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:collection';
import 'dart:io';

import 'package:analyzer/file_system/file_system.dart' as file_system;
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/plugin/options.dart';
import 'package:analyzer/source/analysis_options_provider.dart';
import 'package:analyzer/source/embedder.dart';
import 'package:analyzer/source/error_processor.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_io.dart';
import 'package:analyzer/src/generated/sdk_io.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/task/options.dart';
import 'package:cli_util/cli_util.dart' as cli_util;
import 'package:linter/src/plugin/linter_plugin.dart';
import 'package:package_config/packages.dart' show Packages;
import 'package:package_config/src/packages_impl.dart' show MapPackages;
import 'package:path/path.dart' as path;
import 'package:plugin/manager.dart';
import 'package:plugin/plugin.dart';

class AnalysisDriver {
  Set<Source> _analyzedSources = new HashSet<Source>();

  AnalysisOptionsProvider analysisOptionsProvider =
      new AnalysisOptionsProvider();

  AnalysisContext context;

  DriverOptions options;
  AnalysisDriver(this.options) {
    AnalysisEngine.instance.logger =
        new _StdLogger(outSink: options.outSink, errorSink: options.errorSink);
    _processPlugins();
  }

  String get sdkDir => options.dartSdkPath ?? cli_util.getSdkDir().path;

  List<AnalysisErrorDescription> analyze(Iterable<File> files) {
    List<AnalysisErrorInfo> infos = _analyze(files);
    List<AnalysisErrorDescription> errors = <AnalysisErrorDescription>[];
    for (AnalysisErrorInfo info in infos) {
      for (AnalysisError error in info.errors) {
        if (!_isFiltered(error)) {
          errors.add(new AnalysisErrorDescription(error, info.lineInfo));
        }
      }
    }
    return errors;
  }

  List<AnalysisErrorInfo> _analyze(Iterable<File> files) {
    context = AnalysisEngine.instance.createAnalysisContext();
    _processAnalysisOptions(context, options);
62 63
    PackageInfo packageInfo = new PackageInfo(options.packageMap);
    List<UriResolver> resolvers = _getResolvers(context, packageInfo.asMap());
64
    context.sourceFactory =
65
        new SourceFactory(resolvers, packageInfo.asPackages());
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

    List<Source> sources = <Source>[];
    ChangeSet changeSet = new ChangeSet();
    for (File file in files) {
      JavaFile sourceFile = new JavaFile(path.normalize(file.absolute.path));
      Source source = new FileBasedSource(sourceFile, sourceFile.toURI());
      Uri uri = context.sourceFactory.restoreUri(source);
      if (uri != null) {
        source = new FileBasedSource(sourceFile, uri);
      }
      sources.add(source);
      changeSet.addedSource(source);
    }
    context.applyChanges(changeSet);

    List<AnalysisErrorInfo> infos = <AnalysisErrorInfo>[];
    for (Source source in sources) {
      context.computeErrors(source);
      infos.add(context.getErrors(source));
      _analyzedSources.add(source);
    }

    return infos;
  }

91 92
  List<UriResolver> _getResolvers(InternalAnalysisContext context,
      Map<String, List<file_system.Folder>> packageMap) {
93 94 95
    DirectoryBasedDartSdk sdk = new DirectoryBasedDartSdk(new JavaFile(sdkDir));
    sdk.analysisOptions = context.analysisOptions;
    sdk.useSummary = true;
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    List<UriResolver> resolvers = <UriResolver>[];

    EmbedderYamlLocator yamlLocator = context.embedderYamlLocator;
    yamlLocator.refresh(packageMap);

    EmbedderUriResolver embedderUriResolver =
        new EmbedderUriResolver(yamlLocator.embedderYamls);
    if (embedderUriResolver.length == 0) {
      resolvers.add(new DartUriResolver(sdk));
    } else {
      resolvers.add(embedderUriResolver);
    }

    if (options.packageRootPath != null) {
      JavaFile packageDirectory = new JavaFile(options.packageRootPath);
      resolvers.add(new PackageUriResolver(<JavaFile>[packageDirectory]));
    }

    resolvers.add(new FileUriResolver());
    return resolvers;
  }

  bool _isFiltered(AnalysisError error) {
    ErrorProcessor processor = ErrorProcessor.getProcessor(context, error);
    // Filtered errors are processed to a severity of `null`.
    return processor != null && processor.severity == null;
  }

  void _processAnalysisOptions(
      AnalysisContext context, AnalysisOptions analysisOptions) {
    List<OptionsProcessor> optionsProcessors =
        AnalysisEngine.instance.optionsPlugin.optionsProcessors;
    try {
      String optionsPath = options.analysisOptionsFile;
      if (optionsPath != null) {
        file_system.File file =
            PhysicalResourceProvider.INSTANCE.getFile(optionsPath);
        Map<Object, Object> optionMap =
            analysisOptionsProvider.getOptionsFromFile(file);
        optionsProcessors.forEach(
            (OptionsProcessor p) => p.optionsProcessed(context, optionMap));
        if (optionMap != null) {
          configureContextOptions(context, optionMap);
        }
      }
    } on Exception catch (e) {
      optionsProcessors.forEach((OptionsProcessor p) => p.onError(e));
    }
  }

  void _processPlugins() {
    List<Plugin> plugins = <Plugin>[];
    plugins.addAll(AnalysisEngine.instance.requiredPlugins);
    plugins.add(AnalysisEngine.instance.commandLinePlugin);
    plugins.add(AnalysisEngine.instance.optionsPlugin);
    plugins.add(linterPlugin);
    ExtensionManager manager = new ExtensionManager();
    manager.processPlugins(plugins);
  }
}

class AnalysisDriverException implements Exception {
  final String message;
  AnalysisDriverException([this.message]);

  @override
  String toString() => message == null ? 'Exception' : 'Exception: $message';
}

class AnalysisErrorDescription {
  static Directory cwd = Directory.current.absolute;

  final AnalysisError error;
  final LineInfo line;
  AnalysisErrorDescription(this.error, this.line);

  ErrorCode get errorCode => error.errorCode;

pq's avatar
pq committed
174 175 176
  String get errorType {
    ErrorSeverity severity = errorCode.errorSeverity;
    if (severity == ErrorSeverity.INFO) {
pq's avatar
pq committed
177
      if (errorCode.type == ErrorType.HINT || errorCode.type == ErrorType.LINT)
pq's avatar
pq committed
178 179 180 181
        return errorCode.type.displayName;
    }
    return severity.displayName;
  }
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

  LineInfo_Location get location => line.getLocation(error.offset);

  String get path => _shorten(cwd.path, error.source.fullName);

  Source get source => error.source;

  String asString() => '[$errorType] ${error.message} ($path, '
      'line ${location.lineNumber}, col ${location.columnNumber})';

  static String _shorten(String root, String path) =>
      path.startsWith(root) ? path.substring(root.length + 1) : path;
}

class DriverOptions extends AnalysisOptionsImpl {
  @override
  int cacheSize = 512;

  /// The path to the dart SDK.
  String dartSdkPath;

203 204
  /// Map of packages to folder paths.
  Map<String, String> packageMap;
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

  /// The path to the package root.
  String packageRootPath;

  /// The path to analysis options.
  String analysisOptionsFile;

  @override
  bool generateSdkErrors = false;

  /// Analysis options map.
  Map<Object, Object> analysisOptions;

  @override
  bool lint = true;

  /// Out sink for logging.
  IOSink outSink = stdout;

  /// Error sink for logging.
  IOSink errorSink = stderr;
}

228 229 230 231 232 233 234
class PackageInfo {
  PackageInfo(Map<String, String> packageMap) {
    Map<String, Uri> packages = new HashMap<String, Uri>();
    for (String package in packageMap.keys) {
      String path = packageMap[package];
      packages[package] = new Uri.directory(path);
      _map[package] = <file_system.Folder>[
pq's avatar
pq committed
235
        PhysicalResourceProvider.INSTANCE.getFolder(path)
236 237 238 239 240
      ];
    }
    _packages = new MapPackages(packages);
  }

pq's avatar
pq committed
241 242 243 244
  Packages _packages;
  HashMap<String, List<file_system.Folder>> _map =
      new HashMap<String, List<file_system.Folder>>();

245 246 247 248 249
  Map<String, List<file_system.Folder>> asMap() => _map;

  Packages asPackages() => _packages;
}

250 251 252 253 254 255 256 257 258 259 260 261
class _StdLogger extends Logger {
  final IOSink outSink;
  final IOSink errorSink;
  _StdLogger({this.outSink, this.errorSink});

  @override
  void logError(String message, [Exception exception]) =>
      errorSink.writeln(message);
  @override
  void logInformation(String message, [Exception exception]) =>
      outSink.writeln(message);
}