analysis.dart 7.62 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
import 'dart:async';
6
import 'dart:math' as math;
7

8
import '../base/common.dart';
9
import '../base/file_system.dart' hide IOSink;
10
import '../base/file_system.dart';
11
import '../base/io.dart';
12 13
import '../base/platform.dart';
import '../base/process_manager.dart';
14
import '../base/terminal.dart';
15
import '../base/utils.dart';
16
import '../convert.dart';
17 18 19
import '../globals.dart';

class AnalysisServer {
20
  AnalysisServer(this.sdkPath, this.directories);
21 22 23 24 25 26

  final String sdkPath;
  final List<String> directories;

  Process _process;
  final StreamController<bool> _analyzingController =
27
      StreamController<bool>.broadcast();
28
  final StreamController<FileAnalysisErrors> _errorsController =
29
      StreamController<FileAnalysisErrors>.broadcast();
30
  bool _didServerErrorOccur = false;
31 32 33

  int _id = 0;

34
  Future<void> start() async {
35 36 37 38 39
    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,
40 41
      '--disable-server-feature-completion',
      '--disable-server-feature-search',
42 43 44 45 46 47 48
      '--sdk',
      sdkPath,
    ];

    printTrace('dart ${command.skip(1).join(' ')}');
    _process = await processManager.start(command);
    // This callback hookup can't throw.
49
    unawaited(_process.exitCode.whenComplete(() => _process = null));
50 51

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

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

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

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

67
  bool get didServerErrorOccur => _didServerErrorOccur;
68 69
  Stream<bool> get onAnalyzing => _analyzingController.stream;
  Stream<FileAnalysisErrors> get onErrors => _errorsController.stream;
70

71
  Future<int> get onExit => _process.exitCode;
72

73 74 75 76
  void _sendCommand(String method, Map<String, dynamic> params) {
    final String message = json.encode(<String, dynamic>{
      'id': (++_id).toString(),
      'method': method,
77
      'params': params,
78 79 80
    });
    _process.stdin.writeln(message);
    printTrace('==> $message');
81
  }
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  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']);
        }
109
      }
110
    }
111
  }
112

113 114 115 116 117
  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);
118
    }
119 120
  }

121 122 123 124 125 126
  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']);
    }
127
    _didServerErrorOccur = true;
128 129
  }

130 131 132
  void _handleAnalysisIssues(Map<String, dynamic> issueInfo) {
    // {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}}
    final String file = issueInfo['file'];
133 134 135
    final List<dynamic> errorsList = issueInfo['errors'];
    final List<AnalysisError> errors = errorsList
        .map<Map<String, dynamic>>(castStringKeyedMap)
136
        .map<AnalysisError>((Map<String, dynamic> json) => AnalysisError(json))
137 138
        .toList();
    if (!_errorsController.isClosed)
139
      _errorsController.add(FileAnalysisErrors(file, errors));
140 141
  }

142 143 144 145
  Future<bool> dispose() async {
    await _analyzingController.close();
    await _errorsController.close();
    return _process?.kill();
146 147 148
  }
}

149 150 151 152 153 154 155
enum _AnalysisSeverity {
  error,
  warning,
  info,
  none,
}

156 157
class AnalysisError implements Comparable<AnalysisError> {
  AnalysisError(this.json);
158

159 160 161 162
  static final Map<String, _AnalysisSeverity> _severityMap = <String, _AnalysisSeverity>{
    'INFO': _AnalysisSeverity.info,
    'WARNING': _AnalysisSeverity.warning,
    'ERROR': _AnalysisSeverity.error,
163
  };
164

165
  static final String _separator = platform.isWindows ? '-' : '•';
166

167 168 169 170
  // "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;
171

172
  String get severity => json['severity'];
173 174 175 176 177 178 179 180 181 182 183 184 185
  String get colorSeverity {
    switch(_severityLevel) {
      case _AnalysisSeverity.error:
        return terminal.color(severity, TerminalColor.red);
      case _AnalysisSeverity.warning:
        return terminal.color(severity, TerminalColor.yellow);
      case _AnalysisSeverity.info:
      case _AnalysisSeverity.none:
        return severity;
    }
    return null;
  }
  _AnalysisSeverity get _severityLevel => _severityMap[severity] ?? _AnalysisSeverity.none;
186 187 188
  String get type => json['type'];
  String get message => json['message'];
  String get code => json['code'];
189

190 191 192 193
  String get file => json['location']['file'];
  int get startLine => json['location']['startLine'];
  int get startColumn => json['location']['startColumn'];
  int get offset => json['location']['offset'];
194

195 196 197 198 199
  String get messageSentenceFragment {
    if (message.endsWith('.')) {
      return message.substring(0, message.length - 1);
    } else {
      return message;
pq's avatar
pq committed
200 201
    }
  }
202

203 204 205 206 207
  @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);
208

209 210
    if (offset != other.offset)
      return offset - other.offset;
211

212
    final int diff = other._severityLevel.index - _severityLevel.index;
213 214
    if (diff != 0)
      return diff;
215

216
    return message.compareTo(other.message);
217 218
  }

219 220
  @override
  String toString() {
221 222 223 224
    // Can't use "padLeft" because of ANSI color sequences in the colorized
    // severity.
    final String padding = ' ' * math.max(0, 7 - severity.length);
    return '$padding${colorSeverity.toLowerCase()} $_separator '
225
        '$messageSentenceFragment $_separator '
226 227
        '${fs.path.relative(file)}:$startLine:$startColumn $_separator '
        '$code';
228
  }
229

230 231 232
  String toLegacyString() {
    return '[${severity.toLowerCase()}] $messageSentenceFragment ($file:$startLine:$startColumn)';
  }
233 234
}

235 236
class FileAnalysisErrors {
  FileAnalysisErrors(this.file, this.errors);
237

238 239
  final String file;
  final List<AnalysisError> errors;
240
}