1 | | // Copyright (c) 2014, 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 | | library dart_style.src.source_visitor;
|
6 | |
|
7 | | import 'package:analyzer/dart/ast/ast.dart';
|
8 | | import 'package:analyzer/dart/ast/token.dart';
|
9 | | import 'package:analyzer/dart/ast/visitor.dart';
|
10 | | import 'package:analyzer/src/generated/source.dart';
|
11 | |
|
12 | | import 'argument_list_visitor.dart';
|
13 | | import 'call_chain_visitor.dart';
|
14 | | import 'chunk.dart';
|
15 | | import 'chunk_builder.dart';
|
16 | | import 'dart_formatter.dart';
|
17 | | import 'rule/argument.dart';
|
18 | | import 'rule/combinator.dart';
|
19 | | import 'rule/metadata.dart';
|
20 | | import 'rule/rule.dart';
|
21 | | import 'rule/type_argument.dart';
|
22 | | import 'source_code.dart';
|
23 | | import 'style_fix.dart';
|
24 | | import 'whitespace.dart';
|
25 | |
|
26 | | final _capitalPattern = new RegExp(r"^_?[A-Z].*[a-z]");
|
27 | |
|
28 | | /// Visits every token of the AST and passes all of the relevant bits to a
|
29 | | /// [ChunkBuilder].
|
30 | | class SourceVisitor extends ThrowingAstVisitor {
|
31 | | /// Returns `true` if [node] is a method invocation that looks like it might
|
32 | | /// be a static method or constructor call without a `new` keyword.
|
33 | | ///
|
34 | | /// With optional `new`, we can no longer reliably identify constructor calls
|
35 | | /// statically, but we still don't want to mix named constructor calls into
|
36 | | /// a call chain like:
|
37 | | ///
|
38 | | /// Iterable
|
39 | | /// .generate(...)
|
40 | | /// .toList();
|
41 | | ///
|
42 | | /// And instead prefer:
|
43 | | ///
|
44 | | /// Iterable.generate(...)
|
45 | | /// .toList();
|
46 | | ///
|
47 | | /// So we try to identify these calls syntactically. The heuristic we use is
|
48 | | /// that a target that's a capitalized name (possibly prefixed by "_") is
|
49 | | /// assumed to be a class.
|
50 | | ///
|
51 | | /// This has the effect of also keeping static method calls with the class,
|
52 | | /// but that tends to look pretty good too, and is certainly better than
|
53 | | /// splitting up named constructors.
|
54 | 2 | static bool looksLikeStaticCall(Expression node) {
|
55 | 2 | if (node is! MethodInvocation) return false;
|
56 | | var invocation = node as MethodInvocation;
|
57 | 1 | if (invocation.target == null) return false;
|
58 | |
|
59 | | // A prefixed unnamed constructor call:
|
60 | | //
|
61 | | // prefix.Foo();
|
62 | 2 | if (invocation.target is SimpleIdentifier &&
|
63 | 3 | _looksLikeClassName(invocation.methodName.name)) {
|
64 | | return true;
|
65 | | }
|
66 | |
|
67 | | // A prefixed or unprefixed named constructor call:
|
68 | | //
|
69 | | // Foo.named();
|
70 | | // prefix.Foo.named();
|
71 | 1 | var target = invocation.target;
|
72 | 1 | if (target is PrefixedIdentifier) {
|
73 | 1 | target = (target as PrefixedIdentifier).identifier;
|
74 | | }
|
75 | |
|
76 | 3 | return target is SimpleIdentifier && _looksLikeClassName(target.name);
|
77 | | }
|
78 | |
|
79 | 1 | static bool _looksLikeClassName(String name) {
|
80 | | // Handle the weird lowercase corelib names.
|
81 | 1 | if (name == "bool") return true;
|
82 | 1 | if (name == "double") return true;
|
83 | 1 | if (name == "int") return true;
|
84 | 1 | if (name == "num") return true;
|
85 | |
|
86 | 2 | return _capitalPattern.hasMatch(name);
|
87 | | }
|
88 | |
|
89 | | /// The builder for the block that is currently being visited.
|
90 | | ChunkBuilder builder;
|
91 | |
|
92 | | final DartFormatter _formatter;
|
93 | |
|
94 | | /// Cached line info for calculating blank lines.
|
95 | | LineInfo _lineInfo;
|
96 | |
|
97 | | /// The source being formatted.
|
98 | | final SourceCode _source;
|
99 | |
|
100 | | /// `true` if the visitor has written past the beginning of the selection in
|
101 | | /// the original source text.
|
102 | | bool _passedSelectionStart = false;
|
103 | |
|
104 | | /// `true` if the visitor has written past the end of the selection in the
|
105 | | /// original source text.
|
106 | | bool _passedSelectionEnd = false;
|
107 | |
|
108 | | /// The character offset of the end of the selection, if there is a selection.
|
109 | | ///
|
110 | | /// This is calculated and cached by [_findSelectionEnd].
|
111 | | int _selectionEnd;
|
112 | |
|
113 | | /// How many levels deep inside a constant context the visitor currently is.
|
114 | | int _constNesting = 0;
|
115 | |
|
116 | | /// Whether we are currently fixing a typedef declaration.
|
117 | | ///
|
118 | | /// Set to `true` while traversing the parameters of a typedef being converted
|
119 | | /// to the new syntax. The new syntax does not allow `int foo()` as a
|
120 | | /// parameter declaration, so it needs to be converted to `int Function() foo`
|
121 | | /// as part of the fix.
|
122 | | bool _insideNewTypedefFix = false;
|
123 | |
|
124 | | /// A stack that tracks forcing nested collections to split.
|
125 | | ///
|
126 | | /// Each entry corresponds to a collection currently being visited and the
|
127 | | /// value is whether or not it should be forced to split. Every time a
|
128 | | /// collection is entered, it sets all of the existing elements to `true`
|
129 | | /// then it pushes `false` for itself.
|
130 | | ///
|
131 | | /// When done visiting the elements, it removes its value. If it was set to
|
132 | | /// `true`, we know we visited a nested collection so we force this one to
|
133 | | /// split.
|
134 | | final List<bool> _collectionSplits = [];
|
135 | |
|
136 | | /// The stack of current rules for handling parameter metadata.
|
137 | | ///
|
138 | | /// Each time a parameter (or type parameter) list is begun, a single rule
|
139 | | /// for all of the metadata annotations on parameters in that list is pushed
|
140 | | /// onto this stack. We reuse this rule for all annotations so that they split
|
141 | | /// in unison.
|
142 | | final List<MetadataRule> _metadataRules = [];
|
143 | |
|
144 | | /// The mapping for blocks that are managed by the argument list that contains
|
145 | | /// them.
|
146 | | ///
|
147 | | /// When a block expression, such as a collection literal or a multiline
|
148 | | /// string, appears inside an [ArgumentSublist], the argument list provides a
|
149 | | /// rule for the body to split to ensure that all blocks split in unison. It
|
150 | | /// also tracks the chunk before the argument that determines whether or not
|
151 | | /// the block body is indented like an expression or a statement.
|
152 | | ///
|
153 | | /// Before a block argument is visited, [ArgumentSublist] binds itself to the
|
154 | | /// beginning token of each block it controls. When we later visit that
|
155 | | /// literal, we use the token to find that association.
|
156 | | final Map<Token, ArgumentSublist> _blockArgumentLists = {};
|
157 | |
|
158 | | /// Initialize a newly created visitor to write source code representing
|
159 | | /// the visited nodes to the given [writer].
|
160 | 3 | SourceVisitor(this._formatter, this._lineInfo, this._source) {
|
161 | 12 | builder = new ChunkBuilder(_formatter, _source);
|
162 | | }
|
163 | |
|
164 | | /// Runs the visitor on [node], formatting its contents.
|
165 | | ///
|
166 | | /// Returns a [SourceCode] containing the resulting formatted source and
|
167 | | /// updated selection, if any.
|
168 | | ///
|
169 | | /// This is the only method that should be called externally. Everything else
|
170 | | /// is effectively private.
|
171 | 3 | SourceCode run(AstNode node) {
|
172 | 3 | visit(node);
|
173 | |
|
174 | | // Output trailing comments.
|
175 | 9 | writePrecedingCommentsAndNewlines(node.endToken.next);
|
176 | |
|
177 | 6 | assert(_constNesting == 0, "Should have exited all const contexts.");
|
178 | |
|
179 | | // Finish writing and return the complete result.
|
180 | 6 | return builder.end();
|
181 | | }
|
182 | |
|
183 | 1 | visitAdjacentStrings(AdjacentStrings node) {
|
184 | 2 | builder.startSpan();
|
185 | 2 | builder.startRule();
|
186 | 3 | visitNodes(node.strings, between: splitOrNewline);
|
187 | 2 | builder.endRule();
|
188 | 2 | builder.endSpan();
|
189 | | }
|
190 | |
|
191 | 2 | visitAnnotation(Annotation node) {
|
192 | 4 | token(node.atSign);
|
193 | 4 | visit(node.name);
|
194 | 4 | token(node.period);
|
195 | 4 | visit(node.constructorName);
|
196 | |
|
197 | | // Metadata annotations are always const contexts.
|
198 | 4 | _constNesting++;
|
199 | 4 | visit(node.arguments);
|
200 | 4 | _constNesting--;
|
201 | | }
|
202 | |
|
203 | | /// Visits an argument list.
|
204 | | ///
|
205 | | /// This is a bit complex to handle the rules for formatting positional and
|
206 | | /// named arguments. The goals, in rough order of descending priority are:
|
207 | | ///
|
208 | | /// 1. Keep everything on the first line.
|
209 | | /// 2. Keep the named arguments together on the next line.
|
210 | | /// 3. Keep everything together on the second line.
|
211 | | /// 4. Split between one or more positional arguments, trying to keep as many
|
212 | | /// on earlier lines as possible.
|
213 | | /// 5. Split the named arguments each onto their own line.
|
214 | 3 | visitArgumentList(ArgumentList node, {bool nestExpression: true}) {
|
215 | | // Corner case: handle empty argument lists.
|
216 | 6 | if (node.arguments.isEmpty) {
|
217 | 4 | token(node.leftParenthesis);
|
218 | |
|
219 | | // If there is a comment inside the parens, do allow splitting before it.
|
220 | 5 | if (node.rightParenthesis.precedingComments != null) soloZeroSplit();
|
221 | |
|
222 | 4 | token(node.rightParenthesis);
|
223 | | return;
|
224 | | }
|
225 | |
|
226 | | // If the argument list has a trailing comma, format it like a collection
|
227 | | // literal where each argument goes on its own line, they are indented +2,
|
228 | | // and the ")" ends up on its own line.
|
229 | 18 | if (node.arguments.last.endToken.next.type == TokenType.COMMA) {
|
230 | 1 | _visitCollectionLiteral(
|
231 | 3 | null, node.leftParenthesis, node.arguments, node.rightParenthesis);
|
232 | | return;
|
233 | | }
|
234 | |
|
235 | 4 | if (nestExpression) builder.nestExpression();
|
236 | 6 | new ArgumentListVisitor(this, node).visit();
|
237 | 4 | if (nestExpression) builder.unnest();
|
238 | | }
|
239 | |
|
240 | 1 | visitAsExpression(AsExpression node) {
|
241 | 2 | builder.startSpan();
|
242 | 2 | builder.nestExpression();
|
243 | 2 | visit(node.expression);
|
244 | 1 | soloSplit();
|
245 | 2 | token(node.asOperator);
|
246 | 1 | space();
|
247 | 2 | visit(node.type);
|
248 | 2 | builder.unnest();
|
249 | 2 | builder.endSpan();
|
250 | | }
|
251 | |
|
252 | 1 | visitAssertInitializer(AssertInitializer node) {
|
253 | 2 | token(node.assertKeyword);
|
254 | |
|
255 | 2 | var arguments = <Expression>[node.condition];
|
256 | 1 | if (node.message != null) arguments.add(node.message);
|
257 | |
|
258 | 2 | builder.nestExpression();
|
259 | 1 | var visitor = new ArgumentListVisitor.forArguments(
|
260 | 2 | this, node.leftParenthesis, node.rightParenthesis, arguments);
|
261 | 1 | visitor.visit();
|
262 | 2 | builder.unnest();
|
263 | | }
|
264 | |
|
265 | 1 | visitAssertStatement(AssertStatement node) {
|
266 | 2 | _simpleStatement(node, () {
|
267 | 2 | token(node.assertKeyword);
|
268 | |
|
269 | 2 | var arguments = [node.condition];
|
270 | 3 | if (node.message != null) arguments.add(node.message);
|
271 | |
|
272 | 1 | var visitor = new ArgumentListVisitor.forArguments(
|
273 | 2 | this, node.leftParenthesis, node.rightParenthesis, arguments);
|
274 | 1 | visitor.visit();
|
275 | | });
|
276 | | }
|
277 | |
|
278 | 1 | visitAssignmentExpression(AssignmentExpression node) {
|
279 | 2 | builder.nestExpression();
|
280 | |
|
281 | 2 | visit(node.leftHandSide);
|
282 | 3 | _visitAssignment(node.operator, node.rightHandSide);
|
283 | |
|
284 | 2 | builder.unnest();
|
285 | | }
|
286 | |
|
287 | 1 | visitAwaitExpression(AwaitExpression node) {
|
288 | 2 | token(node.awaitKeyword);
|
289 | 1 | space();
|
290 | 2 | visit(node.expression);
|
291 | | }
|
292 | |
|
293 | 1 | visitBinaryExpression(BinaryExpression node) {
|
294 | 2 | builder.startSpan();
|
295 | |
|
296 | | // If a binary operator sequence appears immediately after a `=>`, don't
|
297 | | // add an extra level of nesting. Instead, let the subsequent operands line
|
298 | | // up with the first, as in:
|
299 | | //
|
300 | | // method() =>
|
301 | | // argument &&
|
302 | | // argument &&
|
303 | | // argument;
|
304 | 2 | var isArrowBody = node.parent is ExpressionFunctionBody;
|
305 | 2 | if (!isArrowBody) builder.nestExpression();
|
306 | |
|
307 | | // Start lazily so we don't force the operator to split if a line comment
|
308 | | // appears before the first operand.
|
309 | 2 | builder.startLazyRule();
|
310 | |
|
311 | | // Flatten out a tree/chain of the same precedence. If we split on this
|
312 | | // precedence level, we will break all of them.
|
313 | 3 | var precedence = node.operator.type.precedence;
|
314 | |
|
315 | 1 | traverse(Expression e) {
|
316 | 5 | if (e is BinaryExpression && e.operator.type.precedence == precedence) {
|
317 | 2 | traverse(e.leftOperand);
|
318 | |
|
319 | 1 | space();
|
320 | 2 | token(e.operator);
|
321 | |
|
322 | 1 | split();
|
323 | 2 | traverse(e.rightOperand);
|
324 | | } else {
|
325 | 1 | visit(e);
|
326 | | }
|
327 | | }
|
328 | |
|
329 | | // Blocks as operands to infix operators should always nest like regular
|
330 | | // operands. (Granted, this case is exceedingly rare in real code.)
|
331 | 2 | builder.startBlockArgumentNesting();
|
332 | |
|
333 | 1 | traverse(node);
|
334 | |
|
335 | 2 | builder.endBlockArgumentNesting();
|
336 | |
|
337 | 2 | if (!isArrowBody) builder.unnest();
|
338 | 2 | builder.endSpan();
|
339 | 2 | builder.endRule();
|
340 | | }
|
341 | |
|
342 | 2 | visitBlock(Block node) {
|
343 | | // Treat empty blocks specially. In most cases, they are not allowed to
|
344 | | // split. However, an empty block as the then statement of an if with an
|
345 | | // else is always split.
|
346 | 4 | if (node.statements.isEmpty &&
|
347 | 4 | node.rightBracket.precedingComments == null) {
|
348 | 4 | token(node.leftBracket);
|
349 | |
|
350 | | // Force a split when used as the then body of an if with an else:
|
351 | | //
|
352 | | // if (condition) {
|
353 | | // } else ...
|
354 | 4 | if (node.parent is IfStatement) {
|
355 | 1 | var ifStatement = node.parent as IfStatement;
|
356 | 1 | if (ifStatement.elseStatement != null &&
|
357 | 2 | ifStatement.thenStatement == node) {
|
358 | 1 | newline();
|
359 | | }
|
360 | | }
|
361 | |
|
362 | 4 | token(node.rightBracket);
|
363 | | return;
|
364 | | }
|
365 | |
|
366 | | // If the block is a function body, it may get expression-level indentation,
|
367 | | // so handle it specially. Otherwise, just bump the indentation and keep it
|
368 | | // in the current block.
|
369 | 4 | if (node.parent is BlockFunctionBody) {
|
370 | 4 | _startLiteralBody(node.leftBracket);
|
371 | | } else {
|
372 | 4 | _beginBody(node.leftBracket);
|
373 | | }
|
374 | |
|
375 | | var needsDouble = true;
|
376 | 4 | for (var statement in node.statements) {
|
377 | | if (needsDouble) {
|
378 | 2 | twoNewlines();
|
379 | | } else {
|
380 | 2 | oneOrTwoNewlines();
|
381 | | }
|
382 | |
|
383 | 2 | visit(statement);
|
384 | |
|
385 | | needsDouble = false;
|
386 | 2 | if (statement is FunctionDeclarationStatement) {
|
387 | | // Add a blank line after non-empty block functions.
|
388 | 3 | var body = statement.functionDeclaration.functionExpression.body;
|
389 | 1 | if (body is BlockFunctionBody) {
|
390 | 3 | needsDouble = body.block.statements.isNotEmpty;
|
391 | | }
|
392 | | }
|
393 | | }
|
394 | |
|
395 | 6 | if (node.statements.isNotEmpty) newline();
|
396 | |
|
397 | 4 | if (node.parent is BlockFunctionBody) {
|
398 | 4 | _endLiteralBody(node.rightBracket,
|
399 | 4 | forceSplit: node.statements.isNotEmpty);
|
400 | | } else {
|
401 | 4 | _endBody(node.rightBracket);
|
402 | | }
|
403 | | }
|
404 | |
|
405 | 2 | visitBlockFunctionBody(BlockFunctionBody node) {
|
406 | | // Space after the parameter list.
|
407 | 2 | space();
|
408 | |
|
409 | | // The "async" or "sync" keyword.
|
410 | 4 | token(node.keyword);
|
411 | |
|
412 | | // The "*" in "async*" or "sync*".
|
413 | 4 | token(node.star);
|
414 | 3 | if (node.keyword != null) space();
|
415 | |
|
416 | 4 | visit(node.block);
|
417 | | }
|
418 | |
|
419 | 1 | visitBooleanLiteral(BooleanLiteral node) {
|
420 | 2 | token(node.literal);
|
421 | | }
|
422 | |
|
423 | 1 | visitBreakStatement(BreakStatement node) {
|
424 | 2 | _simpleStatement(node, () {
|
425 | 2 | token(node.breakKeyword);
|
426 | 3 | visit(node.label, before: space);
|
427 | | });
|
428 | | }
|
429 | |
|
430 | 1 | visitCascadeExpression(CascadeExpression node) {
|
431 | | var splitIfOperandsSplit =
|
432 | 5 | node.cascadeSections.length > 1 || _isCollectionLike(node.target);
|
433 | |
|
434 | | // If the cascade sections have consistent names they can be broken
|
435 | | // normally otherwise they always get their own line.
|
436 | | if (splitIfOperandsSplit) {
|
437 | 2 | builder.startLazyRule(
|
438 | 3 | _allowInlineCascade(node) ? new Rule() : new Rule.hard());
|
439 | | }
|
440 | |
|
441 | | // If the target of the cascade is a method call (or chain of them), we
|
442 | | // treat the nesting specially. Normally, you would end up with:
|
443 | | //
|
444 | | // receiver
|
445 | | // .method()
|
446 | | // .method()
|
447 | | // ..cascade()
|
448 | | // ..cascade();
|
449 | | //
|
450 | | // This is logical, since the method chain is an operand of the cascade
|
451 | | // expression, so it's more deeply nested. But it looks wrong, so we leave
|
452 | | // the method chain's nesting active until after the cascade sections to
|
453 | | // force the *cascades* to be deeper because it looks better:
|
454 | | //
|
455 | | // receiver
|
456 | | // .method()
|
457 | | // .method()
|
458 | | // ..cascade()
|
459 | | // ..cascade();
|
460 | 2 | if (node.target is MethodInvocation) {
|
461 | 3 | new CallChainVisitor(this, node.target).visit(unnest: false);
|
462 | | } else {
|
463 | 2 | visit(node.target);
|
464 | | }
|
465 | |
|
466 | 2 | builder.nestExpression(indent: Indent.cascade, now: true);
|
467 | 2 | builder.startBlockArgumentNesting();
|
468 | |
|
469 | | // If the cascade section shouldn't cause the cascade to split, end the
|
470 | | // rule early so it isn't affected by it.
|
471 | | if (!splitIfOperandsSplit) {
|
472 | 1 | builder
|
473 | 3 | .startRule(_allowInlineCascade(node) ? new Rule() : new Rule.hard());
|
474 | | }
|
475 | |
|
476 | 1 | zeroSplit();
|
477 | |
|
478 | | if (!splitIfOperandsSplit) {
|
479 | 2 | builder.endRule();
|
480 | | }
|
481 | |
|
482 | 3 | visitNodes(node.cascadeSections, between: zeroSplit);
|
483 | |
|
484 | | if (splitIfOperandsSplit) {
|
485 | 2 | builder.endRule();
|
486 | | }
|
487 | |
|
488 | 2 | builder.endBlockArgumentNesting();
|
489 | 2 | builder.unnest();
|
490 | |
|
491 | 4 | if (node.target is MethodInvocation) builder.unnest();
|
492 | | }
|
493 | |
|
494 | | /// Whether [expression] is a collection literal, or a call with a trailing
|
495 | | /// comma in an argument list.
|
496 | | ///
|
497 | | /// In that case, when the expression is a target of a cascade, we don't
|
498 | | /// force a split before the ".." as eagerly to avoid ugly results like:
|
499 | | ///
|
500 | | /// [
|
501 | | /// 1,
|
502 | | /// 2,
|
503 | | /// ]..addAll(numbers);
|
504 | 1 | bool _isCollectionLike(Expression expression) {
|
505 | 1 | if (expression is ListLiteral) return false;
|
506 | 1 | if (expression is MapLiteral) return false;
|
507 | |
|
508 | | // If the target is a call with a trailing comma in the argument list,
|
509 | | // treat it like a collection literal.
|
510 | | ArgumentList arguments;
|
511 | 1 | if (expression is InvocationExpression) {
|
512 | 1 | arguments = expression.argumentList;
|
513 | 1 | } else if (expression is InstanceCreationExpression) {
|
514 | 1 | arguments = expression.argumentList;
|
515 | | }
|
516 | |
|
517 | | // TODO(rnystrom): Do we want to allow an invocation where the last
|
518 | | // argument is a collection literal? Like:
|
519 | | //
|
520 | | // foo(argument, [
|
521 | | // element
|
522 | | // ])..cascade();
|
523 | |
|
524 | | return arguments == null ||
|
525 | 2 | arguments.arguments.isEmpty ||
|
526 | 6 | arguments.arguments.last.endToken.next.type != TokenType.COMMA;
|
527 | | }
|
528 | |
|
529 | | /// Whether a cascade should be allowed to be inline as opposed to one
|
530 | | /// expression per line.
|
531 | 1 | bool _allowInlineCascade(CascadeExpression node) {
|
532 | | // If the receiver is an expression that makes the cascade's very low
|
533 | | // precedence confusing, force it to split. For example:
|
534 | | //
|
535 | | // a ? b : c..d();
|
536 | | //
|
537 | | // Here, the cascade is applied to the result of the conditional, not "c".
|
538 | 2 | if (node.target is ConditionalExpression) return false;
|
539 | 2 | if (node.target is BinaryExpression) return false;
|
540 | 2 | if (node.target is PrefixExpression) return false;
|
541 | 2 | if (node.target is AwaitExpression) return false;
|
542 | |
|
543 | 3 | if (node.cascadeSections.length < 2) return true;
|
544 | |
|
545 | | var name;
|
546 | | // We could be more forgiving about what constitutes sections with
|
547 | | // consistent names but for now we require all sections to have the same
|
548 | | // method name.
|
549 | 2 | for (var expression in node.cascadeSections) {
|
550 | 1 | if (expression is MethodInvocation) {
|
551 | | if (name == null) {
|
552 | 2 | name = expression.methodName.name;
|
553 | 3 | } else if (name != expression.methodName.name) {
|
554 | | return false;
|
555 | | }
|
556 | | } else {
|
557 | | return false;
|
558 | | }
|
559 | | }
|
560 | | return true;
|
561 | | }
|
562 | |
|
563 | 1 | visitCatchClause(CatchClause node) {
|
564 | 3 | token(node.onKeyword, after: space);
|
565 | 2 | visit(node.exceptionType);
|
566 | |
|
567 | 1 | if (node.catchKeyword != null) {
|
568 | 1 | if (node.exceptionType != null) {
|
569 | 1 | space();
|
570 | | }
|
571 | 2 | token(node.catchKeyword);
|
572 | 1 | space();
|
573 | 2 | token(node.leftParenthesis);
|
574 | 2 | visit(node.exceptionParameter);
|
575 | 3 | token(node.comma, after: space);
|
576 | 2 | visit(node.stackTraceParameter);
|
577 | 2 | token(node.rightParenthesis);
|
578 | 1 | space();
|
579 | | } else {
|
580 | 0 | space();
|
581 | | }
|
582 | 2 | visit(node.body);
|
583 | | }
|
584 | |
|
585 | 1 | visitClassDeclaration(ClassDeclaration node) {
|
586 | 2 | visitMetadata(node.metadata);
|
587 | |
|
588 | 2 | builder.nestExpression();
|
589 | 2 | modifier(node.abstractKeyword);
|
590 | 2 | token(node.classKeyword);
|
591 | 1 | space();
|
592 | 2 | visit(node.name);
|
593 | 2 | visit(node.typeParameters);
|
594 | 2 | visit(node.extendsClause);
|
595 | |
|
596 | 3 | builder.startRule(new CombinatorRule());
|
597 | 2 | visit(node.withClause);
|
598 | 2 | visit(node.implementsClause);
|
599 | 2 | builder.endRule();
|
600 | |
|
601 | 3 | visit(node.nativeClause, before: space);
|
602 | 1 | space();
|
603 | |
|
604 | 2 | builder.unnest();
|
605 | 2 | _beginBody(node.leftBracket);
|
606 | 2 | _visitMembers(node.members);
|
607 | 2 | _endBody(node.rightBracket);
|
608 | | }
|
609 | |
|
610 | 1 | visitClassTypeAlias(ClassTypeAlias node) {
|
611 | 2 | visitMetadata(node.metadata);
|
612 | |
|
613 | 2 | _simpleStatement(node, () {
|
614 | 2 | modifier(node.abstractKeyword);
|
615 | 2 | token(node.typedefKeyword);
|
616 | 1 | space();
|
617 | 2 | visit(node.name);
|
618 | 2 | visit(node.typeParameters);
|
619 | 1 | space();
|
620 | 2 | token(node.equals);
|
621 | 1 | space();
|
622 | |
|
623 | 2 | visit(node.superclass);
|
624 | |
|
625 | 3 | builder.startRule(new CombinatorRule());
|
626 | 2 | visit(node.withClause);
|
627 | 2 | visit(node.implementsClause);
|
628 | 2 | builder.endRule();
|
629 | | });
|
630 | | }
|
631 | |
|
632 | 0 | visitComment(Comment node) => null;
|
633 | |
|
634 | 0 | visitCommentReference(CommentReference node) => null;
|
635 | |
|
636 | 3 | visitCompilationUnit(CompilationUnit node) {
|
637 | 6 | visit(node.scriptTag);
|
638 | |
|
639 | | // Put a blank line between the library tag and the other directives.
|
640 | 3 | Iterable<Directive> directives = node.directives;
|
641 | 5 | if (directives.isNotEmpty && directives.first is LibraryDirective) {
|
642 | 2 | visit(directives.first);
|
643 | 1 | twoNewlines();
|
644 | |
|
645 | 1 | directives = directives.skip(1);
|
646 | | }
|
647 | |
|
648 | 6 | visitNodes(directives, between: oneOrTwoNewlines);
|
649 | |
|
650 | | var needsDouble = true;
|
651 | 6 | for (var declaration in node.declarations) {
|
652 | | // Add a blank line before classes.
|
653 | 3 | if (declaration is ClassDeclaration) needsDouble = true;
|
654 | |
|
655 | | if (needsDouble) {
|
656 | 3 | twoNewlines();
|
657 | | } else {
|
658 | | // Variables and arrow-bodied members can be more tightly packed if
|
659 | | // the user wants to group things together.
|
660 | 1 | oneOrTwoNewlines();
|
661 | | }
|
662 | |
|
663 | 3 | visit(declaration);
|
664 | |
|
665 | | needsDouble = false;
|
666 | 3 | if (declaration is ClassDeclaration) {
|
667 | | // Add a blank line after classes.
|
668 | | needsDouble = true;
|
669 | 3 | } else if (declaration is FunctionDeclaration) {
|
670 | | // Add a blank line after non-empty block functions.
|
671 | 6 | var body = declaration.functionExpression.body;
|
672 | 3 | if (body is BlockFunctionBody) {
|
673 | 6 | needsDouble = body.block.statements.isNotEmpty;
|
674 | | }
|
675 | | }
|
676 | | }
|
677 | | }
|
678 | |
|
679 | 1 | visitConditionalExpression(ConditionalExpression node) {
|
680 | 2 | builder.nestExpression();
|
681 | |
|
682 | | // Start lazily so we don't force the operator to split if a line comment
|
683 | | // appears before the first operand. If we split after one clause in a
|
684 | | // conditional, always split after both.
|
685 | 2 | builder.startLazyRule();
|
686 | 2 | visit(node.condition);
|
687 | |
|
688 | | // Push any block arguments all the way past the leading "?" and ":".
|
689 | 2 | builder.nestExpression(indent: Indent.block, now: true);
|
690 | 2 | builder.startBlockArgumentNesting();
|
691 | 2 | builder.unnest();
|
692 | |
|
693 | 2 | builder.startSpan();
|
694 | |
|
695 | 1 | split();
|
696 | 2 | token(node.question);
|
697 | 1 | space();
|
698 | 2 | builder.nestExpression();
|
699 | 2 | visit(node.thenExpression);
|
700 | 2 | builder.unnest();
|
701 | |
|
702 | 1 | split();
|
703 | 2 | token(node.colon);
|
704 | 1 | space();
|
705 | 2 | visit(node.elseExpression);
|
706 | |
|
707 | 2 | builder.endRule();
|
708 | 2 | builder.endSpan();
|
709 | 2 | builder.endBlockArgumentNesting();
|
710 | 2 | builder.unnest();
|
711 | | }
|
712 | |
|
713 | 1 | visitConfiguration(Configuration node) {
|
714 | 2 | token(node.ifKeyword);
|
715 | 1 | space();
|
716 | 2 | token(node.leftParenthesis);
|
717 | 2 | visit(node.name);
|
718 | |
|
719 | 1 | if (node.equalToken != null) {
|
720 | 2 | builder.nestExpression();
|
721 | 1 | space();
|
722 | 2 | token(node.equalToken);
|
723 | 1 | soloSplit();
|
724 | 2 | visit(node.value);
|
725 | 2 | builder.unnest();
|
726 | | }
|
727 | |
|
728 | 2 | token(node.rightParenthesis);
|
729 | 1 | space();
|
730 | 2 | visit(node.uri);
|
731 | | }
|
732 | |
|
733 | 1 | visitConstructorDeclaration(ConstructorDeclaration node) {
|
734 | 2 | visitMetadata(node.metadata);
|
735 | |
|
736 | 2 | modifier(node.externalKeyword);
|
737 | 2 | modifier(node.constKeyword);
|
738 | 2 | modifier(node.factoryKeyword);
|
739 | 2 | visit(node.returnType);
|
740 | 2 | token(node.period);
|
741 | 2 | visit(node.name);
|
742 | |
|
743 | | // Make the rule for the ":" span both the preceding parameter list and
|
744 | | // the entire initialization list. This ensures that we split before the
|
745 | | // ":" if the parameters and initialization list don't all fit on one line.
|
746 | 2 | builder.startRule();
|
747 | |
|
748 | | // If the redirecting constructor happens to wrap, we want to make sure
|
749 | | // the parameter list gets more deeply indented.
|
750 | 3 | if (node.redirectedConstructor != null) builder.nestExpression();
|
751 | |
|
752 | 4 | _visitBody(null, node.parameters, node.body, () {
|
753 | | // Check for redirects or initializer lists.
|
754 | 1 | if (node.redirectedConstructor != null) {
|
755 | 1 | _visitConstructorRedirects(node);
|
756 | 2 | builder.unnest();
|
757 | 2 | } else if (node.initializers.isNotEmpty) {
|
758 | 1 | _visitConstructorInitializers(node);
|
759 | | }
|
760 | | });
|
761 | | }
|
762 | |
|
763 | 1 | void _visitConstructorRedirects(ConstructorDeclaration node) {
|
764 | 3 | token(node.separator /* = */, before: space);
|
765 | 1 | soloSplit();
|
766 | 2 | visitCommaSeparatedNodes(node.initializers);
|
767 | 2 | visit(node.redirectedConstructor);
|
768 | | }
|
769 | |
|
770 | 1 | void _visitConstructorInitializers(ConstructorDeclaration node) {
|
771 | 3 | var hasTrailingComma = node.parameters.parameters.isNotEmpty &&
|
772 | 7 | node.parameters.parameters.last.endToken.next.type == TokenType.COMMA;
|
773 | |
|
774 | | if (hasTrailingComma) {
|
775 | | // Since the ")", "])", or "})" on the preceding line doesn't take up
|
776 | | // much space, it looks weird to move the ":" onto it's own line. Instead,
|
777 | | // keep it and the first initializer on the current line but add enough
|
778 | | // space before it to line it up with any subsequent initializers.
|
779 | | //
|
780 | | // Foo(
|
781 | | // parameter,
|
782 | | // ) : field = value,
|
783 | | // super();
|
784 | 1 | space();
|
785 | 3 | if (node.initializers.length > 1) {
|
786 | 5 | _writeText(node.parameters.parameters.last.isOptional ? " " : " ",
|
787 | 2 | node.separator.offset);
|
788 | | }
|
789 | |
|
790 | | // ":".
|
791 | 2 | token(node.separator);
|
792 | 1 | space();
|
793 | |
|
794 | 2 | builder.indent(6);
|
795 | | } else {
|
796 | | // Shift the itself ":" forward.
|
797 | 2 | builder.indent(Indent.constructorInitializer);
|
798 | |
|
799 | | // If the parameters or initializers split, put the ":" on its own line.
|
800 | 1 | split();
|
801 | |
|
802 | | // ":".
|
803 | 2 | token(node.separator);
|
804 | 1 | space();
|
805 | |
|
806 | | // Try to line up the initializers with the first one that follows the ":":
|
807 | | //
|
808 | | // Foo(notTrailing)
|
809 | | // : initializer = value,
|
810 | | // super(); // +2 from previous line.
|
811 | | //
|
812 | | // Foo(
|
813 | | // trailing,
|
814 | | // ) : initializer = value,
|
815 | | // super(); // +4 from previous line.
|
816 | | //
|
817 | | // This doesn't work if there is a trailing comma in an optional parameter,
|
818 | | // but we don't want to do a weird +5 alignment:
|
819 | | //
|
820 | | // Foo({
|
821 | | // trailing,
|
822 | | // }) : initializer = value,
|
823 | | // super(); // Doesn't quite line up. :(
|
824 | 2 | builder.indent(2);
|
825 | | }
|
826 | |
|
827 | 4 | for (var i = 0; i < node.initializers.length; i++) {
|
828 | 1 | if (i > 0) {
|
829 | | // Preceding comma.
|
830 | 5 | token(node.initializers[i].beginToken.previous);
|
831 | 1 | newline();
|
832 | | }
|
833 | |
|
834 | 3 | node.initializers[i].accept(this);
|
835 | | }
|
836 | |
|
837 | 2 | builder.unindent();
|
838 | 2 | if (!hasTrailingComma) builder.unindent();
|
839 | |
|
840 | | // End the rule for ":" after all of the initializers.
|
841 | 2 | builder.endRule();
|
842 | | }
|
843 | |
|
844 | 1 | visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
|
845 | 2 | builder.nestExpression();
|
846 | |
|
847 | 2 | token(node.thisKeyword);
|
848 | 2 | token(node.period);
|
849 | 2 | visit(node.fieldName);
|
850 | |
|
851 | 3 | _visitAssignment(node.equals, node.expression);
|
852 | |
|
853 | 2 | builder.unnest();
|
854 | | }
|
855 | |
|
856 | 2 | visitConstructorName(ConstructorName node) {
|
857 | 4 | visit(node.type);
|
858 | 4 | token(node.period);
|
859 | 4 | visit(node.name);
|
860 | | }
|
861 | |
|
862 | 1 | visitContinueStatement(ContinueStatement node) {
|
863 | 2 | _simpleStatement(node, () {
|
864 | 2 | token(node.continueKeyword);
|
865 | 3 | visit(node.label, before: space);
|
866 | | });
|
867 | | }
|
868 | |
|
869 | 1 | visitDeclaredIdentifier(DeclaredIdentifier node) {
|
870 | 2 | modifier(node.keyword);
|
871 | 3 | visit(node.type, after: space);
|
872 | 2 | visit(node.identifier);
|
873 | | }
|
874 | |
|
875 | 2 | visitDefaultFormalParameter(DefaultFormalParameter node) {
|
876 | 4 | visit(node.parameter);
|
877 | 2 | if (node.separator != null) {
|
878 | 4 | builder.startSpan();
|
879 | 4 | builder.nestExpression();
|
880 | |
|
881 | 6 | if (_formatter.fixes.contains(StyleFix.namedDefaultSeparator)) {
|
882 | | // Change the separator to "=".
|
883 | 1 | space();
|
884 | 2 | writePrecedingCommentsAndNewlines(node.separator);
|
885 | 3 | _writeText("=", node.separator.offset);
|
886 | | } else {
|
887 | | // The '=' separator is preceded by a space, ":" is not.
|
888 | 4 | if (node.separator.type == TokenType.EQ) space();
|
889 | 2 | token(node.separator);
|
890 | | }
|
891 | |
|
892 | 6 | soloSplit(_assignmentCost(node.defaultValue));
|
893 | 4 | visit(node.defaultValue);
|
894 | |
|
895 | 4 | builder.unnest();
|
896 | 4 | builder.endSpan();
|
897 | | }
|
898 | | }
|
899 | |
|
900 | 1 | visitDoStatement(DoStatement node) {
|
901 | 2 | builder.nestExpression();
|
902 | 2 | token(node.doKeyword);
|
903 | 1 | space();
|
904 | 2 | builder.unnest(now: false);
|
905 | 2 | visit(node.body);
|
906 | |
|
907 | 2 | builder.nestExpression();
|
908 | 1 | space();
|
909 | 2 | token(node.whileKeyword);
|
910 | 1 | space();
|
911 | 2 | token(node.leftParenthesis);
|
912 | 1 | soloZeroSplit();
|
913 | 2 | visit(node.condition);
|
914 | 2 | token(node.rightParenthesis);
|
915 | 2 | token(node.semicolon);
|
916 | 2 | builder.unnest();
|
917 | | }
|
918 | |
|
919 | 1 | visitDottedName(DottedName node) {
|
920 | 2 | for (var component in node.components) {
|
921 | | // Write the preceding ".".
|
922 | 3 | if (component != node.components.first) {
|
923 | 3 | token(component.beginToken.previous);
|
924 | | }
|
925 | |
|
926 | 1 | visit(component);
|
927 | | }
|
928 | | }
|
929 | |
|
930 | 1 | visitDoubleLiteral(DoubleLiteral node) {
|
931 | 2 | token(node.literal);
|
932 | | }
|
933 | |
|
934 | 1 | visitEmptyFunctionBody(EmptyFunctionBody node) {
|
935 | 2 | token(node.semicolon);
|
936 | | }
|
937 | |
|
938 | 1 | visitEmptyStatement(EmptyStatement node) {
|
939 | 2 | token(node.semicolon);
|
940 | | }
|
941 | |
|
942 | 1 | visitEnumConstantDeclaration(EnumConstantDeclaration node) {
|
943 | 2 | visitMetadata(node.metadata);
|
944 | 2 | visit(node.name);
|
945 | | }
|
946 | |
|
947 | 1 | visitEnumDeclaration(EnumDeclaration node) {
|
948 | 2 | visitMetadata(node.metadata);
|
949 | |
|
950 | 2 | token(node.enumKeyword);
|
951 | 1 | space();
|
952 | 2 | visit(node.name);
|
953 | 1 | space();
|
954 | |
|
955 | 2 | _beginBody(node.leftBracket, space: true);
|
956 | 3 | visitCommaSeparatedNodes(node.constants, between: splitOrTwoNewlines);
|
957 | |
|
958 | | // If there is a trailing comma, always force the constants to split.
|
959 | 6 | if (node.constants.last.endToken.next.type == TokenType.COMMA) {
|
960 | 2 | builder.forceRules();
|
961 | | }
|
962 | |
|
963 | 2 | _endBody(node.rightBracket, space: true);
|
964 | | }
|
965 | |
|
966 | 1 | visitExportDirective(ExportDirective node) {
|
967 | 1 | _visitDirectiveMetadata(node);
|
968 | 2 | _simpleStatement(node, () {
|
969 | 2 | token(node.keyword);
|
970 | 1 | space();
|
971 | 2 | visit(node.uri);
|
972 | |
|
973 | 2 | _visitConfigurations(node.configurations);
|
974 | |
|
975 | 3 | builder.startRule(new CombinatorRule());
|
976 | 2 | visitNodes(node.combinators);
|
977 | 2 | builder.endRule();
|
978 | | });
|
979 | | }
|
980 | |
|
981 | 3 | visitExpressionFunctionBody(ExpressionFunctionBody node) {
|
982 | | // Space after the parameter list.
|
983 | 3 | space();
|
984 | |
|
985 | | // The "async" or "sync" keyword.
|
986 | 9 | token(node.keyword, after: space);
|
987 | |
|
988 | | // Try to keep the "(...) => " with the start of the body for anonymous
|
989 | | // functions.
|
990 | 7 | if (_isInLambda(node)) builder.startSpan();
|
991 | |
|
992 | 6 | token(node.functionDefinition); // "=>".
|
993 | |
|
994 | | // Split after the "=>", using the rule created before the parameters
|
995 | | // by _visitBody().
|
996 | 3 | split();
|
997 | |
|
998 | | // If the body is a binary operator expression, then we want to force the
|
999 | | // split at `=>` if the operators split. See visitBinaryExpression().
|
1000 | 12 | if (node.expression is! BinaryExpression) builder.endRule();
|
1001 | |
|
1002 | 7 | if (_isInLambda(node)) builder.endSpan();
|
1003 | |
|
1004 | 6 | builder.startBlockArgumentNesting();
|
1005 | 6 | builder.startSpan();
|
1006 | 6 | visit(node.expression);
|
1007 | 6 | builder.endSpan();
|
1008 | 6 | builder.endBlockArgumentNesting();
|
1009 | |
|
1010 | 8 | if (node.expression is BinaryExpression) builder.endRule();
|
1011 | |
|
1012 | 6 | token(node.semicolon);
|
1013 | | }
|
1014 | |
|
1015 | 2 | visitExpressionStatement(ExpressionStatement node) {
|
1016 | 4 | _simpleStatement(node, () {
|
1017 | 4 | visit(node.expression);
|
1018 | | });
|
1019 | | }
|
1020 | |
|
1021 | 1 | visitExtendsClause(ExtendsClause node) {
|
1022 | 1 | soloSplit();
|
1023 | 2 | token(node.extendsKeyword);
|
1024 | 1 | space();
|
1025 | 2 | visit(node.superclass);
|
1026 | | }
|
1027 | |
|
1028 | 1 | visitFieldDeclaration(FieldDeclaration node) {
|
1029 | 2 | visitMetadata(node.metadata);
|
1030 | |
|
1031 | 2 | _simpleStatement(node, () {
|
1032 | 2 | modifier(node.staticKeyword);
|
1033 | 2 | modifier(node.covariantKeyword);
|
1034 | 2 | visit(node.fields);
|
1035 | | });
|
1036 | | }
|
1037 | |
|
1038 | 1 | visitFieldFormalParameter(FieldFormalParameter node) {
|
1039 | 3 | visitParameterMetadata(node.metadata, () {
|
1040 | 1 | _beginFormalParameter(node);
|
1041 | 3 | token(node.keyword, after: space);
|
1042 | 3 | visit(node.type, after: split);
|
1043 | 2 | token(node.thisKeyword);
|
1044 | 2 | token(node.period);
|
1045 | 2 | visit(node.identifier);
|
1046 | 2 | visit(node.parameters);
|
1047 | 1 | _endFormalParameter(node);
|
1048 | | });
|
1049 | | }
|
1050 | |
|
1051 | 1 | visitForEachStatement(ForEachStatement node) {
|
1052 | 2 | builder.nestExpression();
|
1053 | 3 | token(node.awaitKeyword, after: space);
|
1054 | 2 | token(node.forKeyword);
|
1055 | 1 | space();
|
1056 | 2 | token(node.leftParenthesis);
|
1057 | |
|
1058 | 1 | if (node.loopVariable != null) {
|
1059 | | // TODO(rnystrom): The formatting logic here is slightly different from
|
1060 | | // how parameter metadata is handled and from how variable metadata is
|
1061 | | // handled. I think what it does works better in the context of a for-in
|
1062 | | // loop, but consider trying to unify this with one of the above.
|
1063 | | //
|
1064 | | // Metadata on class and variable declarations is *always* split:
|
1065 | | //
|
1066 | | // @foo
|
1067 | | // class Bar {}
|
1068 | | //
|
1069 | | // Metadata on parameters has some complex logic to handle multiple
|
1070 | | // parameters with metadata. It also indents the parameters farther than
|
1071 | | // the metadata when split:
|
1072 | | //
|
1073 | | // function(
|
1074 | | // @foo(long arg list...)
|
1075 | | // parameter1,
|
1076 | | // @foo
|
1077 | | // parameter2) {}
|
1078 | | //
|
1079 | | // For for-in variables, we allow it to not split, like parameters, but
|
1080 | | // don't indent the variable when it does split:
|
1081 | | //
|
1082 | | // for (
|
1083 | | // @foo
|
1084 | | // @bar
|
1085 | | // var blah in stuff) {}
|
1086 | 2 | builder.startRule();
|
1087 | 5 | visitNodes(node.loopVariable.metadata, between: split, after: split);
|
1088 | 2 | visit(node.loopVariable);
|
1089 | 2 | builder.endRule();
|
1090 | | } else {
|
1091 | 2 | visit(node.identifier);
|
1092 | | }
|
1093 | 1 | soloSplit();
|
1094 | 2 | token(node.inKeyword);
|
1095 | 1 | space();
|
1096 | 2 | visit(node.iterable);
|
1097 | 2 | token(node.rightParenthesis);
|
1098 | 2 | builder.unnest();
|
1099 | |
|
1100 | 2 | _visitLoopBody(node.body);
|
1101 | | }
|
1102 | |
|
1103 | 3 | visitFormalParameterList(FormalParameterList node,
|
1104 | | {bool nestExpression: true}) {
|
1105 | | // Corner case: empty parameter lists.
|
1106 | 6 | if (node.parameters.isEmpty) {
|
1107 | 6 | token(node.leftParenthesis);
|
1108 | |
|
1109 | | // If there is a comment, do allow splitting before it.
|
1110 | 7 | if (node.rightParenthesis.precedingComments != null) soloZeroSplit();
|
1111 | |
|
1112 | 6 | token(node.rightParenthesis);
|
1113 | | return;
|
1114 | | }
|
1115 | |
|
1116 | | // If the parameter list has a trailing comma, format it like a collection
|
1117 | | // literal where each parameter goes on its own line, they are indented +2,
|
1118 | | // and the ")" ends up on its own line.
|
1119 | 12 | if (node.parameters.last.endToken.next.type == TokenType.COMMA) {
|
1120 | 1 | _visitTrailingCommaParameterList(node);
|
1121 | | return;
|
1122 | | }
|
1123 | |
|
1124 | 2 | var requiredParams = node.parameters
|
1125 | 6 | .where((param) => param is! DefaultFormalParameter)
|
1126 | 2 | .toList();
|
1127 | 2 | var optionalParams = node.parameters
|
1128 | 6 | .where((param) => param is DefaultFormalParameter)
|
1129 | 2 | .toList();
|
1130 | |
|
1131 | 2 | if (nestExpression) builder.nestExpression();
|
1132 | 4 | token(node.leftParenthesis);
|
1133 | |
|
1134 | 6 | _metadataRules.add(new MetadataRule());
|
1135 | |
|
1136 | | var rule;
|
1137 | 2 | if (requiredParams.isNotEmpty) {
|
1138 | 2 | rule = new PositionalRule(null, 0, 0);
|
1139 | 6 | _metadataRules.last.bindPositionalRule(rule);
|
1140 | |
|
1141 | 4 | builder.startRule(rule);
|
1142 | 2 | if (_isInLambda(node)) {
|
1143 | | // Don't allow splitting before the first argument (i.e. right after
|
1144 | | // the bare "(" in a lambda. Instead, just stuff a null chunk in there
|
1145 | | // to avoid confusing the arg rule.
|
1146 | 1 | rule.beforeArgument(null);
|
1147 | | } else {
|
1148 | | // Split before the first argument.
|
1149 | 4 | rule.beforeArgument(zeroSplit());
|
1150 | | }
|
1151 | |
|
1152 | 4 | builder.startSpan();
|
1153 | |
|
1154 | 4 | for (var param in requiredParams) {
|
1155 | 2 | visit(param);
|
1156 | |
|
1157 | | // Write the following comma.
|
1158 | 8 | if (param.endToken.next.type == TokenType.COMMA) {
|
1159 | 6 | token(param.endToken.next);
|
1160 | | }
|
1161 | |
|
1162 | 8 | if (param != requiredParams.last) rule.beforeArgument(split());
|
1163 | | }
|
1164 | |
|
1165 | 4 | builder.endSpan();
|
1166 | 4 | builder.endRule();
|
1167 | | }
|
1168 | |
|
1169 | 2 | if (optionalParams.isNotEmpty) {
|
1170 | 2 | var namedRule = new NamedRule(null, 0, 0);
|
1171 | 1 | if (rule != null) rule.setNamedArgsRule(namedRule);
|
1172 | |
|
1173 | 6 | _metadataRules.last.bindNamedRule(namedRule);
|
1174 | |
|
1175 | 4 | builder.startRule(namedRule);
|
1176 | |
|
1177 | | // Make sure multi-line default values are indented.
|
1178 | 4 | builder.startBlockArgumentNesting();
|
1179 | |
|
1180 | 8 | namedRule.beforeArgument(builder.split(space: requiredParams.isNotEmpty));
|
1181 | |
|
1182 | | // "[" or "{" for optional parameters.
|
1183 | 4 | token(node.leftDelimiter);
|
1184 | |
|
1185 | 4 | for (var param in optionalParams) {
|
1186 | 2 | visit(param);
|
1187 | |
|
1188 | | // Write the following comma.
|
1189 | 8 | if (param.endToken.next.type == TokenType.COMMA) {
|
1190 | 6 | token(param.endToken.next);
|
1191 | | }
|
1192 | |
|
1193 | 8 | if (param != optionalParams.last) namedRule.beforeArgument(split());
|
1194 | | }
|
1195 | |
|
1196 | 4 | builder.endBlockArgumentNesting();
|
1197 | 4 | builder.endRule();
|
1198 | |
|
1199 | | // "]" or "}" for optional parameters.
|
1200 | 4 | token(node.rightDelimiter);
|
1201 | | }
|
1202 | |
|
1203 | 4 | _metadataRules.removeLast();
|
1204 | |
|
1205 | 4 | token(node.rightParenthesis);
|
1206 | 2 | if (nestExpression) builder.unnest();
|
1207 | | }
|
1208 | |
|
1209 | 1 | visitForStatement(ForStatement node) {
|
1210 | 2 | builder.nestExpression();
|
1211 | 2 | token(node.forKeyword);
|
1212 | 1 | space();
|
1213 | 2 | token(node.leftParenthesis);
|
1214 | |
|
1215 | 2 | builder.startRule();
|
1216 | |
|
1217 | | // The initialization clause.
|
1218 | 1 | if (node.initialization != null) {
|
1219 | 2 | visit(node.initialization);
|
1220 | 1 | } else if (node.variables != null) {
|
1221 | | // Nest split variables more so they aren't at the same level
|
1222 | | // as the rest of the loop clauses.
|
1223 | 2 | builder.nestExpression();
|
1224 | |
|
1225 | | // Allow the variables to stay unsplit even if the clauses split.
|
1226 | 2 | builder.startRule();
|
1227 | |
|
1228 | 1 | var declaration = node.variables;
|
1229 | 2 | visitMetadata(declaration.metadata);
|
1230 | 2 | modifier(declaration.keyword);
|
1231 | 3 | visit(declaration.type, after: space);
|
1232 | |
|
1233 | 3 | visitCommaSeparatedNodes(declaration.variables, between: () {
|
1234 | 1 | split();
|
1235 | | });
|
1236 | |
|
1237 | 2 | builder.endRule();
|
1238 | 2 | builder.unnest();
|
1239 | | }
|
1240 | |
|
1241 | 2 | token(node.leftSeparator);
|
1242 | |
|
1243 | | // The condition clause.
|
1244 | 2 | if (node.condition != null) split();
|
1245 | 2 | visit(node.condition);
|
1246 | 2 | token(node.rightSeparator);
|
1247 | |
|
1248 | | // The update clause.
|
1249 | 2 | if (node.updaters.isNotEmpty) {
|
1250 | 1 | split();
|
1251 | |
|
1252 | | // Allow the updates to stay unsplit even if the clauses split.
|
1253 | 2 | builder.startRule();
|
1254 | |
|
1255 | 3 | visitCommaSeparatedNodes(node.updaters, between: split);
|
1256 | |
|
1257 | 2 | builder.endRule();
|
1258 | | }
|
1259 | |
|
1260 | 2 | token(node.rightParenthesis);
|
1261 | 2 | builder.endRule();
|
1262 | 2 | builder.unnest();
|
1263 | |
|
1264 | 2 | _visitLoopBody(node.body);
|
1265 | | }
|
1266 | |
|
1267 | 3 | visitFunctionDeclaration(FunctionDeclaration node) {
|
1268 | 6 | _visitMemberDeclaration(node, node.functionExpression);
|
1269 | | }
|
1270 | |
|
1271 | 2 | visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
|
1272 | 4 | visit(node.functionDeclaration);
|
1273 | | }
|
1274 | |
|
1275 | 2 | visitFunctionExpression(FunctionExpression node) {
|
1276 | | // Inside a function body is no longer in the surrounding const context.
|
1277 | 2 | var oldConstNesting = _constNesting;
|
1278 | 2 | _constNesting = 0;
|
1279 | |
|
1280 | | // TODO(rnystrom): This is working but not tested. As of 2016/11/29, the
|
1281 | | // latest version of analyzer on pub does not parse generic lambdas. When
|
1282 | | // a version of it that does is published, upgrade dart_style to use it and
|
1283 | | // then test it:
|
1284 | | //
|
1285 | | // >>> generic function expression
|
1286 | | // main() {
|
1287 | | // var generic = < T,S >(){};
|
1288 | | // }
|
1289 | | // <<<
|
1290 | | // main() {
|
1291 | | // var generic = <T, S>() {};
|
1292 | | // }
|
1293 | 8 | _visitBody(node.typeParameters, node.parameters, node.body);
|
1294 | |
|
1295 | 2 | _constNesting = oldConstNesting;
|
1296 | | }
|
1297 | |
|
1298 | 1 | visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
|
1299 | | // Try to keep the entire invocation one line.
|
1300 | 2 | builder.startSpan();
|
1301 | 2 | builder.nestExpression();
|
1302 | |
|
1303 | 2 | visit(node.function);
|
1304 | 2 | visit(node.typeArguments);
|
1305 | 2 | visitArgumentList(node.argumentList, nestExpression: false);
|
1306 | |
|
1307 | 2 | builder.unnest();
|
1308 | 2 | builder.endSpan();
|
1309 | | }
|
1310 | |
|
1311 | 2 | visitFunctionTypeAlias(FunctionTypeAlias node) {
|
1312 | 4 | visitMetadata(node.metadata);
|
1313 | |
|
1314 | 6 | if (_formatter.fixes.contains(StyleFix.functionTypedefs)) {
|
1315 | 2 | _simpleStatement(node, () {
|
1316 | | // Inlined visitGenericTypeAlias
|
1317 | 3 | _visitGenericTypeAliasHeader(node.typedefKeyword, node.name,
|
1318 | 4 | node.typeParameters, null, (node.returnType ?? node.name).offset);
|
1319 | |
|
1320 | 1 | space();
|
1321 | |
|
1322 | | // Recursively convert function-arguments to Function syntax.
|
1323 | 1 | _insideNewTypedefFix = true;
|
1324 | 1 | _visitGenericFunctionType(
|
1325 | 4 | node.returnType, null, node.name.offset, null, node.parameters);
|
1326 | 1 | _insideNewTypedefFix = false;
|
1327 | | });
|
1328 | | return;
|
1329 | | }
|
1330 | |
|
1331 | 2 | _simpleStatement(node, () {
|
1332 | 2 | token(node.typedefKeyword);
|
1333 | 1 | space();
|
1334 | 3 | visit(node.returnType, after: space);
|
1335 | 2 | visit(node.name);
|
1336 | 2 | visit(node.typeParameters);
|
1337 | 2 | visit(node.parameters);
|
1338 | | });
|
1339 | | }
|
1340 | |
|
1341 | 2 | visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) {
|
1342 | 6 | visitParameterMetadata(node.metadata, () {
|
1343 | 2 | if (!_insideNewTypedefFix) {
|
1344 | 2 | modifier(node.covariantKeyword);
|
1345 | 3 | visit(node.returnType, after: space);
|
1346 | | // Try to keep the function's parameters with its name.
|
1347 | 2 | builder.startSpan();
|
1348 | 2 | visit(node.identifier);
|
1349 | 3 | _visitParameterSignature(node.typeParameters, node.parameters);
|
1350 | 2 | builder.endSpan();
|
1351 | | } else {
|
1352 | 1 | _beginFormalParameter(node);
|
1353 | 4 | _visitGenericFunctionType(node.returnType, null, node.identifier.offset,
|
1354 | 2 | node.typeParameters, node.parameters);
|
1355 | 1 | split();
|
1356 | 2 | visit(node.identifier);
|
1357 | 1 | _endFormalParameter(node);
|
1358 | | }
|
1359 | | });
|
1360 | | }
|
1361 | |
|
1362 | 2 | visitGenericFunctionType(GenericFunctionType node) {
|
1363 | 6 | _visitGenericFunctionType(node.returnType, node.functionKeyword, null,
|
1364 | 4 | node.typeParameters, node.parameters);
|
1365 | | }
|
1366 | |
|
1367 | 2 | visitGenericTypeAlias(GenericTypeAlias node) {
|
1368 | 8 | visitNodes(node.metadata, between: newline, after: newline);
|
1369 | 4 | _simpleStatement(node, () {
|
1370 | 6 | _visitGenericTypeAliasHeader(node.typedefKeyword, node.name,
|
1371 | 4 | node.typeParameters, node.equals, null);
|
1372 | |
|
1373 | 2 | space();
|
1374 | |
|
1375 | 4 | visit(node.functionType);
|
1376 | | });
|
1377 | | }
|
1378 | |
|
1379 | 1 | visitHideCombinator(HideCombinator node) {
|
1380 | 3 | _visitCombinator(node.keyword, node.hiddenNames);
|
1381 | | }
|
1382 | |
|
1383 | 1 | visitIfStatement(IfStatement node) {
|
1384 | 2 | builder.nestExpression();
|
1385 | 2 | token(node.ifKeyword);
|
1386 | 1 | space();
|
1387 | 2 | token(node.leftParenthesis);
|
1388 | 2 | visit(node.condition);
|
1389 | 2 | token(node.rightParenthesis);
|
1390 | 2 | builder.unnest();
|
1391 | |
|
1392 | 1 | visitClause(Statement clause) {
|
1393 | 2 | if (clause is Block || clause is IfStatement) {
|
1394 | 1 | space();
|
1395 | 1 | visit(clause);
|
1396 | | } else {
|
1397 | | // Allow splitting in a statement-bodied if even though it's against
|
1398 | | // the style guide. Since we can't fix the code itself to follow the
|
1399 | | // style guide, we should at least format it as well as we can.
|
1400 | 2 | builder.indent();
|
1401 | 2 | builder.startRule();
|
1402 | |
|
1403 | | // If there is an else clause, always split before both the then and
|
1404 | | // else statements.
|
1405 | 1 | if (node.elseStatement != null) {
|
1406 | 2 | builder.writeWhitespace(Whitespace.newline);
|
1407 | | } else {
|
1408 | 2 | builder.split(nest: false, space: true);
|
1409 | | }
|
1410 | |
|
1411 | 1 | visit(clause);
|
1412 | |
|
1413 | 2 | builder.endRule();
|
1414 | 2 | builder.unindent();
|
1415 | | }
|
1416 | | }
|
1417 | |
|
1418 | 2 | visitClause(node.thenStatement);
|
1419 | |
|
1420 | 1 | if (node.elseStatement != null) {
|
1421 | 2 | if (node.thenStatement is Block) {
|
1422 | 1 | space();
|
1423 | | } else {
|
1424 | | // Corner case where an else follows a single-statement then clause.
|
1425 | | // This is against the style guide, but we still need to handle it. If
|
1426 | | // it happens, put the else on the next line.
|
1427 | 1 | newline();
|
1428 | | }
|
1429 | |
|
1430 | 2 | token(node.elseKeyword);
|
1431 | 2 | visitClause(node.elseStatement);
|
1432 | | }
|
1433 | | }
|
1434 | |
|
1435 | 1 | visitImplementsClause(ImplementsClause node) {
|
1436 | 3 | _visitCombinator(node.implementsKeyword, node.interfaces);
|
1437 | | }
|
1438 | |
|
1439 | 1 | visitImportDirective(ImportDirective node) {
|
1440 | 1 | _visitDirectiveMetadata(node);
|
1441 | 2 | _simpleStatement(node, () {
|
1442 | 2 | token(node.keyword);
|
1443 | 1 | space();
|
1444 | 2 | visit(node.uri);
|
1445 | |
|
1446 | 2 | _visitConfigurations(node.configurations);
|
1447 | |
|
1448 | 1 | if (node.asKeyword != null) {
|
1449 | 1 | soloSplit();
|
1450 | 3 | token(node.deferredKeyword, after: space);
|
1451 | 2 | token(node.asKeyword);
|
1452 | 1 | space();
|
1453 | 2 | visit(node.prefix);
|
1454 | | }
|
1455 | |
|
1456 | 3 | builder.startRule(new CombinatorRule());
|
1457 | 2 | visitNodes(node.combinators);
|
1458 | 2 | builder.endRule();
|
1459 | | });
|
1460 | | }
|
1461 | |
|
1462 | 1 | visitIndexExpression(IndexExpression node) {
|
1463 | 2 | builder.nestExpression();
|
1464 | |
|
1465 | 1 | if (node.isCascaded) {
|
1466 | 0 | token(node.period);
|
1467 | | } else {
|
1468 | 2 | visit(node.target);
|
1469 | | }
|
1470 | |
|
1471 | 1 | finishIndexExpression(node);
|
1472 | |
|
1473 | 2 | builder.unnest();
|
1474 | | }
|
1475 | |
|
1476 | | /// Visit the index part of [node], excluding the target.
|
1477 | | ///
|
1478 | | /// Called by [CallChainVisitor] to handle index expressions in the middle of
|
1479 | | /// call chains.
|
1480 | 1 | void finishIndexExpression(IndexExpression node) {
|
1481 | 2 | if (node.target is IndexExpression) {
|
1482 | | // Edge case: On a chain of [] accesses, allow splitting between them.
|
1483 | | // Produces nicer output in cases like:
|
1484 | | //
|
1485 | | // someJson['property']['property']['property']['property']...
|
1486 | 1 | soloZeroSplit();
|
1487 | | }
|
1488 | |
|
1489 | 2 | builder.startSpan(Cost.index);
|
1490 | 2 | token(node.leftBracket);
|
1491 | 1 | soloZeroSplit();
|
1492 | 2 | visit(node.index);
|
1493 | 2 | token(node.rightBracket);
|
1494 | 2 | builder.endSpan();
|
1495 | | }
|
1496 | |
|
1497 | 2 | visitInstanceCreationExpression(InstanceCreationExpression node) {
|
1498 | 4 | builder.startSpan();
|
1499 | |
|
1500 | | var includeKeyword = true;
|
1501 | |
|
1502 | 2 | if (node.keyword != null) {
|
1503 | 6 | if (node.keyword.keyword == Keyword.NEW &&
|
1504 | 6 | _formatter.fixes.contains(StyleFix.optionalNew)) {
|
1505 | | includeKeyword = false;
|
1506 | 6 | } else if (node.keyword.keyword == Keyword.CONST &&
|
1507 | 6 | _formatter.fixes.contains(StyleFix.optionalConst) &&
|
1508 | 4 | _constNesting > 0) {
|
1509 | | includeKeyword = false;
|
1510 | | }
|
1511 | | }
|
1512 | |
|
1513 | | if (includeKeyword) {
|
1514 | 6 | token(node.keyword, after: space);
|
1515 | | } else {
|
1516 | | // Don't lose comments before the discarded keyword, if any.
|
1517 | 4 | writePrecedingCommentsAndNewlines(node.keyword);
|
1518 | | }
|
1519 | |
|
1520 | 4 | builder.startSpan(Cost.constructorName);
|
1521 | |
|
1522 | | // Start the expression nesting for the argument list here, in case this
|
1523 | | // is a generic constructor with type arguments. If it is, we need the type
|
1524 | | // arguments to be nested too so they get indented past the arguments.
|
1525 | 4 | builder.nestExpression();
|
1526 | 4 | visit(node.constructorName);
|
1527 | |
|
1528 | 4 | _startPossibleConstContext(node.keyword);
|
1529 | |
|
1530 | 4 | builder.endSpan();
|
1531 | 4 | visitArgumentList(node.argumentList, nestExpression: false);
|
1532 | 4 | builder.endSpan();
|
1533 | |
|
1534 | 4 | _endPossibleConstContext(node.keyword);
|
1535 | |
|
1536 | 4 | builder.unnest();
|
1537 | | }
|
1538 | |
|
1539 | 2 | visitIntegerLiteral(IntegerLiteral node) {
|
1540 | 4 | token(node.literal);
|
1541 | | }
|
1542 | |
|
1543 | 2 | visitInterpolationExpression(InterpolationExpression node) {
|
1544 | 4 | builder.preventSplit();
|
1545 | 4 | token(node.leftBracket);
|
1546 | 4 | builder.startSpan();
|
1547 | 4 | visit(node.expression);
|
1548 | 4 | builder.endSpan();
|
1549 | 4 | token(node.rightBracket);
|
1550 | 4 | builder.endPreventSplit();
|
1551 | | }
|
1552 | |
|
1553 | 2 | visitInterpolationString(InterpolationString node) {
|
1554 | 4 | _writeStringLiteral(node.contents);
|
1555 | | }
|
1556 | |
|
1557 | 1 | visitIsExpression(IsExpression node) {
|
1558 | 2 | builder.startSpan();
|
1559 | 2 | builder.nestExpression();
|
1560 | 2 | visit(node.expression);
|
1561 | 1 | soloSplit();
|
1562 | 2 | token(node.isOperator);
|
1563 | 2 | token(node.notOperator);
|
1564 | 1 | space();
|
1565 | 2 | visit(node.type);
|
1566 | 2 | builder.unnest();
|
1567 | 2 | builder.endSpan();
|
1568 | | }
|
1569 | |
|
1570 | 1 | visitLabel(Label node) {
|
1571 | 2 | visit(node.label);
|
1572 | 2 | token(node.colon);
|
1573 | | }
|
1574 | |
|
1575 | 1 | visitLabeledStatement(LabeledStatement node) {
|
1576 | 2 | _visitLabels(node.labels);
|
1577 | 2 | visit(node.statement);
|
1578 | | }
|
1579 | |
|
1580 | 1 | visitLibraryDirective(LibraryDirective node) {
|
1581 | 1 | _visitDirectiveMetadata(node);
|
1582 | 2 | _simpleStatement(node, () {
|
1583 | 2 | token(node.keyword);
|
1584 | 1 | space();
|
1585 | 2 | visit(node.name);
|
1586 | | });
|
1587 | | }
|
1588 | |
|
1589 | 1 | visitLibraryIdentifier(LibraryIdentifier node) {
|
1590 | 3 | visit(node.components.first);
|
1591 | 3 | for (var component in node.components.skip(1)) {
|
1592 | 3 | token(component.beginToken.previous); // "."
|
1593 | 1 | visit(component);
|
1594 | | }
|
1595 | | }
|
1596 | |
|
1597 | 2 | visitListLiteral(ListLiteral node) {
|
1598 | | // Corner case: Splitting inside a list looks bad if there's only one
|
1599 | | // element, so make those more costly.
|
1600 | 6 | var cost = node.elements.length <= 1 ? Cost.singleElementList : Cost.normal;
|
1601 | 2 | _visitCollectionLiteral(
|
1602 | 6 | node, node.leftBracket, node.elements, node.rightBracket, cost);
|
1603 | | }
|
1604 | |
|
1605 | 2 | visitMapLiteral(MapLiteral node) {
|
1606 | 2 | _visitCollectionLiteral(
|
1607 | 6 | node, node.leftBracket, node.entries, node.rightBracket);
|
1608 | | }
|
1609 | |
|
1610 | 1 | visitMapLiteralEntry(MapLiteralEntry node) {
|
1611 | 2 | visit(node.key);
|
1612 | 2 | token(node.separator);
|
1613 | 1 | soloSplit();
|
1614 | 2 | visit(node.value);
|
1615 | | }
|
1616 | |
|
1617 | 1 | visitMethodDeclaration(MethodDeclaration node) {
|
1618 | 1 | _visitMemberDeclaration(node, node);
|
1619 | | }
|
1620 | |
|
1621 | 3 | visitMethodInvocation(MethodInvocation node) {
|
1622 | | // If there's no target, this is a "bare" function call like "foo(1, 2)",
|
1623 | | // or a section in a cascade.
|
1624 | | //
|
1625 | | // If it looks like a constructor or static call, we want to keep the
|
1626 | | // target and method together instead of including the method in the
|
1627 | | // subsequent method chain. When this happens, it's important that this
|
1628 | | // code here has the same rules as in [visitInstanceCreationExpression].
|
1629 | | //
|
1630 | | // That ensures that the way some code is formatted is not affected by the
|
1631 | | // presence or absence of `new`/`const`. In particular, it means that if
|
1632 | | // they run `dartfmt --fix`, and then run `dartfmt` *again*, the second run
|
1633 | | // will not produce any additional changes.
|
1634 | 4 | if (node.target == null || looksLikeStaticCall(node)) {
|
1635 | | // Try to keep the entire method invocation one line.
|
1636 | 6 | builder.nestExpression();
|
1637 | 6 | builder.startSpan();
|
1638 | |
|
1639 | 3 | if (node.target != null) {
|
1640 | 2 | builder.startSpan(Cost.constructorName);
|
1641 | 2 | visit(node.target);
|
1642 | 1 | soloZeroSplit();
|
1643 | | }
|
1644 | |
|
1645 | | // If target is null, this will be `..` for a cascade.
|
1646 | 6 | token(node.operator);
|
1647 | 6 | visit(node.methodName);
|
1648 | |
|
1649 | 5 | if (node.target != null) builder.endSpan();
|
1650 | |
|
1651 | | // TODO(rnystrom): Currently, there are no constraints between a generic
|
1652 | | // method's type arguments and arguments. That can lead to some funny
|
1653 | | // splitting like:
|
1654 | | //
|
1655 | | // method<VeryLongType,
|
1656 | | // AnotherTypeArgument>(argument,
|
1657 | | // argument, argument, argument);
|
1658 | | //
|
1659 | | // The indentation is fine, but splitting in the middle of each argument
|
1660 | | // list looks kind of strange. If this ends up happening in real world
|
1661 | | // code, consider putting a constraint between them.
|
1662 | 6 | builder.nestExpression();
|
1663 | 6 | visit(node.typeArguments);
|
1664 | 6 | visitArgumentList(node.argumentList, nestExpression: false);
|
1665 | 6 | builder.unnest();
|
1666 | |
|
1667 | 6 | builder.endSpan();
|
1668 | 6 | builder.unnest();
|
1669 | | return;
|
1670 | | }
|
1671 | |
|
1672 | 2 | new CallChainVisitor(this, node).visit();
|
1673 | | }
|
1674 | |
|
1675 | 1 | visitMixinDeclaration(MixinDeclaration node) {
|
1676 | 2 | visitMetadata(node.metadata);
|
1677 | |
|
1678 | 2 | builder.nestExpression();
|
1679 | 2 | token(node.mixinKeyword);
|
1680 | 1 | space();
|
1681 | 2 | visit(node.name);
|
1682 | 2 | visit(node.typeParameters);
|
1683 | |
|
1684 | | // If there is only a single superclass constraint, format it like an
|
1685 | | // "extends" in a class.
|
1686 | 1 | if (node.onClause != null &&
|
1687 | 4 | node.onClause.superclassConstraints.length == 1) {
|
1688 | 1 | soloSplit();
|
1689 | 3 | token(node.onClause.onKeyword);
|
1690 | 1 | space();
|
1691 | 4 | visit(node.onClause.superclassConstraints.single);
|
1692 | | }
|
1693 | |
|
1694 | 3 | builder.startRule(new CombinatorRule());
|
1695 | |
|
1696 | | // If there are multiple superclass constraints, format them like the
|
1697 | | // "implements" clause.
|
1698 | 1 | if (node.onClause != null &&
|
1699 | 4 | node.onClause.superclassConstraints.length > 1) {
|
1700 | 2 | visit(node.onClause);
|
1701 | | }
|
1702 | |
|
1703 | 2 | visit(node.implementsClause);
|
1704 | 2 | builder.endRule();
|
1705 | |
|
1706 | 1 | space();
|
1707 | |
|
1708 | 2 | builder.unnest();
|
1709 | 2 | _beginBody(node.leftBracket);
|
1710 | 2 | _visitMembers(node.members);
|
1711 | 2 | _endBody(node.rightBracket);
|
1712 | | }
|
1713 | |
|
1714 | 1 | visitNamedExpression(NamedExpression node) {
|
1715 | 1 | visitNamedArgument(node);
|
1716 | | }
|
1717 | |
|
1718 | 1 | visitNativeClause(NativeClause node) {
|
1719 | 2 | token(node.nativeKeyword);
|
1720 | 3 | visit(node.name, before: space);
|
1721 | | }
|
1722 | |
|
1723 | 1 | visitNativeFunctionBody(NativeFunctionBody node) {
|
1724 | 2 | _simpleStatement(node, () {
|
1725 | 2 | builder.nestExpression(now: true);
|
1726 | 1 | soloSplit();
|
1727 | 2 | token(node.nativeKeyword);
|
1728 | 3 | visit(node.stringLiteral, before: space);
|
1729 | 2 | builder.unnest();
|
1730 | | });
|
1731 | | }
|
1732 | |
|
1733 | 1 | visitNullLiteral(NullLiteral node) {
|
1734 | 2 | token(node.literal);
|
1735 | | }
|
1736 | |
|
1737 | 1 | visitOnClause(OnClause node) {
|
1738 | 3 | _visitCombinator(node.onKeyword, node.superclassConstraints);
|
1739 | | }
|
1740 | |
|
1741 | 1 | visitParenthesizedExpression(ParenthesizedExpression node) {
|
1742 | 2 | builder.nestExpression();
|
1743 | 2 | token(node.leftParenthesis);
|
1744 | 2 | visit(node.expression);
|
1745 | 2 | builder.unnest();
|
1746 | 2 | token(node.rightParenthesis);
|
1747 | | }
|
1748 | |
|
1749 | 1 | visitPartDirective(PartDirective node) {
|
1750 | 1 | _visitDirectiveMetadata(node);
|
1751 | 2 | _simpleStatement(node, () {
|
1752 | 2 | token(node.keyword);
|
1753 | 1 | space();
|
1754 | 2 | visit(node.uri);
|
1755 | | });
|
1756 | | }
|
1757 | |
|
1758 | 1 | visitPartOfDirective(PartOfDirective node) {
|
1759 | 1 | _visitDirectiveMetadata(node);
|
1760 | 2 | _simpleStatement(node, () {
|
1761 | 2 | token(node.keyword);
|
1762 | 1 | space();
|
1763 | 2 | token(node.ofKeyword);
|
1764 | 1 | space();
|
1765 | |
|
1766 | | // Part-of may have either a name or a URI. Only one of these will be
|
1767 | | // non-null. We visit both since visit() ignores null.
|
1768 | 2 | visit(node.libraryName);
|
1769 | 2 | visit(node.uri);
|
1770 | | });
|
1771 | | }
|
1772 | |
|
1773 | 1 | visitPostfixExpression(PostfixExpression node) {
|
1774 | 2 | visit(node.operand);
|
1775 | 2 | token(node.operator);
|
1776 | | }
|
1777 | |
|
1778 | 2 | visitPrefixedIdentifier(PrefixedIdentifier node) {
|
1779 | 4 | new CallChainVisitor(this, node).visit();
|
1780 | | }
|
1781 | |
|
1782 | 1 | visitPrefixExpression(PrefixExpression node) {
|
1783 | 2 | token(node.operator);
|
1784 | |
|
1785 | | // Edge case: put a space after "-" if the operand is "-" or "--" so we
|
1786 | | // don't merge the operators.
|
1787 | 1 | var operand = node.operand;
|
1788 | 1 | if (operand is PrefixExpression &&
|
1789 | 6 | (operand.operator.lexeme == "-" || operand.operator.lexeme == "--")) {
|
1790 | 1 | space();
|
1791 | | }
|
1792 | |
|
1793 | 2 | visit(node.operand);
|
1794 | | }
|
1795 | |
|
1796 | 1 | visitPropertyAccess(PropertyAccess node) {
|
1797 | 1 | if (node.isCascaded) {
|
1798 | 2 | token(node.operator);
|
1799 | 2 | visit(node.propertyName);
|
1800 | | return;
|
1801 | | }
|
1802 | |
|
1803 | 2 | new CallChainVisitor(this, node).visit();
|
1804 | | }
|
1805 | |
|
1806 | 1 | visitRedirectingConstructorInvocation(RedirectingConstructorInvocation node) {
|
1807 | 2 | builder.startSpan();
|
1808 | |
|
1809 | 2 | token(node.thisKeyword);
|
1810 | 2 | token(node.period);
|
1811 | 2 | visit(node.constructorName);
|
1812 | 2 | visit(node.argumentList);
|
1813 | |
|
1814 | 2 | builder.endSpan();
|
1815 | | }
|
1816 | |
|
1817 | 0 | visitRethrowExpression(RethrowExpression node) {
|
1818 | 0 | token(node.rethrowKeyword);
|
1819 | | }
|
1820 | |
|
1821 | 1 | visitReturnStatement(ReturnStatement node) {
|
1822 | 2 | _simpleStatement(node, () {
|
1823 | 2 | token(node.returnKeyword);
|
1824 | 3 | visit(node.expression, before: space);
|
1825 | | });
|
1826 | | }
|
1827 | |
|
1828 | 1 | visitScriptTag(ScriptTag node) {
|
1829 | | // The lexeme includes the trailing newline. Strip it off since the
|
1830 | | // formatter ensures it gets a newline after it. Since the script tag must
|
1831 | | // come at the top of the file, we don't have to worry about preceding
|
1832 | | // comments or whitespace.
|
1833 | 5 | _writeText(node.scriptTag.lexeme.trim(), node.offset);
|
1834 | 1 | newline();
|
1835 | | }
|
1836 | |
|
1837 | 1 | visitSetLiteral(SetLiteral node) {
|
1838 | 1 | _visitCollectionLiteral(
|
1839 | 3 | node, node.leftBracket, node.elements, node.rightBracket);
|
1840 | | }
|
1841 | |
|
1842 | 1 | visitShowCombinator(ShowCombinator node) {
|
1843 | 3 | _visitCombinator(node.keyword, node.shownNames);
|
1844 | | }
|
1845 | |
|
1846 | 2 | visitSimpleFormalParameter(SimpleFormalParameter node) {
|
1847 | 6 | visitParameterMetadata(node.metadata, () {
|
1848 | 2 | _beginFormalParameter(node);
|
1849 | |
|
1850 | 4 | modifier(node.keyword);
|
1851 | 2 | var hasType = node.type != null;
|
1852 | 2 | if (_insideNewTypedefFix && !hasType) {
|
1853 | | // In function declarations and the old typedef syntax, you can have a
|
1854 | | // parameter name without a type. In the new syntax, you can have a type
|
1855 | | // without a name. Add "dynamic" in that case.
|
1856 | |
|
1857 | | // Ensure comments on the identifier comes before the inserted type.
|
1858 | 4 | token(node.identifier.token, before: () {
|
1859 | 3 | _writeText("dynamic", node.identifier.offset);
|
1860 | 1 | split();
|
1861 | | });
|
1862 | | } else {
|
1863 | 4 | visit(node.type);
|
1864 | |
|
1865 | 4 | if (hasType && node.identifier != null) split();
|
1866 | |
|
1867 | 4 | visit(node.identifier);
|
1868 | | }
|
1869 | |
|
1870 | 2 | _endFormalParameter(node);
|
1871 | | });
|
1872 | | }
|
1873 | |
|
1874 | 3 | visitSimpleIdentifier(SimpleIdentifier node) {
|
1875 | 6 | token(node.token);
|
1876 | | }
|
1877 | |
|
1878 | 2 | visitSimpleStringLiteral(SimpleStringLiteral node) {
|
1879 | 4 | _writeStringLiteral(node.literal);
|
1880 | | }
|
1881 | |
|
1882 | 2 | visitStringInterpolation(StringInterpolation node) {
|
1883 | 4 | for (var element in node.elements) {
|
1884 | 2 | visit(element);
|
1885 | | }
|
1886 | | }
|
1887 | |
|
1888 | 1 | visitSuperConstructorInvocation(SuperConstructorInvocation node) {
|
1889 | 2 | builder.startSpan();
|
1890 | |
|
1891 | 2 | token(node.superKeyword);
|
1892 | 2 | token(node.period);
|
1893 | 2 | visit(node.constructorName);
|
1894 | 2 | visit(node.argumentList);
|
1895 | |
|
1896 | 2 | builder.endSpan();
|
1897 | | }
|
1898 | |
|
1899 | 0 | visitSuperExpression(SuperExpression node) {
|
1900 | 0 | token(node.superKeyword);
|
1901 | | }
|
1902 | |
|
1903 | 1 | visitSwitchCase(SwitchCase node) {
|
1904 | 2 | _visitLabels(node.labels);
|
1905 | 2 | token(node.keyword);
|
1906 | 1 | space();
|
1907 | 2 | visit(node.expression);
|
1908 | 2 | token(node.colon);
|
1909 | |
|
1910 | 2 | builder.indent();
|
1911 | | // TODO(rnystrom): Allow inline cases?
|
1912 | 1 | newline();
|
1913 | |
|
1914 | 3 | visitNodes(node.statements, between: oneOrTwoNewlines);
|
1915 | 2 | builder.unindent();
|
1916 | | }
|
1917 | |
|
1918 | 1 | visitSwitchDefault(SwitchDefault node) {
|
1919 | 2 | _visitLabels(node.labels);
|
1920 | 2 | token(node.keyword);
|
1921 | 2 | token(node.colon);
|
1922 | |
|
1923 | 2 | builder.indent();
|
1924 | | // TODO(rnystrom): Allow inline cases?
|
1925 | 1 | newline();
|
1926 | |
|
1927 | 3 | visitNodes(node.statements, between: oneOrTwoNewlines);
|
1928 | 2 | builder.unindent();
|
1929 | | }
|
1930 | |
|
1931 | 1 | visitSwitchStatement(SwitchStatement node) {
|
1932 | 2 | builder.nestExpression();
|
1933 | 2 | token(node.switchKeyword);
|
1934 | 1 | space();
|
1935 | 2 | token(node.leftParenthesis);
|
1936 | 1 | soloZeroSplit();
|
1937 | 2 | visit(node.expression);
|
1938 | 2 | token(node.rightParenthesis);
|
1939 | 1 | space();
|
1940 | 2 | token(node.leftBracket);
|
1941 | 2 | builder.unnest();
|
1942 | 2 | builder.indent();
|
1943 | 1 | newline();
|
1944 | |
|
1945 | 4 | visitNodes(node.members, between: oneOrTwoNewlines, after: newline);
|
1946 | 3 | token(node.rightBracket, before: () {
|
1947 | 2 | builder.unindent();
|
1948 | 1 | newline();
|
1949 | | });
|
1950 | | }
|
1951 | |
|
1952 | 1 | visitSymbolLiteral(SymbolLiteral node) {
|
1953 | 2 | token(node.poundSign);
|
1954 | 1 | var components = node.components;
|
1955 | 2 | for (var component in components) {
|
1956 | | // The '.' separator
|
1957 | 3 | if (component.previous.lexeme == '.') {
|
1958 | 2 | token(component.previous);
|
1959 | | }
|
1960 | 1 | token(component);
|
1961 | | }
|
1962 | | }
|
1963 | |
|
1964 | 1 | visitThisExpression(ThisExpression node) {
|
1965 | 2 | token(node.thisKeyword);
|
1966 | | }
|
1967 | |
|
1968 | 1 | visitThrowExpression(ThrowExpression node) {
|
1969 | 2 | token(node.throwKeyword);
|
1970 | 1 | space();
|
1971 | 2 | visit(node.expression);
|
1972 | | }
|
1973 | |
|
1974 | 2 | visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
|
1975 | 4 | visitMetadata(node.metadata);
|
1976 | |
|
1977 | 4 | _simpleStatement(node, () {
|
1978 | 4 | visit(node.variables);
|
1979 | | });
|
1980 | | }
|
1981 | |
|
1982 | 1 | visitTryStatement(TryStatement node) {
|
1983 | 2 | token(node.tryKeyword);
|
1984 | 1 | space();
|
1985 | 2 | visit(node.body);
|
1986 | 4 | visitNodes(node.catchClauses, before: space, between: space);
|
1987 | 4 | token(node.finallyKeyword, before: space, after: space);
|
1988 | 2 | visit(node.finallyBlock);
|
1989 | | }
|
1990 | |
|
1991 | 2 | visitTypeArgumentList(TypeArgumentList node) {
|
1992 | 8 | _visitGenericList(node.leftBracket, node.rightBracket, node.arguments);
|
1993 | | }
|
1994 | |
|
1995 | 3 | visitTypeName(TypeName node) {
|
1996 | 6 | visit(node.name);
|
1997 | 6 | visit(node.typeArguments);
|
1998 | | }
|
1999 | |
|
2000 | 2 | visitTypeParameter(TypeParameter node) {
|
2001 | 6 | visitParameterMetadata(node.metadata, () {
|
2002 | 4 | visit(node.name);
|
2003 | 8 | token(node.extendsKeyword, before: space, after: space);
|
2004 | 4 | visit(node.bound);
|
2005 | | });
|
2006 | | }
|
2007 | |
|
2008 | 2 | visitTypeParameterList(TypeParameterList node) {
|
2009 | 6 | _metadataRules.add(new MetadataRule());
|
2010 | |
|
2011 | 8 | _visitGenericList(node.leftBracket, node.rightBracket, node.typeParameters);
|
2012 | |
|
2013 | 4 | _metadataRules.removeLast();
|
2014 | | }
|
2015 | |
|
2016 | 2 | visitVariableDeclaration(VariableDeclaration node) {
|
2017 | 4 | visit(node.name);
|
2018 | 2 | if (node.initializer == null) return;
|
2019 | |
|
2020 | | // If there are multiple variables being declared, we want to nest the
|
2021 | | // initializers farther so they don't line up with the variables. Bad:
|
2022 | | //
|
2023 | | // var a =
|
2024 | | // aValue,
|
2025 | | // b =
|
2026 | | // bValue;
|
2027 | | //
|
2028 | | // Good:
|
2029 | | //
|
2030 | | // var a =
|
2031 | | // aValue,
|
2032 | | // b =
|
2033 | | // bValue;
|
2034 | | var hasMultipleVariables =
|
2035 | 8 | (node.parent as VariableDeclarationList).variables.length > 1;
|
2036 | |
|
2037 | 6 | _visitAssignment(node.equals, node.initializer, nest: hasMultipleVariables);
|
2038 | | }
|
2039 | |
|
2040 | 2 | visitVariableDeclarationList(VariableDeclarationList node) {
|
2041 | 4 | visitMetadata(node.metadata);
|
2042 | |
|
2043 | | // Allow but try to avoid splitting between the type and name.
|
2044 | 4 | builder.startSpan();
|
2045 | |
|
2046 | 4 | modifier(node.keyword);
|
2047 | 6 | visit(node.type, after: soloSplit);
|
2048 | |
|
2049 | 4 | builder.endSpan();
|
2050 | |
|
2051 | 4 | _startPossibleConstContext(node.keyword);
|
2052 | |
|
2053 | | // Use a single rule for all of the variables. If there are multiple
|
2054 | | // declarations, we will try to keep them all on one line. If that isn't
|
2055 | | // possible, we split after *every* declaration so that each is on its own
|
2056 | | // line.
|
2057 | 4 | builder.startRule();
|
2058 | 6 | visitCommaSeparatedNodes(node.variables, between: split);
|
2059 | 4 | builder.endRule();
|
2060 | |
|
2061 | 4 | _endPossibleConstContext(node.keyword);
|
2062 | | }
|
2063 | |
|
2064 | 2 | visitVariableDeclarationStatement(VariableDeclarationStatement node) {
|
2065 | 4 | _simpleStatement(node, () {
|
2066 | 4 | visit(node.variables);
|
2067 | | });
|
2068 | | }
|
2069 | |
|
2070 | 1 | visitWhileStatement(WhileStatement node) {
|
2071 | 2 | builder.nestExpression();
|
2072 | 2 | token(node.whileKeyword);
|
2073 | 1 | space();
|
2074 | 2 | token(node.leftParenthesis);
|
2075 | 1 | soloZeroSplit();
|
2076 | 2 | visit(node.condition);
|
2077 | 2 | token(node.rightParenthesis);
|
2078 | 2 | builder.unnest();
|
2079 | |
|
2080 | 2 | _visitLoopBody(node.body);
|
2081 | | }
|
2082 | |
|
2083 | 1 | visitWithClause(WithClause node) {
|
2084 | 3 | _visitCombinator(node.withKeyword, node.mixinTypes);
|
2085 | | }
|
2086 | |
|
2087 | 1 | visitYieldStatement(YieldStatement node) {
|
2088 | 2 | _simpleStatement(node, () {
|
2089 | 2 | token(node.yieldKeyword);
|
2090 | 2 | token(node.star);
|
2091 | 1 | space();
|
2092 | 2 | visit(node.expression);
|
2093 | | });
|
2094 | | }
|
2095 | |
|
2096 | | /// Visit a [node], and if not null, optionally preceded or followed by the
|
2097 | | /// specified functions.
|
2098 | 3 | void visit(AstNode node, {void before(), void after()}) {
|
2099 | | if (node == null) return;
|
2100 | |
|
2101 | 1 | if (before != null) before();
|
2102 | |
|
2103 | 3 | node.accept(this);
|
2104 | |
|
2105 | 3 | if (after != null) after();
|
2106 | | }
|
2107 | |
|
2108 | | /// Visit metadata annotations on declarations, and members.
|
2109 | | ///
|
2110 | | /// These always force the annotations to be on the previous line.
|
2111 | 3 | void visitMetadata(NodeList<Annotation> metadata) {
|
2112 | 9 | visitNodes(metadata, between: newline, after: newline);
|
2113 | | }
|
2114 | |
|
2115 | | /// Visit metadata annotations for a directive.
|
2116 | | ///
|
2117 | | /// Always force the annotations to be on a previous line.
|
2118 | 1 | void _visitDirectiveMetadata(Directive directive) {
|
2119 | | // Preserve a blank line before the first directive since users (in
|
2120 | | // particular the test package) sometimes use that for metadata that
|
2121 | | // applies to the entire library and not the following directive itself.
|
2122 | | var isFirst =
|
2123 | 4 | directive == (directive.parent as CompilationUnit).directives.first;
|
2124 | |
|
2125 | 2 | visitNodes(directive.metadata,
|
2126 | 3 | between: newline, after: isFirst ? oneOrTwoNewlines : newline);
|
2127 | | }
|
2128 | |
|
2129 | | /// Visits metadata annotations on parameters and type parameters.
|
2130 | | ///
|
2131 | | /// Unlike other annotations, these are allowed to stay on the same line as
|
2132 | | /// the parameter.
|
2133 | 2 | void visitParameterMetadata(
|
2134 | | NodeList<Annotation> metadata, void visitParameter()) {
|
2135 | 2 | if (metadata == null || metadata.isEmpty) {
|
2136 | 2 | visitParameter();
|
2137 | | return;
|
2138 | | }
|
2139 | |
|
2140 | | // Split before all of the annotations or none.
|
2141 | 8 | builder.startLazyRule(_metadataRules.last);
|
2142 | |
|
2143 | 6 | visitNodes(metadata, between: split, after: () {
|
2144 | | // Don't nest until right before the last metadata. Ensures we only
|
2145 | | // indent the parameter and not any of the metadata:
|
2146 | | //
|
2147 | | // function(
|
2148 | | // @LongAnnotation
|
2149 | | // @LongAnnotation
|
2150 | | // indentedParameter) {}
|
2151 | 4 | builder.nestExpression(now: true);
|
2152 | 2 | split();
|
2153 | | });
|
2154 | 2 | visitParameter();
|
2155 | |
|
2156 | 4 | builder.unnest();
|
2157 | |
|
2158 | | // Wrap the rule around the parameter too. If it splits, we want to force
|
2159 | | // the annotations to split as well.
|
2160 | 4 | builder.endRule();
|
2161 | | }
|
2162 | |
|
2163 | | /// Visits [node], which may be in an argument list controlled by [rule].
|
2164 | | ///
|
2165 | | /// This is called directly by [ArgumentListVisitor] so that it can pass in
|
2166 | | /// the surrounding named argument rule. That way, this can ensure that a
|
2167 | | /// split between the name and argument forces the argument list to split
|
2168 | | /// too.
|
2169 | 1 | void visitNamedArgument(NamedExpression node, [NamedRule rule]) {
|
2170 | 2 | builder.nestExpression();
|
2171 | 2 | builder.startSpan();
|
2172 | 2 | visit(node.name);
|
2173 | |
|
2174 | | // Don't allow a split between a name and a collection. Instead, we want
|
2175 | | // the collection itself to split, or to split before the argument.
|
2176 | 4 | if (node.expression is ListLiteral || node.expression is MapLiteral) {
|
2177 | 1 | space();
|
2178 | | } else {
|
2179 | 1 | var split = soloSplit();
|
2180 | 1 | if (rule != null) split.imply(rule);
|
2181 | | }
|
2182 | |
|
2183 | 2 | visit(node.expression);
|
2184 | 2 | builder.endSpan();
|
2185 | 2 | builder.unnest();
|
2186 | | }
|
2187 | |
|
2188 | | /// Visits the `=` and the following expression in any place where an `=`
|
2189 | | /// appears:
|
2190 | | ///
|
2191 | | /// * Assignment
|
2192 | | /// * Variable declaration
|
2193 | | /// * Constructor initialization
|
2194 | | ///
|
2195 | | /// If [nest] is true, an extra level of expression nesting is added after
|
2196 | | /// the "=".
|
2197 | 2 | void _visitAssignment(Token equalsOperator, Expression rightHandSide,
|
2198 | | {bool nest: false}) {
|
2199 | 2 | space();
|
2200 | 2 | token(equalsOperator);
|
2201 | |
|
2202 | 2 | if (nest) builder.nestExpression(now: true);
|
2203 | |
|
2204 | 4 | soloSplit(_assignmentCost(rightHandSide));
|
2205 | 4 | builder.startSpan();
|
2206 | 2 | visit(rightHandSide);
|
2207 | 4 | builder.endSpan();
|
2208 | |
|
2209 | 2 | if (nest) builder.unnest();
|
2210 | | }
|
2211 | |
|
2212 | | /// Visits a type parameter or type argument list.
|
2213 | 2 | void _visitGenericList(
|
2214 | | Token leftBracket, Token rightBracket, List<AstNode> nodes) {
|
2215 | 2 | var rule = new TypeArgumentRule();
|
2216 | 4 | builder.startLazyRule(rule);
|
2217 | 4 | builder.startSpan();
|
2218 | 4 | builder.nestExpression();
|
2219 | |
|
2220 | 2 | token(leftBracket);
|
2221 | 4 | rule.beforeArgument(zeroSplit());
|
2222 | |
|
2223 | 4 | for (var node in nodes) {
|
2224 | 2 | visit(node);
|
2225 | |
|
2226 | | // Write the trailing comma.
|
2227 | 4 | if (node != nodes.last) {
|
2228 | 6 | token(node.endToken.next);
|
2229 | 4 | rule.beforeArgument(split());
|
2230 | | }
|
2231 | | }
|
2232 | |
|
2233 | 2 | token(rightBracket);
|
2234 | |
|
2235 | 4 | builder.unnest();
|
2236 | 4 | builder.endSpan();
|
2237 | 4 | builder.endRule();
|
2238 | | }
|
2239 | |
|
2240 | | /// Visits a sequence of labels before a statement or switch case.
|
2241 | 1 | void _visitLabels(NodeList<Label> labels) {
|
2242 | 3 | visitNodes(labels, between: newline, after: newline);
|
2243 | | }
|
2244 | |
|
2245 | | /// Visits the list of members in a class or mixin declaration.
|
2246 | 1 | void _visitMembers(NodeList<ClassMember> members) {
|
2247 | 2 | for (var member in members) {
|
2248 | 1 | visit(member);
|
2249 | |
|
2250 | 2 | if (member == members.last) {
|
2251 | 1 | newline();
|
2252 | | break;
|
2253 | | }
|
2254 | |
|
2255 | | // Add a blank line after non-empty block methods.
|
2256 | | var needsDouble = false;
|
2257 | 3 | if (member is MethodDeclaration && member.body is BlockFunctionBody) {
|
2258 | 1 | var body = member.body as BlockFunctionBody;
|
2259 | 3 | needsDouble = body.block.statements.isNotEmpty;
|
2260 | | }
|
2261 | |
|
2262 | | if (needsDouble) {
|
2263 | 1 | twoNewlines();
|
2264 | | } else {
|
2265 | | // Variables and arrow-bodied members can be more tightly packed if
|
2266 | | // the user wants to group things together.
|
2267 | 1 | oneOrTwoNewlines();
|
2268 | | }
|
2269 | | }
|
2270 | | }
|
2271 | |
|
2272 | | /// Visits a top-level function or method declaration.
|
2273 | | ///
|
2274 | | /// The two AST node types are very similar but, alas, share no common
|
2275 | | /// interface type in analyzer, hence the dynamic typing.
|
2276 | 3 | void _visitMemberDeclaration(
|
2277 | | /* FunctionDeclaration|MethodDeclaration */ node,
|
2278 | | /* FunctionExpression|MethodDeclaration */ function) {
|
2279 | 6 | visitMetadata(node.metadata as NodeList<Annotation>);
|
2280 | |
|
2281 | | // Nest the signature in case we have to split between the return type and
|
2282 | | // name.
|
2283 | 6 | builder.nestExpression();
|
2284 | 6 | builder.startSpan();
|
2285 | 6 | modifier(node.externalKeyword);
|
2286 | 5 | if (node is MethodDeclaration) modifier(node.modifierKeyword);
|
2287 | 9 | visit(node.returnType, after: soloSplit);
|
2288 | 6 | modifier(node.propertyKeyword);
|
2289 | 5 | if (node is MethodDeclaration) modifier(node.operatorKeyword);
|
2290 | 6 | visit(node.name);
|
2291 | 6 | builder.endSpan();
|
2292 | |
|
2293 | | TypeParameterList typeParameters;
|
2294 | 3 | if (node is FunctionDeclaration) {
|
2295 | 6 | typeParameters = node.functionExpression.typeParameters;
|
2296 | | } else {
|
2297 | 1 | typeParameters = (node as MethodDeclaration).typeParameters;
|
2298 | | }
|
2299 | |
|
2300 | 12 | _visitBody(typeParameters, function.parameters, function.body, () {
|
2301 | | // If the body is a block, we need to exit nesting before we hit the body
|
2302 | | // indentation, but we do want to wrap it around the parameters.
|
2303 | 10 | if (function.body is! ExpressionFunctionBody) builder.unnest();
|
2304 | | });
|
2305 | |
|
2306 | | // If it's an expression, we want to wrap the nesting around that so that
|
2307 | | // the body gets nested farther.
|
2308 | 10 | if (function.body is ExpressionFunctionBody) builder.unnest();
|
2309 | | }
|
2310 | |
|
2311 | | /// Visit the given function [parameters] followed by its [body], printing a
|
2312 | | /// space before it if it's not empty.
|
2313 | | ///
|
2314 | | /// If [beforeBody] is provided, it is invoked before the body is visited.
|
2315 | 3 | void _visitBody(TypeParameterList typeParameters,
|
2316 | | FormalParameterList parameters, FunctionBody body,
|
2317 | | [beforeBody()]) {
|
2318 | | // If the body is "=>", add an extra level of indentation around the
|
2319 | | // parameters and a rule that spans the parameters and the "=>". This
|
2320 | | // ensures that if the parameters wrap, they wrap more deeply than the "=>"
|
2321 | | // does, as in:
|
2322 | | //
|
2323 | | // someFunction(parameter,
|
2324 | | // parameter, parameter) =>
|
2325 | | // "the body";
|
2326 | | //
|
2327 | | // Also, it ensures that if the parameters wrap, we split at the "=>" too
|
2328 | | // to avoid:
|
2329 | | //
|
2330 | | // someFunction(parameter,
|
2331 | | // parameter) => function(
|
2332 | | // argument);
|
2333 | | //
|
2334 | | // This is confusing because it looks like those two lines are at the same
|
2335 | | // level when they are actually unrelated. Splitting at "=>" forces:
|
2336 | | //
|
2337 | | // someFunction(parameter,
|
2338 | | // parameter) =>
|
2339 | | // function(
|
2340 | | // argument);
|
2341 | 3 | if (body is ExpressionFunctionBody) {
|
2342 | 6 | builder.nestExpression();
|
2343 | |
|
2344 | | // This rule is ended by visitExpressionFunctionBody().
|
2345 | 9 | builder.startLazyRule(new Rule(Cost.arrow));
|
2346 | | }
|
2347 | |
|
2348 | 3 | _visitParameterSignature(typeParameters, parameters);
|
2349 | |
|
2350 | 3 | if (beforeBody != null) beforeBody();
|
2351 | 3 | visit(body);
|
2352 | |
|
2353 | 9 | if (body is ExpressionFunctionBody) builder.unnest();
|
2354 | | }
|
2355 | |
|
2356 | | /// Visits the type parameters (if any) and formal parameters of a method
|
2357 | | /// declaration, function declaration, or generic function type.
|
2358 | 3 | void _visitParameterSignature(
|
2359 | | TypeParameterList typeParameters, FormalParameterList parameters) {
|
2360 | | // Start the nesting for the parameters here, so they indent past the
|
2361 | | // type parameters too, if any.
|
2362 | 6 | builder.nestExpression();
|
2363 | |
|
2364 | 3 | visit(typeParameters);
|
2365 | | if (parameters != null) {
|
2366 | 3 | visitFormalParameterList(parameters, nestExpression: false);
|
2367 | | }
|
2368 | |
|
2369 | 6 | builder.unnest();
|
2370 | | }
|
2371 | |
|
2372 | | /// Visits the body statement of a `for`, `for in`, or `while` loop.
|
2373 | 1 | void _visitLoopBody(Statement body) {
|
2374 | 1 | if (body is EmptyStatement) {
|
2375 | | // No space before the ";".
|
2376 | 1 | visit(body);
|
2377 | 1 | } else if (body is Block) {
|
2378 | 1 | space();
|
2379 | 1 | visit(body);
|
2380 | | } else {
|
2381 | | // Allow splitting in a statement-bodied loop even though it's against
|
2382 | | // the style guide. Since we can't fix the code itself to follow the
|
2383 | | // style guide, we should at least format it as well as we can.
|
2384 | 2 | builder.indent();
|
2385 | 2 | builder.startRule();
|
2386 | |
|
2387 | 2 | builder.split(nest: false, space: true);
|
2388 | 1 | visit(body);
|
2389 | |
|
2390 | 2 | builder.endRule();
|
2391 | 2 | builder.unindent();
|
2392 | | }
|
2393 | | }
|
2394 | |
|
2395 | | /// Visit a list of [nodes] if not null, optionally separated and/or preceded
|
2396 | | /// and followed by the given functions.
|
2397 | 3 | void visitNodes(Iterable<AstNode> nodes, {before(), between(), after()}) {
|
2398 | 3 | if (nodes == null || nodes.isEmpty) return;
|
2399 | |
|
2400 | 1 | if (before != null) before();
|
2401 | |
|
2402 | 4 | visit(nodes.first);
|
2403 | 3 | for (var node in nodes.skip(1)) {
|
2404 | 1 | if (between != null) between();
|
2405 | 1 | visit(node);
|
2406 | | }
|
2407 | |
|
2408 | 2 | if (after != null) after();
|
2409 | | }
|
2410 | |
|
2411 | | /// Visit a comma-separated list of [nodes] if not null.
|
2412 | 2 | void visitCommaSeparatedNodes(Iterable<AstNode> nodes, {between()}) {
|
2413 | 2 | if (nodes == null || nodes.isEmpty) return;
|
2414 | |
|
2415 | 0 | if (between == null) between = space;
|
2416 | |
|
2417 | | var first = true;
|
2418 | 4 | for (var node in nodes) {
|
2419 | 1 | if (!first) between();
|
2420 | | first = false;
|
2421 | |
|
2422 | 2 | visit(node);
|
2423 | |
|
2424 | | // The comma after the node.
|
2425 | 11 | if (node.endToken.next.lexeme == ",") token(node.endToken.next);
|
2426 | | }
|
2427 | | }
|
2428 | |
|
2429 | | /// Visits the collection literal [node] whose body starts with [leftBracket],
|
2430 | | /// ends with [rightBracket] and contains [elements].
|
2431 | | ///
|
2432 | | /// This is also used for argument lists with a trailing comma which are
|
2433 | | /// considered "collection-like". In that case, [node] is `null`.
|
2434 | 2 | void _visitCollectionLiteral(TypedLiteral node, Token leftBracket,
|
2435 | | Iterable<AstNode> elements, Token rightBracket,
|
2436 | | [int cost]) {
|
2437 | | if (node != null) {
|
2438 | | // See if `const` should be removed.
|
2439 | 2 | if (node.constKeyword != null &&
|
2440 | 4 | _constNesting > 0 &&
|
2441 | 6 | _formatter.fixes.contains(StyleFix.optionalConst)) {
|
2442 | | // Don't lose comments before the discarded keyword, if any.
|
2443 | 4 | writePrecedingCommentsAndNewlines(node.constKeyword);
|
2444 | | } else {
|
2445 | 4 | modifier(node.constKeyword);
|
2446 | | }
|
2447 | |
|
2448 | 4 | visit(node.typeArguments);
|
2449 | | }
|
2450 | |
|
2451 | | // Don't allow splitting in an empty collection.
|
2452 | 4 | if (elements.isEmpty && rightBracket.precedingComments == null) {
|
2453 | 2 | token(leftBracket);
|
2454 | 2 | token(rightBracket);
|
2455 | | return;
|
2456 | | }
|
2457 | |
|
2458 | | // Force all of the surrounding collections to split.
|
2459 | 7 | for (var i = 0; i < _collectionSplits.length; i++) {
|
2460 | 2 | _collectionSplits[i] = true;
|
2461 | | }
|
2462 | |
|
2463 | | // Add this collection to the stack.
|
2464 | 4 | _collectionSplits.add(false);
|
2465 | |
|
2466 | 2 | _startLiteralBody(leftBracket);
|
2467 | 4 | if (node != null) _startPossibleConstContext(node.constKeyword);
|
2468 | |
|
2469 | | // If a collection contains a line comment, we assume it's a big complex
|
2470 | | // blob of data with some documented structure. In that case, the user
|
2471 | | // probably broke the elements into lines deliberately, so preserve those.
|
2472 | 2 | var preserveNewlines = _containsLineComments(elements, rightBracket);
|
2473 | |
|
2474 | | var rule;
|
2475 | | var lineRule;
|
2476 | | if (preserveNewlines) {
|
2477 | | // Newlines are significant, so we'll explicitly write those. Elements
|
2478 | | // on the same line all share an argument-list-like rule that allows
|
2479 | | // splitting between zero, one, or all of them. This is faster in long
|
2480 | | // lists than using individual splits after each element.
|
2481 | 1 | lineRule = new TypeArgumentRule();
|
2482 | 2 | builder.startLazyRule(lineRule);
|
2483 | | } else {
|
2484 | | // Newlines aren't significant, so use a hard rule to split the elements.
|
2485 | | // The parent chunk of the collection will handle the unsplit case, so
|
2486 | | // this only comes into play when the collection is split.
|
2487 | 2 | rule = new Rule.hard();
|
2488 | 4 | builder.startRule(rule);
|
2489 | | }
|
2490 | |
|
2491 | 4 | for (var element in elements) {
|
2492 | 4 | if (element != elements.first) {
|
2493 | | if (preserveNewlines) {
|
2494 | | // See if the next element is on the next line.
|
2495 | 4 | if (_endLine(element.beginToken.previous) !=
|
2496 | 2 | _startLine(element.beginToken)) {
|
2497 | 1 | oneOrTwoNewlines();
|
2498 | |
|
2499 | | // Start a new rule for the new line.
|
2500 | 2 | builder.endRule();
|
2501 | 1 | lineRule = new TypeArgumentRule();
|
2502 | 2 | builder.startLazyRule(lineRule);
|
2503 | | } else {
|
2504 | 2 | lineRule.beforeArgument(split());
|
2505 | | }
|
2506 | | } else {
|
2507 | 4 | builder.split(nest: false, space: true);
|
2508 | | }
|
2509 | | }
|
2510 | |
|
2511 | 4 | builder.nestExpression();
|
2512 | 2 | visit(element);
|
2513 | |
|
2514 | | // The comma after the element.
|
2515 | 8 | if (element.endToken.next.type == TokenType.COMMA) {
|
2516 | 6 | token(element.endToken.next);
|
2517 | | }
|
2518 | |
|
2519 | 4 | builder.unnest();
|
2520 | | }
|
2521 | |
|
2522 | 4 | builder.endRule();
|
2523 | |
|
2524 | | // If there is a collection inside this one, it forces this one to split.
|
2525 | 4 | var force = _collectionSplits.removeLast();
|
2526 | |
|
2527 | | // If the collection has a trailing comma, the user must want it to split.
|
2528 | 2 | if (elements.isNotEmpty &&
|
2529 | 10 | elements.last.endToken.next.type == TokenType.COMMA) {
|
2530 | | force = true;
|
2531 | | }
|
2532 | |
|
2533 | 4 | if (node != null) _endPossibleConstContext(node.constKeyword);
|
2534 | 2 | _endLiteralBody(rightBracket, ignoredRule: rule, forceSplit: force);
|
2535 | | }
|
2536 | |
|
2537 | | /// Writes [parameters], which is assumed to have a trailing comma after the
|
2538 | | /// last parameter.
|
2539 | | ///
|
2540 | | /// Parameter lists with trailing commas are formatted differently from
|
2541 | | /// regular parameter lists. They are treated more like collection literals.
|
2542 | | ///
|
2543 | | /// We don't reuse [_visitCollectionLiteral] here because there are enough
|
2544 | | /// weird differences around optional parameters that it's easiest just to
|
2545 | | /// give them their own method.
|
2546 | 1 | void _visitTrailingCommaParameterList(FormalParameterList parameters) {
|
2547 | | // Can't have a trailing comma if there are no parameters.
|
2548 | 2 | assert(parameters.parameters.isNotEmpty);
|
2549 | |
|
2550 | 3 | _metadataRules.add(new MetadataRule());
|
2551 | |
|
2552 | | // Always split the parameters.
|
2553 | 3 | builder.startRule(new Rule.hard());
|
2554 | |
|
2555 | 2 | token(parameters.leftParenthesis);
|
2556 | |
|
2557 | | // Find the parameter immediately preceding the optional parameters (if
|
2558 | | // there are any).
|
2559 | | FormalParameter lastRequired;
|
2560 | 4 | for (var i = 0; i < parameters.parameters.length; i++) {
|
2561 | 3 | if (parameters.parameters[i] is DefaultFormalParameter) {
|
2562 | 4 | if (i > 0) lastRequired = parameters.parameters[i - 1];
|
2563 | | break;
|
2564 | | }
|
2565 | | }
|
2566 | |
|
2567 | | // If all parameters are optional, put the "[" or "{" right after "(".
|
2568 | 3 | if (parameters.parameters.first is DefaultFormalParameter) {
|
2569 | 2 | token(parameters.leftDelimiter);
|
2570 | | }
|
2571 | |
|
2572 | | // Process the parameters as a separate set of chunks.
|
2573 | 3 | builder = builder.startBlock(null);
|
2574 | |
|
2575 | 2 | for (var parameter in parameters.parameters) {
|
2576 | 1 | visit(parameter);
|
2577 | |
|
2578 | | // The comma after the parameter.
|
2579 | 4 | if (parameter.endToken.next.type == TokenType.COMMA) {
|
2580 | 3 | token(parameter.endToken.next);
|
2581 | | }
|
2582 | |
|
2583 | | // If the optional parameters start after this one, put the delimiter
|
2584 | | // at the end of its line.
|
2585 | 1 | if (parameter == lastRequired) {
|
2586 | 1 | space();
|
2587 | 2 | token(parameters.leftDelimiter);
|
2588 | | lastRequired = null;
|
2589 | | }
|
2590 | |
|
2591 | 1 | newline();
|
2592 | | }
|
2593 | |
|
2594 | | // Put comments before the closing ")", "]", or "}" inside the block.
|
2595 | | var firstDelimiter =
|
2596 | 2 | parameters.rightDelimiter ?? parameters.rightParenthesis;
|
2597 | 1 | writePrecedingCommentsAndNewlines(firstDelimiter);
|
2598 | 3 | builder = builder.endBlock(null, forceSplit: true);
|
2599 | 2 | builder.endRule();
|
2600 | |
|
2601 | 2 | _metadataRules.removeLast();
|
2602 | |
|
2603 | | // Now write the delimiter itself.
|
2604 | 3 | _writeText(firstDelimiter.lexeme, firstDelimiter.offset);
|
2605 | 2 | if (firstDelimiter != parameters.rightParenthesis) {
|
2606 | 2 | token(parameters.rightParenthesis);
|
2607 | | }
|
2608 | | }
|
2609 | |
|
2610 | | /// Begins writing a formal parameter of any kind.
|
2611 | 2 | void _beginFormalParameter(FormalParameter node) {
|
2612 | 6 | builder.startLazyRule(new Rule(Cost.parameterType));
|
2613 | 4 | builder.nestExpression();
|
2614 | 4 | modifier(node.covariantKeyword);
|
2615 | | }
|
2616 | |
|
2617 | | /// Ends writing a formal parameter of any kind.
|
2618 | 2 | void _endFormalParameter(FormalParameter node) {
|
2619 | 4 | builder.unnest();
|
2620 | 4 | builder.endRule();
|
2621 | | }
|
2622 | |
|
2623 | | /// Writes a `Function` function type.
|
2624 | | ///
|
2625 | | /// Used also by a fix, so there may not be a [functionKeyword].
|
2626 | | /// In that case [functionKeywordPosition] should be the source position
|
2627 | | /// used for the inserted "Function" text.
|
2628 | 2 | void _visitGenericFunctionType(
|
2629 | | AstNode returnType,
|
2630 | | Token functionKeyword,
|
2631 | | int functionKeywordPosition,
|
2632 | | TypeParameterList typeParameters,
|
2633 | | FormalParameterList parameters) {
|
2634 | 4 | builder.startLazyRule();
|
2635 | 4 | builder.nestExpression();
|
2636 | |
|
2637 | 4 | visit(returnType, after: split);
|
2638 | | if (functionKeyword != null) {
|
2639 | 2 | token(functionKeyword);
|
2640 | | } else {
|
2641 | 1 | _writeText("Function", functionKeywordPosition);
|
2642 | | }
|
2643 | |
|
2644 | 4 | builder.unnest();
|
2645 | 4 | builder.endRule();
|
2646 | 2 | _visitParameterSignature(typeParameters, parameters);
|
2647 | | }
|
2648 | |
|
2649 | | /// Writes the header of a new-style typedef.
|
2650 | | ///
|
2651 | | /// Also used by a fix so there may not be an [equals] token.
|
2652 | | /// If [equals] is `null`, then [equalsPosition] must be a
|
2653 | | /// position to use for the inserted text "=".
|
2654 | 2 | void _visitGenericTypeAliasHeader(Token typedefKeyword, AstNode name,
|
2655 | | AstNode typeParameters, Token equals, int equalsPosition) {
|
2656 | 2 | token(typedefKeyword);
|
2657 | 2 | space();
|
2658 | |
|
2659 | | // If the typedef's type parameters split, split after the "=" too,
|
2660 | | // mainly to ensure the function's type parameters and parameters get
|
2661 | | // end up on successive lines with the same indentation.
|
2662 | 4 | builder.startRule();
|
2663 | |
|
2664 | 2 | visit(name);
|
2665 | |
|
2666 | 2 | visit(typeParameters);
|
2667 | 2 | split();
|
2668 | |
|
2669 | | if (equals != null) {
|
2670 | 2 | token(equals);
|
2671 | | } else {
|
2672 | 1 | _writeText("=", equalsPosition);
|
2673 | | }
|
2674 | |
|
2675 | 4 | builder.endRule();
|
2676 | | }
|
2677 | |
|
2678 | | /// Gets the cost to split at an assignment (or `:` in the case of a named
|
2679 | | /// default value) with the given [rightHandSide].
|
2680 | | ///
|
2681 | | /// "Block-like" expressions (collections and cascades) bind a bit tighter
|
2682 | | /// because it looks better to have code like:
|
2683 | | ///
|
2684 | | /// var list = [
|
2685 | | /// element,
|
2686 | | /// element,
|
2687 | | /// element
|
2688 | | /// ];
|
2689 | | ///
|
2690 | | /// var builder = new SomeBuilderClass()
|
2691 | | /// ..method()
|
2692 | | /// ..method();
|
2693 | | ///
|
2694 | | /// over:
|
2695 | | ///
|
2696 | | /// var list =
|
2697 | | /// [element, element, element];
|
2698 | | ///
|
2699 | | /// var builder =
|
2700 | | /// new SomeBuilderClass()..method()..method();
|
2701 | 2 | int _assignmentCost(Expression rightHandSide) {
|
2702 | 2 | if (rightHandSide is ListLiteral) return Cost.assignBlock;
|
2703 | 2 | if (rightHandSide is MapLiteral) return Cost.assignBlock;
|
2704 | 2 | if (rightHandSide is CascadeExpression) return Cost.assignBlock;
|
2705 | |
|
2706 | | return Cost.assign;
|
2707 | | }
|
2708 | |
|
2709 | | /// Returns `true` if the collection withs [elements] delimited by
|
2710 | | /// [rightBracket] contains any line comments.
|
2711 | | ///
|
2712 | | /// This only looks for comments at the element boundary. Comments within an
|
2713 | | /// element are ignored.
|
2714 | 2 | bool _containsLineComments(Iterable<AstNode> elements, Token rightBracket) {
|
2715 | 2 | hasLineCommentBefore(token) {
|
2716 | 2 | var comment = token.precedingComments;
|
2717 | 1 | for (; comment != null; comment = comment.next) {
|
2718 | 2 | if (comment.type == TokenType.SINGLE_LINE_COMMENT) return true;
|
2719 | | }
|
2720 | |
|
2721 | | return false;
|
2722 | | }
|
2723 | |
|
2724 | | // Look before each element.
|
2725 | 4 | for (var element in elements) {
|
2726 | 4 | if (hasLineCommentBefore(element.beginToken)) return true;
|
2727 | | }
|
2728 | |
|
2729 | | // Look before the closing bracket.
|
2730 | 2 | return hasLineCommentBefore(rightBracket);
|
2731 | | }
|
2732 | |
|
2733 | | /// Begins writing a literal body: a collection or block-bodied function
|
2734 | | /// expression.
|
2735 | | ///
|
2736 | | /// Writes the delimiter and then creates the [Rule] that handles splitting
|
2737 | | /// the body.
|
2738 | 2 | void _startLiteralBody(Token leftBracket) {
|
2739 | 2 | token(leftBracket);
|
2740 | |
|
2741 | | // See if this literal is associated with an argument list that wants to
|
2742 | | // handle splitting and indenting it. If not, we'll use a default rule.
|
2743 | | var rule;
|
2744 | | var argumentChunk;
|
2745 | 4 | if (_blockArgumentLists.containsKey(leftBracket)) {
|
2746 | 2 | var argumentList = _blockArgumentLists[leftBracket];
|
2747 | 1 | rule = argumentList.blockRule;
|
2748 | 1 | argumentChunk = argumentList.previousSplit;
|
2749 | | }
|
2750 | |
|
2751 | | // Create a rule for whether or not to split the block contents.
|
2752 | 4 | builder.startRule(rule);
|
2753 | |
|
2754 | | // Process the collection contents as a separate set of chunks.
|
2755 | 6 | builder = builder.startBlock(argumentChunk);
|
2756 | | }
|
2757 | |
|
2758 | | /// Ends the literal body started by a call to [_startLiteralBody()].
|
2759 | | ///
|
2760 | | /// If [forceSplit] is `true`, forces the body to split. If [ignoredRule] is
|
2761 | | /// given, ignores that rule inside the body when determining if it should
|
2762 | | /// split.
|
2763 | 2 | void _endLiteralBody(Token rightBracket,
|
2764 | | {Rule ignoredRule, bool forceSplit}) {
|
2765 | | if (forceSplit == null) forceSplit = false;
|
2766 | |
|
2767 | | // Put comments before the closing delimiter inside the block.
|
2768 | 2 | var hasLeadingNewline = writePrecedingCommentsAndNewlines(rightBracket);
|
2769 | |
|
2770 | 6 | builder = builder.endBlock(ignoredRule,
|
2771 | | forceSplit: hasLeadingNewline || forceSplit);
|
2772 | |
|
2773 | 4 | builder.endRule();
|
2774 | |
|
2775 | | // Now write the delimiter itself.
|
2776 | 6 | _writeText(rightBracket.lexeme, rightBracket.offset);
|
2777 | | }
|
2778 | |
|
2779 | | /// Visits a list of configurations in an import or export directive.
|
2780 | 1 | void _visitConfigurations(NodeList<Configuration> configurations) {
|
2781 | 1 | if (configurations.isEmpty) return;
|
2782 | |
|
2783 | 2 | builder.startRule();
|
2784 | |
|
2785 | 2 | for (var configuration in configurations) {
|
2786 | 1 | split();
|
2787 | 1 | visit(configuration);
|
2788 | | }
|
2789 | |
|
2790 | 2 | builder.endRule();
|
2791 | | }
|
2792 | |
|
2793 | | /// Visits a "combinator".
|
2794 | | ///
|
2795 | | /// This is a [keyword] followed by a list of [nodes], with specific line
|
2796 | | /// splitting rules. As the name implies, this is used for [HideCombinator]
|
2797 | | /// and [ShowCombinator], but it also used for "with" and "implements"
|
2798 | | /// clauses in class declarations, which are formatted the same way.
|
2799 | | ///
|
2800 | | /// This assumes the current rule is a [CombinatorRule].
|
2801 | 1 | void _visitCombinator(Token keyword, Iterable<AstNode> nodes) {
|
2802 | | // Allow splitting before the keyword.
|
2803 | 2 | var rule = builder.rule as CombinatorRule;
|
2804 | 2 | rule.addCombinator(split());
|
2805 | |
|
2806 | 2 | builder.nestExpression();
|
2807 | 1 | token(keyword);
|
2808 | |
|
2809 | 2 | rule.addName(split());
|
2810 | 4 | visitCommaSeparatedNodes(nodes, between: () => rule.addName(split()));
|
2811 | |
|
2812 | 2 | builder.unnest();
|
2813 | | }
|
2814 | |
|
2815 | | /// If [keyword] is `const`, begins a new constant context.
|
2816 | 2 | void _startPossibleConstContext(Token keyword) {
|
2817 | 4 | if (keyword != null && keyword.keyword == Keyword.CONST) {
|
2818 | 4 | _constNesting++;
|
2819 | | }
|
2820 | | }
|
2821 | |
|
2822 | | /// If [keyword] is `const`, ends the current outermost constant context.
|
2823 | 2 | void _endPossibleConstContext(Token keyword) {
|
2824 | 4 | if (keyword != null && keyword.keyword == Keyword.CONST) {
|
2825 | 4 | _constNesting--;
|
2826 | | }
|
2827 | | }
|
2828 | |
|
2829 | | /// Writes the simple statement or semicolon-delimited top-level declaration.
|
2830 | | ///
|
2831 | | /// Handles nesting if a line break occurs in the statement and writes the
|
2832 | | /// terminating semicolon. Invokes [body] which should write statement itself.
|
2833 | 2 | void _simpleStatement(AstNode node, body()) {
|
2834 | 4 | builder.nestExpression();
|
2835 | 2 | body();
|
2836 | |
|
2837 | | // TODO(rnystrom): Can the analyzer move "semicolon" to some shared base
|
2838 | | // type?
|
2839 | 4 | token((node as dynamic).semicolon);
|
2840 | 4 | builder.unnest();
|
2841 | | }
|
2842 | |
|
2843 | | /// Marks the block that starts with [token] as being controlled by
|
2844 | | /// [argumentList].
|
2845 | | ///
|
2846 | | /// When the block is visited, [argumentList] will determine the
|
2847 | | /// indentation and splitting rule for the block.
|
2848 | 1 | void beforeBlock(Token token, ArgumentSublist argumentList) {
|
2849 | 2 | _blockArgumentLists[token] = argumentList;
|
2850 | | }
|
2851 | |
|
2852 | | /// Writes the beginning of a brace-delimited body and handles indenting and
|
2853 | | /// starting the rule used to split the contents.
|
2854 | 2 | void _beginBody(Token leftBracket, {bool space: false}) {
|
2855 | 2 | token(leftBracket);
|
2856 | |
|
2857 | | // Indent the body.
|
2858 | 4 | builder.indent();
|
2859 | |
|
2860 | | // Split after the bracket.
|
2861 | 4 | builder.startRule();
|
2862 | 4 | builder.split(isDouble: false, nest: false, space: space);
|
2863 | | }
|
2864 | |
|
2865 | | /// Finishes the body started by a call to [_beginBody].
|
2866 | 2 | void _endBody(Token rightBracket, {bool space: false}) {
|
2867 | 4 | token(rightBracket, before: () {
|
2868 | | // Split before the closing bracket character.
|
2869 | 4 | builder.unindent();
|
2870 | 4 | builder.split(nest: false, space: space);
|
2871 | | });
|
2872 | |
|
2873 | 4 | builder.endRule();
|
2874 | | }
|
2875 | |
|
2876 | | /// Returns `true` if [node] is immediately contained within an anonymous
|
2877 | | /// [FunctionExpression].
|
2878 | 3 | bool _isInLambda(AstNode node) =>
|
2879 | 6 | node.parent is FunctionExpression &&
|
2880 | 9 | node.parent.parent is! FunctionDeclaration;
|
2881 | |
|
2882 | | /// Writes the string literal [string] to the output.
|
2883 | | ///
|
2884 | | /// Splits multiline strings into separate chunks so that the line splitter
|
2885 | | /// can handle them correctly.
|
2886 | 3 | void _writeStringLiteral(Token string) {
|
2887 | | // Since we output the string literal manually, ensure any preceding
|
2888 | | // comments are written first.
|
2889 | 3 | writePrecedingCommentsAndNewlines(string);
|
2890 | |
|
2891 | | // Split each line of a multiline string into separate chunks.
|
2892 | 12 | var lines = string.lexeme.split(_formatter.lineEnding);
|
2893 | 3 | var offset = string.offset;
|
2894 | |
|
2895 | 6 | _writeText(lines.first, offset);
|
2896 | 9 | offset += lines.first.length;
|
2897 | |
|
2898 | 4 | for (var line in lines.skip(1)) {
|
2899 | 2 | builder.writeWhitespace(Whitespace.newlineFlushLeft);
|
2900 | 1 | offset++;
|
2901 | 1 | _writeText(line, offset);
|
2902 | 2 | offset += line.length;
|
2903 | | }
|
2904 | | }
|
2905 | |
|
2906 | | /// Emit the given [modifier] if it's non null, followed by non-breaking
|
2907 | | /// whitespace.
|
2908 | 3 | void modifier(Token modifier) {
|
2909 | 6 | token(modifier, after: space);
|
2910 | | }
|
2911 | |
|
2912 | | /// Emit a non-breaking space.
|
2913 | 3 | void space() {
|
2914 | 6 | builder.writeWhitespace(Whitespace.space);
|
2915 | | }
|
2916 | |
|
2917 | | /// Emit a single mandatory newline.
|
2918 | 2 | void newline() {
|
2919 | 4 | builder.writeWhitespace(Whitespace.newline);
|
2920 | | }
|
2921 | |
|
2922 | | /// Emit a two mandatory newlines.
|
2923 | 3 | void twoNewlines() {
|
2924 | 6 | builder.writeWhitespace(Whitespace.twoNewlines);
|
2925 | | }
|
2926 | |
|
2927 | | /// Allow either a single split or newline to be emitted before the next
|
2928 | | /// non-whitespace token based on whether a newline exists in the source
|
2929 | | /// between the last token and the next one.
|
2930 | 1 | void splitOrNewline() {
|
2931 | 2 | builder.writeWhitespace(Whitespace.splitOrNewline);
|
2932 | | }
|
2933 | |
|
2934 | | /// Allow either a single split or newline to be emitted before the next
|
2935 | | /// non-whitespace token based on whether a newline exists in the source
|
2936 | | /// between the last token and the next one.
|
2937 | 1 | void splitOrTwoNewlines() {
|
2938 | 2 | builder.writeWhitespace(Whitespace.splitOrTwoNewlines);
|
2939 | | }
|
2940 | |
|
2941 | | /// Allow either one or two newlines to be emitted before the next
|
2942 | | /// non-whitespace token based on whether more than one newline exists in the
|
2943 | | /// source between the last token and the next one.
|
2944 | 2 | void oneOrTwoNewlines() {
|
2945 | 4 | builder.writeWhitespace(Whitespace.oneOrTwoNewlines);
|
2946 | | }
|
2947 | |
|
2948 | | /// Writes a single space split owned by the current rule.
|
2949 | | ///
|
2950 | | /// Returns the chunk the split was applied to.
|
2951 | 9 | Chunk split() => builder.split(space: true);
|
2952 | |
|
2953 | | /// Writes a zero-space split owned by the current rule.
|
2954 | | ///
|
2955 | | /// Returns the chunk the split was applied to.
|
2956 | 6 | Chunk zeroSplit() => builder.split();
|
2957 | |
|
2958 | | /// Writes a single space split with its own rule.
|
2959 | 3 | Rule soloSplit([int cost]) {
|
2960 | 3 | var rule = new Rule(cost);
|
2961 | 6 | builder.startRule(rule);
|
2962 | 3 | split();
|
2963 | 6 | builder.endRule();
|
2964 | | return rule;
|
2965 | | }
|
2966 | |
|
2967 | | /// Writes a zero-space split with its own rule.
|
2968 | 2 | void soloZeroSplit() {
|
2969 | 4 | builder.startRule();
|
2970 | 4 | builder.split();
|
2971 | 4 | builder.endRule();
|
2972 | | }
|
2973 | |
|
2974 | | /// Emit [token], along with any comments and formatted whitespace that comes
|
2975 | | /// before it.
|
2976 | | ///
|
2977 | | /// Does nothing if [token] is `null`. If [before] is given, it will be
|
2978 | | /// executed before the token is outout. Likewise, [after] will be called
|
2979 | | /// after the token is output.
|
2980 | 3 | void token(Token token, {before(), after()}) {
|
2981 | | if (token == null) return;
|
2982 | |
|
2983 | 3 | writePrecedingCommentsAndNewlines(token);
|
2984 | |
|
2985 | 2 | if (before != null) before();
|
2986 | |
|
2987 | 9 | _writeText(token.lexeme, token.offset);
|
2988 | |
|
2989 | 2 | if (after != null) after();
|
2990 | | }
|
2991 | |
|
2992 | | /// Writes all formatted whitespace and comments that appear before [token].
|
2993 | 3 | bool writePrecedingCommentsAndNewlines(Token token) {
|
2994 | 3 | var comment = token.precedingComments;
|
2995 | |
|
2996 | | // For performance, avoid calculating newlines between tokens unless
|
2997 | | // actually needed.
|
2998 | | if (comment == null) {
|
2999 | 6 | if (builder.needsToPreserveNewlines) {
|
3000 | 12 | builder.preserveNewlines(_startLine(token) - _endLine(token.previous));
|
3001 | | }
|
3002 | |
|
3003 | | return false;
|
3004 | | }
|
3005 | |
|
3006 | 4 | var previousLine = _endLine(token.previous);
|
3007 | 2 | var tokenLine = _startLine(token);
|
3008 | |
|
3009 | | // Edge case: The analyzer includes the "\n" in the script tag's lexeme,
|
3010 | | // which confuses some of these calculations. We don't want to allow a
|
3011 | | // blank line between the script tag and a following comment anyway, so
|
3012 | | // just override the script tag's line.
|
3013 | 6 | if (token.previous.type == TokenType.SCRIPT_TAG) previousLine = tokenLine;
|
3014 | |
|
3015 | 2 | var comments = <SourceComment>[];
|
3016 | | while (comment != null) {
|
3017 | 2 | var commentLine = _startLine(comment);
|
3018 | |
|
3019 | | // Don't preserve newlines at the top of the file.
|
3020 | 4 | if (comment == token.precedingComments &&
|
3021 | 6 | token.previous.type == TokenType.EOF) {
|
3022 | | previousLine = commentLine;
|
3023 | | }
|
3024 | |
|
3025 | 4 | var text = comment.lexeme.trim();
|
3026 | 2 | var linesBefore = commentLine - previousLine;
|
3027 | 4 | var flushLeft = _startColumn(comment) == 1;
|
3028 | |
|
3029 | 3 | if (text.startsWith("///") && !text.startsWith("////")) {
|
3030 | | // Line doc comments are always indented even if they were flush left.
|
3031 | | flushLeft = false;
|
3032 | |
|
3033 | | // Always add a blank line (if possible) before a doc comment block.
|
3034 | 2 | if (comment == token.precedingComments) linesBefore = 2;
|
3035 | | }
|
3036 | |
|
3037 | 2 | var sourceComment = new SourceComment(text, linesBefore,
|
3038 | 4 | isLineComment: comment.type == TokenType.SINGLE_LINE_COMMENT,
|
3039 | | flushLeft: flushLeft);
|
3040 | |
|
3041 | | // If this comment contains either of the selection endpoints, mark them
|
3042 | | // in the comment.
|
3043 | 6 | var start = _getSelectionStartWithin(comment.offset, comment.length);
|
3044 | 0 | if (start != null) sourceComment.startSelection(start);
|
3045 | |
|
3046 | 6 | var end = _getSelectionEndWithin(comment.offset, comment.length);
|
3047 | 0 | if (end != null) sourceComment.endSelection(end);
|
3048 | |
|
3049 | 2 | comments.add(sourceComment);
|
3050 | |
|
3051 | 2 | previousLine = _endLine(comment);
|
3052 | 2 | comment = comment.next;
|
3053 | | }
|
3054 | |
|
3055 | 8 | builder.writeComments(comments, tokenLine - previousLine, token.lexeme);
|
3056 | |
|
3057 | | // TODO(rnystrom): This is wrong. Consider:
|
3058 | | //
|
3059 | | // [/* inline comment */
|
3060 | | // // line comment
|
3061 | | // element];
|
3062 | 6 | return comments.first.linesBefore > 0;
|
3063 | | }
|
3064 | |
|
3065 | | /// Write [text] to the current chunk, given that it starts at [offset] in
|
3066 | | /// the original source.
|
3067 | | ///
|
3068 | | /// Also outputs the selection endpoints if needed.
|
3069 | 3 | void _writeText(String text, int offset) {
|
3070 | 6 | builder.write(text);
|
3071 | |
|
3072 | | // If this text contains either of the selection endpoints, mark them in
|
3073 | | // the chunk.
|
3074 | 6 | var start = _getSelectionStartWithin(offset, text.length);
|
3075 | | if (start != null) {
|
3076 | 4 | builder.startSelectionFromEnd(text.length - start);
|
3077 | | }
|
3078 | |
|
3079 | 6 | var end = _getSelectionEndWithin(offset, text.length);
|
3080 | | if (end != null) {
|
3081 | 4 | builder.endSelectionFromEnd(text.length - end);
|
3082 | | }
|
3083 | | }
|
3084 | |
|
3085 | | /// Returns the number of characters past [offset] in the source where the
|
3086 | | /// selection start appears if it appears before `offset + length`.
|
3087 | | ///
|
3088 | | /// Returns `null` if the selection start has already been processed or is
|
3089 | | /// not within that range.
|
3090 | 3 | int _getSelectionStartWithin(int offset, int length) {
|
3091 | | // If there is no selection, do nothing.
|
3092 | 6 | if (_source.selectionStart == null) return null;
|
3093 | |
|
3094 | | // If we've already passed it, don't consider it again.
|
3095 | 1 | if (_passedSelectionStart) return null;
|
3096 | |
|
3097 | 3 | var start = _source.selectionStart - offset;
|
3098 | |
|
3099 | | // If it started in whitespace before this text, push it forward to the
|
3100 | | // beginning of the non-whitespace text.
|
3101 | 1 | if (start < 0) start = 0;
|
3102 | |
|
3103 | | // If we haven't reached it yet, don't consider it.
|
3104 | 1 | if (start >= length) return null;
|
3105 | |
|
3106 | | // We found it.
|
3107 | 1 | _passedSelectionStart = true;
|
3108 | |
|
3109 | | return start;
|
3110 | | }
|
3111 | |
|
3112 | | /// Returns the number of characters past [offset] in the source where the
|
3113 | | /// selection endpoint appears if it appears before `offset + length`.
|
3114 | | ///
|
3115 | | /// Returns `null` if the selection endpoint has already been processed or is
|
3116 | | /// not within that range.
|
3117 | 3 | int _getSelectionEndWithin(int offset, int length) {
|
3118 | | // If there is no selection, do nothing.
|
3119 | 6 | if (_source.selectionLength == null) return null;
|
3120 | |
|
3121 | | // If we've already passed it, don't consider it again.
|
3122 | 1 | if (_passedSelectionEnd) return null;
|
3123 | |
|
3124 | 2 | var end = _findSelectionEnd() - offset;
|
3125 | |
|
3126 | | // If it started in whitespace before this text, push it forward to the
|
3127 | | // beginning of the non-whitespace text.
|
3128 | 1 | if (end < 0) end = 0;
|
3129 | |
|
3130 | | // If we haven't reached it yet, don't consider it.
|
3131 | 1 | if (end > length) return null;
|
3132 | |
|
3133 | 5 | if (end == length && _findSelectionEnd() == _source.selectionStart) {
|
3134 | | return null;
|
3135 | | }
|
3136 | |
|
3137 | | // We found it.
|
3138 | 1 | _passedSelectionEnd = true;
|
3139 | |
|
3140 | | return end;
|
3141 | | }
|
3142 | |
|
3143 | | /// Calculates the character offset in the source text of the end of the
|
3144 | | /// selection.
|
3145 | | ///
|
3146 | | /// Removes any trailing whitespace from the selection.
|
3147 | 1 | int _findSelectionEnd() {
|
3148 | 2 | if (_selectionEnd != null) return _selectionEnd;
|
3149 | |
|
3150 | 6 | _selectionEnd = _source.selectionStart + _source.selectionLength;
|
3151 | |
|
3152 | | // If the selection bumps to the end of the source, pin it there.
|
3153 | 5 | if (_selectionEnd == _source.text.length) return _selectionEnd;
|
3154 | |
|
3155 | | // Trim off any trailing whitespace. We want the selection to "rubberband"
|
3156 | | // around the selected non-whitespace tokens since the whitespace will
|
3157 | | // be munged by the formatter itself.
|
3158 | 4 | while (_selectionEnd > _source.selectionStart) {
|
3159 | | // Stop if we hit anything other than space, tab, newline or carriage
|
3160 | | // return.
|
3161 | 5 | var char = _source.text.codeUnitAt(_selectionEnd - 1);
|
3162 | 4 | if (char != 0x20 && char != 0x09 && char != 0x0a && char != 0x0d) {
|
3163 | | break;
|
3164 | | }
|
3165 | |
|
3166 | 2 | _selectionEnd--;
|
3167 | | }
|
3168 | |
|
3169 | 1 | return _selectionEnd;
|
3170 | | }
|
3171 | |
|
3172 | | /// Gets the 1-based line number that the beginning of [token] lies on.
|
3173 | 10 | int _startLine(Token token) => _lineInfo.getLocation(token.offset).lineNumber;
|
3174 | |
|
3175 | | /// Gets the 1-based line number that the end of [token] lies on.
|
3176 | 10 | int _endLine(Token token) => _lineInfo.getLocation(token.end).lineNumber;
|
3177 | |
|
3178 | | /// Gets the 1-based column number that the beginning of [token] lies on.
|
3179 | 2 | int _startColumn(Token token) =>
|
3180 | 8 | _lineInfo.getLocation(token.offset).columnNumber;
|
3181 | | }
|