1// Copyright 2016 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5import 'dart:async'; 6import 'dart:math' as math; 7 8import '../base/common.dart'; 9import '../base/file_system.dart' hide IOSink; 10import '../base/file_system.dart'; 11import '../base/io.dart'; 12import '../base/platform.dart'; 13import '../base/process_manager.dart'; 14import '../base/terminal.dart'; 15import '../base/utils.dart'; 16import '../convert.dart'; 17import '../globals.dart'; 18 19class AnalysisServer { 20 AnalysisServer(this.sdkPath, this.directories); 21 22 final String sdkPath; 23 final List<String> directories; 24 25 Process _process; 26 final StreamController<bool> _analyzingController = 27 StreamController<bool>.broadcast(); 28 final StreamController<FileAnalysisErrors> _errorsController = 29 StreamController<FileAnalysisErrors>.broadcast(); 30 bool _didServerErrorOccur = false; 31 32 int _id = 0; 33 34 Future<void> start() async { 35 final String snapshot = 36 fs.path.join(sdkPath, 'bin/snapshots/analysis_server.dart.snapshot'); 37 final List<String> command = <String>[ 38 fs.path.join(sdkPath, 'bin', 'dart'), 39 snapshot, 40 '--disable-server-feature-completion', 41 '--disable-server-feature-search', 42 '--sdk', 43 sdkPath, 44 ]; 45 46 printTrace('dart ${command.skip(1).join(' ')}'); 47 _process = await processManager.start(command); 48 // 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 errorStream.listen(printError); 54 55 final Stream<String> inStream = 56 _process.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()); 57 inStream.listen(_handleServerResponse); 58 59 _sendCommand('server.setSubscriptions', <String, dynamic>{ 60 'subscriptions': <String>['STATUS'], 61 }); 62 63 _sendCommand('analysis.setAnalysisRoots', 64 <String, dynamic>{'included': directories, 'excluded': <String>[]}); 65 } 66 67 bool get didServerErrorOccur => _didServerErrorOccur; 68 Stream<bool> get onAnalyzing => _analyzingController.stream; 69 Stream<FileAnalysisErrors> get onErrors => _errorsController.stream; 70 71 Future<int> get onExit => _process.exitCode; 72 73 void _sendCommand(String method, Map<String, dynamic> params) { 74 final String message = json.encode(<String, dynamic>{ 75 'id': (++_id).toString(), 76 'method': method, 77 'params': params, 78 }); 79 _process.stdin.writeln(message); 80 printTrace('==> $message'); 81 } 82 83 void _handleServerResponse(String line) { 84 printTrace('<== $line'); 85 86 final dynamic response = json.decode(line); 87 88 if (response is Map<dynamic, dynamic>) { 89 if (response['event'] != null) { 90 final String event = response['event']; 91 final dynamic params = response['params']; 92 93 if (params is Map<dynamic, dynamic>) { 94 if (event == 'server.status') 95 _handleStatus(response['params']); 96 else if (event == 'analysis.errors') 97 _handleAnalysisIssues(response['params']); 98 else if (event == 'server.error') 99 _handleServerError(response['params']); 100 } 101 } else if (response['error'] != null) { 102 // Fields are 'code', 'message', and 'stackTrace'. 103 final Map<String, dynamic> error = response['error']; 104 printError( 105 'Error response from the server: ${error['code']} ${error['message']}'); 106 if (error['stackTrace'] != null) { 107 printError(error['stackTrace']); 108 } 109 } 110 } 111 } 112 113 void _handleStatus(Map<String, dynamic> statusInfo) { 114 // {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}} 115 if (statusInfo['analysis'] != null && !_analyzingController.isClosed) { 116 final bool isAnalyzing = statusInfo['analysis']['isAnalyzing']; 117 _analyzingController.add(isAnalyzing); 118 } 119 } 120 121 void _handleServerError(Map<String, dynamic> error) { 122 // Fields are 'isFatal', 'message', and 'stackTrace'. 123 printError('Error from the analysis server: ${error['message']}'); 124 if (error['stackTrace'] != null) { 125 printError(error['stackTrace']); 126 } 127 _didServerErrorOccur = true; 128 } 129 130 void _handleAnalysisIssues(Map<String, dynamic> issueInfo) { 131 // {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}} 132 final String file = issueInfo['file']; 133 final List<dynamic> errorsList = issueInfo['errors']; 134 final List<AnalysisError> errors = errorsList 135 .map<Map<String, dynamic>>(castStringKeyedMap) 136 .map<AnalysisError>((Map<String, dynamic> json) => AnalysisError(json)) 137 .toList(); 138 if (!_errorsController.isClosed) 139 _errorsController.add(FileAnalysisErrors(file, errors)); 140 } 141 142 Future<bool> dispose() async { 143 await _analyzingController.close(); 144 await _errorsController.close(); 145 return _process?.kill(); 146 } 147} 148 149enum _AnalysisSeverity { 150 error, 151 warning, 152 info, 153 none, 154} 155 156class AnalysisError implements Comparable<AnalysisError> { 157 AnalysisError(this.json); 158 159 static final Map<String, _AnalysisSeverity> _severityMap = <String, _AnalysisSeverity>{ 160 'INFO': _AnalysisSeverity.info, 161 'WARNING': _AnalysisSeverity.warning, 162 'ERROR': _AnalysisSeverity.error, 163 }; 164 165 static final String _separator = platform.isWindows ? '-' : '•'; 166 167 // "severity":"INFO","type":"TODO","location":{ 168 // "file":"/Users/.../lib/test.dart","offset":362,"length":72,"startLine":15,"startColumn":4 169 // },"message":"...","hasFix":false} 170 Map<String, dynamic> json; 171 172 String get severity => json['severity']; 173 String get colorSeverity { 174 switch(_severityLevel) { 175 case _AnalysisSeverity.error: 176 return terminal.color(severity, TerminalColor.red); 177 case _AnalysisSeverity.warning: 178 return terminal.color(severity, TerminalColor.yellow); 179 case _AnalysisSeverity.info: 180 case _AnalysisSeverity.none: 181 return severity; 182 } 183 return null; 184 } 185 _AnalysisSeverity get _severityLevel => _severityMap[severity] ?? _AnalysisSeverity.none; 186 String get type => json['type']; 187 String get message => json['message']; 188 String get code => json['code']; 189 190 String get file => json['location']['file']; 191 int get startLine => json['location']['startLine']; 192 int get startColumn => json['location']['startColumn']; 193 int get offset => json['location']['offset']; 194 195 String get messageSentenceFragment { 196 if (message.endsWith('.')) { 197 return message.substring(0, message.length - 1); 198 } else { 199 return message; 200 } 201 } 202 203 @override 204 int compareTo(AnalysisError other) { 205 // Sort in order of file path, error location, severity, and message. 206 if (file != other.file) 207 return file.compareTo(other.file); 208 209 if (offset != other.offset) 210 return offset - other.offset; 211 212 final int diff = other._severityLevel.index - _severityLevel.index; 213 if (diff != 0) 214 return diff; 215 216 return message.compareTo(other.message); 217 } 218 219 @override 220 String toString() { 221 // Can't use "padLeft" because of ANSI color sequences in the colorized 222 // severity. 223 final String padding = ' ' * math.max(0, 7 - severity.length); 224 return '$padding${colorSeverity.toLowerCase()} $_separator ' 225 '$messageSentenceFragment $_separator ' 226 '${fs.path.relative(file)}:$startLine:$startColumn $_separator ' 227 '$code'; 228 } 229 230 String toLegacyString() { 231 return '[${severity.toLowerCase()}] $messageSentenceFragment ($file:$startLine:$startColumn)'; 232 } 233} 234 235class FileAnalysisErrors { 236 FileAnalysisErrors(this.file, this.errors); 237 238 final String file; 239 final List<AnalysisError> errors; 240} 241