// 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:async'; import 'dart:math' as math; import '../base/common.dart'; import '../base/file_system.dart' hide IOSink; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/platform.dart'; import '../base/process_manager.dart'; import '../base/terminal.dart'; import '../base/utils.dart'; import '../convert.dart'; import '../globals.dart'; class AnalysisServer { AnalysisServer(this.sdkPath, this.directories); final String sdkPath; final List directories; Process _process; final StreamController _analyzingController = StreamController.broadcast(); final StreamController _errorsController = StreamController.broadcast(); int _id = 0; Future start() async { final String snapshot = fs.path.join(sdkPath, 'bin/snapshots/analysis_server.dart.snapshot'); final List command = [ fs.path.join(sdkPath, 'bin', 'dart'), snapshot, '--sdk', sdkPath, ]; printTrace('dart ${command.skip(1).join(' ')}'); _process = await processManager.start(command); // This callback hookup can't throw. unawaited(_process.exitCode.whenComplete(() => _process = null)); final Stream errorStream = _process.stderr.transform(utf8.decoder).transform(const LineSplitter()); errorStream.listen(printError); final Stream inStream = _process.stdout.transform(utf8.decoder).transform(const LineSplitter()); inStream.listen(_handleServerResponse); _sendCommand('server.setSubscriptions', { 'subscriptions': ['STATUS'] }); _sendCommand('analysis.setAnalysisRoots', {'included': directories, 'excluded': []}); } Stream get onAnalyzing => _analyzingController.stream; Stream get onErrors => _errorsController.stream; Future get onExit => _process.exitCode; void _sendCommand(String method, Map params) { final String message = json.encode({ 'id': (++_id).toString(), 'method': method, 'params': params }); _process.stdin.writeln(message); printTrace('==> $message'); } void _handleServerResponse(String line) { printTrace('<== $line'); final dynamic response = json.decode(line); if (response is Map) { if (response['event'] != null) { final String event = response['event']; final dynamic params = response['params']; if (params is Map) { 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 error = response['error']; printError( 'Error response from the server: ${error['code']} ${error['message']}'); if (error['stackTrace'] != null) { printError(error['stackTrace']); } } } } void _handleStatus(Map statusInfo) { // {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}} if (statusInfo['analysis'] != null && !_analyzingController.isClosed) { final bool isAnalyzing = statusInfo['analysis']['isAnalyzing']; _analyzingController.add(isAnalyzing); } } void _handleServerError(Map error) { // Fields are 'isFatal', 'message', and 'stackTrace'. printError('Error from the analysis server: ${error['message']}'); if (error['stackTrace'] != null) { printError(error['stackTrace']); } } void _handleAnalysisIssues(Map issueInfo) { // {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}} final String file = issueInfo['file']; final List errorsList = issueInfo['errors']; final List errors = errorsList .map>(castStringKeyedMap) .map((Map json) => AnalysisError(json)) .toList(); if (!_errorsController.isClosed) _errorsController.add(FileAnalysisErrors(file, errors)); } Future dispose() async { await _analyzingController.close(); await _errorsController.close(); return _process?.kill(); } } enum _AnalysisSeverity { error, warning, info, none, } class AnalysisError implements Comparable { AnalysisError(this.json); static final Map _severityMap = { 'INFO': _AnalysisSeverity.info, 'WARNING': _AnalysisSeverity.warning, 'ERROR': _AnalysisSeverity.error, }; static final String _separator = platform.isWindows ? '-' : '•'; // "severity":"INFO","type":"TODO","location":{ // "file":"/Users/.../lib/test.dart","offset":362,"length":72,"startLine":15,"startColumn":4 // },"message":"...","hasFix":false} Map json; String get severity => json['severity']; 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; String get type => json['type']; String get message => json['message']; String get code => json['code']; String get file => json['location']['file']; int get startLine => json['location']['startLine']; int get startColumn => json['location']['startColumn']; int get offset => json['location']['offset']; String get messageSentenceFragment { if (message.endsWith('.')) { return message.substring(0, message.length - 1); } else { return message; } } @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); if (offset != other.offset) return offset - other.offset; final int diff = other._severityLevel.index - _severityLevel.index; if (diff != 0) return diff; return message.compareTo(other.message); } @override String toString() { // 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 ' '$messageSentenceFragment $_separator ' '${fs.path.relative(file)}:$startLine:$startColumn $_separator ' '$code'; } String toLegacyString() { return '[${severity.toLowerCase()}] $messageSentenceFragment ($file:$startLine:$startColumn)'; } } class FileAnalysisErrors { FileAnalysisErrors(this.file, this.errors); final String file; final List errors; }