Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1032)

Side by Side Diff: pkg/analysis_server/lib/src/services/completion/postfix/postfix_completion.dart

Issue 2917943002: Postfix completion (Closed)
Patch Set: typo Created 3 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 import 'dart:async';
6
7 import 'package:analysis_server/src/protocol_server.dart' hide Element;
8 import 'package:analysis_server/src/services/correction/util.dart';
9 import 'package:analyzer/dart/ast/ast.dart';
10 import 'package:analyzer/dart/element/element.dart';
11 import 'package:analyzer/dart/element/type.dart';
12 import 'package:analyzer/error/error.dart' as engine;
13 import 'package:analyzer/src/dart/analysis/driver.dart';
14 import 'package:analyzer/src/dart/ast/utilities.dart';
15 import 'package:analyzer/src/generated/engine.dart';
16 import 'package:analyzer/src/generated/java_core.dart';
17 import 'package:analyzer/src/generated/resolver.dart';
18 import 'package:analyzer/src/generated/source.dart';
19 import 'package:analyzer_plugin/utilities/change_builder/change_builder_dart.dar t';
20 import 'package:analyzer_plugin/utilities/range_factory.dart';
21
22 /**
23 * An enumeration of possible postfix completion kinds.
24 */
25 class DartPostfixCompletion {
26 static const NO_TEMPLATE =
27 const PostfixCompletionKind('', 'no change', null, null);
28 static const ALL_TEMPLATES = const [
29 const PostfixCompletionKind("assert", "expr.assert -> assert(expr);",
30 isAssertContext, expandAssert),
31 const PostfixCompletionKind(
32 "fori",
33 "limit.fori -> for(var i = 0; i < limit; i++) {}",
34 isIntContext,
35 expandFori),
36 const PostfixCompletionKind(
37 "for",
38 "values.for -> for(var value in values) {}",
39 isIterableContext,
40 expandFor),
41 const PostfixCompletionKind(
42 "iter",
43 "values.iter -> for(var value in values) {}",
44 isIterableContext,
45 expandFor),
46 const PostfixCompletionKind(
47 "not", "bool.not -> !bool", isBoolContext, expandNegate),
48 const PostfixCompletionKind(
49 "!", "bool! -> !bool", isBoolContext, expandNegate),
50 const PostfixCompletionKind(
51 "else", "bool.else -> if (!bool) {}", isBoolContext, expandElse),
52 const PostfixCompletionKind(
53 "if", "bool.if -> if (bool) {}", isBoolContext, expandIf),
54 const PostfixCompletionKind("nn", "expr.nn -> if (expr != null) {}",
55 isObjectContext, expandNotNull),
56 const PostfixCompletionKind("notnull",
57 "expr.notnull -> if (expr != null) {}", isObjectContext, expandNotNull),
58 const PostfixCompletionKind("null", "expr.null -> if (expr == null) {}",
59 isObjectContext, expandNull),
60 const PostfixCompletionKind(
61 "par", "expr.par -> (expr)", isObjectContext, expandParen),
62 const PostfixCompletionKind(
63 "return", "expr.return -> return expr", isObjectContext, expandReturn),
64 const PostfixCompletionKind("switch", "expr.switch -> switch (expr) {}",
65 isSwitchContext, expandSwitch),
66 const PostfixCompletionKind("try", "stmt.try -> try {stmt} catch (e,s) {}",
67 isStatementContext, expandTry),
68 const PostfixCompletionKind(
69 "tryon",
70 "stmt.try -> try {stmt} on Exception catch (e,s) {}",
71 isStatementContext,
72 expandTryon),
73 const PostfixCompletionKind(
74 "while", "expr.while -> while (expr) {}", isBoolContext, expandWhile),
75 ];
76
77 static Future<PostfixCompletion> expandAssert(
78 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
79 return processor.expand(kind, processor.findAssertExpression, (expr) {
80 return "assert(${processor.utils.getNodeText(expr)});";
81 }, withBraces: false);
82 }
83
84 static Future<PostfixCompletion> expandElse(
85 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
86 return processor.expand(kind, processor.findBoolExpression,
87 (expr) => "if (${processor.makeNegatedBoolExpr(expr)})");
88 }
89
90 static Future<PostfixCompletion> expandFor(
91 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
92 return processor.expand(kind, processor.findIterableExpression, (expr) {
93 String value = processor.newVariable("value");
94 return "for (var $value in ${processor.utils.getNodeText(expr)})";
95 });
96 }
97
98 static Future<PostfixCompletion> expandFori(
99 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
100 return processor.expand(kind, processor.findIntExpression, (expr) {
101 String index = processor.newVariable("i");
102 return "for (int $index = 0; $index < ${processor.utils.getNodeText(
103 expr)}; $index++)";
104 });
105 }
106
107 static Future<PostfixCompletion> expandIf(
108 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
109 return processor.expand(kind, processor.findBoolExpression,
110 (expr) => "if (${processor.utils.getNodeText(expr)})");
111 }
112
113 static Future<PostfixCompletion> expandNegate(
114 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
115 return processor.expand(kind, processor.findBoolExpression,
116 (expr) => processor.makeNegatedBoolExpr(expr),
117 withBraces: false);
118 }
119
120 static Future<PostfixCompletion> expandNotNull(
121 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
122 return processor.expand(kind, processor.findObjectExpression, (expr) {
123 return expr is NullLiteral
124 ? "if (false)"
125 : "if (${processor.utils.getNodeText(expr)} != null)";
126 });
127 }
128
129 static Future<PostfixCompletion> expandNull(
130 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
131 return processor.expand(kind, processor.findObjectExpression, (expr) {
132 return expr is NullLiteral
133 ? "if (true)"
134 : "if (${processor.utils.getNodeText(expr)} == null)";
135 });
136 }
137
138 static Future<PostfixCompletion> expandParen(
139 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
140 return processor.expand(kind, processor.findObjectExpression,
141 (expr) => "(${processor.utils.getNodeText(expr)})",
142 withBraces: false);
143 }
144
145 static Future<PostfixCompletion> expandReturn(
146 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
147 return processor.expand(kind, processor.findObjectExpression,
148 (expr) => "return ${processor.utils.getNodeText(expr)};",
149 withBraces: false);
150 }
151
152 static Future<PostfixCompletion> expandSwitch(
153 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
154 return processor.expand(kind, processor.findObjectExpression,
155 (expr) => "switch (${processor.utils.getNodeText(expr)})");
156 }
157
158 static Future<PostfixCompletion> expandTry(
159 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
160 return processor.expandTry(kind, processor.findStatement, withOn: false);
161 }
162
163 static Future<PostfixCompletion> expandTryon(
164 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
165 return processor.expandTry(kind, processor.findStatement, withOn: true);
166 }
167
168 static Future<PostfixCompletion> expandWhile(
169 PostfixCompletionProcessor processor, PostfixCompletionKind kind) async {
170 return processor.expand(kind, processor.findBoolExpression,
171 (expr) => "while (${processor.utils.getNodeText(expr)})");
172 }
173
174 static PostfixCompletionKind forKey(String key) =>
175 ALL_TEMPLATES.firstWhere((kind) => kind.key == key, orElse: () => null);
176
177 static bool isAssertContext(PostfixCompletionProcessor processor) {
178 return processor.findAssertExpression() != null;
179 }
180
181 static bool isBoolContext(PostfixCompletionProcessor processor) {
182 return processor.findBoolExpression() != null;
183 }
184
185 static bool isIntContext(PostfixCompletionProcessor processor) {
186 return processor.findIntExpression() != null;
187 }
188
189 static bool isIterableContext(PostfixCompletionProcessor processor) {
190 return processor.findIterableExpression() != null;
191 }
192
193 static bool isObjectContext(PostfixCompletionProcessor processor) {
194 return processor.findObjectExpression() != null;
195 }
196
197 static bool isStatementContext(PostfixCompletionProcessor processor) {
198 return processor.findStatement() != null;
199 }
200
201 static bool isSwitchContext(PostfixCompletionProcessor processor) {
202 return processor.findObjectExpression() != null;
203 }
204 }
205
206 /**
207 * A description of a postfix completion.
208 *
209 * Clients may not extend, implement or mix-in this class.
210 */
211 class PostfixCompletion {
212 /**
213 * A description of the assist being proposed.
214 */
215 final PostfixCompletionKind kind;
216
217 /**
218 * The change to be made in order to apply the assist.
219 */
220 final SourceChange change;
221
222 /**
223 * Initialize a newly created completion to have the given [kind] and [change] .
224 */
225 PostfixCompletion(this.kind, this.change);
226 }
227
228 /**
229 * The context for computing a postfix completion.
230 */
231 class PostfixCompletionContext {
232 final String file;
233 final LineInfo lineInfo;
234 final int selectionOffset;
235 final String key;
236 final AnalysisDriver driver;
237 final CompilationUnit unit;
238 final CompilationUnitElement unitElement;
239 final List<engine.AnalysisError> errors;
240
241 PostfixCompletionContext(this.file, this.lineInfo, this.selectionOffset,
242 this.key, this.driver, this.unit, this.unitElement, this.errors) {
243 if (unitElement.context == null) {
244 throw new Error(); // not reached
245 }
246 }
247 }
248
249 /**
250 * A description of a template for postfix completion. Instances are intended to
251 * hold the functions required to determine applicability and expand the
252 * template, in addition to its name and simple example. The example is shown
253 * (in IntelliJ) in a code-completion menu, so must be quite short.
254 *
255 * Clients may not extend, implement or mix-in this class.
256 */
257 class PostfixCompletionKind {
258 final String name, example;
259 final Function selector;
260 final Function computer;
261
262 const PostfixCompletionKind(
263 this.name, this.example, this.selector, this.computer);
264
265 String get key => name == '!' ? name : '.$name';
266
267 String get message => 'Expand $key';
268
269 @override
270 String toString() => name;
271 }
272
273 /**
274 * The computer for Dart postfix completions.
275 */
276 class PostfixCompletionProcessor {
277 static final NO_COMPLETION = new PostfixCompletion(
278 DartPostfixCompletion.NO_TEMPLATE, new SourceChange("", edits: []));
279
280 final PostfixCompletionContext completionContext;
281 final AnalysisContext analysisContext;
282 final CorrectionUtils utils;
283 int fileStamp;
284 AstNode node;
285 PostfixCompletion completion;
286 SourceChange change = new SourceChange('postfix-completion');
287 final Map<String, LinkedEditGroup> linkedPositionGroups =
288 <String, LinkedEditGroup>{};
289 Position exitPosition = null;
290 TypeProvider _typeProvider;
291
292 PostfixCompletionProcessor(this.completionContext)
293 : analysisContext = completionContext.unitElement.context,
294 utils = new CorrectionUtils(completionContext.unit) {
295 fileStamp = _modificationStamp(file);
296 }
297
298 AnalysisDriver get driver => completionContext.driver;
299
300 String get eol => utils.endOfLine;
301
302 String get file => completionContext.file;
303
304 String get key => completionContext.key;
305
306 LineInfo get lineInfo => completionContext.lineInfo;
307
308 int get requestLine => lineInfo.getLocation(selectionOffset).lineNumber;
309
310 int get selectionOffset => completionContext.selectionOffset;
311
312 Source get source => completionContext.unitElement.source;
313
314 TypeProvider get typeProvider {
315 return _typeProvider ??= unitElement.context.typeProvider;
316 }
317
318 CompilationUnit get unit => completionContext.unit;
319
320 CompilationUnitElement get unitElement => completionContext.unitElement;
321
322 Future<PostfixCompletion> compute() async {
323 // If the source was changed between the constructor and running
324 // this asynchronous method, it is not safe to use the unit.
325 if (_modificationStamp(file) != fileStamp) {
326 return NO_COMPLETION;
327 }
328 node = _selectedNode();
329 if (node == null) {
330 return NO_COMPLETION;
331 }
332 PostfixCompletionKind completer = DartPostfixCompletion.forKey(key);
333 return completer?.computer(this, completer) ?? NO_COMPLETION;
334 }
335
336 Future<PostfixCompletion> expand(
337 PostfixCompletionKind kind, Function contexter, Function sourcer,
338 {bool withBraces: true}) async {
339 AstNode expr = contexter();
340 if (expr == null) {
341 return null;
342 }
343
344 DartChangeBuilder changeBuilder = new DartChangeBuilder(driver);
345 await changeBuilder.addFileEdit(file, fileStamp,
346 (DartFileEditBuilder builder) {
347 builder.addReplacement(range.node(expr), (DartEditBuilder builder) {
348 String newSrc = sourcer(expr);
349 if (newSrc == null) {
350 return null;
351 }
352 builder.write(newSrc);
353 if (withBraces) {
354 builder.write(" {");
355 builder.write(eol);
356 String indent = utils.getNodePrefix(expr);
357 builder.write(indent);
358 builder.write(utils.getIndent(1));
359 builder.selectHere();
360 builder.write(eol);
361 builder.write(indent);
362 builder.write("}");
363 } else {
364 builder.selectHere();
365 }
366 });
367 });
368 _setCompletionFromBuilder(changeBuilder, kind);
369 return completion;
370 }
371
372 Future<PostfixCompletion> expandTry(
373 PostfixCompletionKind kind, Function contexter,
374 {bool withOn: false}) async {
375 AstNode stmt = contexter();
376 if (stmt == null) {
377 return null;
378 }
379 DartChangeBuilder changeBuilder = new DartChangeBuilder(driver);
380 await changeBuilder.addFileEdit(file, fileStamp,
381 (DartFileEditBuilder builder) {
382 // Embed the full line(s) of the statement in the try block.
383 var startLine = lineInfo.getLocation(stmt.offset).lineNumber - 1;
384 var endLine = lineInfo.getLocation(stmt.end).lineNumber - 1;
385 if (stmt is ExpressionStatement && !stmt.semicolon.isSynthetic) {
386 endLine += 1;
387 }
388 var startOffset = lineInfo.getOffsetOfLine(startLine);
389 var endOffset = lineInfo.getOffsetOfLine(endLine);
390 var src = utils.getText(startOffset, endOffset - startOffset);
391 String indent = utils.getLinePrefix(stmt.offset);
392 builder.addReplacement(range.startOffsetEndOffset(startOffset, endOffset),
393 (DartEditBuilder builder) {
394 builder.write(indent);
395 builder.write('try {');
396 builder.write(eol);
397 builder.write(src.replaceAll(new RegExp("^$indent", multiLine: true),
398 "$indent${utils.getIndent(1)}"));
399 builder.selectHere();
400 builder.write(indent);
401 builder.write('}');
402 if (withOn) {
403 builder.write(' on ');
404 builder.addSimpleLinkedEdit('NAME', nameOfExceptionThrownBy(stmt));
405 }
406 builder.write(' catch (e, s) {');
407 builder.write(eol);
408 builder.write(indent);
409 builder.write(utils.getIndent(1));
410 builder.write('print(s);');
411 builder.write(eol);
412 builder.write(indent);
413 builder.write("}");
414 builder.write(eol);
415 });
416 });
417 _setCompletionFromBuilder(changeBuilder, kind);
418 return completion;
419 }
420
421 Expression findAssertExpression() {
422 if (node is Expression) {
423 Expression boolExpr = _findOuterExpression(node, typeProvider.boolType);
424 if (boolExpr == null) {
425 return null;
426 }
427 if (boolExpr.parent is ExpressionFunctionBody &&
428 boolExpr.parent.parent is FunctionExpression) {
429 FunctionExpression fnExpr = boolExpr.parent.parent;
430 var type = fnExpr.bestType;
431 if (type is! FunctionType) {
432 return boolExpr;
433 }
434 FunctionType fnType = type;
435 if (fnType.returnType == typeProvider.boolType) {
436 return fnExpr;
437 }
438 }
439 if (boolExpr.bestType == typeProvider.boolType) {
440 return boolExpr;
441 }
442 }
443 return null;
444 }
445
446 Expression findBoolExpression() =>
447 _findOuterExpression(node, typeProvider.boolType);
448
449 Expression findIntExpression() =>
450 _findOuterExpression(node, typeProvider.intType);
451
452 Expression findIterableExpression() =>
453 _findOuterExpression(node, typeProvider.iterableType);
454
455 Expression findObjectExpression() =>
456 _findOuterExpression(node, typeProvider.objectType);
457
458 AstNode findStatement() {
459 var astNode = node;
460 while (astNode != null) {
461 if (astNode is Statement && astNode is! Block) {
462 // Disallow control-flow statements.
463 if (astNode is DoStatement ||
464 astNode is IfStatement ||
465 astNode is ForEachStatement ||
466 astNode is ForStatement ||
467 astNode is SwitchStatement ||
468 astNode is TryStatement ||
469 astNode is WhileStatement) {
470 return null;
471 }
472 return astNode;
473 }
474 astNode = astNode.parent;
475 }
476 return null;
477 }
478
479 Future<bool> isApplicable() async {
480 if (_modificationStamp(file) != fileStamp) {
481 return false;
482 }
483 node = _selectedNode();
484 if (node == null) {
485 return false;
486 }
487 PostfixCompletionKind completer = DartPostfixCompletion.forKey(key);
488 return completer?.selector(this);
489 }
490
491 String makeNegatedBoolExpr(Expression expr) {
492 String originalSrc = utils.getNodeText(expr);
493 String newSrc = utils.invertCondition(expr);
494 if (newSrc != originalSrc) {
495 return newSrc;
496 } else {
497 return "!${utils.getNodeText(expr)}";
498 }
499 }
500
501 String nameOfExceptionThrownBy(AstNode astNode) {
502 if (astNode is ExpressionStatement) {
503 astNode = (astNode as ExpressionStatement).expression;
504 }
505 if (astNode is ThrowExpression) {
506 ThrowExpression expr = astNode;
507 var type = expr.expression.bestType;
508 return type.displayName;
509 }
510 return 'Exception';
511 }
512
513 String newVariable(String base) {
514 String name = base;
515 int i = 1;
516 Set<String> vars =
517 utils.findPossibleLocalVariableConflicts(selectionOffset);
518 while (vars.contains(name)) {
519 name = "$base${i++}";
520 }
521 return name;
522 }
523
524 Expression _findOuterExpression(AstNode start, InterfaceType builtInType) {
525 AstNode parent;
526 if (start is Expression) {
527 parent = start;
528 } else if (start is ArgumentList) {
529 parent = start.parent;
530 }
531 if (parent == null) {
532 return null;
533 }
534 var list = <Expression>[];
535 while (parent is Expression) {
536 list.add(parent);
537 parent = parent.parent;
538 }
539 Expression expr = list.firstWhere((expr) {
540 DartType type = expr.bestType;
541 if (type.isSubtypeOf(builtInType)) return true;
542 Element element = type.element;
543 if (element is TypeDefiningElement) {
544 TypeDefiningElement typeDefElem = element;
545 type = typeDefElem.type;
546 if (type is ParameterizedType) {
547 ParameterizedType pType = type;
548 type = pType.instantiate(new List.filled(
549 pType.typeParameters.length, typeProvider.dynamicType));
550 }
551 }
552 return type.isSubtypeOf(builtInType);
553 }, orElse: () => null);
554 if (expr is SimpleIdentifier && expr.parent is PropertyAccess) {
555 expr = expr.parent;
556 }
557 if (expr?.parent is CascadeExpression) {
558 expr = expr.parent;
559 }
560 return expr;
561 }
562
563 int _modificationStamp(String filePath) {
564 // TODO(brianwilkerson) We have lost the ability for clients to know whether
565 // it is safe to apply an edit.
566 return driver.fsState.getFileForPath(filePath).exists ? 0 : -1;
567 }
568
569 AstNode _selectedNode({int at: null}) =>
570 new NodeLocator(at == null ? selectionOffset : at).searchWithin(unit);
571
572 void _setCompletionFromBuilder(
573 DartChangeBuilder builder, PostfixCompletionKind kind,
574 [List args]) {
575 SourceChange change = builder.sourceChange;
576 if (change.edits.isEmpty) {
577 completion = null;
578 return;
579 }
580 change.message = formatList(kind.message, args);
581 completion = new PostfixCompletion(kind, change);
582 }
583 }
OLDNEW
« no previous file with comments | « pkg/analysis_server/lib/src/edit/edit_domain.dart ('k') | pkg/analysis_server/test/edit/postfix_completion_test.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698