ContinuationIndenter.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. //===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// \brief This file implements the continuation indenter.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "BreakableToken.h"
  15. #include "ContinuationIndenter.h"
  16. #include "WhitespaceManager.h"
  17. #include "clang/Basic/OperatorPrecedence.h"
  18. #include "clang/Basic/SourceManager.h"
  19. #include "clang/Format/Format.h"
  20. #include "llvm/Support/Debug.h"
  21. #include <string>
  22. #define DEBUG_TYPE "format-formatter"
  23. namespace clang {
  24. namespace format {
  25. // Returns the length of everything up to the first possible line break after
  26. // the ), ], } or > matching \c Tok.
  27. static unsigned getLengthToMatchingParen(const FormatToken &Tok) {
  28. if (!Tok.MatchingParen)
  29. return 0;
  30. FormatToken *End = Tok.MatchingParen;
  31. while (End->Next && !End->Next->CanBreakBefore) {
  32. End = End->Next;
  33. }
  34. return End->TotalLength - Tok.TotalLength + 1;
  35. }
  36. // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
  37. // segment of a builder type call.
  38. static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
  39. return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
  40. }
  41. // Returns \c true if \c Current starts a new parameter.
  42. static bool startsNextParameter(const FormatToken &Current,
  43. const FormatStyle &Style) {
  44. const FormatToken &Previous = *Current.Previous;
  45. if (Current.is(TT_CtorInitializerComma) &&
  46. Style.BreakConstructorInitializersBeforeComma)
  47. return true;
  48. return Previous.is(tok::comma) && !Current.isTrailingComment() &&
  49. (Previous.isNot(TT_CtorInitializerComma) ||
  50. !Style.BreakConstructorInitializersBeforeComma);
  51. }
  52. ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
  53. const AdditionalKeywords &Keywords,
  54. SourceManager &SourceMgr,
  55. WhitespaceManager &Whitespaces,
  56. encoding::Encoding Encoding,
  57. bool BinPackInconclusiveFunctions)
  58. : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
  59. Whitespaces(Whitespaces), Encoding(Encoding),
  60. BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
  61. CommentPragmasRegex(Style.CommentPragmas) {}
  62. LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
  63. const AnnotatedLine *Line,
  64. bool DryRun) {
  65. LineState State;
  66. State.FirstIndent = FirstIndent;
  67. State.Column = FirstIndent;
  68. State.Line = Line;
  69. State.NextToken = Line->First;
  70. State.Stack.push_back(ParenState(FirstIndent, Line->Level, FirstIndent,
  71. /*AvoidBinPacking=*/false,
  72. /*NoLineBreak=*/false));
  73. State.LineContainsContinuedForLoopSection = false;
  74. State.StartOfStringLiteral = 0;
  75. State.StartOfLineLevel = 0;
  76. State.LowestLevelOnLine = 0;
  77. State.IgnoreStackForComparison = false;
  78. // The first token has already been indented and thus consumed.
  79. moveStateToNextToken(State, DryRun, /*Newline=*/false);
  80. return State;
  81. }
  82. bool ContinuationIndenter::canBreak(const LineState &State) {
  83. const FormatToken &Current = *State.NextToken;
  84. const FormatToken &Previous = *Current.Previous;
  85. assert(&Previous == Current.Previous);
  86. if (!Current.CanBreakBefore &&
  87. !(State.Stack.back().BreakBeforeClosingBrace &&
  88. Current.closesBlockTypeList(Style)))
  89. return false;
  90. // The opening "{" of a braced list has to be on the same line as the first
  91. // element if it is nested in another braced init list or function call.
  92. if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
  93. Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
  94. Previous.Previous &&
  95. Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
  96. return false;
  97. // This prevents breaks like:
  98. // ...
  99. // SomeParameter, OtherParameter).DoSomething(
  100. // ...
  101. // As they hide "DoSomething" and are generally bad for readability.
  102. if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
  103. State.LowestLevelOnLine < State.StartOfLineLevel &&
  104. State.LowestLevelOnLine < Current.NestingLevel)
  105. return false;
  106. if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
  107. return false;
  108. // Don't create a 'hanging' indent if there are multiple blocks in a single
  109. // statement.
  110. if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
  111. State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
  112. State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
  113. return false;
  114. // Don't break after very short return types (e.g. "void") as that is often
  115. // unexpected.
  116. if (Current.is(TT_FunctionDeclarationName) &&
  117. Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_None &&
  118. State.Column < 6)
  119. return false;
  120. return !State.Stack.back().NoLineBreak;
  121. }
  122. bool ContinuationIndenter::mustBreak(const LineState &State) {
  123. const FormatToken &Current = *State.NextToken;
  124. const FormatToken &Previous = *Current.Previous;
  125. if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
  126. return true;
  127. if (State.Stack.back().BreakBeforeClosingBrace &&
  128. Current.closesBlockTypeList(Style))
  129. return true;
  130. if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
  131. return true;
  132. if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
  133. (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
  134. Previous.isNot(tok::question)) ||
  135. (!Style.BreakBeforeTernaryOperators &&
  136. Previous.is(TT_ConditionalExpr))) &&
  137. State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
  138. !Current.isOneOf(tok::r_paren, tok::r_brace))
  139. return true;
  140. if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
  141. Previous.is(TT_ArrayInitializerLSquare)) &&
  142. Style.ColumnLimit > 0 &&
  143. getLengthToMatchingParen(Previous) + State.Column - 1 >
  144. getColumnLimit(State))
  145. return true;
  146. if (Current.is(TT_CtorInitializerColon) &&
  147. ((Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All) ||
  148. Style.BreakConstructorInitializersBeforeComma || Style.ColumnLimit != 0))
  149. return true;
  150. if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound &&
  151. State.Stack.back().BreakBeforeParameter)
  152. return true;
  153. unsigned NewLineColumn = getNewLineColumn(State);
  154. if (State.Column < NewLineColumn)
  155. return false;
  156. if (Style.AlwaysBreakBeforeMultilineStrings &&
  157. (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
  158. Previous.is(tok::comma) || Current.NestingLevel < 2) &&
  159. !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
  160. !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
  161. nextIsMultilineString(State))
  162. return true;
  163. // Using CanBreakBefore here and below takes care of the decision whether the
  164. // current style uses wrapping before or after operators for the given
  165. // operator.
  166. if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
  167. // If we need to break somewhere inside the LHS of a binary expression, we
  168. // should also break after the operator. Otherwise, the formatting would
  169. // hide the operator precedence, e.g. in:
  170. // if (aaaaaaaaaaaaaa ==
  171. // bbbbbbbbbbbbbb && c) {..
  172. // For comparisons, we only apply this rule, if the LHS is a binary
  173. // expression itself as otherwise, the line breaks seem superfluous.
  174. // We need special cases for ">>" which we have split into two ">" while
  175. // lexing in order to make template parsing easier.
  176. bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
  177. Previous.getPrecedence() == prec::Equality) &&
  178. Previous.Previous &&
  179. Previous.Previous->isNot(TT_BinaryOperator); // For >>.
  180. bool LHSIsBinaryExpr =
  181. Previous.Previous && Previous.Previous->EndsBinaryExpression;
  182. if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
  183. Previous.getPrecedence() != prec::Assignment &&
  184. State.Stack.back().BreakBeforeParameter)
  185. return true;
  186. } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
  187. State.Stack.back().BreakBeforeParameter) {
  188. return true;
  189. }
  190. // Same as above, but for the first "<<" operator.
  191. if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
  192. State.Stack.back().BreakBeforeParameter &&
  193. State.Stack.back().FirstLessLess == 0)
  194. return true;
  195. if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
  196. // Always break after "template <...>" and leading annotations. This is only
  197. // for cases where the entire line does not fit on a single line as a
  198. // different LineFormatter would be used otherwise.
  199. if (Previous.ClosesTemplateDeclaration)
  200. return true;
  201. if (Previous.is(TT_FunctionAnnotationRParen))
  202. return true;
  203. if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
  204. Current.isNot(TT_LeadingJavaAnnotation))
  205. return true;
  206. }
  207. // If the return type spans multiple lines, wrap before the function name.
  208. if (Current.isOneOf(TT_FunctionDeclarationName, tok::kw_operator) &&
  209. State.Stack.back().BreakBeforeParameter)
  210. return true;
  211. if (startsSegmentOfBuilderTypeCall(Current) &&
  212. (State.Stack.back().CallContinuation != 0 ||
  213. State.Stack.back().BreakBeforeParameter))
  214. return true;
  215. // The following could be precomputed as they do not depend on the state.
  216. // However, as they should take effect only if the UnwrappedLine does not fit
  217. // into the ColumnLimit, they are checked here in the ContinuationIndenter.
  218. if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
  219. Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
  220. return true;
  221. if (Current.is(tok::lessless) && Previous.is(tok::identifier) &&
  222. Previous.TokenText == "endl")
  223. return true;
  224. return false;
  225. }
  226. unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
  227. bool DryRun,
  228. unsigned ExtraSpaces) {
  229. const FormatToken &Current = *State.NextToken;
  230. assert(!State.Stack.empty());
  231. if ((Current.is(TT_ImplicitStringLiteral) &&
  232. (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
  233. Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
  234. tok::pp_not_keyword))) {
  235. unsigned EndColumn =
  236. SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
  237. if (Current.LastNewlineOffset != 0) {
  238. // If there is a newline within this token, the final column will solely
  239. // determined by the current end column.
  240. State.Column = EndColumn;
  241. } else {
  242. unsigned StartColumn =
  243. SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
  244. assert(EndColumn >= StartColumn);
  245. State.Column += EndColumn - StartColumn;
  246. }
  247. moveStateToNextToken(State, DryRun, /*Newline=*/false);
  248. return 0;
  249. }
  250. unsigned Penalty = 0;
  251. if (Newline)
  252. Penalty = addTokenOnNewLine(State, DryRun);
  253. else
  254. addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
  255. return moveStateToNextToken(State, DryRun, Newline) + Penalty;
  256. }
  257. void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
  258. unsigned ExtraSpaces) {
  259. FormatToken &Current = *State.NextToken;
  260. const FormatToken &Previous = *State.NextToken->Previous;
  261. if (Current.is(tok::equal) &&
  262. (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
  263. State.Stack.back().VariablePos == 0) {
  264. State.Stack.back().VariablePos = State.Column;
  265. // Move over * and & if they are bound to the variable name.
  266. const FormatToken *Tok = &Previous;
  267. while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
  268. State.Stack.back().VariablePos -= Tok->ColumnWidth;
  269. if (Tok->SpacesRequiredBefore != 0)
  270. break;
  271. Tok = Tok->Previous;
  272. }
  273. if (Previous.PartOfMultiVariableDeclStmt)
  274. State.Stack.back().LastSpace = State.Stack.back().VariablePos;
  275. }
  276. unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
  277. if (!DryRun)
  278. Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, /*IndentLevel=*/0,
  279. Spaces, State.Column + Spaces);
  280. if (Current.is(TT_SelectorName) &&
  281. !State.Stack.back().ObjCSelectorNameFound) {
  282. if (Current.LongestObjCSelectorName == 0)
  283. State.Stack.back().AlignColons = false;
  284. else if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
  285. State.Column + Spaces + Current.ColumnWidth)
  286. State.Stack.back().ColonPos =
  287. std::max(State.FirstIndent + Style.ContinuationIndentWidth,
  288. State.Stack.back().Indent) +
  289. Current.LongestObjCSelectorName;
  290. else
  291. State.Stack.back().ColonPos = State.Column + Spaces + Current.ColumnWidth;
  292. }
  293. if (Style.AlignAfterOpenBracket && Previous.opensScope() &&
  294. Previous.isNot(TT_ObjCMethodExpr) &&
  295. (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
  296. State.Stack.back().Indent = State.Column + Spaces;
  297. if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
  298. State.Stack.back().NoLineBreak = true;
  299. if (startsSegmentOfBuilderTypeCall(Current) &&
  300. State.Column > getNewLineColumn(State))
  301. State.Stack.back().ContainsUnwrappedBuilder = true;
  302. if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
  303. State.Stack.back().NoLineBreak = true;
  304. if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
  305. (Previous.MatchingParen &&
  306. (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
  307. // If there is a function call with long parameters, break before trailing
  308. // calls. This prevents things like:
  309. // EXPECT_CALL(SomeLongParameter).Times(
  310. // 2);
  311. // We don't want to do this for short parameters as they can just be
  312. // indexes.
  313. State.Stack.back().NoLineBreak = true;
  314. }
  315. State.Column += Spaces;
  316. if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
  317. Previous.Previous &&
  318. Previous.Previous->isOneOf(tok::kw_if, tok::kw_for)) {
  319. // Treat the condition inside an if as if it was a second function
  320. // parameter, i.e. let nested calls have a continuation indent.
  321. State.Stack.back().LastSpace = State.Column;
  322. State.Stack.back().NestedBlockIndent = State.Column;
  323. } else if (!Current.isOneOf(tok::comment, tok::caret) &&
  324. (Previous.is(tok::comma) ||
  325. (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
  326. State.Stack.back().LastSpace = State.Column;
  327. } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
  328. TT_CtorInitializerColon)) &&
  329. ((Previous.getPrecedence() != prec::Assignment &&
  330. (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
  331. !Previous.LastOperator)) ||
  332. Current.StartsBinaryExpression)) {
  333. // Always indent relative to the RHS of the expression unless this is a
  334. // simple assignment without binary expression on the RHS. Also indent
  335. // relative to unary operators and the colons of constructor initializers.
  336. State.Stack.back().LastSpace = State.Column;
  337. } else if (Previous.is(TT_InheritanceColon)) {
  338. State.Stack.back().Indent = State.Column;
  339. State.Stack.back().LastSpace = State.Column;
  340. } else if (Previous.opensScope()) {
  341. // If a function has a trailing call, indent all parameters from the
  342. // opening parenthesis. This avoids confusing indents like:
  343. // OuterFunction(InnerFunctionCall( // break
  344. // ParameterToInnerFunction)) // break
  345. // .SecondInnerFunctionCall();
  346. bool HasTrailingCall = false;
  347. if (Previous.MatchingParen) {
  348. const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
  349. HasTrailingCall = Next && Next->isMemberAccess();
  350. }
  351. if (HasTrailingCall && State.Stack.size() > 1 &&
  352. State.Stack[State.Stack.size() - 2].CallContinuation == 0)
  353. State.Stack.back().LastSpace = State.Column;
  354. }
  355. }
  356. unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
  357. bool DryRun) {
  358. FormatToken &Current = *State.NextToken;
  359. const FormatToken &Previous = *State.NextToken->Previous;
  360. // Extra penalty that needs to be added because of the way certain line
  361. // breaks are chosen.
  362. unsigned Penalty = 0;
  363. const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
  364. const FormatToken *NextNonComment = Previous.getNextNonComment();
  365. if (!NextNonComment)
  366. NextNonComment = &Current;
  367. // The first line break on any NestingLevel causes an extra penalty in order
  368. // prefer similar line breaks.
  369. if (!State.Stack.back().ContainsLineBreak)
  370. Penalty += 15;
  371. State.Stack.back().ContainsLineBreak = true;
  372. Penalty += State.NextToken->SplitPenalty;
  373. // Breaking before the first "<<" is generally not desirable if the LHS is
  374. // short. Also always add the penalty if the LHS is split over mutliple lines
  375. // to avoid unnecessary line breaks that just work around this penalty.
  376. if (NextNonComment->is(tok::lessless) &&
  377. State.Stack.back().FirstLessLess == 0 &&
  378. (State.Column <= Style.ColumnLimit / 3 ||
  379. State.Stack.back().BreakBeforeParameter))
  380. Penalty += Style.PenaltyBreakFirstLessLess;
  381. State.Column = getNewLineColumn(State);
  382. // Indent nested blocks relative to this column, unless in a very specific
  383. // JavaScript special case where:
  384. //
  385. // var loooooong_name =
  386. // function() {
  387. // // code
  388. // }
  389. //
  390. // is common and should be formatted like a free-standing function.
  391. if (Style.Language != FormatStyle::LK_JavaScript ||
  392. Current.NestingLevel != 0 || !PreviousNonComment->is(tok::equal) ||
  393. !Current.is(Keywords.kw_function))
  394. State.Stack.back().NestedBlockIndent = State.Column;
  395. if (NextNonComment->isMemberAccess()) {
  396. if (State.Stack.back().CallContinuation == 0)
  397. State.Stack.back().CallContinuation = State.Column;
  398. } else if (NextNonComment->is(TT_SelectorName)) {
  399. if (!State.Stack.back().ObjCSelectorNameFound) {
  400. if (NextNonComment->LongestObjCSelectorName == 0) {
  401. State.Stack.back().AlignColons = false;
  402. } else {
  403. State.Stack.back().ColonPos =
  404. (Style.IndentWrappedFunctionNames
  405. ? std::max(State.Stack.back().Indent,
  406. State.FirstIndent + Style.ContinuationIndentWidth)
  407. : State.Stack.back().Indent) +
  408. NextNonComment->LongestObjCSelectorName;
  409. }
  410. } else if (State.Stack.back().AlignColons &&
  411. State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
  412. State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
  413. }
  414. } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
  415. PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
  416. // FIXME: This is hacky, find a better way. The problem is that in an ObjC
  417. // method expression, the block should be aligned to the line starting it,
  418. // e.g.:
  419. // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
  420. // ^(int *i) {
  421. // // ...
  422. // }];
  423. // Thus, we set LastSpace of the next higher NestingLevel, to which we move
  424. // when we consume all of the "}"'s FakeRParens at the "{".
  425. if (State.Stack.size() > 1)
  426. State.Stack[State.Stack.size() - 2].LastSpace =
  427. std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
  428. Style.ContinuationIndentWidth;
  429. }
  430. if ((Previous.isOneOf(tok::comma, tok::semi) &&
  431. !State.Stack.back().AvoidBinPacking) ||
  432. Previous.is(TT_BinaryOperator))
  433. State.Stack.back().BreakBeforeParameter = false;
  434. if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
  435. Current.NestingLevel == 0)
  436. State.Stack.back().BreakBeforeParameter = false;
  437. if (NextNonComment->is(tok::question) ||
  438. (PreviousNonComment && PreviousNonComment->is(tok::question)))
  439. State.Stack.back().BreakBeforeParameter = true;
  440. if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
  441. State.Stack.back().BreakBeforeParameter = false;
  442. if (!DryRun) {
  443. unsigned Newlines = std::max(
  444. 1u, std::min(Current.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1));
  445. Whitespaces.replaceWhitespace(Current, Newlines,
  446. State.Stack.back().IndentLevel, State.Column,
  447. State.Column, State.Line->InPPDirective);
  448. }
  449. if (!Current.isTrailingComment())
  450. State.Stack.back().LastSpace = State.Column;
  451. State.StartOfLineLevel = Current.NestingLevel;
  452. State.LowestLevelOnLine = Current.NestingLevel;
  453. // Any break on this level means that the parent level has been broken
  454. // and we need to avoid bin packing there.
  455. bool NestedBlockSpecialCase =
  456. Current.is(tok::r_brace) && State.Stack.size() > 1 &&
  457. State.Stack[State.Stack.size() - 2].NestedBlockInlined;
  458. if (!NestedBlockSpecialCase)
  459. for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
  460. State.Stack[i].BreakBeforeParameter = true;
  461. if (PreviousNonComment &&
  462. !PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
  463. (PreviousNonComment->isNot(TT_TemplateCloser) ||
  464. Current.NestingLevel != 0) &&
  465. !PreviousNonComment->isOneOf(
  466. TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
  467. TT_LeadingJavaAnnotation) &&
  468. Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
  469. State.Stack.back().BreakBeforeParameter = true;
  470. // If we break after { or the [ of an array initializer, we should also break
  471. // before the corresponding } or ].
  472. if (PreviousNonComment &&
  473. (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)))
  474. State.Stack.back().BreakBeforeClosingBrace = true;
  475. if (State.Stack.back().AvoidBinPacking) {
  476. // If we are breaking after '(', '{', '<', this is not bin packing
  477. // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
  478. // dict/object literal.
  479. if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
  480. (!Style.AllowAllParametersOfDeclarationOnNextLine &&
  481. State.Line->MustBeDeclaration) ||
  482. Previous.is(TT_DictLiteral))
  483. State.Stack.back().BreakBeforeParameter = true;
  484. }
  485. return Penalty;
  486. }
  487. unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
  488. if (!State.NextToken || !State.NextToken->Previous)
  489. return 0;
  490. FormatToken &Current = *State.NextToken;
  491. const FormatToken &Previous = *Current.Previous;
  492. // If we are continuing an expression, we want to use the continuation indent.
  493. unsigned ContinuationIndent =
  494. std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
  495. Style.ContinuationIndentWidth;
  496. const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
  497. const FormatToken *NextNonComment = Previous.getNextNonComment();
  498. if (!NextNonComment)
  499. NextNonComment = &Current;
  500. // Java specific bits.
  501. if (Style.Language == FormatStyle::LK_Java &&
  502. Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
  503. return std::max(State.Stack.back().LastSpace,
  504. State.Stack.back().Indent + Style.ContinuationIndentWidth);
  505. if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
  506. return Current.NestingLevel == 0 ? State.FirstIndent
  507. : State.Stack.back().Indent;
  508. if (Current.isOneOf(tok::r_brace, tok::r_square) && State.Stack.size() > 1) {
  509. if (Current.closesBlockTypeList(Style))
  510. return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
  511. if (Current.MatchingParen &&
  512. Current.MatchingParen->BlockKind == BK_BracedInit)
  513. return State.Stack[State.Stack.size() - 2].LastSpace;
  514. return State.FirstIndent;
  515. }
  516. if (Current.is(tok::identifier) && Current.Next &&
  517. Current.Next->is(TT_DictLiteral))
  518. return State.Stack.back().Indent;
  519. if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
  520. return State.StartOfStringLiteral;
  521. if (NextNonComment->is(TT_ObjCStringLiteral) &&
  522. State.StartOfStringLiteral != 0)
  523. return State.StartOfStringLiteral - 1;
  524. if (NextNonComment->is(tok::lessless) &&
  525. State.Stack.back().FirstLessLess != 0)
  526. return State.Stack.back().FirstLessLess;
  527. if (NextNonComment->isMemberAccess()) {
  528. if (State.Stack.back().CallContinuation == 0)
  529. return ContinuationIndent;
  530. return State.Stack.back().CallContinuation;
  531. }
  532. if (State.Stack.back().QuestionColumn != 0 &&
  533. ((NextNonComment->is(tok::colon) &&
  534. NextNonComment->is(TT_ConditionalExpr)) ||
  535. Previous.is(TT_ConditionalExpr)))
  536. return State.Stack.back().QuestionColumn;
  537. if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
  538. return State.Stack.back().VariablePos;
  539. if ((PreviousNonComment &&
  540. (PreviousNonComment->ClosesTemplateDeclaration ||
  541. PreviousNonComment->isOneOf(
  542. TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
  543. TT_LeadingJavaAnnotation))) ||
  544. (!Style.IndentWrappedFunctionNames &&
  545. NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
  546. return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
  547. if (NextNonComment->is(TT_SelectorName)) {
  548. if (!State.Stack.back().ObjCSelectorNameFound) {
  549. if (NextNonComment->LongestObjCSelectorName == 0)
  550. return State.Stack.back().Indent;
  551. return (Style.IndentWrappedFunctionNames
  552. ? std::max(State.Stack.back().Indent,
  553. State.FirstIndent + Style.ContinuationIndentWidth)
  554. : State.Stack.back().Indent) +
  555. NextNonComment->LongestObjCSelectorName -
  556. NextNonComment->ColumnWidth;
  557. }
  558. if (!State.Stack.back().AlignColons)
  559. return State.Stack.back().Indent;
  560. if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
  561. return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
  562. return State.Stack.back().Indent;
  563. }
  564. if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
  565. if (State.Stack.back().StartOfArraySubscripts != 0)
  566. return State.Stack.back().StartOfArraySubscripts;
  567. return ContinuationIndent;
  568. }
  569. // This ensure that we correctly format ObjC methods calls without inputs,
  570. // i.e. where the last element isn't selector like: [callee method];
  571. if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
  572. NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
  573. return State.Stack.back().Indent;
  574. if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
  575. Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
  576. return ContinuationIndent;
  577. if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
  578. PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
  579. return ContinuationIndent;
  580. if (NextNonComment->is(TT_CtorInitializerColon))
  581. return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
  582. if (NextNonComment->is(TT_CtorInitializerComma))
  583. return State.Stack.back().Indent;
  584. if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
  585. !Current.isOneOf(tok::colon, tok::comment))
  586. return ContinuationIndent;
  587. if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
  588. PreviousNonComment->isNot(tok::r_brace))
  589. // Ensure that we fall back to the continuation indent width instead of
  590. // just flushing continuations left.
  591. return State.Stack.back().Indent + Style.ContinuationIndentWidth;
  592. return State.Stack.back().Indent;
  593. }
  594. unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
  595. bool DryRun, bool Newline) {
  596. assert(State.Stack.size());
  597. const FormatToken &Current = *State.NextToken;
  598. if (Current.is(TT_InheritanceColon))
  599. State.Stack.back().AvoidBinPacking = true;
  600. if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
  601. if (State.Stack.back().FirstLessLess == 0)
  602. State.Stack.back().FirstLessLess = State.Column;
  603. else
  604. State.Stack.back().LastOperatorWrapped = Newline;
  605. }
  606. if ((Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) ||
  607. Current.is(TT_ConditionalExpr))
  608. State.Stack.back().LastOperatorWrapped = Newline;
  609. if (Current.is(TT_ArraySubscriptLSquare) &&
  610. State.Stack.back().StartOfArraySubscripts == 0)
  611. State.Stack.back().StartOfArraySubscripts = State.Column;
  612. if ((Current.is(tok::question) && Style.BreakBeforeTernaryOperators) ||
  613. (Current.getPreviousNonComment() && Current.isNot(tok::colon) &&
  614. Current.getPreviousNonComment()->is(tok::question) &&
  615. !Style.BreakBeforeTernaryOperators))
  616. State.Stack.back().QuestionColumn = State.Column;
  617. if (!Current.opensScope() && !Current.closesScope())
  618. State.LowestLevelOnLine =
  619. std::min(State.LowestLevelOnLine, Current.NestingLevel);
  620. if (Current.isMemberAccess())
  621. State.Stack.back().StartOfFunctionCall =
  622. Current.LastOperator ? 0 : State.Column;
  623. if (Current.is(TT_SelectorName))
  624. State.Stack.back().ObjCSelectorNameFound = true;
  625. if (Current.is(TT_CtorInitializerColon)) {
  626. // Indent 2 from the column, so:
  627. // SomeClass::SomeClass()
  628. // : First(...), ...
  629. // Next(...)
  630. // ^ line up here.
  631. State.Stack.back().Indent =
  632. State.Column + (Style.BreakConstructorInitializersBeforeComma ? 0 : 2);
  633. State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
  634. if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
  635. State.Stack.back().AvoidBinPacking = true;
  636. State.Stack.back().BreakBeforeParameter = false;
  637. }
  638. if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
  639. State.Stack.back().NestedBlockIndent =
  640. State.Column + Current.ColumnWidth + 1;
  641. // Insert scopes created by fake parenthesis.
  642. const FormatToken *Previous = Current.getPreviousNonComment();
  643. // Add special behavior to support a format commonly used for JavaScript
  644. // closures:
  645. // SomeFunction(function() {
  646. // foo();
  647. // bar();
  648. // }, a, b, c);
  649. if (Current.isNot(tok::comment) && Previous &&
  650. Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
  651. State.Stack.size() > 1) {
  652. if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
  653. for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
  654. State.Stack[i].NoLineBreak = true;
  655. State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
  656. }
  657. if (Previous && (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
  658. Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
  659. !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
  660. State.Stack.back().NestedBlockInlined =
  661. !Newline &&
  662. (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
  663. }
  664. moveStatePastFakeLParens(State, Newline);
  665. moveStatePastScopeOpener(State, Newline);
  666. moveStatePastScopeCloser(State);
  667. moveStatePastFakeRParens(State);
  668. if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
  669. State.StartOfStringLiteral = State.Column;
  670. if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
  671. State.StartOfStringLiteral = State.Column + 1;
  672. else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
  673. !Current.isStringLiteral())
  674. State.StartOfStringLiteral = 0;
  675. State.Column += Current.ColumnWidth;
  676. State.NextToken = State.NextToken->Next;
  677. unsigned Penalty = breakProtrudingToken(Current, State, DryRun);
  678. if (State.Column > getColumnLimit(State)) {
  679. unsigned ExcessCharacters = State.Column - getColumnLimit(State);
  680. Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
  681. }
  682. if (Current.Role)
  683. Current.Role->formatFromToken(State, this, DryRun);
  684. // If the previous has a special role, let it consume tokens as appropriate.
  685. // It is necessary to start at the previous token for the only implemented
  686. // role (comma separated list). That way, the decision whether or not to break
  687. // after the "{" is already done and both options are tried and evaluated.
  688. // FIXME: This is ugly, find a better way.
  689. if (Previous && Previous->Role)
  690. Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
  691. return Penalty;
  692. }
  693. void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
  694. bool Newline) {
  695. const FormatToken &Current = *State.NextToken;
  696. const FormatToken *Previous = Current.getPreviousNonComment();
  697. // Don't add extra indentation for the first fake parenthesis after
  698. // 'return', assignments or opening <({[. The indentation for these cases
  699. // is special cased.
  700. bool SkipFirstExtraIndent =
  701. (Previous && (Previous->opensScope() ||
  702. Previous->isOneOf(tok::semi, tok::kw_return) ||
  703. (Previous->getPrecedence() == prec::Assignment &&
  704. Style.AlignOperands) ||
  705. Previous->is(TT_ObjCMethodExpr)));
  706. for (SmallVectorImpl<prec::Level>::const_reverse_iterator
  707. I = Current.FakeLParens.rbegin(),
  708. E = Current.FakeLParens.rend();
  709. I != E; ++I) {
  710. ParenState NewParenState = State.Stack.back();
  711. NewParenState.ContainsLineBreak = false;
  712. // Indent from 'LastSpace' unless these are fake parentheses encapsulating
  713. // a builder type call after 'return' or, if the alignment after opening
  714. // brackets is disabled.
  715. if (!Current.isTrailingComment() &&
  716. (Style.AlignOperands || *I < prec::Assignment) &&
  717. (!Previous || Previous->isNot(tok::kw_return) ||
  718. (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
  719. (Style.AlignAfterOpenBracket || *I != prec::Comma ||
  720. Current.NestingLevel == 0))
  721. NewParenState.Indent =
  722. std::max(std::max(State.Column, NewParenState.Indent),
  723. State.Stack.back().LastSpace);
  724. // Don't allow the RHS of an operator to be split over multiple lines unless
  725. // there is a line-break right after the operator.
  726. // Exclude relational operators, as there, it is always more desirable to
  727. // have the LHS 'left' of the RHS.
  728. if (Previous && Previous->getPrecedence() > prec::Assignment &&
  729. Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
  730. Previous->getPrecedence() != prec::Relational) {
  731. bool BreakBeforeOperator =
  732. Previous->is(tok::lessless) ||
  733. (Previous->is(TT_BinaryOperator) &&
  734. Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
  735. (Previous->is(TT_ConditionalExpr) &&
  736. Style.BreakBeforeTernaryOperators);
  737. if ((!Newline && !BreakBeforeOperator) ||
  738. (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
  739. NewParenState.NoLineBreak = true;
  740. }
  741. // Do not indent relative to the fake parentheses inserted for "." or "->".
  742. // This is a special case to make the following to statements consistent:
  743. // OuterFunction(InnerFunctionCall( // break
  744. // ParameterToInnerFunction));
  745. // OuterFunction(SomeObject.InnerFunctionCall( // break
  746. // ParameterToInnerFunction));
  747. if (*I > prec::Unknown)
  748. NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
  749. if (*I != prec::Conditional && !Current.is(TT_UnaryOperator))
  750. NewParenState.StartOfFunctionCall = State.Column;
  751. // Always indent conditional expressions. Never indent expression where
  752. // the 'operator' is ',', ';' or an assignment (i.e. *I <=
  753. // prec::Assignment) as those have different indentation rules. Indent
  754. // other expression, unless the indentation needs to be skipped.
  755. if (*I == prec::Conditional ||
  756. (!SkipFirstExtraIndent && *I > prec::Assignment &&
  757. !Current.isTrailingComment()))
  758. NewParenState.Indent += Style.ContinuationIndentWidth;
  759. if ((Previous && !Previous->opensScope()) || *I > prec::Comma)
  760. NewParenState.BreakBeforeParameter = false;
  761. State.Stack.push_back(NewParenState);
  762. SkipFirstExtraIndent = false;
  763. }
  764. }
  765. void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
  766. for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
  767. unsigned VariablePos = State.Stack.back().VariablePos;
  768. if (State.Stack.size() == 1) {
  769. // Do not pop the last element.
  770. break;
  771. }
  772. State.Stack.pop_back();
  773. State.Stack.back().VariablePos = VariablePos;
  774. }
  775. }
  776. void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
  777. bool Newline) {
  778. const FormatToken &Current = *State.NextToken;
  779. if (!Current.opensScope())
  780. return;
  781. if (Current.MatchingParen && Current.BlockKind == BK_Block) {
  782. moveStateToNewBlock(State);
  783. return;
  784. }
  785. unsigned NewIndent;
  786. unsigned NewIndentLevel = State.Stack.back().IndentLevel;
  787. unsigned LastSpace = State.Stack.back().LastSpace;
  788. bool AvoidBinPacking;
  789. bool BreakBeforeParameter = false;
  790. unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
  791. State.Stack.back().NestedBlockIndent);
  792. if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) {
  793. if (Current.opensBlockTypeList(Style)) {
  794. NewIndent = State.Stack.back().NestedBlockIndent + Style.IndentWidth;
  795. NewIndent = std::min(State.Column + 2, NewIndent);
  796. ++NewIndentLevel;
  797. } else {
  798. NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
  799. }
  800. const FormatToken *NextNoComment = Current.getNextNonComment();
  801. AvoidBinPacking =
  802. Current.isOneOf(TT_ArrayInitializerLSquare, TT_DictLiteral) ||
  803. Style.Language == FormatStyle::LK_Proto || !Style.BinPackArguments ||
  804. (NextNoComment && NextNoComment->is(TT_DesignatedInitializerPeriod));
  805. if (Current.ParameterCount > 1)
  806. NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
  807. } else {
  808. NewIndent = Style.ContinuationIndentWidth +
  809. std::max(State.Stack.back().LastSpace,
  810. State.Stack.back().StartOfFunctionCall);
  811. // Ensure that different different brackets force relative alignment, e.g.:
  812. // void SomeFunction(vector< // break
  813. // int> v);
  814. // FIXME: We likely want to do this for more combinations of brackets.
  815. // Verify that it is wanted for ObjC, too.
  816. if (Current.Tok.getKind() == tok::less &&
  817. Current.ParentBracket == tok::l_paren) {
  818. NewIndent = std::max(NewIndent, State.Stack.back().Indent);
  819. LastSpace = std::max(LastSpace, State.Stack.back().Indent);
  820. }
  821. AvoidBinPacking =
  822. (State.Line->MustBeDeclaration && !Style.BinPackParameters) ||
  823. (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
  824. (Style.ExperimentalAutoDetectBinPacking &&
  825. (Current.PackingKind == PPK_OnePerLine ||
  826. (!BinPackInconclusiveFunctions &&
  827. Current.PackingKind == PPK_Inconclusive)));
  828. if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) {
  829. if (Style.ColumnLimit) {
  830. // If this '[' opens an ObjC call, determine whether all parameters fit
  831. // into one line and put one per line if they don't.
  832. if (getLengthToMatchingParen(Current) + State.Column >
  833. getColumnLimit(State))
  834. BreakBeforeParameter = true;
  835. } else {
  836. // For ColumnLimit = 0, we have to figure out whether there is or has to
  837. // be a line break within this call.
  838. for (const FormatToken *Tok = &Current;
  839. Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
  840. if (Tok->MustBreakBefore ||
  841. (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
  842. BreakBeforeParameter = true;
  843. break;
  844. }
  845. }
  846. }
  847. }
  848. }
  849. bool NoLineBreak = State.Stack.back().NoLineBreak ||
  850. (Current.is(TT_TemplateOpener) &&
  851. State.Stack.back().ContainsUnwrappedBuilder);
  852. State.Stack.push_back(ParenState(NewIndent, NewIndentLevel, LastSpace,
  853. AvoidBinPacking, NoLineBreak));
  854. State.Stack.back().NestedBlockIndent = NestedBlockIndent;
  855. State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
  856. State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
  857. }
  858. void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
  859. const FormatToken &Current = *State.NextToken;
  860. if (!Current.closesScope())
  861. return;
  862. // If we encounter a closing ), ], } or >, we can remove a level from our
  863. // stacks.
  864. if (State.Stack.size() > 1 &&
  865. (Current.isOneOf(tok::r_paren, tok::r_square) ||
  866. (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
  867. State.NextToken->is(TT_TemplateCloser)))
  868. State.Stack.pop_back();
  869. if (Current.is(tok::r_square)) {
  870. // If this ends the array subscript expr, reset the corresponding value.
  871. const FormatToken *NextNonComment = Current.getNextNonComment();
  872. if (NextNonComment && NextNonComment->isNot(tok::l_square))
  873. State.Stack.back().StartOfArraySubscripts = 0;
  874. }
  875. }
  876. void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
  877. unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
  878. // ObjC block sometimes follow special indentation rules.
  879. unsigned NewIndent =
  880. NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
  881. ? Style.ObjCBlockIndentWidth
  882. : Style.IndentWidth);
  883. State.Stack.push_back(ParenState(
  884. NewIndent, /*NewIndentLevel=*/State.Stack.back().IndentLevel + 1,
  885. State.Stack.back().LastSpace, /*AvoidBinPacking=*/true,
  886. State.Stack.back().NoLineBreak));
  887. State.Stack.back().NestedBlockIndent = NestedBlockIndent;
  888. State.Stack.back().BreakBeforeParameter = true;
  889. }
  890. unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
  891. LineState &State) {
  892. // Break before further function parameters on all levels.
  893. for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
  894. State.Stack[i].BreakBeforeParameter = true;
  895. unsigned ColumnsUsed = State.Column;
  896. // We can only affect layout of the first and the last line, so the penalty
  897. // for all other lines is constant, and we ignore it.
  898. State.Column = Current.LastLineColumnWidth;
  899. if (ColumnsUsed > getColumnLimit(State))
  900. return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
  901. return 0;
  902. }
  903. unsigned ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
  904. LineState &State,
  905. bool DryRun) {
  906. // Don't break multi-line tokens other than block comments. Instead, just
  907. // update the state.
  908. if (Current.isNot(TT_BlockComment) && Current.IsMultiline)
  909. return addMultilineToken(Current, State);
  910. // Don't break implicit string literals or import statements.
  911. if (Current.is(TT_ImplicitStringLiteral) ||
  912. State.Line->Type == LT_ImportStatement)
  913. return 0;
  914. if (!Current.isStringLiteral() && !Current.is(tok::comment))
  915. return 0;
  916. std::unique_ptr<BreakableToken> Token;
  917. unsigned StartColumn = State.Column - Current.ColumnWidth;
  918. unsigned ColumnLimit = getColumnLimit(State);
  919. if (Current.isStringLiteral()) {
  920. // FIXME: String literal breaking is currently disabled for Java and JS, as
  921. // it requires strings to be merged using "+" which we don't support.
  922. if (Style.Language == FormatStyle::LK_Java ||
  923. Style.Language == FormatStyle::LK_JavaScript)
  924. return 0;
  925. // Don't break string literals inside preprocessor directives (except for
  926. // #define directives, as their contents are stored in separate lines and
  927. // are not affected by this check).
  928. // This way we avoid breaking code with line directives and unknown
  929. // preprocessor directives that contain long string literals.
  930. if (State.Line->Type == LT_PreprocessorDirective)
  931. return 0;
  932. // Exempts unterminated string literals from line breaking. The user will
  933. // likely want to terminate the string before any line breaking is done.
  934. if (Current.IsUnterminatedLiteral)
  935. return 0;
  936. StringRef Text = Current.TokenText;
  937. StringRef Prefix;
  938. StringRef Postfix;
  939. bool IsNSStringLiteral = false;
  940. // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
  941. // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
  942. // reduce the overhead) for each FormatToken, which is a string, so that we
  943. // don't run multiple checks here on the hot path.
  944. if (Text.startswith("\"") && Current.Previous &&
  945. Current.Previous->is(tok::at)) {
  946. IsNSStringLiteral = true;
  947. Prefix = "@\"";
  948. }
  949. if ((Text.endswith(Postfix = "\"") &&
  950. (IsNSStringLiteral || Text.startswith(Prefix = "\"") ||
  951. Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
  952. Text.startswith(Prefix = "u8\"") ||
  953. Text.startswith(Prefix = "L\""))) ||
  954. (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
  955. Token.reset(new BreakableStringLiteral(
  956. Current, State.Line->Level, StartColumn, Prefix, Postfix,
  957. State.Line->InPPDirective, Encoding, Style));
  958. } else {
  959. return 0;
  960. }
  961. } else if (Current.is(TT_BlockComment) && Current.isTrailingComment()) {
  962. if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
  963. return 0;
  964. Token.reset(new BreakableBlockComment(
  965. Current, State.Line->Level, StartColumn, Current.OriginalColumn,
  966. !Current.Previous, State.Line->InPPDirective, Encoding, Style));
  967. } else if (Current.is(TT_LineComment) &&
  968. (Current.Previous == nullptr ||
  969. Current.Previous->isNot(TT_ImplicitStringLiteral))) {
  970. if (CommentPragmasRegex.match(Current.TokenText.substr(2)))
  971. return 0;
  972. Token.reset(new BreakableLineComment(Current, State.Line->Level,
  973. StartColumn, /*InPPDirective=*/false,
  974. Encoding, Style));
  975. // We don't insert backslashes when breaking line comments.
  976. ColumnLimit = Style.ColumnLimit;
  977. } else {
  978. return 0;
  979. }
  980. if (Current.UnbreakableTailLength >= ColumnLimit)
  981. return 0;
  982. unsigned RemainingSpace = ColumnLimit - Current.UnbreakableTailLength;
  983. bool BreakInserted = false;
  984. unsigned Penalty = 0;
  985. unsigned RemainingTokenColumns = 0;
  986. for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
  987. LineIndex != EndIndex; ++LineIndex) {
  988. if (!DryRun)
  989. Token->replaceWhitespaceBefore(LineIndex, Whitespaces);
  990. unsigned TailOffset = 0;
  991. RemainingTokenColumns =
  992. Token->getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos);
  993. while (RemainingTokenColumns > RemainingSpace) {
  994. BreakableToken::Split Split =
  995. Token->getSplit(LineIndex, TailOffset, ColumnLimit);
  996. if (Split.first == StringRef::npos) {
  997. // The last line's penalty is handled in addNextStateToQueue().
  998. if (LineIndex < EndIndex - 1)
  999. Penalty += Style.PenaltyExcessCharacter *
  1000. (RemainingTokenColumns - RemainingSpace);
  1001. break;
  1002. }
  1003. assert(Split.first != 0);
  1004. unsigned NewRemainingTokenColumns = Token->getLineLengthAfterSplit(
  1005. LineIndex, TailOffset + Split.first + Split.second, StringRef::npos);
  1006. // We can remove extra whitespace instead of breaking the line.
  1007. if (RemainingTokenColumns + 1 - Split.second <= RemainingSpace) {
  1008. RemainingTokenColumns = 0;
  1009. if (!DryRun)
  1010. Token->replaceWhitespace(LineIndex, TailOffset, Split, Whitespaces);
  1011. break;
  1012. }
  1013. // When breaking before a tab character, it may be moved by a few columns,
  1014. // but will still be expanded to the next tab stop, so we don't save any
  1015. // columns.
  1016. if (NewRemainingTokenColumns == RemainingTokenColumns)
  1017. break;
  1018. assert(NewRemainingTokenColumns < RemainingTokenColumns);
  1019. if (!DryRun)
  1020. Token->insertBreak(LineIndex, TailOffset, Split, Whitespaces);
  1021. Penalty += Current.SplitPenalty;
  1022. unsigned ColumnsUsed =
  1023. Token->getLineLengthAfterSplit(LineIndex, TailOffset, Split.first);
  1024. if (ColumnsUsed > ColumnLimit) {
  1025. Penalty += Style.PenaltyExcessCharacter * (ColumnsUsed - ColumnLimit);
  1026. }
  1027. TailOffset += Split.first + Split.second;
  1028. RemainingTokenColumns = NewRemainingTokenColumns;
  1029. BreakInserted = true;
  1030. }
  1031. }
  1032. State.Column = RemainingTokenColumns;
  1033. if (BreakInserted) {
  1034. // If we break the token inside a parameter list, we need to break before
  1035. // the next parameter on all levels, so that the next parameter is clearly
  1036. // visible. Line comments already introduce a break.
  1037. if (Current.isNot(TT_LineComment)) {
  1038. for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
  1039. State.Stack[i].BreakBeforeParameter = true;
  1040. }
  1041. Penalty += Current.isStringLiteral() ? Style.PenaltyBreakString
  1042. : Style.PenaltyBreakComment;
  1043. State.Stack.back().LastSpace = StartColumn;
  1044. }
  1045. return Penalty;
  1046. }
  1047. unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
  1048. // In preprocessor directives reserve two chars for trailing " \"
  1049. return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
  1050. }
  1051. bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
  1052. const FormatToken &Current = *State.NextToken;
  1053. if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
  1054. return false;
  1055. // We never consider raw string literals "multiline" for the purpose of
  1056. // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
  1057. // (see TokenAnnotator::mustBreakBefore().
  1058. if (Current.TokenText.startswith("R\""))
  1059. return false;
  1060. if (Current.IsMultiline)
  1061. return true;
  1062. if (Current.getNextNonComment() &&
  1063. Current.getNextNonComment()->isStringLiteral())
  1064. return true; // Implicit concatenation.
  1065. if (Style.ColumnLimit != 0 &&
  1066. State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
  1067. Style.ColumnLimit)
  1068. return true; // String will be split.
  1069. return false;
  1070. }
  1071. } // namespace format
  1072. } // namespace clang