analysis.dart 6.94 KB
Newer Older
1 2 3 4
// 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.

5 6
import 'dart:async';
import 'dart:convert';
7

8
import '../base/file_system.dart' hide IOSink;
9
import '../base/file_system.dart';
10
import '../base/io.dart';
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
import '../base/platform.dart';
import '../base/process_manager.dart';
import '../globals.dart';

class AnalysisServer {
  AnalysisServer(this.sdkPath, this.directories, {this.previewDart2: false});

  final String sdkPath;
  final List<String> directories;
  final bool previewDart2;

  Process _process;
  final StreamController<bool> _analyzingController =
      new StreamController<bool>.broadcast();
  final StreamController<FileAnalysisErrors> _errorsController =
      new StreamController<FileAnalysisErrors>.broadcast();

  int _id = 0;

  Future<Null> start() async {
    final String snapshot =
        fs.path.join(sdkPath, 'bin/snapshots/analysis_server.dart.snapshot');
    final List<String> command = <String>[
      fs.path.join(sdkPath, 'bin', 'dart'),
      snapshot,
      '--sdk',
      sdkPath,
    ];

    if (previewDart2) {
      command.add('--preview-dart-2');
    } else {
      command.add('--no-preview-dart-2');
    }
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    printTrace('dart ${command.skip(1).join(' ')}');
    _process = await processManager.start(command);
    // This callback hookup can't throw.
    _process.exitCode
        .whenComplete(() => _process = null); // ignore: unawaited_futures

    final Stream<String> errorStream =
        _process.stderr.transform(utf8.decoder).transform(const LineSplitter());
    errorStream.listen(printError);

    final Stream<String> inStream =
        _process.stdout.transform(utf8.decoder).transform(const LineSplitter());
    inStream.listen(_handleServerResponse);

    // Available options (many of these are obsolete):
    //   enableAsync, enableDeferredLoading, enableEnums, enableNullAwareOperators,
    //   enableSuperMixins, generateDart2jsHints, generateHints, generateLints
    _sendCommand('analysis.updateOptions', <String, dynamic>{
      'options': <String, dynamic>{'enableSuperMixins': true}
    });

    _sendCommand('server.setSubscriptions', <String, dynamic>{
      'subscriptions': <String>['STATUS']
    });

    _sendCommand('analysis.setAnalysisRoots',
        <String, dynamic>{'included': directories, 'excluded': <String>[]});
73
  }
74

75 76
  Stream<bool> get onAnalyzing => _analyzingController.stream;
  Stream<FileAnalysisErrors> get onErrors => _errorsController.stream;
77

78
  Future<int> get onExit => _process.exitCode;
79

80 81 82 83 84 85 86 87
  void _sendCommand(String method, Map<String, dynamic> params) {
    final String message = json.encode(<String, dynamic>{
      'id': (++_id).toString(),
      'method': method,
      'params': params
    });
    _process.stdin.writeln(message);
    printTrace('==> $message');
88
  }
89

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  void _handleServerResponse(String line) {
    printTrace('<== $line');

    final dynamic response = json.decode(line);

    if (response is Map<dynamic, dynamic>) {
      if (response['event'] != null) {
        final String event = response['event'];
        final dynamic params = response['params'];

        if (params is Map<dynamic, dynamic>) {
          if (event == 'server.status')
            _handleStatus(response['params']);
          else if (event == 'analysis.errors')
            _handleAnalysisIssues(response['params']);
          else if (event == 'server.error')
            _handleServerError(response['params']);
        }
      } else if (response['error'] != null) {
        // Fields are 'code', 'message', and 'stackTrace'.
        final Map<String, dynamic> error = response['error'];
        printError(
            'Error response from the server: ${error['code']} ${error['message']}');
        if (error['stackTrace'] != null) {
          printError(error['stackTrace']);
        }
116
      }
117
    }
118
  }
119

120 121 122 123 124
  void _handleStatus(Map<String, dynamic> statusInfo) {
    // {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}}
    if (statusInfo['analysis'] != null && !_analyzingController.isClosed) {
      final bool isAnalyzing = statusInfo['analysis']['isAnalyzing'];
      _analyzingController.add(isAnalyzing);
125
    }
126 127
  }

128 129 130 131 132 133
  void _handleServerError(Map<String, dynamic> error) {
    // Fields are 'isFatal', 'message', and 'stackTrace'.
    printError('Error from the analysis server: ${error['message']}');
    if (error['stackTrace'] != null) {
      printError(error['stackTrace']);
    }
134 135
  }

136 137 138 139 140 141 142 143
  void _handleAnalysisIssues(Map<String, dynamic> issueInfo) {
    // {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}}
    final String file = issueInfo['file'];
    final List<AnalysisError> errors = issueInfo['errors']
        .map((Map<String, dynamic> json) => new AnalysisError(json))
        .toList();
    if (!_errorsController.isClosed)
      _errorsController.add(new FileAnalysisErrors(file, errors));
144 145
  }

146 147 148 149
  Future<bool> dispose() async {
    await _analyzingController.close();
    await _errorsController.close();
    return _process?.kill();
150 151 152
  }
}

153 154
class AnalysisError implements Comparable<AnalysisError> {
  AnalysisError(this.json);
155

156 157 158 159 160
  static final Map<String, int> _severityMap = <String, int>{
    'ERROR': 3,
    'WARNING': 2,
    'INFO': 1
  };
161

162
  static final String _separator = platform.isWindows ? '-' : '•';
163

164 165 166 167
  // "severity":"INFO","type":"TODO","location":{
  //   "file":"/Users/.../lib/test.dart","offset":362,"length":72,"startLine":15,"startColumn":4
  // },"message":"...","hasFix":false}
  Map<String, dynamic> json;
168

169 170 171 172 173
  String get severity => json['severity'];
  int get severityLevel => _severityMap[severity] ?? 0;
  String get type => json['type'];
  String get message => json['message'];
  String get code => json['code'];
174

175 176 177 178
  String get file => json['location']['file'];
  int get startLine => json['location']['startLine'];
  int get startColumn => json['location']['startColumn'];
  int get offset => json['location']['offset'];
179

180 181 182 183 184
  String get messageSentenceFragment {
    if (message.endsWith('.')) {
      return message.substring(0, message.length - 1);
    } else {
      return message;
pq's avatar
pq committed
185 186
    }
  }
187

188 189 190 191 192
  @override
  int compareTo(AnalysisError other) {
    // Sort in order of file path, error location, severity, and message.
    if (file != other.file)
      return file.compareTo(other.file);
193

194 195
    if (offset != other.offset)
      return offset - other.offset;
196

197 198 199
    final int diff = other.severityLevel - severityLevel;
    if (diff != 0)
      return diff;
200

201
    return message.compareTo(other.message);
202 203
  }

204 205 206 207 208
  @override
  String toString() {
    return '${severity.toLowerCase().padLeft(7)} $_separator '
        '$messageSentenceFragment $_separator '
        '${fs.path.relative(file)}:$startLine:$startColumn';
209
  }
210

211 212 213
  String toLegacyString() {
    return '[${severity.toLowerCase()}] $messageSentenceFragment ($file:$startLine:$startColumn)';
  }
214 215
}

216 217
class FileAnalysisErrors {
  FileAnalysisErrors(this.file, this.errors);
218

219 220
  final String file;
  final List<AnalysisError> errors;
221
}