-
Notifications
You must be signed in to change notification settings - Fork 276
/
FormatOps.scala
2892 lines (2663 loc) · 101 KB
/
FormatOps.scala
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
package org.scalafmt.internal
import org.scalafmt.Error.UnexpectedTree
import org.scalafmt.config.{
BinPack,
IndentOperator,
Indents,
Newlines,
ScalafmtConfig,
ScalafmtRunner,
TrailingCommas
}
import org.scalafmt.internal.Length.Num
import org.scalafmt.internal.Policy.NoPolicy
import org.scalafmt.util._
import org.scalafmt.util.InfixApp._
import org.scalafmt.util.LoggerOps._
import org.scalameta.FileLine
import scala.annotation.tailrec
import scala.collection.mutable
import scala.meta.classifiers.Classifier
import scala.meta._
import scala.meta.tokens.{Token => T}
/** Helper functions for generating splits/policies for a given tree.
*/
class FormatOps(
val topSourceTree: Tree,
baseStyle: ScalafmtConfig,
val filename: String = ""
) {
import FormatOps._
import PolicyOps._
import TokenOps._
import TreeOps._
private val (initStyle, ownersMap) =
getStyleAndOwners(topSourceTree, baseStyle)
val runner: ScalafmtRunner = initStyle.runner
implicit val dialect: Dialect = initStyle.dialect
implicit val (tokens: FormatTokens, styleMap: StyleMap) =
FormatTokens(topSourceTree.tokens, owners)(initStyle)
import tokens.{
matching,
matchingOpt,
isEnclosedInMatching,
isEnclosedInParens,
findTokenWith,
tokenBefore,
tokenAfter,
prev,
next,
prevNonComment,
prevNonCommentBefore,
nextNonComment,
nextNonCommentSameLine
}
private val usedTokens = tokens.head.left +: tokens.map(_.right)
private[internal] val soft = new SoftKeywordClasses(dialect)
private[internal] val statementStarts =
getStatementStarts(topSourceTree, soft)
// Maps token to number of non-whitespace bytes before the token's position.
private final val nonWhitespaceOffset: Map[T, Int] = {
val resultB = Map.newBuilder[T, Int]
var curr = 0
usedTokens.foreach { t =>
resultB += (t -> curr)
curr += (t.end - t.start)
}
resultB.result()
}
val (forceConfigStyle, emptyQueueSpots) = getForceConfigStyle
@inline
def owners(token: T): Tree = ownersMap(hash(token))
/*
* The tokens on the left hand side of Pkg
*
* For example Set(org, ., scalafmt) in:
*
* package org.scalafmt
*
* import foo.bar
* ...
*
*/
val (argumentStarts, optionalNewlines) = {
val arguments = mutable.Map.empty[TokenHash, Tree]
val optional = Set.newBuilder[TokenHash]
def getHeadHash(tree: Tree): Option[TokenHash] =
tokens.getHeadOpt(tree).map(x => hash(x.left))
def add(tree: Tree): Unit =
getHeadHash(tree).foreach { x =>
if (!arguments.contains(x)) arguments += x -> tree
}
def addOptional(tree: Tree): Unit =
getHeadHash(tree).foreach { optional += _ }
val queue = new mutable.ListBuffer[Seq[Tree]]
queue += topSourceTree :: Nil
while (queue.nonEmpty) queue.remove(0).foreach { tree =>
tree match {
case _: Lit.Unit | _: Member.SyntaxValuesClause =>
case t: Term.Param =>
add(t)
t.mods.foreach(addOptional)
addOptional(t.name)
case t: Term => add(t)
case t: Pat.Extract => t.argClause.values.foreach(add)
case _ =>
}
queue += tree.children
}
(arguments.toMap, optional.result())
}
class ExtractFromMeta[A](f: FormatToken => Option[A]) {
def unapply(meta: FormatToken.Meta): Option[A] = f(tokens(meta.idx))
}
@inline
final def findFirst(start: FormatToken, end: T)(
f: FormatToken => Boolean
): Option[FormatToken] = {
findFirst(start, end.end)(f)
}
@tailrec
final def findFirst(start: FormatToken, end: Int)(
f: FormatToken => Boolean
): Option[FormatToken] = {
if (start.left.end >= end) None
else if (f(start)) Some(start)
else {
val next_ = next(start)
if (next_ == start) None
else findFirst(next_, end)(f)
}
}
def findFirstOnRight[A](start: FormatToken, end: T)(implicit
classifier: Classifier[T, A]
): Option[T] =
findFirst(start, end.start)(x => classifier(x.right)).map(_.right)
final def rhsOptimalToken(
start: FormatToken,
end: Int = Int.MaxValue
): T =
findTokenWith(start, next) { start =>
start.right match {
case t if t.end >= end => Some(start.left)
case _ if start.hasBlankLine => Some(start.left)
case _: T.RightParen
if start.left.is[T.RightParen] || start.left.is[T.LeftParen] =>
None
case _: T.RightBracket if start.left.is[T.RightBracket] => None
case _: T.Comma | _: T.LeftParen | _: T.Semicolon | _: T.RightArrow |
_: T.Equals if isInfixRhs(start) || !startsNewBlockOnRight(start) =>
None
case c: T.Comment
if start.noBreak && (!start.left.is[T.LeftParen] ||
tokens.isBreakAfterRight(start)) =>
Some(c)
case _ => Some(start.left)
}
}.fold(_.right, identity)
@tailrec
final def endOfSingleLineBlock(
start: FormatToken
)(implicit style: ScalafmtConfig): T = {
lazy val isInfix = isInfixRhs(start)
val endFound = start.right match {
case _: T.Comma | _: T.LeftParen | _: T.Semicolon | _: T.RightArrow |
_: T.Equals =>
None
case _: T.RightParen if start.left.is[T.LeftParen] => None
case c: T.Comment if start.noBreak && tokens.isBreakAfterRight(start) =>
Some(c)
case _ if start.noBreak && isInfix => None
case _ => Some(start.left)
}
endFound match {
case Some(t) => t
case None =>
if (!tokens.hasNext(start)) start.right
else if (!isInfix && startsNewBlockOnRight(start)) start.left
else endOfSingleLineBlock(next(start))
}
}
final def isInfixRhs(ft: FormatToken): Boolean = {
val tree = ft.meta.rightOwner
@inline def checkToken = tokens.tokenJustBeforeOpt(tree).contains(ft)
tree.parent.exists {
case ia: Member.Infix =>
(ia.op eq tree) || (ia.arg eq tree) &&
(ft.right.is[T.LeftParen] || checkToken)
case t: Member.ArgClause =>
t.parent.exists(_.is[Member.Infix]) && checkToken
case _ => false
}
}
final def startsNewBlockOnRight(ft: FormatToken): Boolean =
ft.meta.rightOwner match {
case _: Member.ArgClause => false
case t => tokens.tokenBeforeOpt(t).contains(ft)
}
/** js.native is very special in Scala.js.
*
* Context: https://github.com/scalameta/scalafmt/issues/108
*/
def isJsNative(body: Tree): Boolean =
initStyle.newlines.neverBeforeJsNative && (body match {
case Term.Select(Term.Name("js"), Term.Name("native")) => true
case _ => false
})
@inline
final def startsStatement(tok: FormatToken): Option[Tree] =
startsStatement(tok.right)
@inline
final def startsStatement(token: T): Option[Tree] =
statementStarts.get(hash(token))
val StartsStatementRight = new ExtractFromMeta[Tree](startsStatement)
def parensTuple(token: T): TokenRanges =
matchingOpt(token).fold(TokenRanges.empty) { other =>
TokenRanges(TokenRange(token, other))
}
def insideBlock[A](start: FormatToken, end: T)(implicit
classifier: Classifier[T, A]
): TokenRanges =
insideBlock(start, end, x => classifier(x.left))
def insideBlock(
start: FormatToken,
end: T,
matches: FormatToken => Boolean
): TokenRanges =
insideBlock { x =>
if (matches(x)) matchingOpt(x.left) else None
}(start, end)
def insideBracesBlock(
start: FormatToken,
end: T,
parensToo: Boolean = false
)(implicit style: ScalafmtConfig): TokenRanges =
insideBlock(x => getEndOfBlock(x, parensToo))(start, end)
def insideBlock(matches: FormatToken => Option[T])(
start: FormatToken,
end: T
): TokenRanges = {
var result = TokenRanges.empty
@tailrec
def run(tok: FormatToken): Unit =
if (tok.left.start < end.start) {
val nextTokOpt = matches(tok).flatMap { close =>
val open = tok.left
if (open.start >= close.end) None
else {
result = result.append(TokenRange(open, close))
Some(tokens(close))
}
}
val nextTok = nextTokOpt.getOrElse(next(tok))
if (nextTok ne tok) run(nextTok)
}
run(next(start))
result
}
// invoked on closing paren, part of ParamClause
@tailrec
final def defnSiteLastToken(close: FormatToken, t: Tree): T = {
def alt = getLastToken(t)
t match {
case _: Term.ParamClause | _: Type.FuncParamClause |
_: Member.ParamClauseGroup =>
t.parent match {
case Some(p) => defnSiteLastToken(close, p)
case _ => alt
}
case t: Defn.Def =>
tokens.getHeadOpt(t.body).fold(alt) { ft =>
if (ft.left.is[T.LeftBrace] && t.body.is[Term.Block]) ft.left
else prevNonCommentBefore(ft).left
}
case _: Ctor.Primary =>
close match {
// This is a terrible terrible hack. Please consider removing this.
// The RightParen() LeftBrace() pair is presumably a ") {" combination
// at a class definition
case FormatToken(_: T.RightParen, b: T.LeftBrace, _) => b
case _ => close.left
}
case t =>
t.tokens.find(x => x.is[T.Equals] && owners(x) == t).getOrElse(alt)
}
}
@inline
def splitOneArgOneLine(close: T, owner: Tree)(implicit
fileLine: FileLine,
style: ScalafmtConfig
): Policy = {
val pf =
if (style.poorMansTrailingCommasInConfigStyle)
splitOneArgPerLineBeforeComma(owner)
else
splitOneArgPerLineAfterComma(owner)
Policy.before(close)(pf)
}
def splitOneArgPerLineBeforeComma(owner: Tree): Policy.Pf = {
// TODO(olafur) clear queue between arguments, they are independent.
case Decision(t @ FormatToken(_, _: T.Comma, _), splits)
if owner == t.meta.rightOwner && !next(t).right.is[T.Comment] =>
splits.map(x => if (x.modExt.mod ne NoSplit) x else x.withMod(Newline))
case Decision(t @ FormatToken(_: T.Comma, right, _), splits)
if owner == t.meta.leftOwner &&
!right.is[T.LeftBrace] &&
// If comment is bound to comma, see unit/Comment.
(!right.is[T.Comment] || t.hasBreak) =>
val isNewline = right.is[T.Comment]
splits.filter(_.isNL == isNewline)
}
def splitOneArgPerLineAfterComma(owner: Tree): Policy.Pf = {
// Newline on every comma.
case Decision(t @ FormatToken(_: T.Comma, right, m), splits)
if owner == m.leftOwner &&
// TODO(olafur) what the right { decides to be single line?
// If comment is bound to comma, see unit/Comment.
(!right.is[T.Comment] || t.hasBreak) =>
getOneArgPerLineSplitsAfterComma(right, splits)
}
def splitOneArgPerLineAfterCommaOnBreak(comma: T): Policy =
delayedBreakPolicyBefore(comma) {
Policy.after(comma) {
case Decision(t @ FormatToken(`comma`, right, _), splits)
if !right.is[T.Comment] || t.hasBreak =>
getOneArgPerLineSplitsAfterComma(right, splits)
}
}
private def getOneArgPerLineSplitsAfterComma(r: T, s: Seq[Split]) =
if (r.is[T.LeftBrace]) SplitTag.OneArgPerLine.activateOnly(s)
else Decision.onlyNewlineSplits(s)
def penalizeNewlineByNesting(from: T, to: T)(implicit
fileLine: FileLine
): Policy = {
val policy = Policy.before(to) { case Decision(FormatToken(l, _, m), s) =>
val nonBoolPenalty = if (isBoolOperator(l)) 0 else 5
val penalty = nestedSelect(m.leftOwner) +
nestedApplies(m.rightOwner) + nonBoolPenalty
s.map { x => if (x.isNL) x.withPenalty(penalty) else x }
}
new Policy.Delay(policy, Policy.End.Before(from))
}
val WithTemplateOnLeft = new ExtractFromMeta(ft =>
ft.meta.leftOwner match {
case lo: Stat.WithTemplate => Some(lo.templ)
case _ => None
}
)
val TemplateOnRight = new ExtractFromMeta(ft =>
ft.meta.rightOwner match {
case ro: Template => Some(ro)
case _ => None
}
)
def templateCurlyFt(template: Template): Option[FormatToken] =
getStartOfTemplateBody(template).map(tokenBefore)
def templateCurly(template: Template): Option[T] =
templateCurlyFt(template).map(_.left)
def templateCurlyOrLastNonTrivial(template: Template): T =
templateCurly(template).getOrElse(getLastNonTrivialToken(template))
def templateDerivesOrCurlyOrLastNonTrivial(
template: Template
)(implicit ft: FormatToken): T =
findTemplateGroupOnRight(_.getExpireToken)(template)
.getOrElse(templateCurlyOrLastNonTrivial(template))
private def findTreeInGroup[A](
trees: Seq[Tree],
func: TemplateSupertypeGroup => A
)(expireFunc: Seq[Tree] => T)(implicit ft: FormatToken): Option[A] =
trees.find(_.pos.end >= ft.right.end).map { x =>
func(TemplateSupertypeGroup(x, trees, expireFunc))
}
def findTemplateGroupOnRight[A](
func: TemplateSupertypeGroup => A
)(template: Template)(implicit ft: FormatToken): Option[A] = {
@tailrec
def iter(groups: Seq[Seq[Tree]]): Option[A] =
if (isSeqSingle(groups))
// for the last group, return '{' or ':'
findTreeInGroup(groups.head, func) { x =>
templateCurly(template).getOrElse(getLastNonTrivialToken(x.last))
}
else {
// for intermediate groups, return its last token
val res = findTreeInGroup(groups.head, func)(x => tokenAfter(x).left)
if (res.isDefined) res else iter(groups.tail)
}
getTemplateGroups(template).flatMap(iter)
}
@inline
def getBreakBeforeElsePolicy(term: Term.If): Policy =
getElseChain(term, Nil).foldLeft(Policy.noPolicy) { case (res, els) =>
val policy = Policy.on(els) {
case d @ Decision(FormatToken(_, `els`, _), _) =>
d.onlyNewlinesWithFallback(Split(Newline, 0))
}
Policy.Relay(policy, res)
}
@tailrec
private final def getElseChain(term: Term.If, res: Seq[T]): Seq[T] = {
tokens.getHeadOpt(term.elsep) match {
case Some(ftElsep) =>
val beforeElsep = prevNonCommentBefore(ftElsep)
val newRes = beforeElsep.left match {
case els: T.KwElse
if initStyle.newlines.alwaysBeforeElseAfterCurlyIf ||
!prev(beforeElsep).left.is[T.RightBrace] =>
els +: res
case _ => res
}
term.elsep match {
case t: Term.If => getElseChain(t, newRes)
case b @ Term.Block(List(t: Term.If))
if !tokens.areMatching(ftElsep.left)(getLastToken(b)) =>
getElseChain(t, newRes)
case _ => newRes
}
case _ => res
}
}
def getOptimalTokenFor(token: T): T =
getOptimalTokenFor(tokens(token))
def getOptimalTokenFor(ft: FormatToken): T =
if (tokens.isAttachedCommentThenBreak(ft)) ft.right else ft.left
def insideInfixSplit(
app: Member.Infix,
ft: FormatToken
)(implicit style: ScalafmtConfig): Seq[Split] =
app match {
case t: Type.ApplyInfix
if style.spaces.neverAroundInfixTypes.contains(t.op.value) =>
Seq(Split(NoSplit, 0))
case t =>
val isBeforeOp = ft.meta.leftOwner ne app.op
def useSpace = style.spaces.beforeInfixArgInParens(app.op.value) ||
(app.arg match {
case _: Lit.Unit => false
case x: Member.ArgClause if x.values.lengthCompare(1) != 0 => false
case x => !isEnclosedInParens(x)
})
val afterInfix = style.breakAfterInfix(t)
if (isBeforeOp && endsWithFewerBraces(app.lhs)) Seq(Split(Newline, 0))
else if (afterInfix ne Newlines.AfterInfix.keep) {
if (isBeforeOp) Seq(Split(Space, 0))
else {
val spaceMod = Space(useSpace)
val fullInfix = InfixSplits.findEnclosingInfix(app)
val ok = isEnclosedInParens(fullInfix) || fullInfix.parent.forall {
case t: Defn.Val => t.rhs eq fullInfix
case t: Defn.Var => t.body eq fullInfix
case _ => true
}
if (ok)
InfixSplits(app, ft, fullInfix)
.getBeforeLhsOrRhs(afterInfix, spaceMod = spaceMod)
else Seq(Split(spaceMod, 0))
}
} else {
// we don't modify line breaks generally around infix expressions
// TODO: if that ever changes, modify how rewrite rules handle infix
val mod = getMod(ft)
val modOrNoSplit =
if (mod != Space || isBeforeOp || useSpace) mod else NoSplit
Seq(InfixSplits.withNLIndent(Split(modOrNoSplit, 0))(app, ft))
}
}
def getInfixSplitsBeforeLhs(
lhsApp: Member.Infix,
ft: FormatToken,
afterInfix: Newlines.AfterInfix,
newStmtMod: Option[Modification] = None
)(implicit style: ScalafmtConfig): Seq[Split] = {
val fullInfixTreeOpt =
findTreeWithParentSimple(lhsApp, false)(isInfixApp)
val fullInfix = fullInfixTreeOpt.flatMap(asInfixApp).getOrElse(lhsApp)
val app = findLeftInfix(fullInfix)
new InfixSplits(app, ft, fullInfix, app)
.getBeforeLhsOrRhs(afterInfix, newStmtMod)
}
final def maybeGetInfixSplitsBeforeLhs(
ft: FormatToken,
mod: => Option[Modification] = None
)(nonInfixSplits: => Seq[Split])(implicit
style: ScalafmtConfig
): Seq[Split] = {
val tree = ft.meta.rightOwner
val ai = style.breakAfterInfix(tree)
val app = if (ai eq Newlines.AfterInfix.keep) None else asInfixApp(tree)
app.fold(nonInfixSplits)(getInfixSplitsBeforeLhs(_, ft, ai, mod))
}
private[internal] object InfixSplits {
def apply(app: Member.Infix, ft: FormatToken)(implicit
style: ScalafmtConfig
): InfixSplits =
apply(app, ft, findEnclosingInfix(app))
def apply(app: Member.Infix, ft: FormatToken, fullInfix: Member.Infix)(
implicit style: ScalafmtConfig
): InfixSplits = {
val leftInfix = findLeftInfix(fullInfix)
new InfixSplits(app, ft, fullInfix, leftInfix)
}
private def switch(splits: Seq[Split], triggers: T*): Seq[Split] =
splits.map { x =>
triggers.foldLeft(x) { case (y, trigger) => y.switch(trigger, false) }
}
@tailrec
private def findEnclosingInfix(
child: Member.Infix,
childTree: Tree
): Member.Infix =
if (isEnclosedInParens(childTree)) child
else
childTree.parent match {
case Some(p: Member.Infix) if !p.isAssignment =>
findEnclosingInfix(p, p)
case Some(p @ Member.ArgClause(_ :: Nil)) =>
findEnclosingInfix(child, p)
case _ => child
}
private[FormatOps] def findEnclosingInfix(app: Member.Infix): Member.Infix =
findEnclosingInfix(app, app)
def withNLIndent(split: Split)(app: Member.Infix, ft: FormatToken)(implicit
style: ScalafmtConfig
): Split = {
val noNL = !split.isNL && {
val nextFt = nextNonCommentSameLine(ft)
nextFt.eq(ft) || nextFt.noBreak
}
if (noNL) split else apply(app, ft).withNLIndent(split)
}
}
private[internal] class InfixSplits(
app: Member.Infix,
ft: FormatToken,
fullInfix: Member.Infix,
leftInfix: Member.Infix
)(implicit style: ScalafmtConfig) {
private val beforeLhs = ft.left.start < app.pos.start
private val fullExpire = getLastEnclosedToken(fullInfix)
private val isFirstOp = beforeLhs || (leftInfix.op eq app.op)
private val assignBodyExpire = {
val prevFt = tokenBefore(fullInfix)
val prevOwner = prevFt.meta.leftOwner
prevFt.left match {
case _: T.Equals => Some(getLastToken(prevOwner))
case _: T.LeftParen | _: T.LeftBracket
if fullInfix.parent.contains(prevOwner) && !(prevOwner match {
case po: Member.ArgClause => po.parent.exists(isInfixApp)
case po => isInfixApp(po)
}) && isSeqSingle(getArgs(prevOwner, orNil = true)) =>
Some(getLastToken(fullInfix))
case _ => None
}
}
private val skipInfixIndent: Boolean = {
@tailrec
def getLastPat(t: Tree): Tree =
t.parent match {
case Some(p @ (_: Pat | _: Pat.ArgClause)) => getLastPat(p)
case _ => t
}
def getChild = fullInfix match {
case t: Pat => getLastPat(t)
case t => t
}
def isOldTopLevel(child: Tree) = child.parent.exists {
case _: Term.Block | _: Term.If | _: Term.While | _: Source => true
case fun: Term.FunctionTerm => isBlockFunction(fun)
case t: Case => t.pat.eq(child) || t.body.eq(child)
case SingleArgInBraces(_, arg, _) => child eq arg
case _ => false
}
def isAloneEnclosed(child: Tree) = child.parent.exists {
case p: Case => p.pat eq child
case p: Term.If => p.cond eq child
case p: Term.While => p.expr eq child
case p: Term.Do => p.expr eq child
case p: Term.Block => isSingleElement(p.stats, child)
case p: Term.FunctionTerm => isBlockFunction(p)
case p @ Member.ArgClause(`child` :: Nil) => isEnclosedInMatching(p)
case Member.Tuple(`child` :: Nil) => true
case _ => false
}
def isAloneArgOrBody(child: Tree) = child.parent.exists {
case t: Case => t.pat.eq(child) || t.body.eq(child)
case _: Term.If | _: Term.While | _: Term.Do => true
case _: Member.ArgClause => true
case p: Term.Block => isSingleElement(p.stats, child)
case _: Init | _: Term.Super | _: Member.Tuple => true
case t: Tree.WithBody => t.body eq child
case t: Term.Param => t.default.contains(child)
case _ => false
}
val allowNoIndent = style.indentOperator.getExemptScope match {
case IndentOperator.Exempt.all => true
case IndentOperator.Exempt.oldTopLevel => isOldTopLevel(getChild)
case IndentOperator.Exempt.aloneEnclosed => isAloneEnclosed(getChild)
case IndentOperator.Exempt.aloneArgOrBody => isAloneArgOrBody(getChild)
}
def isInfixTopLevelMatch(op: String, noindent: Boolean): Boolean = {
noindent == style.indentOperator.noindent(op) &&
noindent == allowNoIndent
}
if (style.verticalAlignMultilineOperators)
!isAssignment(ft.meta.left.text)
else if (beforeLhs) assignBodyExpire.isEmpty
else if (
!app.singleArg.exists { x =>
x.is[Term.Block] || x.is[Term.NewAnonymous]
} && isInfixTopLevelMatch(ft.meta.left.text, false)
) false
else if (isInfixTopLevelMatch(app.op.value, true)) true
else if (app.is[Pat] && isChildOfCaseClause(app)) true
else false
}
private val fullIndent: Indent = {
val expire = assignBodyExpire match {
case Some(x) if beforeLhs => x
case _ => fullExpire
}
Indent(Num(style.indent.main), expire, ExpiresOn.After)
}
val (nlIndent, nlPolicy) = {
def policy(triggers: T*)(implicit fileLine: FileLine) =
if (triggers.isEmpty) Policy.NoPolicy
else
Policy.on(fullExpire) {
case Decision(t: FormatToken, s)
if isInfixOp(t.meta.leftOwner) ||
isInfixOp(t.meta.rightOwner) &&
!t.meta.rightOwner.parent.exists(style.formatInfix(_)) =>
InfixSplits.switch(s, triggers: _*)
}
val fullTok = getIndentTrigger(fullInfix)
val noAssign = assignBodyExpire.isEmpty
if (!noAssign && beforeLhs) (fullIndent, policy(fullTok))
else if (skipInfixIndent) {
if (noAssign) (Indent.Empty, Policy.NoPolicy)
else (Indent.before(fullIndent, fullTok), policy(fullTok))
} else {
val opTok = getIndentTrigger(leftInfix.op)
val ind =
if (isFirstOp) fullIndent else Indent.before(fullIndent, opTok)
if (noAssign) (ind, policy(opTok))
else (Indent.Switch(fullIndent, fullTok, ind), policy(fullTok, opTok))
}
}
private def withNLIndent(split: Split): Split =
split.withIndent(nlIndent).andPolicy(nlPolicy)
def getBeforeLhsOrRhs(
afterInfix: Newlines.AfterInfix,
newStmtMod: Option[Modification] = None,
spaceMod: Modification = Space
): Seq[Split] = {
val beforeLhs = ft.meta.leftOwner ne app.op
val maxPrecedence =
if (beforeLhs) 0 // not used
else infixSequenceMaxPrecedence(fullInfix)
val closeOpt = matchingOpt(ft.right)
val expiresOpt =
if (closeOpt.isDefined) None
else {
val res = mutable.Buffer.empty[Member.Infix]
findNextInfixes(fullInfix, app.lhs, res)
val infixes = if (beforeLhs) res.toSeq else res.toSeq.tail
val filtered =
if (!style.newlines.afterInfixBreakOnNested) infixes
else infixes.takeWhile(x => !isEnclosedInParens(x.lhs))
if (filtered.isEmpty) None
else {
val res = filtered.foldLeft(Seq.empty[(T, Int)]) { case (out, ia) =>
val cost = maxPrecedence - ia.precedence
if (out.nonEmpty && out.head._2 <= cost) out
else (getMidInfixToken(ia) -> cost) +: out
}
Some(res)
}
}
val breakPenalty = if (beforeLhs) 1 else maxPrecedence - app.precedence
val expires = expiresOpt.fold(Seq(fullExpire -> 0)) { x =>
(if (x.head._2 == 0) x else (fullExpire -> 0) +: x).reverse
}
val infixTooLong = infixSequenceLength(fullInfix) >
style.newlines.afterInfixMaxCountPerExprForSome
val breakMany = infixTooLong || afterInfix == Newlines.AfterInfix.many
val rightAsInfix = asInfixApp(ft.meta.rightOwner)
def breakAfterComment(t: FormatToken) = {
val end = nextNonCommentSameLine(t)
if (end.right.is[T.LeftBrace] || end.right.is[T.Comment]) None
else if (end eq t) Some(decideNewlinesOnlyAfterToken(end.left))
else Some(decideNewlinesOnlyAfterClose(end.left))
}
val nlMod = newStmtMod.getOrElse {
Space.orNL(ft.noBreak && ft.right.is[T.Comment])
}
val delayedBreak = if (nlMod.isNewline) None else breakAfterComment(ft)
val (singleLineExpire, singleLineIndent) = {
val skip = skipInfixIndent
if (isFirstOp) (fullExpire, if (skip) Indent.Empty else fullIndent)
else {
val expire = expires.head._1
val indentLen = if (skip) 0 else style.indent.main
val indent = Indent(Num(indentLen), expire, ExpiresOn.After)
(expire, indent)
}
}
val singleLinePolicy =
if (infixTooLong || !isFirstOp) None
else Some(getSingleLineInfixPolicy(fullExpire))
val nlSinglelineSplit = Split(nlMod, 0)
.onlyIf(singleLinePolicy.isDefined && beforeLhs)
.withIndent(singleLineIndent)
.withSingleLine(singleLineExpire)
.andPolicyOpt(singleLinePolicy)
.andPolicyOpt(delayedBreak)
val spaceSingleLine = Split(spaceMod, 0)
.onlyIf(newStmtMod.isEmpty)
.withSingleLine(singleLineExpire)
.andPolicyOpt(singleLinePolicy)
val singleLineSplits = Seq(
spaceSingleLine.onlyFor(SplitTag.InfixChainNoNL),
spaceSingleLine.onlyIf(singleLinePolicy.isDefined),
nlSinglelineSplit
)
val otherSplits = closeOpt.fold {
val nlSplit = Split(nlMod, 1 + breakPenalty)
Seq(nlSplit.withIndent(nlIndent).withPolicy(nlPolicy & delayedBreak))
} { close =>
val noSingleLine = newStmtMod.isDefined || breakMany ||
rightAsInfix.exists(10 < infixSequenceLength(_))
val nextOp =
if (!style.newlines.afterInfixBreakOnNested) None
else if (beforeLhs) Some(app.op)
else
getInfixRhsAsInfix(app) match {
case Some(ia) => Some(findLeftInfix(ia).op)
case _ => findNextInfixInParent(app, fullInfix)
}
val endOfNextOp = nextOp.map(tokens.getLast)
val breakAfterClose = endOfNextOp.flatMap(breakAfterComment)
val nlSplit = Split(nlMod, 0)
.andPolicyOpt(breakAfterClose)
.withIndent(nlIndent)
.withPolicy(nlPolicy)
val singleLineSplit = Split(spaceMod, 0)
.notIf(noSingleLine)
.withSingleLine(endOfNextOp.fold(close)(_.left))
.andPolicyOpt(breakAfterClose)
.andPolicy(getSingleLineInfixPolicy(close))
Seq(singleLineSplit, nlSplit)
}
val spaceSplits: Seq[Split] =
if (ft.right.is[T.Comment]) Seq.empty
else if (closeOpt.isDefined) Seq.empty
else {
val nextFT = if (rightAsInfix.isDefined) next(ft) else ft
expires.filter(_._2 <= breakPenalty).takeRight(3).map {
case (expire, cost) =>
val exclude =
if (breakMany) TokenRanges.empty
else insideBracesBlock(nextFT, expire, true)
Split(ModExt(newStmtMod.getOrElse(spaceMod)), cost)
.withSingleLine(expire, exclude)
}
}
singleLineSplits ++ spaceSplits ++ otherSplits
}
}
def getSingleLineInfixPolicy(end: T) =
Policy.on(end) {
case Decision(t: FormatToken, s) if isInfixOp(t.meta.leftOwner) =>
SplitTag.InfixChainNoNL.activateOnly(s)
}
def getMidInfixToken(app: Member.Infix): T = {
val opToken = app.op.tokens.head
val opFollowsComment = tokens(opToken, -1).left.is[T.Comment]
if (opFollowsComment) getLastNonTrivialToken(app.lhs) else opToken
}
def getLastEnclosedToken(tree: Tree): T = {
tokens.getLastExceptParen(tree).left
}
@tailrec
private def findNextInfixes(
fullTree: Tree,
tree: Tree,
res: mutable.Buffer[Member.Infix]
): Unit = if (tree ne fullTree)
tree.parent match {
case Some(ia: Member.Infix) =>
if (ia.lhs eq tree) {
res += ia
findNestedInfixes(ia.arg, res)
}
findNextInfixes(fullTree, ia, res)
case Some(p: Member.ArgClause) =>
p.parent match {
case Some(pp: Member.Infix) =>
findNextInfixes(fullTree, pp, res)
case _ =>
}
case _ =>
}
private def findNestedInfixes(
tree: Tree,
res: mutable.Buffer[Member.Infix]
): Unit = tree match {
case Member.ArgClause(arg :: Nil) if !isEnclosedInParens(tree) =>
findNestedInfixes(arg, res)
case ia: Member.Infix if !isEnclosedInParens(tree) =>
findNestedInfixes(ia.lhs, res)
res += ia
ia.singleArg.foreach(findNestedInfixes(_, res))
case _ =>
}
@tailrec
final def findLeftInfix(app: Member.Infix): Member.Infix =
app.lhs match {
case t: Member.Infix if !isEnclosedInParens(t) =>
findLeftInfix(t)
case _ => app
}
private def getInfixRhsAsInfix(app: Member.Infix): Option[Member.Infix] =
app.singleArg match {
case Some(t: Member.Infix) if !isEnclosedInParens(t) => Some(t)
case _ => None // multiple parameters to infix are always enclosed
}
private def infixSequenceMaxPrecedence(app: Member.Infix): Int = {
val queue = new mutable.Queue[Member.Infix]()
queue += app
var maxPrecedence = 0
while (queue.nonEmpty) {
val elem = queue.dequeue()
val elemPrecedence = elem.precedence
if (maxPrecedence < elemPrecedence)
maxPrecedence = elemPrecedence
queue ++= elem.nestedInfixApps.filter(x => !isEnclosedInParens(x))
}
maxPrecedence
}
def functionExpire(function: Term.FunctionTerm): (T, ExpiresOn) =
function.parent match {
case Some(SingleArgInBraces.OrBlock(_, _, e)) =>
e.left -> ExpiresOn.Before
case _ =>
tokens.getLastExceptParen(function).left -> ExpiresOn.After
}
def noOptimizationZones(): Set[T] = {
val result = Set.newBuilder[T]
var expire: T = null
tokens.foreach {
case FormatToken(x, _, _) if expire ne null =>
if (x eq expire) expire = null else result += x
case FormatToken(t: T.LeftParen, _, m) if (m.leftOwner match {
// TODO(olafur) https://github.com/scalameta/scalameta/issues/345
case lo: Term.ArgClause => !lo.parent.exists(_.is[Term.ApplyInfix])
case _: Term.Apply => true // legacy: when enclosed in parens
case _ => false
}) =>
expire = matching(t)
case FormatToken(t: T.LeftBrace, _, m) if (m.leftOwner match {
// Type compounds can be inside defn.defs
case _: Type.Refine => true
case _ => false
}) =>
expire = matching(t)
case _ =>
}
result.result()
}
def mustUseConfigStyle(
ft: FormatToken,
beforeCloseFt: => FormatToken,
allowForce: => Boolean = true
)(implicit style: ScalafmtConfig): Boolean =
style.optIn.configStyleArguments &&
couldUseConfigStyle(ft, beforeCloseFt, allowForce)
def couldUseConfigStyle(
ft: FormatToken,
beforeCloseFt: => FormatToken,
allowForce: => Boolean = true
)(implicit style: ScalafmtConfig): Boolean = {
def opensImplicit = (next(ft).hasBreak ||
style.newlines.forceAfterImplicitParamListModifier) &&
opensConfigStyleImplicitParamList(ft)
val opensConfigStyle = !style.newlines.sourceIgnored && // classic
(ft.hasBreak || opensImplicit) && beforeCloseFt.hasBreak
opensConfigStyle || allowForce && forceConfigStyle(hash(ft.left))
}
/** Works for `using` as well */
def opensConfigStyleImplicitParamList(
formatToken: FormatToken
)(implicit style: ScalafmtConfig): Boolean =
soft.ImplicitOrUsing.unapply(formatToken.right) &&
style.newlines.notBeforeImplicitParamListModifier &&
hasImplicitParamList(formatToken.meta.rightOwner)
val ImplicitUsingOnLeft =
new ExtractFromMeta(ft => getImplicitParamList(ft.meta.leftOwner))
def isSingleIdentifierAnnotation(tok: FormatToken): Boolean = {
val toMatch = if (tok.right.is[T.RightParen]) {
// Hack to allow any annotations with arguments like @foo(1)
tokens(matching(tok.right), -2)
} else {
tok
}
toMatch match {
case FormatToken(T.At(), _: T.Ident, _) => true
case _ => false
}
}