-
Notifications
You must be signed in to change notification settings - Fork 121
/
source_visitor.dart
4450 lines (3748 loc) · 133 KB
/
source_visitor.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// ignore_for_file: avoid_dynamic_calls
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/source/line_info.dart';
// ignore: implementation_imports
import 'package:analyzer/src/clients/dart_style/rewrite_cascade.dart';
import 'argument_list_visitor.dart';
import 'ast_extensions.dart';
import 'call_chain_visitor.dart';
import 'chunk.dart';
import 'chunk_builder.dart';
import 'constants.dart';
import 'dart_formatter.dart';
import 'rule/argument.dart';
import 'rule/combinator.dart';
import 'rule/rule.dart';
import 'rule/type_argument.dart';
import 'source_code.dart';
import 'style_fix.dart';
/// Visits every token of the AST and passes all of the relevant bits to a
/// [ChunkBuilder].
class SourceVisitor extends ThrowingAstVisitor {
/// The builder for the block that is currently being visited.
ChunkBuilder builder;
final DartFormatter _formatter;
/// Cached line info for calculating blank lines.
final LineInfo _lineInfo;
/// The source being formatted.
final SourceCode _source;
/// The most recently written token.
///
/// This is used to determine how many lines are between a pair of tokens in
/// the original source in places where a user can control whether or not a
/// blank line or newline is left in the output.
late Token _lastToken;
/// `true` if the visitor has written past the beginning of the selection in
/// the original source text.
bool _passedSelectionStart = false;
/// `true` if the visitor has written past the end of the selection in the
/// original source text.
bool _passedSelectionEnd = false;
/// The character offset of the end of the selection, if there is a selection.
///
/// This is calculated and cached by [_findSelectionEnd].
int? _selectionEnd;
/// How many levels deep inside a constant context the visitor currently is.
int _constNesting = 0;
/// Whether we are currently fixing a typedef declaration.
///
/// Set to `true` while traversing the parameters of a typedef being converted
/// to the new syntax. The new syntax does not allow `int foo()` as a
/// parameter declaration, so it needs to be converted to `int Function() foo`
/// as part of the fix.
bool _insideNewTypedefFix = false;
/// A stack that tracks forcing nested collections to split.
///
/// Each entry corresponds to a collection currently being visited and the
/// value is whether or not it should be forced to split. Every time a
/// collection is entered, it sets all of the existing elements to `true`
/// then it pushes `false` for itself.
///
/// When done visiting the elements, it removes its value. If it was set to
/// `true`, we know we visited a nested collection so we force this one to
/// split.
final List<bool> _collectionSplits = [];
/// The mapping for blocks that are managed by the argument list that contains
/// them.
///
/// When a block expression, such as a collection literal or a multiline
/// string, appears inside an [ArgumentSublist], the argument list provides a
/// rule for the body to split to ensure that all blocks split in unison. It
/// also tracks the chunk before the argument that determines whether or not
/// the block body is indented like an expression or a statement.
///
/// Before a block argument is visited, [ArgumentSublist] binds itself to the
/// beginning token of each block it controls. When we later visit that
/// literal, we use the token to find that association.
///
/// This mapping is also used for spread collection literals that appear
/// inside control flow elements to ensure that when a "then" collection
/// splits, the corresponding "else" one does too.
final Map<Token, Rule> _blockRules = {};
final Map<Token, Chunk> _blockPreviousChunks = {};
/// Comments and new lines attached to tokens added here are suppressed
/// from the output.
final Set<Token> _suppressPrecedingCommentsAndNewLines = {};
/// Initialize a newly created visitor to write source code representing
/// the visited nodes to the given [writer].
SourceVisitor(this._formatter, this._lineInfo, this._source)
: builder = ChunkBuilder(_formatter, _source);
/// Runs the visitor on [node], formatting its contents.
///
/// Returns a [SourceCode] containing the resulting formatted source and
/// updated selection, if any.
///
/// This is the only method that should be called externally. Everything else
/// is effectively private.
SourceCode run(AstNode node) {
visit(node);
// Output trailing comments.
writePrecedingCommentsAndNewlines(node.endToken.next!);
assert(_constNesting == 0, 'Should have exited all const contexts.');
// Finish writing and return the complete result.
return builder.end();
}
@override
void visitAdjacentStrings(AdjacentStrings node) {
// We generally want to indent adjacent strings because it can be confusing
// otherwise when they appear in a list of expressions, like:
//
// [
// "one",
// "two"
// "three",
// "four"
// ]
//
// Especially when these stings are longer, it can be hard to tell that
// "three" is a continuation of the previous argument.
//
// However, the indentation is distracting in argument lists that don't
// suffer from this ambiguity:
//
// test(
// "A very long test description..."
// "this indentation looks bad.", () { ... });
//
// To balance these, we omit the indentation when an adjacent string
// expression is the only string in an argument list.
var shouldNest = true;
var parent = node.parent;
if (parent is ArgumentList) {
shouldNest = false;
for (var argument in parent.arguments) {
if (argument == node) continue;
if (argument is StringLiteral) {
shouldNest = true;
break;
}
}
} else if (parent is Assertion) {
// Treat asserts like argument lists.
shouldNest = false;
if (parent.condition != node && parent.condition is StringLiteral) {
shouldNest = true;
}
if (parent.message != node && parent.message is StringLiteral) {
shouldNest = true;
}
} else if (parent is VariableDeclaration ||
parent is AssignmentExpression &&
parent.rightHandSide == node &&
parent.parent is ExpressionStatement) {
// Don't add extra indentation in a variable initializer or assignment:
//
// var variable =
// "no extra"
// "indent";
shouldNest = false;
} else if (parent is NamedExpression || parent is ExpressionFunctionBody) {
shouldNest = false;
}
builder.startSpan();
builder.startRule();
if (shouldNest) builder.nestExpression();
visitNodes(node.strings, between: splitOrNewline);
if (shouldNest) builder.unnest();
builder.endRule();
builder.endSpan();
}
@override
void visitAnnotation(Annotation node) {
token(node.atSign);
visit(node.name);
builder.nestExpression();
visit(node.typeArguments);
token(node.period);
visit(node.constructorName);
if (node.arguments != null) {
// Metadata annotations are always const contexts.
_constNesting++;
visitArgumentList(node.arguments!, nestExpression: false);
_constNesting--;
}
builder.unnest();
}
/// Visits an argument list.
///
/// This is a bit complex to handle the rules for formatting positional and
/// named arguments. The goals, in rough order of descending priority are:
///
/// 1. Keep everything on the first line.
/// 2. Keep the named arguments together on the next line.
/// 3. Keep everything together on the second line.
/// 4. Split between one or more positional arguments, trying to keep as many
/// on earlier lines as possible.
/// 5. Split the named arguments each onto their own line.
@override
void visitArgumentList(ArgumentList node, {bool nestExpression = true}) {
// Corner case: handle empty argument lists.
if (node.arguments.isEmpty) {
token(node.leftParenthesis);
// If there is a comment inside the parens, do allow splitting before it.
if (node.rightParenthesis.precedingComments != null) soloZeroSplit();
token(node.rightParenthesis);
return;
}
// If the argument list has a trailing comma, format it like a collection
// literal where each argument goes on its own line, they are indented +2,
// and the ")" ends up on its own line.
if (node.arguments.hasCommaAfter) {
_visitCollectionLiteral(
node.leftParenthesis, node.arguments, node.rightParenthesis);
return;
}
if (nestExpression) builder.nestExpression();
ArgumentListVisitor(this, node).visit();
if (nestExpression) builder.unnest();
}
@override
void visitAsExpression(AsExpression node) {
builder.startSpan();
builder.nestExpression();
visit(node.expression);
soloSplit();
token(node.asOperator);
space();
visit(node.type);
builder.unnest();
builder.endSpan();
}
@override
void visitAssertInitializer(AssertInitializer node) {
token(node.assertKeyword);
var arguments = <Expression>[node.condition];
if (node.message != null) arguments.add(node.message!);
// If the argument list has a trailing comma, format it like a collection
// literal where each argument goes on its own line, they are indented +2,
// and the ")" ends up on its own line.
if (arguments.hasCommaAfter) {
_visitCollectionLiteral(
node.leftParenthesis, arguments, node.rightParenthesis);
return;
}
builder.nestExpression();
var visitor = ArgumentListVisitor.forArguments(
this, node.leftParenthesis, node.rightParenthesis, arguments);
visitor.visit();
builder.unnest();
}
@override
void visitAssertStatement(AssertStatement node) {
_simpleStatement(node, () {
token(node.assertKeyword);
var arguments = [node.condition];
if (node.message != null) arguments.add(node.message!);
// If the argument list has a trailing comma, format it like a collection
// literal where each argument goes on its own line, they are indented +2,
// and the ")" ends up on its own line.
if (arguments.hasCommaAfter) {
_visitCollectionLiteral(
node.leftParenthesis, arguments, node.rightParenthesis);
return;
}
var visitor = ArgumentListVisitor.forArguments(
this, node.leftParenthesis, node.rightParenthesis, arguments);
visitor.visit();
});
}
@override
void visitAssignedVariablePattern(AssignedVariablePattern node) {
token(node.name);
}
@override
void visitAssignmentExpression(AssignmentExpression node) {
builder.nestExpression();
visit(node.leftHandSide);
_visitAssignment(node.operator, node.rightHandSide);
builder.unnest();
}
@override
void visitAwaitExpression(AwaitExpression node) {
token(node.awaitKeyword);
space();
visit(node.expression);
}
@override
void visitBinaryExpression(BinaryExpression node) {
// If a binary operator sequence appears immediately after a `=>`, don't
// add an extra level of nesting. Instead, let the subsequent operands line
// up with the first, as in:
//
// method() =>
// argument &&
// argument &&
// argument;
var nest = node.parent is! ExpressionFunctionBody;
_visitBinary<BinaryExpression>(
node,
precedence: node.operator.type.precedence,
nest: nest,
(expression) => BinaryNode(expression.leftOperand, expression.operator,
expression.rightOperand));
}
@override
void visitBlock(Block node) {
// Treat empty blocks specially. In most cases, they are not allowed to
// split. However, an empty block as the then statement of an if with an
// else is always split.
if (node.statements.isEmptyBody(node.rightBracket)) {
token(node.leftBracket);
if (_splitEmptyBlock(node)) newline();
token(node.rightBracket);
return;
}
_visitBody(node.leftBracket, node.statements, node.rightBracket);
}
@override
void visitBlockFunctionBody(BlockFunctionBody node) {
// Space after the parameter list.
space();
// The "async" or "sync" keyword.
token(node.keyword);
// The "*" in "async*" or "sync*".
token(node.star);
if (node.keyword != null) space();
visit(node.block);
}
@override
void visitBooleanLiteral(BooleanLiteral node) {
token(node.literal);
}
@override
void visitBreakStatement(BreakStatement node) {
_simpleStatement(node, () {
token(node.breakKeyword);
visit(node.label, before: space);
});
}
@override
void visitCascadeExpression(CascadeExpression node) {
// Optimized path if we know the cascade will split.
if (node.cascadeSections.length > 1) {
_visitSplitCascade(node);
return;
}
// Whether a split in the cascade target expression forces the cascade to
// move to the next line. It looks weird to move the cascade down if the
// target expression is a collection, so we don't:
//
// var list = [
// stuff
// ]
// ..add(more);
var target = node.target;
var splitIfTargetSplits = true;
if (node.cascadeSections.length > 1) {
// Always split if there are multiple cascade sections.
} else if (target.isCollectionLiteral) {
splitIfTargetSplits = false;
} else if (target is InvocationExpression) {
// If the target is a call with a trailing comma in the argument list,
// treat it like a collection literal.
splitIfTargetSplits = !target.argumentList.arguments.hasCommaAfter;
} else if (target is InstanceCreationExpression) {
// If the target is a call with a trailing comma in the argument list,
// treat it like a collection literal.
splitIfTargetSplits = !target.argumentList.arguments.hasCommaAfter;
}
if (splitIfTargetSplits) {
builder.startLazyRule(node.allowInline ? Rule() : Rule.hard());
}
visit(node.target);
builder.nestExpression(indent: Indent.cascade, now: true);
builder.startBlockArgumentNesting();
// If the cascade section shouldn't cause the cascade to split, end the
// rule early so it isn't affected by it.
if (!splitIfTargetSplits) {
builder.startRule(node.allowInline ? Rule() : Rule.hard());
}
zeroSplit();
if (!splitIfTargetSplits) builder.endRule();
visitNodes(node.cascadeSections, between: zeroSplit);
if (splitIfTargetSplits) builder.endRule();
builder.endBlockArgumentNesting();
builder.unnest();
}
/// Format the cascade using a nested block instead of a single inline
/// expression.
///
/// If the cascade has multiple sections, we know each section will be on its
/// own line and we know there will be at least one trailing section following
/// a preceding one. That let's us treat all of the earlier sections as a
/// separate block like we do with collections and functions, instead of a
/// monolithic expression. Using a block in turn makes big cascades much
/// faster to format (like 10x) since the block formatting is memoized and
/// each cascade section in it is formatted independently.
///
/// The tricky part is that block formatting assumes the entire line will be
/// part of the block. This is not true of the last section in a cascade,
/// which may have other trailing code, like the `;` here:
///
/// var x = someLeadingExpression
/// ..firstCascade()
/// ..secondCascade()
/// ..thirdCascade()
/// ..fourthCascade();
///
/// To handle that, we don't put the last section in the block and instead
/// format it with the surrounding expression. So, from the formatter's
/// view, the above casade is formatted like:
///
/// var x = someLeadingExpression
/// [ begin block ]
/// ..firstCascade()
/// ..secondCascade()
/// ..thirdCascade()
/// [ end block ]
/// ..fourthCascade();
///
/// This somewhere between clever and hacky, but it works and allows cascades
/// of essentially unbounded length to be formatted quickly.
void _visitSplitCascade(CascadeExpression node) {
// Rule to split the block.
builder.startLazyRule(Rule.hard());
visit(node.target);
builder.nestExpression(indent: Indent.cascade, now: true);
builder.startBlockArgumentNesting();
// If there are comments before the first section, keep them outside of the
// block. That way code like:
//
// receiver // comment
// ..cascade();
//
// Keeps the comment on the first line.
var firstCommentToken = node.cascadeSections.first.beginToken;
writePrecedingCommentsAndNewlines(firstCommentToken);
_suppressPrecedingCommentsAndNewLines.add(firstCommentToken);
// Process the inner cascade sections as a separate block. This way the
// entire cascade expression isn't line split as a single monolithic unit,
// which is very slow.
builder = builder.startBlock(indent: false);
for (var i = 0; i < node.cascadeSections.length - 1; i++) {
newline();
visit(node.cascadeSections[i]);
}
// Put comments before the last section inside the block.
var lastCommentToken = node.cascadeSections.last.beginToken;
writePrecedingCommentsAndNewlines(lastCommentToken);
_suppressPrecedingCommentsAndNewLines.add(lastCommentToken);
builder = builder.endBlock();
// The last section is outside of the block.
visit(node.cascadeSections.last);
builder.endRule();
builder.endBlockArgumentNesting();
builder.unnest();
}
@override
void visitCastPattern(CastPattern node) {
builder.startSpan();
builder.nestExpression();
visit(node.pattern);
soloSplit();
token(node.asToken);
space();
visit(node.type);
builder.unnest();
builder.endSpan();
}
@override
void visitCatchClause(CatchClause node) {
token(node.onKeyword, after: space);
visit(node.exceptionType);
if (node.catchKeyword != null) {
if (node.exceptionType != null) {
space();
}
token(node.catchKeyword);
space();
token(node.leftParenthesis);
visit(node.exceptionParameter);
token(node.comma, after: space);
visit(node.stackTraceParameter);
token(node.rightParenthesis);
space();
} else {
space();
}
visit(node.body);
}
@override
visitCatchClauseParameter(CatchClauseParameter node) {
token(node.name);
}
@override
void visitClassDeclaration(ClassDeclaration node) {
visitMetadata(node.metadata);
builder.nestExpression();
modifier(node.abstractKeyword);
modifier(node.baseKeyword);
modifier(node.interfaceKeyword);
modifier(node.finalKeyword);
modifier(node.sealedKeyword);
modifier(node.mixinKeyword);
modifier(node.inlineKeyword);
token(node.classKeyword);
space();
token(node.name);
visit(node.typeParameters);
visit(node.extendsClause);
_visitClauses(node.withClause, node.implementsClause);
visit(node.nativeClause, before: space);
space();
builder.unnest();
_visitBody(node.leftBracket, node.members, node.rightBracket);
}
@override
void visitClassTypeAlias(ClassTypeAlias node) {
visitMetadata(node.metadata);
_simpleStatement(node, () {
modifier(node.abstractKeyword);
modifier(node.baseKeyword);
modifier(node.interfaceKeyword);
modifier(node.finalKeyword);
modifier(node.sealedKeyword);
modifier(node.mixinKeyword);
token(node.typedefKeyword);
space();
token(node.name);
visit(node.typeParameters);
space();
token(node.equals);
space();
visit(node.superclass);
_visitClauses(node.withClause, node.implementsClause);
});
}
@override
void visitComment(Comment node) {}
@override
void visitCommentReference(CommentReference node) {}
@override
void visitCompilationUnit(CompilationUnit node) {
visit(node.scriptTag);
// Put a blank line between the library tag and the other directives.
Iterable<Directive> directives = node.directives;
if (directives.isNotEmpty && directives.first is LibraryDirective) {
visit(directives.first);
twoNewlines();
directives = directives.skip(1);
}
visitNodes(directives, between: oneOrTwoNewlines);
var needsDouble = true;
for (var declaration in node.declarations) {
var hasBody = declaration is ClassDeclaration ||
declaration is EnumDeclaration ||
declaration is ExtensionDeclaration;
// Add a blank line before types with bodies.
if (hasBody) needsDouble = true;
if (needsDouble) {
twoNewlines();
} else {
// Variables and arrow-bodied members can be more tightly packed if
// the user wants to group things together.
oneOrTwoNewlines();
}
visit(declaration);
needsDouble = false;
if (hasBody) {
// Add a blank line after types declarations with bodies.
needsDouble = true;
} else if (declaration is FunctionDeclaration) {
// Add a blank line after non-empty block functions.
var body = declaration.functionExpression.body;
if (body is BlockFunctionBody) {
needsDouble = body.block.statements.isNotEmpty;
}
}
}
}
@override
void visitConditionalExpression(ConditionalExpression node) {
// TODO(rnystrom): Consider revisiting whether users prefer this after 2.13.
/*
// Flatten else-if style chained conditionals.
var shouldNest = node.parent is! ConditionalExpression ||
(node.parent as ConditionalExpression).elseExpression != node;
if (shouldNest) builder.nestExpression();
*/
builder.nestExpression();
// Start lazily so we don't force the operator to split if a line comment
// appears before the first operand. If we split after one clause in a
// conditional, always split after both.
builder.startLazyRule();
visit(node.condition);
// Push any block arguments all the way past the leading "?" and ":".
builder.nestExpression(indent: Indent.block, now: true);
builder.startBlockArgumentNesting();
builder.unnest();
builder.startSpan();
split();
token(node.question);
space();
builder.nestExpression();
visit(node.thenExpression);
builder.unnest();
split();
token(node.colon);
space();
visit(node.elseExpression);
// If conditional expressions are directly nested, force them all to split.
// This line here forces the child, which implicitly forces the surrounding
// parent rules to split too.
if (node.parent is ConditionalExpression) builder.forceRules();
builder.endRule();
builder.endSpan();
builder.endBlockArgumentNesting();
// TODO(rnystrom): Consider revisiting whether users prefer this after 2.13.
/*
if (shouldNest) builder.unnest();
*/
builder.unnest();
}
@override
void visitConfiguration(Configuration node) {
token(node.ifKeyword);
space();
token(node.leftParenthesis);
visit(node.name);
if (node.equalToken != null) {
builder.nestExpression();
space();
token(node.equalToken);
soloSplit();
visit(node.value);
builder.unnest();
}
token(node.rightParenthesis);
space();
visit(node.uri);
}
@override
void visitConstantPattern(ConstantPattern node) {
token(node.constKeyword, after: space);
visit(node.expression);
}
@override
void visitConstructorDeclaration(ConstructorDeclaration node) {
visitMetadata(node.metadata);
modifier(node.externalKeyword);
modifier(node.constKeyword);
modifier(node.factoryKeyword);
visit(node.returnType);
token(node.period);
token(node.name);
// Make the rule for the ":" span both the preceding parameter list and
// the entire initialization list. This ensures that we split before the
// ":" if the parameters and initialization list don't all fit on one line.
if (node.initializers.isNotEmpty) builder.startRule();
// If the redirecting constructor happens to wrap, we want to make sure
// the parameter list gets more deeply indented.
if (node.redirectedConstructor != null) builder.nestExpression();
_visitFunctionBody(null, node.parameters, node.body, () {
// Check for redirects or initializer lists.
if (node.redirectedConstructor != null) {
_visitConstructorRedirects(node);
builder.unnest();
} else if (node.initializers.isNotEmpty) {
_visitConstructorInitializers(node);
// End the rule for ":" after all of the initializers.
builder.endRule();
}
});
}
void _visitConstructorRedirects(ConstructorDeclaration node) {
token(node.separator /* = */, before: space);
soloSplit();
visitCommaSeparatedNodes(node.initializers);
visit(node.redirectedConstructor);
}
void _visitConstructorInitializers(ConstructorDeclaration node) {
var hasTrailingComma = node.parameters.parameters.hasCommaAfter;
if (hasTrailingComma) {
// Since the ")", "])", or "})" on the preceding line doesn't take up
// much space, it looks weird to move the ":" onto it's own line. Instead,
// keep it and the first initializer on the current line but add enough
// space before it to line it up with any subsequent initializers.
//
// Foo(
// parameter,
// ) : field = value,
// super();
space();
if (node.initializers.length > 1) {
var padding = ' ';
if (node.parameters.parameters.last.isNamed ||
node.parameters.parameters.last.isOptionalPositional) {
padding = ' ';
}
_writeText(padding, node.separator!);
}
// ":".
token(node.separator);
space();
builder.indent(6);
} else {
// Shift the itself ":" forward.
builder.indent(Indent.constructorInitializer);
// If the parameters or initializers split, put the ":" on its own line.
split();
// ":".
token(node.separator);
space();
// Try to line up the initializers with the first one that follows the ":":
//
// Foo(notTrailing)
// : initializer = value,
// super(); // +2 from previous line.
//
// Foo(
// trailing,
// ) : initializer = value,
// super(); // +4 from previous line.
//
// This doesn't work if there is a trailing comma in an optional parameter,
// but we don't want to do a weird +5 alignment:
//
// Foo({
// trailing,
// }) : initializer = value,
// super(); // Doesn't quite line up. :(
builder.indent(2);
}
for (var i = 0; i < node.initializers.length; i++) {
if (i > 0) {
// Preceding comma.
token(node.initializers[i].beginToken.previous);
newline();
}
node.initializers[i].accept(this);
}
builder.unindent();
if (!hasTrailingComma) builder.unindent();
}
@override
void visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
builder.nestExpression();
token(node.thisKeyword);
token(node.period);
visit(node.fieldName);
_visitAssignment(node.equals, node.expression);
builder.unnest();
}
@override
void visitConstructorName(ConstructorName node) {
visit(node.type);
token(node.period);
visit(node.name);
}
@override
void visitContinueStatement(ContinueStatement node) {
_simpleStatement(node, () {
token(node.continueKeyword);
visit(node.label, before: space);
});
}
@override
void visitDeclaredIdentifier(DeclaredIdentifier node) {
modifier(node.keyword);
visit(node.type, after: space);
token(node.name);
}
@override
void visitDeclaredVariablePattern(DeclaredVariablePattern node) {
_visitVariablePattern(node.keyword, node.type, node.name);
}
@override
void visitDefaultFormalParameter(DefaultFormalParameter node) {
visit(node.parameter);
if (node.separator != null) {
builder.startSpan();
builder.nestExpression();
if (_formatter.fixes.contains(StyleFix.namedDefaultSeparator)) {
// Change the separator to "=".
space();
writePrecedingCommentsAndNewlines(node.separator!);
_writeText('=', node.separator!);
} else {
// The '=' separator is preceded by a space, ":" is not.
if (node.separator!.type == TokenType.EQ) space();
token(node.separator);
}
soloSplit(_assignmentCost(node.defaultValue!));
visit(node.defaultValue);
builder.unnest();
builder.endSpan();
}
}
@override
void visitDoStatement(DoStatement node) {
builder.nestExpression();
token(node.doKeyword);
space();
builder.unnest(now: false);
visit(node.body);
builder.nestExpression();
space();
token(node.whileKeyword);
space();
token(node.leftParenthesis);
soloZeroSplit();
visit(node.condition);
token(node.rightParenthesis);
token(node.semicolon);
builder.unnest();
}
@override
void visitDottedName(DottedName node) {
for (var component in node.components) {
// Write the preceding ".".
if (component != node.components.first) {
token(component.beginToken.previous);
}
visit(component);
}
}
@override
void visitDoubleLiteral(DoubleLiteral node) {
token(node.literal);
}
@override
void visitEmptyFunctionBody(EmptyFunctionBody node) {
token(node.semicolon);
}
@override
void visitEmptyStatement(EmptyStatement node) {
token(node.semicolon);
}
@override
void visitEnumConstantDeclaration(EnumConstantDeclaration node) {
visitMetadata(node.metadata);
token(node.name);
var arguments = node.arguments;
if (arguments != null) {
builder.nestExpression();
visit(arguments.typeArguments);