forked from dart-lang/dart-pad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
completion.dart
253 lines (202 loc) · 7.58 KB
/
completion.dart
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
62
63
64
65
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
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
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library dartpad.completion;
import 'dart:convert' show jsonDecode;
import 'package:async/async.dart';
import 'editing/editor.dart';
import 'services/dartservices.dart' as ds;
// TODO: For CodeMirror, we get a request each time the user hits a key when the
// completion popup is open. We need to cache the results when appropriate.
class DartCompleter extends CodeCompleter {
final ds.DartservicesApi servicesApi;
final Document document;
CancelableCompleter? _lastCompleter;
DartCompleter(this.servicesApi, this.document);
@override
Future<CompletionResult> complete(
Editor editor, {
bool onlyShowFixes = false,
}) {
// Cancel any open completion request.
_lastCompleter?.operation.cancel();
final offset = editor.document.indexFromPos(editor.document.cursor);
final request = ds.SourceRequest()
..source = editor.document.value
..offset = offset;
final completer = CancelableCompleter<CompletionResult>();
_lastCompleter = completer;
if (onlyShowFixes) {
final completions = <Completion>[];
final fixesFuture =
servicesApi.fixes(request).then((ds.FixesResponse response) {
for (final problemFix in response.fixes) {
for (final fix in problemFix.fixes) {
final fixes = fix.edits.map((edit) {
return SourceEdit(edit.length, edit.offset, edit.replacement);
}).toList();
completions.add(Completion(
'',
displayString: fix.message,
type: 'type-quick_fix',
quickFixes: fixes,
));
}
}
});
final assistsFuture =
servicesApi.assists(request).then((ds.AssistsResponse response) {
for (final assist in response.assists) {
final sourceEdits = assist.edits
.map((edit) =>
SourceEdit(edit.length, edit.offset, edit.replacement))
.toList();
int? absoluteCursorPosition;
// TODO(redbrogdon): Find a way to properly use these linked edit
// groups via selections and multiple cursors.
if (assist.linkedEditGroups.isNotEmpty) {
absoluteCursorPosition =
assist.linkedEditGroups.first.positions.first;
}
// If a specific offset is provided, prefer it to the one calculated
// from the linked edit groups.
if (assist.hasSelectionOffset()) {
absoluteCursorPosition = assist.selectionOffset;
}
final completion = Completion(
'',
displayString: assist.message,
type: 'type-quick_fix',
quickFixes: sourceEdits,
absoluteCursorPosition: absoluteCursorPosition,
);
completions.add(completion);
}
});
Future.wait([fixesFuture, assistsFuture]).then((_) {
completer.complete(CompletionResult(completions,
replaceOffset: offset, replaceLength: 0));
});
} else {
servicesApi.complete(request).then((ds.CompleteResponse response) {
if (completer.isCanceled) return;
final replaceOffset = response.replacementOffset;
final replaceLength = response.replacementLength;
final responses = response.completions.map((completion) {
return AnalysisCompletion(replaceOffset, replaceLength, completion);
});
final completions = responses.map((completion) {
// TODO: Move to using a LabelProvider; decouple the data and rendering.
var displayString = completion.isMethod
? '${completion.text}${completion.parameters}'
: completion.text;
if (completion.isMethod && completion.returnType != null) {
displayString += ' → ${completion.returnType}';
}
var text = completion.text;
if (completion.isMethod) {
text += '()';
}
if (completion.isConstructor) {
displayString += '()';
}
final deprecatedClass = completion.isDeprecated ? ' deprecated' : '';
if (completion.type == null) {
return Completion(
text,
displayString: displayString,
type: deprecatedClass,
);
} else {
int? cursorPos;
if (completion.isMethod && completion.parameterCount! > 0) {
cursorPos = text.indexOf('(') + 1;
}
if (completion.selectionOffset != 0) {
cursorPos = completion.selectionOffset;
}
return Completion(
text,
displayString: displayString,
type: 'type-${completion.type!.toLowerCase()}$deprecatedClass',
cursorOffset: cursorPos,
);
}
}).toList();
// Removes duplicates when a completion is both a getter and a setter.
for (final completion in completions) {
for (final other in completions) {
if (completion.isSetterAndMatchesGetter(other)) {
completions.removeWhere((c) => completion == c);
other.type = 'type-getter_and_setter';
}
}
}
completer.complete(CompletionResult(
completions,
replaceOffset: replaceOffset,
replaceLength: replaceLength,
));
}).catchError((e) {
completer.completeError(e as Object);
});
}
return completer.operation.value;
}
}
class AnalysisCompletion implements Comparable {
final int offset;
final int length;
final Map<String, dynamic> _map;
AnalysisCompletion(this.offset, this.length, ds.Completion completion)
: _map = Map<String, dynamic>.from(completion.completion) {
// TODO: We need to pass this completion info better.
_convert('element');
_convert('parameterNames');
_convert('parameterTypes');
if (_map.containsKey('element')) _map['element'].remove('location');
}
// Convert maps and lists that have been passed as json.
void _convert(String key) {
if (_map[key] is String) {
_map[key] = jsonDecode(_map[key] as String);
}
}
// KEYWORD, INVOCATION, ...
String? get kind => _map['kind'] as String?;
bool get isMethod {
final element = _map['element'];
return element is Map
? (element['kind'] == 'FUNCTION' || element['kind'] == 'METHOD')
: false;
}
bool get isConstructor => type == 'CONSTRUCTOR';
String? get parameters =>
isMethod ? _map['element']['parameters'] as String? : null;
int? get parameterCount =>
isMethod ? _map['parameterNames'].length as int? : null;
String get text {
final str = _map['completion'] as String;
if (str.startsWith('(') && str.endsWith(')')) {
return str.substring(1, str.length - 1);
} else {
return str;
}
}
String? get returnType => _map['returnType'] as String?;
bool get isDeprecated => _map['isDeprecated'] == 'true';
int get selectionOffset => _int(_map['selectionOffset'] as String?);
// FUNCTION, GETTER, CLASS, ...
String? get type =>
_map.containsKey('element') ? _map['element']['kind'] as String? : kind;
@override
int compareTo(other) {
if (other is AnalysisCompletion) {
return text.compareTo(other.text);
}
return -1;
}
@override
String toString() => text;
int _int(String? val) => val == null ? 0 : int.parse(val);
}