ContinuationIndenter.cpp 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188
  1. //===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// This file implements the continuation indenter.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "ContinuationIndenter.h"
  14. #include "BreakableToken.h"
  15. #include "FormatInternal.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. #define DEBUG_TYPE "format-indenter"
  22. namespace clang {
  23. namespace format {
  24. // Returns true if a TT_SelectorName should be indented when wrapped,
  25. // false otherwise.
  26. static bool shouldIndentWrappedSelectorName(const FormatStyle &Style,
  27. LineType LineType) {
  28. return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;
  29. }
  30. // Returns the length of everything up to the first possible line break after
  31. // the ), ], } or > matching \c Tok.
  32. static unsigned getLengthToMatchingParen(const FormatToken &Tok,
  33. const std::vector<ParenState> &Stack) {
  34. // Normally whether or not a break before T is possible is calculated and
  35. // stored in T.CanBreakBefore. Braces, array initializers and text proto
  36. // messages like `key: < ... >` are an exception: a break is possible
  37. // before a closing brace R if a break was inserted after the corresponding
  38. // opening brace. The information about whether or not a break is needed
  39. // before a closing brace R is stored in the ParenState field
  40. // S.BreakBeforeClosingBrace where S is the state that R closes.
  41. //
  42. // In order to decide whether there can be a break before encountered right
  43. // braces, this implementation iterates over the sequence of tokens and over
  44. // the paren stack in lockstep, keeping track of the stack level which visited
  45. // right braces correspond to in MatchingStackIndex.
  46. //
  47. // For example, consider:
  48. // L. <- line number
  49. // 1. {
  50. // 2. {1},
  51. // 3. {2},
  52. // 4. {{3}}}
  53. // ^ where we call this method with this token.
  54. // The paren stack at this point contains 3 brace levels:
  55. // 0. { at line 1, BreakBeforeClosingBrace: true
  56. // 1. first { at line 4, BreakBeforeClosingBrace: false
  57. // 2. second { at line 4, BreakBeforeClosingBrace: false,
  58. // where there might be fake parens levels in-between these levels.
  59. // The algorithm will start at the first } on line 4, which is the matching
  60. // brace of the initial left brace and at level 2 of the stack. Then,
  61. // examining BreakBeforeClosingBrace: false at level 2, it will continue to
  62. // the second } on line 4, and will traverse the stack downwards until it
  63. // finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:
  64. // false at level 1, it will continue to the third } on line 4 and will
  65. // traverse the stack downwards until it finds the matching { on level 0.
  66. // Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm
  67. // will stop and will use the second } on line 4 to determine the length to
  68. // return, as in this example the range will include the tokens: {3}}
  69. //
  70. // The algorithm will only traverse the stack if it encounters braces, array
  71. // initializer squares or text proto angle brackets.
  72. if (!Tok.MatchingParen)
  73. return 0;
  74. FormatToken *End = Tok.MatchingParen;
  75. // Maintains a stack level corresponding to the current End token.
  76. int MatchingStackIndex = Stack.size() - 1;
  77. // Traverses the stack downwards, looking for the level to which LBrace
  78. // corresponds. Returns either a pointer to the matching level or nullptr if
  79. // LParen is not found in the initial portion of the stack up to
  80. // MatchingStackIndex.
  81. auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
  82. while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
  83. --MatchingStackIndex;
  84. return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
  85. };
  86. for (; End->Next; End = End->Next) {
  87. if (End->Next->CanBreakBefore)
  88. break;
  89. if (!End->Next->closesScope())
  90. continue;
  91. if (End->Next->MatchingParen &&
  92. End->Next->MatchingParen->isOneOf(
  93. tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
  94. const ParenState *State = FindParenState(End->Next->MatchingParen);
  95. if (State && State->BreakBeforeClosingBrace)
  96. break;
  97. }
  98. }
  99. return End->TotalLength - Tok.TotalLength + 1;
  100. }
  101. static unsigned getLengthToNextOperator(const FormatToken &Tok) {
  102. if (!Tok.NextOperator)
  103. return 0;
  104. return Tok.NextOperator->TotalLength - Tok.TotalLength;
  105. }
  106. // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
  107. // segment of a builder type call.
  108. static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
  109. return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
  110. }
  111. // Returns \c true if \c Current starts a new parameter.
  112. static bool startsNextParameter(const FormatToken &Current,
  113. const FormatStyle &Style) {
  114. const FormatToken &Previous = *Current.Previous;
  115. if (Current.is(TT_CtorInitializerComma) &&
  116. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
  117. return true;
  118. if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
  119. return true;
  120. return Previous.is(tok::comma) && !Current.isTrailingComment() &&
  121. ((Previous.isNot(TT_CtorInitializerComma) ||
  122. Style.BreakConstructorInitializers !=
  123. FormatStyle::BCIS_BeforeComma) &&
  124. (Previous.isNot(TT_InheritanceComma) ||
  125. Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma));
  126. }
  127. static bool opensProtoMessageField(const FormatToken &LessTok,
  128. const FormatStyle &Style) {
  129. if (LessTok.isNot(tok::less))
  130. return false;
  131. return Style.Language == FormatStyle::LK_TextProto ||
  132. (Style.Language == FormatStyle::LK_Proto &&
  133. (LessTok.NestingLevel > 0 ||
  134. (LessTok.Previous && LessTok.Previous->is(tok::equal))));
  135. }
  136. // Returns the delimiter of a raw string literal, or None if TokenText is not
  137. // the text of a raw string literal. The delimiter could be the empty string.
  138. // For example, the delimiter of R"deli(cont)deli" is deli.
  139. static llvm::Optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
  140. if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
  141. || !TokenText.startswith("R\"") || !TokenText.endswith("\""))
  142. return None;
  143. // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has
  144. // size at most 16 by the standard, so the first '(' must be among the first
  145. // 19 bytes.
  146. size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
  147. if (LParenPos == StringRef::npos)
  148. return None;
  149. StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
  150. // Check that the string ends in ')Delimiter"'.
  151. size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
  152. if (TokenText[RParenPos] != ')')
  153. return None;
  154. if (!TokenText.substr(RParenPos + 1).startswith(Delimiter))
  155. return None;
  156. return Delimiter;
  157. }
  158. // Returns the canonical delimiter for \p Language, or the empty string if no
  159. // canonical delimiter is specified.
  160. static StringRef
  161. getCanonicalRawStringDelimiter(const FormatStyle &Style,
  162. FormatStyle::LanguageKind Language) {
  163. for (const auto &Format : Style.RawStringFormats) {
  164. if (Format.Language == Language)
  165. return StringRef(Format.CanonicalDelimiter);
  166. }
  167. return "";
  168. }
  169. RawStringFormatStyleManager::RawStringFormatStyleManager(
  170. const FormatStyle &CodeStyle) {
  171. for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
  172. llvm::Optional<FormatStyle> LanguageStyle =
  173. CodeStyle.GetLanguageStyle(RawStringFormat.Language);
  174. if (!LanguageStyle) {
  175. FormatStyle PredefinedStyle;
  176. if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
  177. RawStringFormat.Language, &PredefinedStyle)) {
  178. PredefinedStyle = getLLVMStyle();
  179. PredefinedStyle.Language = RawStringFormat.Language;
  180. }
  181. LanguageStyle = PredefinedStyle;
  182. }
  183. LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
  184. for (StringRef Delimiter : RawStringFormat.Delimiters) {
  185. DelimiterStyle.insert({Delimiter, *LanguageStyle});
  186. }
  187. for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions) {
  188. EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
  189. }
  190. }
  191. }
  192. llvm::Optional<FormatStyle>
  193. RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {
  194. auto It = DelimiterStyle.find(Delimiter);
  195. if (It == DelimiterStyle.end())
  196. return None;
  197. return It->second;
  198. }
  199. llvm::Optional<FormatStyle>
  200. RawStringFormatStyleManager::getEnclosingFunctionStyle(
  201. StringRef EnclosingFunction) const {
  202. auto It = EnclosingFunctionStyle.find(EnclosingFunction);
  203. if (It == EnclosingFunctionStyle.end())
  204. return None;
  205. return It->second;
  206. }
  207. ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
  208. const AdditionalKeywords &Keywords,
  209. const SourceManager &SourceMgr,
  210. WhitespaceManager &Whitespaces,
  211. encoding::Encoding Encoding,
  212. bool BinPackInconclusiveFunctions)
  213. : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
  214. Whitespaces(Whitespaces), Encoding(Encoding),
  215. BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
  216. CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
  217. LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
  218. unsigned FirstStartColumn,
  219. const AnnotatedLine *Line,
  220. bool DryRun) {
  221. LineState State;
  222. State.FirstIndent = FirstIndent;
  223. if (FirstStartColumn && Line->First->NewlinesBefore == 0)
  224. State.Column = FirstStartColumn;
  225. else
  226. State.Column = FirstIndent;
  227. // With preprocessor directive indentation, the line starts on column 0
  228. // since it's indented after the hash, but FirstIndent is set to the
  229. // preprocessor indent.
  230. if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
  231. (Line->Type == LT_PreprocessorDirective ||
  232. Line->Type == LT_ImportStatement))
  233. State.Column = 0;
  234. State.Line = Line;
  235. State.NextToken = Line->First;
  236. State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,
  237. /*AvoidBinPacking=*/false,
  238. /*NoLineBreak=*/false));
  239. State.LineContainsContinuedForLoopSection = false;
  240. State.NoContinuation = false;
  241. State.StartOfStringLiteral = 0;
  242. State.StartOfLineLevel = 0;
  243. State.LowestLevelOnLine = 0;
  244. State.IgnoreStackForComparison = false;
  245. if (Style.Language == FormatStyle::LK_TextProto) {
  246. // We need this in order to deal with the bin packing of text fields at
  247. // global scope.
  248. State.Stack.back().AvoidBinPacking = true;
  249. State.Stack.back().BreakBeforeParameter = true;
  250. State.Stack.back().AlignColons = false;
  251. }
  252. // The first token has already been indented and thus consumed.
  253. moveStateToNextToken(State, DryRun, /*Newline=*/false);
  254. return State;
  255. }
  256. bool ContinuationIndenter::canBreak(const LineState &State) {
  257. const FormatToken &Current = *State.NextToken;
  258. const FormatToken &Previous = *Current.Previous;
  259. assert(&Previous == Current.Previous);
  260. if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
  261. Current.closesBlockOrBlockTypeList(Style)))
  262. return false;
  263. // The opening "{" of a braced list has to be on the same line as the first
  264. // element if it is nested in another braced init list or function call.
  265. if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
  266. Previous.isNot(TT_DictLiteral) && Previous.BlockKind == BK_BracedInit &&
  267. Previous.Previous &&
  268. Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
  269. return false;
  270. // This prevents breaks like:
  271. // ...
  272. // SomeParameter, OtherParameter).DoSomething(
  273. // ...
  274. // As they hide "DoSomething" and are generally bad for readability.
  275. if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
  276. State.LowestLevelOnLine < State.StartOfLineLevel &&
  277. State.LowestLevelOnLine < Current.NestingLevel)
  278. return false;
  279. if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
  280. return false;
  281. // Don't create a 'hanging' indent if there are multiple blocks in a single
  282. // statement.
  283. if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
  284. State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
  285. State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
  286. return false;
  287. // Don't break after very short return types (e.g. "void") as that is often
  288. // unexpected.
  289. if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
  290. if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
  291. return false;
  292. }
  293. // If binary operators are moved to the next line (including commas for some
  294. // styles of constructor initializers), that's always ok.
  295. if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
  296. State.Stack.back().NoLineBreakInOperand)
  297. return false;
  298. if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
  299. return false;
  300. return !State.Stack.back().NoLineBreak;
  301. }
  302. bool ContinuationIndenter::mustBreak(const LineState &State) {
  303. const FormatToken &Current = *State.NextToken;
  304. const FormatToken &Previous = *Current.Previous;
  305. if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
  306. return true;
  307. if (State.Stack.back().BreakBeforeClosingBrace &&
  308. Current.closesBlockOrBlockTypeList(Style))
  309. return true;
  310. if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
  311. return true;
  312. if (Style.Language == FormatStyle::LK_ObjC &&
  313. Current.ObjCSelectorNameParts > 1 &&
  314. Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
  315. return true;
  316. }
  317. if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
  318. (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
  319. Style.isCpp() &&
  320. // FIXME: This is a temporary workaround for the case where clang-format
  321. // sets BreakBeforeParameter to avoid bin packing and this creates a
  322. // completely unnecessary line break after a template type that isn't
  323. // line-wrapped.
  324. (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
  325. (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
  326. Previous.isNot(tok::question)) ||
  327. (!Style.BreakBeforeTernaryOperators &&
  328. Previous.is(TT_ConditionalExpr))) &&
  329. State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
  330. !Current.isOneOf(tok::r_paren, tok::r_brace))
  331. return true;
  332. if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
  333. (Previous.is(TT_ArrayInitializerLSquare) &&
  334. Previous.ParameterCount > 1) ||
  335. opensProtoMessageField(Previous, Style)) &&
  336. Style.ColumnLimit > 0 &&
  337. getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
  338. getColumnLimit(State))
  339. return true;
  340. const FormatToken &BreakConstructorInitializersToken =
  341. Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
  342. ? Previous
  343. : Current;
  344. if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
  345. (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
  346. getColumnLimit(State) ||
  347. State.Stack.back().BreakBeforeParameter) &&
  348. (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||
  349. Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||
  350. Style.ColumnLimit != 0))
  351. return true;
  352. if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
  353. State.Line->startsWith(TT_ObjCMethodSpecifier))
  354. return true;
  355. if (Current.is(TT_SelectorName) && !Previous.is(tok::at) &&
  356. State.Stack.back().ObjCSelectorNameFound &&
  357. State.Stack.back().BreakBeforeParameter)
  358. return true;
  359. unsigned NewLineColumn = getNewLineColumn(State);
  360. if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
  361. State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
  362. (State.Column > NewLineColumn ||
  363. Current.NestingLevel < State.StartOfLineLevel))
  364. return true;
  365. if (startsSegmentOfBuilderTypeCall(Current) &&
  366. (State.Stack.back().CallContinuation != 0 ||
  367. State.Stack.back().BreakBeforeParameter) &&
  368. // JavaScript is treated different here as there is a frequent pattern:
  369. // SomeFunction(function() {
  370. // ...
  371. // }.bind(...));
  372. // FIXME: We should find a more generic solution to this problem.
  373. !(State.Column <= NewLineColumn &&
  374. Style.Language == FormatStyle::LK_JavaScript) &&
  375. !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn))
  376. return true;
  377. // If the template declaration spans multiple lines, force wrap before the
  378. // function/class declaration
  379. if (Previous.ClosesTemplateDeclaration &&
  380. State.Stack.back().BreakBeforeParameter && Current.CanBreakBefore)
  381. return true;
  382. if (State.Column <= NewLineColumn)
  383. return false;
  384. if (Style.AlwaysBreakBeforeMultilineStrings &&
  385. (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
  386. Previous.is(tok::comma) || Current.NestingLevel < 2) &&
  387. !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at) &&
  388. !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
  389. nextIsMultilineString(State))
  390. return true;
  391. // Using CanBreakBefore here and below takes care of the decision whether the
  392. // current style uses wrapping before or after operators for the given
  393. // operator.
  394. if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
  395. // If we need to break somewhere inside the LHS of a binary expression, we
  396. // should also break after the operator. Otherwise, the formatting would
  397. // hide the operator precedence, e.g. in:
  398. // if (aaaaaaaaaaaaaa ==
  399. // bbbbbbbbbbbbbb && c) {..
  400. // For comparisons, we only apply this rule, if the LHS is a binary
  401. // expression itself as otherwise, the line breaks seem superfluous.
  402. // We need special cases for ">>" which we have split into two ">" while
  403. // lexing in order to make template parsing easier.
  404. bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
  405. Previous.getPrecedence() == prec::Equality ||
  406. Previous.getPrecedence() == prec::Spaceship) &&
  407. Previous.Previous &&
  408. Previous.Previous->isNot(TT_BinaryOperator); // For >>.
  409. bool LHSIsBinaryExpr =
  410. Previous.Previous && Previous.Previous->EndsBinaryExpression;
  411. if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
  412. Previous.getPrecedence() != prec::Assignment &&
  413. State.Stack.back().BreakBeforeParameter)
  414. return true;
  415. } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
  416. State.Stack.back().BreakBeforeParameter) {
  417. return true;
  418. }
  419. // Same as above, but for the first "<<" operator.
  420. if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
  421. State.Stack.back().BreakBeforeParameter &&
  422. State.Stack.back().FirstLessLess == 0)
  423. return true;
  424. if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
  425. // Always break after "template <...>" and leading annotations. This is only
  426. // for cases where the entire line does not fit on a single line as a
  427. // different LineFormatter would be used otherwise.
  428. if (Previous.ClosesTemplateDeclaration)
  429. return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No;
  430. if (Previous.is(TT_FunctionAnnotationRParen))
  431. return true;
  432. if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
  433. Current.isNot(TT_LeadingJavaAnnotation))
  434. return true;
  435. }
  436. // If the return type spans multiple lines, wrap before the function name.
  437. if ((Current.is(TT_FunctionDeclarationName) ||
  438. (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
  439. !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter)
  440. return true;
  441. // The following could be precomputed as they do not depend on the state.
  442. // However, as they should take effect only if the UnwrappedLine does not fit
  443. // into the ColumnLimit, they are checked here in the ContinuationIndenter.
  444. if (Style.ColumnLimit != 0 && Previous.BlockKind == BK_Block &&
  445. Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
  446. return true;
  447. if (Current.is(tok::lessless) &&
  448. ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
  449. (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
  450. Previous.TokenText == "\'\\n\'"))))
  451. return true;
  452. if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
  453. return true;
  454. if (State.NoContinuation)
  455. return true;
  456. return false;
  457. }
  458. unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
  459. bool DryRun,
  460. unsigned ExtraSpaces) {
  461. const FormatToken &Current = *State.NextToken;
  462. assert(!State.Stack.empty());
  463. State.NoContinuation = false;
  464. if ((Current.is(TT_ImplicitStringLiteral) &&
  465. (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
  466. Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
  467. tok::pp_not_keyword))) {
  468. unsigned EndColumn =
  469. SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
  470. if (Current.LastNewlineOffset != 0) {
  471. // If there is a newline within this token, the final column will solely
  472. // determined by the current end column.
  473. State.Column = EndColumn;
  474. } else {
  475. unsigned StartColumn =
  476. SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
  477. assert(EndColumn >= StartColumn);
  478. State.Column += EndColumn - StartColumn;
  479. }
  480. moveStateToNextToken(State, DryRun, /*Newline=*/false);
  481. return 0;
  482. }
  483. unsigned Penalty = 0;
  484. if (Newline)
  485. Penalty = addTokenOnNewLine(State, DryRun);
  486. else
  487. addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
  488. return moveStateToNextToken(State, DryRun, Newline) + Penalty;
  489. }
  490. void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
  491. unsigned ExtraSpaces) {
  492. FormatToken &Current = *State.NextToken;
  493. const FormatToken &Previous = *State.NextToken->Previous;
  494. if (Current.is(tok::equal) &&
  495. (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
  496. State.Stack.back().VariablePos == 0) {
  497. State.Stack.back().VariablePos = State.Column;
  498. // Move over * and & if they are bound to the variable name.
  499. const FormatToken *Tok = &Previous;
  500. while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
  501. State.Stack.back().VariablePos -= Tok->ColumnWidth;
  502. if (Tok->SpacesRequiredBefore != 0)
  503. break;
  504. Tok = Tok->Previous;
  505. }
  506. if (Previous.PartOfMultiVariableDeclStmt)
  507. State.Stack.back().LastSpace = State.Stack.back().VariablePos;
  508. }
  509. unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
  510. // Indent preprocessor directives after the hash if required.
  511. int PPColumnCorrection = 0;
  512. if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
  513. Previous.is(tok::hash) && State.FirstIndent > 0 &&
  514. (State.Line->Type == LT_PreprocessorDirective ||
  515. State.Line->Type == LT_ImportStatement)) {
  516. Spaces += State.FirstIndent;
  517. // For preprocessor indent with tabs, State.Column will be 1 because of the
  518. // hash. This causes second-level indents onward to have an extra space
  519. // after the tabs. We avoid this misalignment by subtracting 1 from the
  520. // column value passed to replaceWhitespace().
  521. if (Style.UseTab != FormatStyle::UT_Never)
  522. PPColumnCorrection = -1;
  523. }
  524. if (!DryRun)
  525. Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
  526. State.Column + Spaces + PPColumnCorrection);
  527. // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
  528. // declaration unless there is multiple inheritance.
  529. if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
  530. Current.is(TT_InheritanceColon))
  531. State.Stack.back().NoLineBreak = true;
  532. if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon &&
  533. Previous.is(TT_InheritanceColon))
  534. State.Stack.back().NoLineBreak = true;
  535. if (Current.is(TT_SelectorName) &&
  536. !State.Stack.back().ObjCSelectorNameFound) {
  537. unsigned MinIndent =
  538. std::max(State.FirstIndent + Style.ContinuationIndentWidth,
  539. State.Stack.back().Indent);
  540. unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
  541. if (Current.LongestObjCSelectorName == 0)
  542. State.Stack.back().AlignColons = false;
  543. else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
  544. State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName;
  545. else
  546. State.Stack.back().ColonPos = FirstColonPos;
  547. }
  548. // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by
  549. // disallowing any further line breaks if there is no line break after the
  550. // opening parenthesis. Don't break if it doesn't conserve columns.
  551. if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak &&
  552. Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) &&
  553. State.Column > getNewLineColumn(State) &&
  554. (!Previous.Previous || !Previous.Previous->isOneOf(
  555. tok::kw_for, tok::kw_while, tok::kw_switch)) &&
  556. // Don't do this for simple (no expressions) one-argument function calls
  557. // as that feels like needlessly wasting whitespace, e.g.:
  558. //
  559. // caaaaaaaaaaaall(
  560. // caaaaaaaaaaaall(
  561. // caaaaaaaaaaaall(
  562. // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
  563. Current.FakeLParens.size() > 0 &&
  564. Current.FakeLParens.back() > prec::Unknown)
  565. State.Stack.back().NoLineBreak = true;
  566. if (Previous.is(TT_TemplateString) && Previous.opensScope())
  567. State.Stack.back().NoLineBreak = true;
  568. if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
  569. Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
  570. (Current.isNot(TT_LineComment) || Previous.BlockKind == BK_BracedInit))
  571. State.Stack.back().Indent = State.Column + Spaces;
  572. if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
  573. State.Stack.back().NoLineBreak = true;
  574. if (startsSegmentOfBuilderTypeCall(Current) &&
  575. State.Column > getNewLineColumn(State))
  576. State.Stack.back().ContainsUnwrappedBuilder = true;
  577. if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
  578. State.Stack.back().NoLineBreak = true;
  579. if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
  580. (Previous.MatchingParen &&
  581. (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10)))
  582. // If there is a function call with long parameters, break before trailing
  583. // calls. This prevents things like:
  584. // EXPECT_CALL(SomeLongParameter).Times(
  585. // 2);
  586. // We don't want to do this for short parameters as they can just be
  587. // indexes.
  588. State.Stack.back().NoLineBreak = true;
  589. // Don't allow the RHS of an operator to be split over multiple lines unless
  590. // there is a line-break right after the operator.
  591. // Exclude relational operators, as there, it is always more desirable to
  592. // have the LHS 'left' of the RHS.
  593. const FormatToken *P = Current.getPreviousNonComment();
  594. if (!Current.is(tok::comment) && P &&
  595. (P->isOneOf(TT_BinaryOperator, tok::comma) ||
  596. (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
  597. !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
  598. P->getPrecedence() != prec::Assignment &&
  599. P->getPrecedence() != prec::Relational &&
  600. P->getPrecedence() != prec::Spaceship) {
  601. bool BreakBeforeOperator =
  602. P->MustBreakBefore || P->is(tok::lessless) ||
  603. (P->is(TT_BinaryOperator) &&
  604. Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
  605. (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
  606. // Don't do this if there are only two operands. In these cases, there is
  607. // always a nice vertical separation between them and the extra line break
  608. // does not help.
  609. bool HasTwoOperands =
  610. P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
  611. if ((!BreakBeforeOperator && !(HasTwoOperands && Style.AlignOperands)) ||
  612. (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
  613. State.Stack.back().NoLineBreakInOperand = true;
  614. }
  615. State.Column += Spaces;
  616. if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
  617. Previous.Previous &&
  618. (Previous.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
  619. Previous.Previous->endsSequence(tok::kw_constexpr, tok::kw_if))) {
  620. // Treat the condition inside an if as if it was a second function
  621. // parameter, i.e. let nested calls have a continuation indent.
  622. State.Stack.back().LastSpace = State.Column;
  623. State.Stack.back().NestedBlockIndent = State.Column;
  624. } else if (!Current.isOneOf(tok::comment, tok::caret) &&
  625. ((Previous.is(tok::comma) &&
  626. !Previous.is(TT_OverloadedOperator)) ||
  627. (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
  628. State.Stack.back().LastSpace = State.Column;
  629. } else if (Previous.is(TT_CtorInitializerColon) &&
  630. Style.BreakConstructorInitializers ==
  631. FormatStyle::BCIS_AfterColon) {
  632. State.Stack.back().Indent = State.Column;
  633. State.Stack.back().LastSpace = State.Column;
  634. } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
  635. TT_CtorInitializerColon)) &&
  636. ((Previous.getPrecedence() != prec::Assignment &&
  637. (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
  638. Previous.NextOperator)) ||
  639. Current.StartsBinaryExpression)) {
  640. // Indent relative to the RHS of the expression unless this is a simple
  641. // assignment without binary expression on the RHS. Also indent relative to
  642. // unary operators and the colons of constructor initializers.
  643. if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None)
  644. State.Stack.back().LastSpace = State.Column;
  645. } else if (Previous.is(TT_InheritanceColon)) {
  646. State.Stack.back().Indent = State.Column;
  647. State.Stack.back().LastSpace = State.Column;
  648. } else if (Previous.opensScope()) {
  649. // If a function has a trailing call, indent all parameters from the
  650. // opening parenthesis. This avoids confusing indents like:
  651. // OuterFunction(InnerFunctionCall( // break
  652. // ParameterToInnerFunction)) // break
  653. // .SecondInnerFunctionCall();
  654. bool HasTrailingCall = false;
  655. if (Previous.MatchingParen) {
  656. const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
  657. HasTrailingCall = Next && Next->isMemberAccess();
  658. }
  659. if (HasTrailingCall && State.Stack.size() > 1 &&
  660. State.Stack[State.Stack.size() - 2].CallContinuation == 0)
  661. State.Stack.back().LastSpace = State.Column;
  662. }
  663. }
  664. unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
  665. bool DryRun) {
  666. FormatToken &Current = *State.NextToken;
  667. const FormatToken &Previous = *State.NextToken->Previous;
  668. // Extra penalty that needs to be added because of the way certain line
  669. // breaks are chosen.
  670. unsigned Penalty = 0;
  671. const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
  672. const FormatToken *NextNonComment = Previous.getNextNonComment();
  673. if (!NextNonComment)
  674. NextNonComment = &Current;
  675. // The first line break on any NestingLevel causes an extra penalty in order
  676. // prefer similar line breaks.
  677. if (!State.Stack.back().ContainsLineBreak)
  678. Penalty += 15;
  679. State.Stack.back().ContainsLineBreak = true;
  680. Penalty += State.NextToken->SplitPenalty;
  681. // Breaking before the first "<<" is generally not desirable if the LHS is
  682. // short. Also always add the penalty if the LHS is split over multiple lines
  683. // to avoid unnecessary line breaks that just work around this penalty.
  684. if (NextNonComment->is(tok::lessless) &&
  685. State.Stack.back().FirstLessLess == 0 &&
  686. (State.Column <= Style.ColumnLimit / 3 ||
  687. State.Stack.back().BreakBeforeParameter))
  688. Penalty += Style.PenaltyBreakFirstLessLess;
  689. State.Column = getNewLineColumn(State);
  690. // Indent nested blocks relative to this column, unless in a very specific
  691. // JavaScript special case where:
  692. //
  693. // var loooooong_name =
  694. // function() {
  695. // // code
  696. // }
  697. //
  698. // is common and should be formatted like a free-standing function. The same
  699. // goes for wrapping before the lambda return type arrow.
  700. if (!Current.is(TT_LambdaArrow) &&
  701. (Style.Language != FormatStyle::LK_JavaScript ||
  702. Current.NestingLevel != 0 || !PreviousNonComment ||
  703. !PreviousNonComment->is(tok::equal) ||
  704. !Current.isOneOf(Keywords.kw_async, Keywords.kw_function)))
  705. State.Stack.back().NestedBlockIndent = State.Column;
  706. if (NextNonComment->isMemberAccess()) {
  707. if (State.Stack.back().CallContinuation == 0)
  708. State.Stack.back().CallContinuation = State.Column;
  709. } else if (NextNonComment->is(TT_SelectorName)) {
  710. if (!State.Stack.back().ObjCSelectorNameFound) {
  711. if (NextNonComment->LongestObjCSelectorName == 0) {
  712. State.Stack.back().AlignColons = false;
  713. } else {
  714. State.Stack.back().ColonPos =
  715. (shouldIndentWrappedSelectorName(Style, State.Line->Type)
  716. ? std::max(State.Stack.back().Indent,
  717. State.FirstIndent + Style.ContinuationIndentWidth)
  718. : State.Stack.back().Indent) +
  719. std::max(NextNonComment->LongestObjCSelectorName,
  720. NextNonComment->ColumnWidth);
  721. }
  722. } else if (State.Stack.back().AlignColons &&
  723. State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
  724. State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
  725. }
  726. } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
  727. PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
  728. // FIXME: This is hacky, find a better way. The problem is that in an ObjC
  729. // method expression, the block should be aligned to the line starting it,
  730. // e.g.:
  731. // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
  732. // ^(int *i) {
  733. // // ...
  734. // }];
  735. // Thus, we set LastSpace of the next higher NestingLevel, to which we move
  736. // when we consume all of the "}"'s FakeRParens at the "{".
  737. if (State.Stack.size() > 1)
  738. State.Stack[State.Stack.size() - 2].LastSpace =
  739. std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
  740. Style.ContinuationIndentWidth;
  741. }
  742. if ((PreviousNonComment &&
  743. PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
  744. !State.Stack.back().AvoidBinPacking) ||
  745. Previous.is(TT_BinaryOperator))
  746. State.Stack.back().BreakBeforeParameter = false;
  747. if (PreviousNonComment &&
  748. PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
  749. Current.NestingLevel == 0)
  750. State.Stack.back().BreakBeforeParameter = false;
  751. if (NextNonComment->is(tok::question) ||
  752. (PreviousNonComment && PreviousNonComment->is(tok::question)))
  753. State.Stack.back().BreakBeforeParameter = true;
  754. if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
  755. State.Stack.back().BreakBeforeParameter = false;
  756. if (!DryRun) {
  757. unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
  758. if (Current.is(tok::r_brace) && Current.MatchingParen &&
  759. // Only strip trailing empty lines for l_braces that have children, i.e.
  760. // for function expressions (lambdas, arrows, etc).
  761. !Current.MatchingParen->Children.empty()) {
  762. // lambdas and arrow functions are expressions, thus their r_brace is not
  763. // on its own line, and thus not covered by UnwrappedLineFormatter's logic
  764. // about removing empty lines on closing blocks. Special case them here.
  765. MaxEmptyLinesToKeep = 1;
  766. }
  767. unsigned Newlines =
  768. std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
  769. bool ContinuePPDirective =
  770. State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
  771. Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
  772. ContinuePPDirective);
  773. }
  774. if (!Current.isTrailingComment())
  775. State.Stack.back().LastSpace = State.Column;
  776. if (Current.is(tok::lessless))
  777. // If we are breaking before a "<<", we always want to indent relative to
  778. // RHS. This is necessary only for "<<", as we special-case it and don't
  779. // always indent relative to the RHS.
  780. State.Stack.back().LastSpace += 3; // 3 -> width of "<< ".
  781. State.StartOfLineLevel = Current.NestingLevel;
  782. State.LowestLevelOnLine = Current.NestingLevel;
  783. // Any break on this level means that the parent level has been broken
  784. // and we need to avoid bin packing there.
  785. bool NestedBlockSpecialCase =
  786. !Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
  787. State.Stack[State.Stack.size() - 2].NestedBlockInlined;
  788. if (!NestedBlockSpecialCase)
  789. for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
  790. State.Stack[i].BreakBeforeParameter = true;
  791. if (PreviousNonComment &&
  792. !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
  793. (PreviousNonComment->isNot(TT_TemplateCloser) ||
  794. Current.NestingLevel != 0) &&
  795. !PreviousNonComment->isOneOf(
  796. TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
  797. TT_LeadingJavaAnnotation) &&
  798. Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
  799. State.Stack.back().BreakBeforeParameter = true;
  800. // If we break after { or the [ of an array initializer, we should also break
  801. // before the corresponding } or ].
  802. if (PreviousNonComment &&
  803. (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
  804. opensProtoMessageField(*PreviousNonComment, Style)))
  805. State.Stack.back().BreakBeforeClosingBrace = true;
  806. if (State.Stack.back().AvoidBinPacking) {
  807. // If we are breaking after '(', '{', '<', this is not bin packing
  808. // unless AllowAllParametersOfDeclarationOnNextLine is false or this is a
  809. // dict/object literal.
  810. if (!Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
  811. (!Style.AllowAllParametersOfDeclarationOnNextLine &&
  812. State.Line->MustBeDeclaration) ||
  813. Previous.is(TT_DictLiteral))
  814. State.Stack.back().BreakBeforeParameter = true;
  815. }
  816. return Penalty;
  817. }
  818. unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
  819. if (!State.NextToken || !State.NextToken->Previous)
  820. return 0;
  821. FormatToken &Current = *State.NextToken;
  822. const FormatToken &Previous = *Current.Previous;
  823. // If we are continuing an expression, we want to use the continuation indent.
  824. unsigned ContinuationIndent =
  825. std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
  826. Style.ContinuationIndentWidth;
  827. const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
  828. const FormatToken *NextNonComment = Previous.getNextNonComment();
  829. if (!NextNonComment)
  830. NextNonComment = &Current;
  831. // Java specific bits.
  832. if (Style.Language == FormatStyle::LK_Java &&
  833. Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
  834. return std::max(State.Stack.back().LastSpace,
  835. State.Stack.back().Indent + Style.ContinuationIndentWidth);
  836. if (NextNonComment->is(tok::l_brace) && NextNonComment->BlockKind == BK_Block)
  837. return Current.NestingLevel == 0 ? State.FirstIndent
  838. : State.Stack.back().Indent;
  839. if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
  840. (Current.is(tok::greater) &&
  841. (Style.Language == FormatStyle::LK_Proto ||
  842. Style.Language == FormatStyle::LK_TextProto))) &&
  843. State.Stack.size() > 1) {
  844. if (Current.closesBlockOrBlockTypeList(Style))
  845. return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
  846. if (Current.MatchingParen &&
  847. Current.MatchingParen->BlockKind == BK_BracedInit)
  848. return State.Stack[State.Stack.size() - 2].LastSpace;
  849. return State.FirstIndent;
  850. }
  851. // Indent a closing parenthesis at the previous level if followed by a semi or
  852. // opening brace. This allows indentations such as:
  853. // foo(
  854. // a,
  855. // );
  856. // function foo(
  857. // a,
  858. // ) {
  859. // code(); //
  860. // }
  861. if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
  862. (!Current.Next || Current.Next->isOneOf(tok::semi, tok::l_brace)))
  863. return State.Stack[State.Stack.size() - 2].LastSpace;
  864. if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
  865. return State.Stack[State.Stack.size() - 2].LastSpace;
  866. if (Current.is(tok::identifier) && Current.Next &&
  867. (Current.Next->is(TT_DictLiteral) ||
  868. ((Style.Language == FormatStyle::LK_Proto ||
  869. Style.Language == FormatStyle::LK_TextProto) &&
  870. Current.Next->isOneOf(tok::less, tok::l_brace))))
  871. return State.Stack.back().Indent;
  872. if (NextNonComment->is(TT_ObjCStringLiteral) &&
  873. State.StartOfStringLiteral != 0)
  874. return State.StartOfStringLiteral - 1;
  875. if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
  876. return State.StartOfStringLiteral;
  877. if (NextNonComment->is(tok::lessless) &&
  878. State.Stack.back().FirstLessLess != 0)
  879. return State.Stack.back().FirstLessLess;
  880. if (NextNonComment->isMemberAccess()) {
  881. if (State.Stack.back().CallContinuation == 0)
  882. return ContinuationIndent;
  883. return State.Stack.back().CallContinuation;
  884. }
  885. if (State.Stack.back().QuestionColumn != 0 &&
  886. ((NextNonComment->is(tok::colon) &&
  887. NextNonComment->is(TT_ConditionalExpr)) ||
  888. Previous.is(TT_ConditionalExpr)))
  889. return State.Stack.back().QuestionColumn;
  890. if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
  891. return State.Stack.back().VariablePos;
  892. if ((PreviousNonComment &&
  893. (PreviousNonComment->ClosesTemplateDeclaration ||
  894. PreviousNonComment->isOneOf(
  895. TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
  896. TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
  897. (!Style.IndentWrappedFunctionNames &&
  898. NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
  899. return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
  900. if (NextNonComment->is(TT_SelectorName)) {
  901. if (!State.Stack.back().ObjCSelectorNameFound) {
  902. unsigned MinIndent = State.Stack.back().Indent;
  903. if (shouldIndentWrappedSelectorName(Style, State.Line->Type))
  904. MinIndent = std::max(MinIndent,
  905. State.FirstIndent + Style.ContinuationIndentWidth);
  906. // If LongestObjCSelectorName is 0, we are indenting the first
  907. // part of an ObjC selector (or a selector component which is
  908. // not colon-aligned due to block formatting).
  909. //
  910. // Otherwise, we are indenting a subsequent part of an ObjC
  911. // selector which should be colon-aligned to the longest
  912. // component of the ObjC selector.
  913. //
  914. // In either case, we want to respect Style.IndentWrappedFunctionNames.
  915. return MinIndent +
  916. std::max(NextNonComment->LongestObjCSelectorName,
  917. NextNonComment->ColumnWidth) -
  918. NextNonComment->ColumnWidth;
  919. }
  920. if (!State.Stack.back().AlignColons)
  921. return State.Stack.back().Indent;
  922. if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
  923. return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
  924. return State.Stack.back().Indent;
  925. }
  926. if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
  927. return State.Stack.back().ColonPos;
  928. if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
  929. if (State.Stack.back().StartOfArraySubscripts != 0)
  930. return State.Stack.back().StartOfArraySubscripts;
  931. return ContinuationIndent;
  932. }
  933. // This ensure that we correctly format ObjC methods calls without inputs,
  934. // i.e. where the last element isn't selector like: [callee method];
  935. if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
  936. NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
  937. return State.Stack.back().Indent;
  938. if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
  939. Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
  940. return ContinuationIndent;
  941. if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
  942. PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
  943. return ContinuationIndent;
  944. if (NextNonComment->is(TT_CtorInitializerComma))
  945. return State.Stack.back().Indent;
  946. if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
  947. Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon)
  948. return State.Stack.back().Indent;
  949. if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
  950. Style.BreakInheritanceList == FormatStyle::BILS_AfterColon)
  951. return State.Stack.back().Indent;
  952. if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
  953. TT_InheritanceComma))
  954. return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
  955. if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
  956. !Current.isOneOf(tok::colon, tok::comment))
  957. return ContinuationIndent;
  958. if (Current.is(TT_ProtoExtensionLSquare))
  959. return State.Stack.back().Indent;
  960. if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
  961. PreviousNonComment->isNot(tok::r_brace))
  962. // Ensure that we fall back to the continuation indent width instead of
  963. // just flushing continuations left.
  964. return State.Stack.back().Indent + Style.ContinuationIndentWidth;
  965. return State.Stack.back().Indent;
  966. }
  967. unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
  968. bool DryRun, bool Newline) {
  969. assert(State.Stack.size());
  970. const FormatToken &Current = *State.NextToken;
  971. if (Current.isOneOf(tok::comma, TT_BinaryOperator))
  972. State.Stack.back().NoLineBreakInOperand = false;
  973. if (Current.is(TT_InheritanceColon))
  974. State.Stack.back().AvoidBinPacking = true;
  975. if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
  976. if (State.Stack.back().FirstLessLess == 0)
  977. State.Stack.back().FirstLessLess = State.Column;
  978. else
  979. State.Stack.back().LastOperatorWrapped = Newline;
  980. }
  981. if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
  982. State.Stack.back().LastOperatorWrapped = Newline;
  983. if (Current.is(TT_ConditionalExpr) && Current.Previous &&
  984. !Current.Previous->is(TT_ConditionalExpr))
  985. State.Stack.back().LastOperatorWrapped = Newline;
  986. if (Current.is(TT_ArraySubscriptLSquare) &&
  987. State.Stack.back().StartOfArraySubscripts == 0)
  988. State.Stack.back().StartOfArraySubscripts = State.Column;
  989. if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
  990. State.Stack.back().QuestionColumn = State.Column;
  991. if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
  992. const FormatToken *Previous = Current.Previous;
  993. while (Previous && Previous->isTrailingComment())
  994. Previous = Previous->Previous;
  995. if (Previous && Previous->is(tok::question))
  996. State.Stack.back().QuestionColumn = State.Column;
  997. }
  998. if (!Current.opensScope() && !Current.closesScope() &&
  999. !Current.is(TT_PointerOrReference))
  1000. State.LowestLevelOnLine =
  1001. std::min(State.LowestLevelOnLine, Current.NestingLevel);
  1002. if (Current.isMemberAccess())
  1003. State.Stack.back().StartOfFunctionCall =
  1004. !Current.NextOperator ? 0 : State.Column;
  1005. if (Current.is(TT_SelectorName))
  1006. State.Stack.back().ObjCSelectorNameFound = true;
  1007. if (Current.is(TT_CtorInitializerColon) &&
  1008. Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
  1009. // Indent 2 from the column, so:
  1010. // SomeClass::SomeClass()
  1011. // : First(...), ...
  1012. // Next(...)
  1013. // ^ line up here.
  1014. State.Stack.back().Indent =
  1015. State.Column +
  1016. (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma
  1017. ? 0
  1018. : 2);
  1019. State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
  1020. if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
  1021. State.Stack.back().AvoidBinPacking = true;
  1022. State.Stack.back().BreakBeforeParameter = false;
  1023. }
  1024. if (Current.is(TT_CtorInitializerColon) &&
  1025. Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
  1026. State.Stack.back().Indent =
  1027. State.FirstIndent + Style.ConstructorInitializerIndentWidth;
  1028. State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
  1029. if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
  1030. State.Stack.back().AvoidBinPacking = true;
  1031. }
  1032. if (Current.is(TT_InheritanceColon))
  1033. State.Stack.back().Indent =
  1034. State.FirstIndent + Style.ConstructorInitializerIndentWidth;
  1035. if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
  1036. State.Stack.back().NestedBlockIndent =
  1037. State.Column + Current.ColumnWidth + 1;
  1038. if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
  1039. State.Stack.back().LastSpace = State.Column;
  1040. // Insert scopes created by fake parenthesis.
  1041. const FormatToken *Previous = Current.getPreviousNonComment();
  1042. // Add special behavior to support a format commonly used for JavaScript
  1043. // closures:
  1044. // SomeFunction(function() {
  1045. // foo();
  1046. // bar();
  1047. // }, a, b, c);
  1048. if (Current.isNot(tok::comment) && Previous &&
  1049. Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
  1050. !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
  1051. !State.Stack.back().HasMultipleNestedBlocks) {
  1052. if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
  1053. for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
  1054. State.Stack[i].NoLineBreak = true;
  1055. State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
  1056. }
  1057. if (Previous &&
  1058. (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
  1059. Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
  1060. !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
  1061. State.Stack.back().NestedBlockInlined =
  1062. !Newline &&
  1063. (Previous->isNot(tok::l_paren) || Previous->ParameterCount > 1);
  1064. }
  1065. moveStatePastFakeLParens(State, Newline);
  1066. moveStatePastScopeCloser(State);
  1067. bool AllowBreak = !State.Stack.back().NoLineBreak &&
  1068. !State.Stack.back().NoLineBreakInOperand;
  1069. moveStatePastScopeOpener(State, Newline);
  1070. moveStatePastFakeRParens(State);
  1071. if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
  1072. State.StartOfStringLiteral = State.Column + 1;
  1073. else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
  1074. State.StartOfStringLiteral = State.Column;
  1075. else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
  1076. !Current.isStringLiteral())
  1077. State.StartOfStringLiteral = 0;
  1078. State.Column += Current.ColumnWidth;
  1079. State.NextToken = State.NextToken->Next;
  1080. unsigned Penalty = handleEndOfLine(Current, State, DryRun, AllowBreak);
  1081. if (Current.Role)
  1082. Current.Role->formatFromToken(State, this, DryRun);
  1083. // If the previous has a special role, let it consume tokens as appropriate.
  1084. // It is necessary to start at the previous token for the only implemented
  1085. // role (comma separated list). That way, the decision whether or not to break
  1086. // after the "{" is already done and both options are tried and evaluated.
  1087. // FIXME: This is ugly, find a better way.
  1088. if (Previous && Previous->Role)
  1089. Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
  1090. return Penalty;
  1091. }
  1092. void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
  1093. bool Newline) {
  1094. const FormatToken &Current = *State.NextToken;
  1095. const FormatToken *Previous = Current.getPreviousNonComment();
  1096. // Don't add extra indentation for the first fake parenthesis after
  1097. // 'return', assignments or opening <({[. The indentation for these cases
  1098. // is special cased.
  1099. bool SkipFirstExtraIndent =
  1100. (Previous && (Previous->opensScope() ||
  1101. Previous->isOneOf(tok::semi, tok::kw_return) ||
  1102. (Previous->getPrecedence() == prec::Assignment &&
  1103. Style.AlignOperands) ||
  1104. Previous->is(TT_ObjCMethodExpr)));
  1105. for (SmallVectorImpl<prec::Level>::const_reverse_iterator
  1106. I = Current.FakeLParens.rbegin(),
  1107. E = Current.FakeLParens.rend();
  1108. I != E; ++I) {
  1109. ParenState NewParenState = State.Stack.back();
  1110. NewParenState.Tok = nullptr;
  1111. NewParenState.ContainsLineBreak = false;
  1112. NewParenState.LastOperatorWrapped = true;
  1113. NewParenState.NoLineBreak =
  1114. NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand;
  1115. // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
  1116. if (*I > prec::Comma)
  1117. NewParenState.AvoidBinPacking = false;
  1118. // Indent from 'LastSpace' unless these are fake parentheses encapsulating
  1119. // a builder type call after 'return' or, if the alignment after opening
  1120. // brackets is disabled.
  1121. if (!Current.isTrailingComment() &&
  1122. (Style.AlignOperands || *I < prec::Assignment) &&
  1123. (!Previous || Previous->isNot(tok::kw_return) ||
  1124. (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
  1125. (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
  1126. *I != prec::Comma || Current.NestingLevel == 0))
  1127. NewParenState.Indent =
  1128. std::max(std::max(State.Column, NewParenState.Indent),
  1129. State.Stack.back().LastSpace);
  1130. // Do not indent relative to the fake parentheses inserted for "." or "->".
  1131. // This is a special case to make the following to statements consistent:
  1132. // OuterFunction(InnerFunctionCall( // break
  1133. // ParameterToInnerFunction));
  1134. // OuterFunction(SomeObject.InnerFunctionCall( // break
  1135. // ParameterToInnerFunction));
  1136. if (*I > prec::Unknown)
  1137. NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
  1138. if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) &&
  1139. Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
  1140. NewParenState.StartOfFunctionCall = State.Column;
  1141. // Always indent conditional expressions. Never indent expression where
  1142. // the 'operator' is ',', ';' or an assignment (i.e. *I <=
  1143. // prec::Assignment) as those have different indentation rules. Indent
  1144. // other expression, unless the indentation needs to be skipped.
  1145. if (*I == prec::Conditional ||
  1146. (!SkipFirstExtraIndent && *I > prec::Assignment &&
  1147. !Current.isTrailingComment()))
  1148. NewParenState.Indent += Style.ContinuationIndentWidth;
  1149. if ((Previous && !Previous->opensScope()) || *I != prec::Comma)
  1150. NewParenState.BreakBeforeParameter = false;
  1151. State.Stack.push_back(NewParenState);
  1152. SkipFirstExtraIndent = false;
  1153. }
  1154. }
  1155. void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
  1156. for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
  1157. unsigned VariablePos = State.Stack.back().VariablePos;
  1158. if (State.Stack.size() == 1) {
  1159. // Do not pop the last element.
  1160. break;
  1161. }
  1162. State.Stack.pop_back();
  1163. State.Stack.back().VariablePos = VariablePos;
  1164. }
  1165. }
  1166. void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
  1167. bool Newline) {
  1168. const FormatToken &Current = *State.NextToken;
  1169. if (!Current.opensScope())
  1170. return;
  1171. if (Current.MatchingParen && Current.BlockKind == BK_Block) {
  1172. moveStateToNewBlock(State);
  1173. return;
  1174. }
  1175. unsigned NewIndent;
  1176. unsigned LastSpace = State.Stack.back().LastSpace;
  1177. bool AvoidBinPacking;
  1178. bool BreakBeforeParameter = false;
  1179. unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
  1180. State.Stack.back().NestedBlockIndent);
  1181. if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
  1182. opensProtoMessageField(Current, Style)) {
  1183. if (Current.opensBlockOrBlockTypeList(Style)) {
  1184. NewIndent = Style.IndentWidth +
  1185. std::min(State.Column, State.Stack.back().NestedBlockIndent);
  1186. } else {
  1187. NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
  1188. }
  1189. const FormatToken *NextNoComment = Current.getNextNonComment();
  1190. bool EndsInComma = Current.MatchingParen &&
  1191. Current.MatchingParen->Previous &&
  1192. Current.MatchingParen->Previous->is(tok::comma);
  1193. AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
  1194. Style.Language == FormatStyle::LK_Proto ||
  1195. Style.Language == FormatStyle::LK_TextProto ||
  1196. !Style.BinPackArguments ||
  1197. (NextNoComment &&
  1198. NextNoComment->isOneOf(TT_DesignatedInitializerPeriod,
  1199. TT_DesignatedInitializerLSquare));
  1200. BreakBeforeParameter = EndsInComma;
  1201. if (Current.ParameterCount > 1)
  1202. NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
  1203. } else {
  1204. NewIndent = Style.ContinuationIndentWidth +
  1205. std::max(State.Stack.back().LastSpace,
  1206. State.Stack.back().StartOfFunctionCall);
  1207. // Ensure that different different brackets force relative alignment, e.g.:
  1208. // void SomeFunction(vector< // break
  1209. // int> v);
  1210. // FIXME: We likely want to do this for more combinations of brackets.
  1211. if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
  1212. NewIndent = std::max(NewIndent, State.Stack.back().Indent);
  1213. LastSpace = std::max(LastSpace, State.Stack.back().Indent);
  1214. }
  1215. bool EndsInComma =
  1216. Current.MatchingParen &&
  1217. Current.MatchingParen->getPreviousNonComment() &&
  1218. Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
  1219. // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
  1220. // for backwards compatibility.
  1221. bool ObjCBinPackProtocolList =
  1222. (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
  1223. Style.BinPackParameters) ||
  1224. Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
  1225. bool BinPackDeclaration =
  1226. (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
  1227. (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
  1228. AvoidBinPacking =
  1229. (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) ||
  1230. (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
  1231. (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
  1232. (Style.ExperimentalAutoDetectBinPacking &&
  1233. (Current.PackingKind == PPK_OnePerLine ||
  1234. (!BinPackInconclusiveFunctions &&
  1235. Current.PackingKind == PPK_Inconclusive)));
  1236. if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen) {
  1237. if (Style.ColumnLimit) {
  1238. // If this '[' opens an ObjC call, determine whether all parameters fit
  1239. // into one line and put one per line if they don't.
  1240. if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
  1241. getColumnLimit(State))
  1242. BreakBeforeParameter = true;
  1243. } else {
  1244. // For ColumnLimit = 0, we have to figure out whether there is or has to
  1245. // be a line break within this call.
  1246. for (const FormatToken *Tok = &Current;
  1247. Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
  1248. if (Tok->MustBreakBefore ||
  1249. (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
  1250. BreakBeforeParameter = true;
  1251. break;
  1252. }
  1253. }
  1254. }
  1255. }
  1256. if (Style.Language == FormatStyle::LK_JavaScript && EndsInComma)
  1257. BreakBeforeParameter = true;
  1258. }
  1259. // Generally inherit NoLineBreak from the current scope to nested scope.
  1260. // However, don't do this for non-empty nested blocks, dict literals and
  1261. // array literals as these follow different indentation rules.
  1262. bool NoLineBreak =
  1263. Current.Children.empty() &&
  1264. !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
  1265. (State.Stack.back().NoLineBreak ||
  1266. State.Stack.back().NoLineBreakInOperand ||
  1267. (Current.is(TT_TemplateOpener) &&
  1268. State.Stack.back().ContainsUnwrappedBuilder));
  1269. State.Stack.push_back(
  1270. ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
  1271. State.Stack.back().NestedBlockIndent = NestedBlockIndent;
  1272. State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
  1273. State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
  1274. State.Stack.back().IsInsideObjCArrayLiteral =
  1275. Current.is(TT_ArrayInitializerLSquare) && Current.Previous &&
  1276. Current.Previous->is(tok::at);
  1277. }
  1278. void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
  1279. const FormatToken &Current = *State.NextToken;
  1280. if (!Current.closesScope())
  1281. return;
  1282. // If we encounter a closing ), ], } or >, we can remove a level from our
  1283. // stacks.
  1284. if (State.Stack.size() > 1 &&
  1285. (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
  1286. (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
  1287. State.NextToken->is(TT_TemplateCloser) ||
  1288. (Current.is(tok::greater) && Current.is(TT_DictLiteral))))
  1289. State.Stack.pop_back();
  1290. // Reevaluate whether ObjC message arguments fit into one line.
  1291. // If a receiver spans multiple lines, e.g.:
  1292. // [[object block:^{
  1293. // return 42;
  1294. // }] a:42 b:42];
  1295. // BreakBeforeParameter is calculated based on an incorrect assumption
  1296. // (it is checked whether the whole expression fits into one line without
  1297. // considering a line break inside a message receiver).
  1298. // We check whether arguements fit after receiver scope closer (into the same
  1299. // line).
  1300. if (State.Stack.back().BreakBeforeParameter && Current.MatchingParen &&
  1301. Current.MatchingParen->Previous) {
  1302. const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
  1303. if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
  1304. CurrentScopeOpener.MatchingParen) {
  1305. int NecessarySpaceInLine =
  1306. getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
  1307. CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
  1308. if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
  1309. Style.ColumnLimit)
  1310. State.Stack.back().BreakBeforeParameter = false;
  1311. }
  1312. }
  1313. if (Current.is(tok::r_square)) {
  1314. // If this ends the array subscript expr, reset the corresponding value.
  1315. const FormatToken *NextNonComment = Current.getNextNonComment();
  1316. if (NextNonComment && NextNonComment->isNot(tok::l_square))
  1317. State.Stack.back().StartOfArraySubscripts = 0;
  1318. }
  1319. }
  1320. void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
  1321. unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
  1322. // ObjC block sometimes follow special indentation rules.
  1323. unsigned NewIndent =
  1324. NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
  1325. ? Style.ObjCBlockIndentWidth
  1326. : Style.IndentWidth);
  1327. State.Stack.push_back(ParenState(State.NextToken, NewIndent,
  1328. State.Stack.back().LastSpace,
  1329. /*AvoidBinPacking=*/true,
  1330. /*NoLineBreak=*/false));
  1331. State.Stack.back().NestedBlockIndent = NestedBlockIndent;
  1332. State.Stack.back().BreakBeforeParameter = true;
  1333. }
  1334. static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
  1335. unsigned TabWidth,
  1336. encoding::Encoding Encoding) {
  1337. size_t LastNewlinePos = Text.find_last_of("\n");
  1338. if (LastNewlinePos == StringRef::npos) {
  1339. return StartColumn +
  1340. encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
  1341. } else {
  1342. return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
  1343. /*StartColumn=*/0, TabWidth, Encoding);
  1344. }
  1345. }
  1346. unsigned ContinuationIndenter::reformatRawStringLiteral(
  1347. const FormatToken &Current, LineState &State,
  1348. const FormatStyle &RawStringStyle, bool DryRun) {
  1349. unsigned StartColumn = State.Column - Current.ColumnWidth;
  1350. StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
  1351. StringRef NewDelimiter =
  1352. getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
  1353. if (NewDelimiter.empty() || OldDelimiter.empty())
  1354. NewDelimiter = OldDelimiter;
  1355. // The text of a raw string is between the leading 'R"delimiter(' and the
  1356. // trailing 'delimiter)"'.
  1357. unsigned OldPrefixSize = 3 + OldDelimiter.size();
  1358. unsigned OldSuffixSize = 2 + OldDelimiter.size();
  1359. // We create a virtual text environment which expects a null-terminated
  1360. // string, so we cannot use StringRef.
  1361. std::string RawText =
  1362. Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize);
  1363. if (NewDelimiter != OldDelimiter) {
  1364. // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
  1365. // raw string.
  1366. std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
  1367. if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
  1368. NewDelimiter = OldDelimiter;
  1369. }
  1370. unsigned NewPrefixSize = 3 + NewDelimiter.size();
  1371. unsigned NewSuffixSize = 2 + NewDelimiter.size();
  1372. // The first start column is the column the raw text starts after formatting.
  1373. unsigned FirstStartColumn = StartColumn + NewPrefixSize;
  1374. // The next start column is the intended indentation a line break inside
  1375. // the raw string at level 0. It is determined by the following rules:
  1376. // - if the content starts on newline, it is one level more than the current
  1377. // indent, and
  1378. // - if the content does not start on a newline, it is the first start
  1379. // column.
  1380. // These rules have the advantage that the formatted content both does not
  1381. // violate the rectangle rule and visually flows within the surrounding
  1382. // source.
  1383. bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
  1384. // If this token is the last parameter (checked by looking if it's followed by
  1385. // `)`, the base the indent off the line's nested block indent. Otherwise,
  1386. // base the indent off the arguments indent, so we can achieve:
  1387. // fffffffffff(1, 2, 3, R"pb(
  1388. // key1: 1 #
  1389. // key2: 2)pb");
  1390. //
  1391. // fffffffffff(1, 2, 3,
  1392. // R"pb(
  1393. // key1: 1 #
  1394. // key2: 2
  1395. // )pb",
  1396. // 5);
  1397. unsigned CurrentIndent = (Current.Next && Current.Next->is(tok::r_paren))
  1398. ? State.Stack.back().NestedBlockIndent
  1399. : State.Stack.back().Indent;
  1400. unsigned NextStartColumn = ContentStartsOnNewline
  1401. ? CurrentIndent + Style.IndentWidth
  1402. : FirstStartColumn;
  1403. // The last start column is the column the raw string suffix starts if it is
  1404. // put on a newline.
  1405. // The last start column is the intended indentation of the raw string postfix
  1406. // if it is put on a newline. It is determined by the following rules:
  1407. // - if the raw string prefix starts on a newline, it is the column where
  1408. // that raw string prefix starts, and
  1409. // - if the raw string prefix does not start on a newline, it is the current
  1410. // indent.
  1411. unsigned LastStartColumn =
  1412. Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
  1413. std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
  1414. RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
  1415. FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
  1416. /*Status=*/nullptr);
  1417. auto NewCode = applyAllReplacements(RawText, Fixes.first);
  1418. tooling::Replacements NoFixes;
  1419. if (!NewCode) {
  1420. return addMultilineToken(Current, State);
  1421. }
  1422. if (!DryRun) {
  1423. if (NewDelimiter != OldDelimiter) {
  1424. // In 'R"delimiter(...', the delimiter starts 2 characters after the start
  1425. // of the token.
  1426. SourceLocation PrefixDelimiterStart =
  1427. Current.Tok.getLocation().getLocWithOffset(2);
  1428. auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
  1429. SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
  1430. if (PrefixErr) {
  1431. llvm::errs()
  1432. << "Failed to update the prefix delimiter of a raw string: "
  1433. << llvm::toString(std::move(PrefixErr)) << "\n";
  1434. }
  1435. // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
  1436. // position length - 1 - |delimiter|.
  1437. SourceLocation SuffixDelimiterStart =
  1438. Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
  1439. 1 - OldDelimiter.size());
  1440. auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
  1441. SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
  1442. if (SuffixErr) {
  1443. llvm::errs()
  1444. << "Failed to update the suffix delimiter of a raw string: "
  1445. << llvm::toString(std::move(SuffixErr)) << "\n";
  1446. }
  1447. }
  1448. SourceLocation OriginLoc =
  1449. Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
  1450. for (const tooling::Replacement &Fix : Fixes.first) {
  1451. auto Err = Whitespaces.addReplacement(tooling::Replacement(
  1452. SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
  1453. Fix.getLength(), Fix.getReplacementText()));
  1454. if (Err) {
  1455. llvm::errs() << "Failed to reformat raw string: "
  1456. << llvm::toString(std::move(Err)) << "\n";
  1457. }
  1458. }
  1459. }
  1460. unsigned RawLastLineEndColumn = getLastLineEndColumn(
  1461. *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
  1462. State.Column = RawLastLineEndColumn + NewSuffixSize;
  1463. // Since we're updating the column to after the raw string literal here, we
  1464. // have to manually add the penalty for the prefix R"delim( over the column
  1465. // limit.
  1466. unsigned PrefixExcessCharacters =
  1467. StartColumn + NewPrefixSize > Style.ColumnLimit
  1468. ? StartColumn + NewPrefixSize - Style.ColumnLimit
  1469. : 0;
  1470. bool IsMultiline =
  1471. ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
  1472. if (IsMultiline) {
  1473. // Break before further function parameters on all levels.
  1474. for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
  1475. State.Stack[i].BreakBeforeParameter = true;
  1476. }
  1477. return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
  1478. }
  1479. unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
  1480. LineState &State) {
  1481. // Break before further function parameters on all levels.
  1482. for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
  1483. State.Stack[i].BreakBeforeParameter = true;
  1484. unsigned ColumnsUsed = State.Column;
  1485. // We can only affect layout of the first and the last line, so the penalty
  1486. // for all other lines is constant, and we ignore it.
  1487. State.Column = Current.LastLineColumnWidth;
  1488. if (ColumnsUsed > getColumnLimit(State))
  1489. return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
  1490. return 0;
  1491. }
  1492. unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
  1493. LineState &State, bool DryRun,
  1494. bool AllowBreak) {
  1495. unsigned Penalty = 0;
  1496. // Compute the raw string style to use in case this is a raw string literal
  1497. // that can be reformatted.
  1498. auto RawStringStyle = getRawStringStyle(Current, State);
  1499. if (RawStringStyle && !Current.Finalized) {
  1500. Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun);
  1501. } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
  1502. // Don't break multi-line tokens other than block comments and raw string
  1503. // literals. Instead, just update the state.
  1504. Penalty = addMultilineToken(Current, State);
  1505. } else if (State.Line->Type != LT_ImportStatement) {
  1506. // We generally don't break import statements.
  1507. LineState OriginalState = State;
  1508. // Whether we force the reflowing algorithm to stay strictly within the
  1509. // column limit.
  1510. bool Strict = false;
  1511. // Whether the first non-strict attempt at reflowing did intentionally
  1512. // exceed the column limit.
  1513. bool Exceeded = false;
  1514. std::tie(Penalty, Exceeded) = breakProtrudingToken(
  1515. Current, State, AllowBreak, /*DryRun=*/true, Strict);
  1516. if (Exceeded) {
  1517. // If non-strict reflowing exceeds the column limit, try whether strict
  1518. // reflowing leads to an overall lower penalty.
  1519. LineState StrictState = OriginalState;
  1520. unsigned StrictPenalty =
  1521. breakProtrudingToken(Current, StrictState, AllowBreak,
  1522. /*DryRun=*/true, /*Strict=*/true)
  1523. .first;
  1524. Strict = StrictPenalty <= Penalty;
  1525. if (Strict) {
  1526. Penalty = StrictPenalty;
  1527. State = StrictState;
  1528. }
  1529. }
  1530. if (!DryRun) {
  1531. // If we're not in dry-run mode, apply the changes with the decision on
  1532. // strictness made above.
  1533. breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
  1534. Strict);
  1535. }
  1536. }
  1537. if (State.Column > getColumnLimit(State)) {
  1538. unsigned ExcessCharacters = State.Column - getColumnLimit(State);
  1539. Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
  1540. }
  1541. return Penalty;
  1542. }
  1543. // Returns the enclosing function name of a token, or the empty string if not
  1544. // found.
  1545. static StringRef getEnclosingFunctionName(const FormatToken &Current) {
  1546. // Look for: 'function(' or 'function<templates>(' before Current.
  1547. auto Tok = Current.getPreviousNonComment();
  1548. if (!Tok || !Tok->is(tok::l_paren))
  1549. return "";
  1550. Tok = Tok->getPreviousNonComment();
  1551. if (!Tok)
  1552. return "";
  1553. if (Tok->is(TT_TemplateCloser)) {
  1554. Tok = Tok->MatchingParen;
  1555. if (Tok)
  1556. Tok = Tok->getPreviousNonComment();
  1557. }
  1558. if (!Tok || !Tok->is(tok::identifier))
  1559. return "";
  1560. return Tok->TokenText;
  1561. }
  1562. llvm::Optional<FormatStyle>
  1563. ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
  1564. const LineState &State) {
  1565. if (!Current.isStringLiteral())
  1566. return None;
  1567. auto Delimiter = getRawStringDelimiter(Current.TokenText);
  1568. if (!Delimiter)
  1569. return None;
  1570. auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
  1571. if (!RawStringStyle && Delimiter->empty())
  1572. RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
  1573. getEnclosingFunctionName(Current));
  1574. if (!RawStringStyle)
  1575. return None;
  1576. RawStringStyle->ColumnLimit = getColumnLimit(State);
  1577. return RawStringStyle;
  1578. }
  1579. std::unique_ptr<BreakableToken>
  1580. ContinuationIndenter::createBreakableToken(const FormatToken &Current,
  1581. LineState &State, bool AllowBreak) {
  1582. unsigned StartColumn = State.Column - Current.ColumnWidth;
  1583. if (Current.isStringLiteral()) {
  1584. // FIXME: String literal breaking is currently disabled for Java and JS, as
  1585. // it requires strings to be merged using "+" which we don't support.
  1586. if (Style.Language == FormatStyle::LK_Java ||
  1587. Style.Language == FormatStyle::LK_JavaScript ||
  1588. !Style.BreakStringLiterals || !AllowBreak)
  1589. return nullptr;
  1590. // Don't break string literals inside preprocessor directives (except for
  1591. // #define directives, as their contents are stored in separate lines and
  1592. // are not affected by this check).
  1593. // This way we avoid breaking code with line directives and unknown
  1594. // preprocessor directives that contain long string literals.
  1595. if (State.Line->Type == LT_PreprocessorDirective)
  1596. return nullptr;
  1597. // Exempts unterminated string literals from line breaking. The user will
  1598. // likely want to terminate the string before any line breaking is done.
  1599. if (Current.IsUnterminatedLiteral)
  1600. return nullptr;
  1601. // Don't break string literals inside Objective-C array literals (doing so
  1602. // raises the warning -Wobjc-string-concatenation).
  1603. if (State.Stack.back().IsInsideObjCArrayLiteral) {
  1604. return nullptr;
  1605. }
  1606. StringRef Text = Current.TokenText;
  1607. StringRef Prefix;
  1608. StringRef Postfix;
  1609. // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
  1610. // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
  1611. // reduce the overhead) for each FormatToken, which is a string, so that we
  1612. // don't run multiple checks here on the hot path.
  1613. if ((Text.endswith(Postfix = "\"") &&
  1614. (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
  1615. Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
  1616. Text.startswith(Prefix = "u8\"") ||
  1617. Text.startswith(Prefix = "L\""))) ||
  1618. (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
  1619. // We need this to address the case where there is an unbreakable tail
  1620. // only if certain other formatting decisions have been taken. The
  1621. // UnbreakableTailLength of Current is an overapproximation is that case
  1622. // and we need to be correct here.
  1623. unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
  1624. ? 0
  1625. : Current.UnbreakableTailLength;
  1626. return llvm::make_unique<BreakableStringLiteral>(
  1627. Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
  1628. State.Line->InPPDirective, Encoding, Style);
  1629. }
  1630. } else if (Current.is(TT_BlockComment)) {
  1631. if (!Style.ReflowComments ||
  1632. // If a comment token switches formatting, like
  1633. // /* clang-format on */, we don't want to break it further,
  1634. // but we may still want to adjust its indentation.
  1635. switchesFormatting(Current)) {
  1636. return nullptr;
  1637. }
  1638. return llvm::make_unique<BreakableBlockComment>(
  1639. Current, StartColumn, Current.OriginalColumn, !Current.Previous,
  1640. State.Line->InPPDirective, Encoding, Style);
  1641. } else if (Current.is(TT_LineComment) &&
  1642. (Current.Previous == nullptr ||
  1643. Current.Previous->isNot(TT_ImplicitStringLiteral))) {
  1644. if (!Style.ReflowComments ||
  1645. CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
  1646. switchesFormatting(Current))
  1647. return nullptr;
  1648. return llvm::make_unique<BreakableLineCommentSection>(
  1649. Current, StartColumn, Current.OriginalColumn, !Current.Previous,
  1650. /*InPPDirective=*/false, Encoding, Style);
  1651. }
  1652. return nullptr;
  1653. }
  1654. std::pair<unsigned, bool>
  1655. ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
  1656. LineState &State, bool AllowBreak,
  1657. bool DryRun, bool Strict) {
  1658. std::unique_ptr<const BreakableToken> Token =
  1659. createBreakableToken(Current, State, AllowBreak);
  1660. if (!Token)
  1661. return {0, false};
  1662. assert(Token->getLineCount() > 0);
  1663. unsigned ColumnLimit = getColumnLimit(State);
  1664. if (Current.is(TT_LineComment)) {
  1665. // We don't insert backslashes when breaking line comments.
  1666. ColumnLimit = Style.ColumnLimit;
  1667. }
  1668. if (Current.UnbreakableTailLength >= ColumnLimit)
  1669. return {0, false};
  1670. // ColumnWidth was already accounted into State.Column before calling
  1671. // breakProtrudingToken.
  1672. unsigned StartColumn = State.Column - Current.ColumnWidth;
  1673. unsigned NewBreakPenalty = Current.isStringLiteral()
  1674. ? Style.PenaltyBreakString
  1675. : Style.PenaltyBreakComment;
  1676. // Stores whether we intentionally decide to let a line exceed the column
  1677. // limit.
  1678. bool Exceeded = false;
  1679. // Stores whether we introduce a break anywhere in the token.
  1680. bool BreakInserted = Token->introducesBreakBeforeToken();
  1681. // Store whether we inserted a new line break at the end of the previous
  1682. // logical line.
  1683. bool NewBreakBefore = false;
  1684. // We use a conservative reflowing strategy. Reflow starts after a line is
  1685. // broken or the corresponding whitespace compressed. Reflow ends as soon as a
  1686. // line that doesn't get reflown with the previous line is reached.
  1687. bool Reflow = false;
  1688. // Keep track of where we are in the token:
  1689. // Where we are in the content of the current logical line.
  1690. unsigned TailOffset = 0;
  1691. // The column number we're currently at.
  1692. unsigned ContentStartColumn =
  1693. Token->getContentStartColumn(0, /*Break=*/false);
  1694. // The number of columns left in the current logical line after TailOffset.
  1695. unsigned RemainingTokenColumns =
  1696. Token->getRemainingLength(0, TailOffset, ContentStartColumn);
  1697. // Adapt the start of the token, for example indent.
  1698. if (!DryRun)
  1699. Token->adaptStartOfLine(0, Whitespaces);
  1700. unsigned ContentIndent = 0;
  1701. unsigned Penalty = 0;
  1702. LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
  1703. << StartColumn << ".\n");
  1704. for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
  1705. LineIndex != EndIndex; ++LineIndex) {
  1706. LLVM_DEBUG(llvm::dbgs()
  1707. << " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
  1708. NewBreakBefore = false;
  1709. // If we did reflow the previous line, we'll try reflowing again. Otherwise
  1710. // we'll start reflowing if the current line is broken or whitespace is
  1711. // compressed.
  1712. bool TryReflow = Reflow;
  1713. // Break the current token until we can fit the rest of the line.
  1714. while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
  1715. LLVM_DEBUG(llvm::dbgs() << " Over limit, need: "
  1716. << (ContentStartColumn + RemainingTokenColumns)
  1717. << ", space: " << ColumnLimit
  1718. << ", reflown prefix: " << ContentStartColumn
  1719. << ", offset in line: " << TailOffset << "\n");
  1720. // If the current token doesn't fit, find the latest possible split in the
  1721. // current line so that breaking at it will be under the column limit.
  1722. // FIXME: Use the earliest possible split while reflowing to correctly
  1723. // compress whitespace within a line.
  1724. BreakableToken::Split Split =
  1725. Token->getSplit(LineIndex, TailOffset, ColumnLimit,
  1726. ContentStartColumn, CommentPragmasRegex);
  1727. if (Split.first == StringRef::npos) {
  1728. // No break opportunity - update the penalty and continue with the next
  1729. // logical line.
  1730. if (LineIndex < EndIndex - 1)
  1731. // The last line's penalty is handled in addNextStateToQueue() or when
  1732. // calling replaceWhitespaceAfterLastLine below.
  1733. Penalty += Style.PenaltyExcessCharacter *
  1734. (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
  1735. LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n");
  1736. break;
  1737. }
  1738. assert(Split.first != 0);
  1739. if (Token->supportsReflow()) {
  1740. // Check whether the next natural split point after the current one can
  1741. // still fit the line, either because we can compress away whitespace,
  1742. // or because the penalty the excess characters introduce is lower than
  1743. // the break penalty.
  1744. // We only do this for tokens that support reflowing, and thus allow us
  1745. // to change the whitespace arbitrarily (e.g. comments).
  1746. // Other tokens, like string literals, can be broken on arbitrary
  1747. // positions.
  1748. // First, compute the columns from TailOffset to the next possible split
  1749. // position.
  1750. // For example:
  1751. // ColumnLimit: |
  1752. // // Some text that breaks
  1753. // ^ tail offset
  1754. // ^-- split
  1755. // ^-------- to split columns
  1756. // ^--- next split
  1757. // ^--------------- to next split columns
  1758. unsigned ToSplitColumns = Token->getRangeLength(
  1759. LineIndex, TailOffset, Split.first, ContentStartColumn);
  1760. LLVM_DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n");
  1761. BreakableToken::Split NextSplit = Token->getSplit(
  1762. LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
  1763. ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
  1764. // Compute the columns necessary to fit the next non-breakable sequence
  1765. // into the current line.
  1766. unsigned ToNextSplitColumns = 0;
  1767. if (NextSplit.first == StringRef::npos) {
  1768. ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
  1769. ContentStartColumn);
  1770. } else {
  1771. ToNextSplitColumns = Token->getRangeLength(
  1772. LineIndex, TailOffset,
  1773. Split.first + Split.second + NextSplit.first, ContentStartColumn);
  1774. }
  1775. // Compress the whitespace between the break and the start of the next
  1776. // unbreakable sequence.
  1777. ToNextSplitColumns =
  1778. Token->getLengthAfterCompression(ToNextSplitColumns, Split);
  1779. LLVM_DEBUG(llvm::dbgs()
  1780. << " ContentStartColumn: " << ContentStartColumn << "\n");
  1781. LLVM_DEBUG(llvm::dbgs()
  1782. << " ToNextSplit: " << ToNextSplitColumns << "\n");
  1783. // If the whitespace compression makes us fit, continue on the current
  1784. // line.
  1785. bool ContinueOnLine =
  1786. ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
  1787. unsigned ExcessCharactersPenalty = 0;
  1788. if (!ContinueOnLine && !Strict) {
  1789. // Similarly, if the excess characters' penalty is lower than the
  1790. // penalty of introducing a new break, continue on the current line.
  1791. ExcessCharactersPenalty =
  1792. (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
  1793. Style.PenaltyExcessCharacter;
  1794. LLVM_DEBUG(llvm::dbgs()
  1795. << " Penalty excess: " << ExcessCharactersPenalty
  1796. << "\n break : " << NewBreakPenalty << "\n");
  1797. if (ExcessCharactersPenalty < NewBreakPenalty) {
  1798. Exceeded = true;
  1799. ContinueOnLine = true;
  1800. }
  1801. }
  1802. if (ContinueOnLine) {
  1803. LLVM_DEBUG(llvm::dbgs() << " Continuing on line...\n");
  1804. // The current line fits after compressing the whitespace - reflow
  1805. // the next line into it if possible.
  1806. TryReflow = true;
  1807. if (!DryRun)
  1808. Token->compressWhitespace(LineIndex, TailOffset, Split,
  1809. Whitespaces);
  1810. // When we continue on the same line, leave one space between content.
  1811. ContentStartColumn += ToSplitColumns + 1;
  1812. Penalty += ExcessCharactersPenalty;
  1813. TailOffset += Split.first + Split.second;
  1814. RemainingTokenColumns = Token->getRemainingLength(
  1815. LineIndex, TailOffset, ContentStartColumn);
  1816. continue;
  1817. }
  1818. }
  1819. LLVM_DEBUG(llvm::dbgs() << " Breaking...\n");
  1820. // Update the ContentIndent only if the current line was not reflown with
  1821. // the previous line, since in that case the previous line should still
  1822. // determine the ContentIndent. Also never intent the last line.
  1823. if (!Reflow)
  1824. ContentIndent = Token->getContentIndent(LineIndex);
  1825. LLVM_DEBUG(llvm::dbgs()
  1826. << " ContentIndent: " << ContentIndent << "\n");
  1827. ContentStartColumn = ContentIndent + Token->getContentStartColumn(
  1828. LineIndex, /*Break=*/true);
  1829. unsigned NewRemainingTokenColumns = Token->getRemainingLength(
  1830. LineIndex, TailOffset + Split.first + Split.second,
  1831. ContentStartColumn);
  1832. if (NewRemainingTokenColumns == 0) {
  1833. // No content to indent.
  1834. ContentIndent = 0;
  1835. ContentStartColumn =
  1836. Token->getContentStartColumn(LineIndex, /*Break=*/true);
  1837. NewRemainingTokenColumns = Token->getRemainingLength(
  1838. LineIndex, TailOffset + Split.first + Split.second,
  1839. ContentStartColumn);
  1840. }
  1841. // When breaking before a tab character, it may be moved by a few columns,
  1842. // but will still be expanded to the next tab stop, so we don't save any
  1843. // columns.
  1844. if (NewRemainingTokenColumns == RemainingTokenColumns) {
  1845. // FIXME: Do we need to adjust the penalty?
  1846. break;
  1847. }
  1848. assert(NewRemainingTokenColumns < RemainingTokenColumns);
  1849. LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first
  1850. << ", " << Split.second << "\n");
  1851. if (!DryRun)
  1852. Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
  1853. Whitespaces);
  1854. Penalty += NewBreakPenalty;
  1855. TailOffset += Split.first + Split.second;
  1856. RemainingTokenColumns = NewRemainingTokenColumns;
  1857. BreakInserted = true;
  1858. NewBreakBefore = true;
  1859. }
  1860. // In case there's another line, prepare the state for the start of the next
  1861. // line.
  1862. if (LineIndex + 1 != EndIndex) {
  1863. unsigned NextLineIndex = LineIndex + 1;
  1864. if (NewBreakBefore)
  1865. // After breaking a line, try to reflow the next line into the current
  1866. // one once RemainingTokenColumns fits.
  1867. TryReflow = true;
  1868. if (TryReflow) {
  1869. // We decided that we want to try reflowing the next line into the
  1870. // current one.
  1871. // We will now adjust the state as if the reflow is successful (in
  1872. // preparation for the next line), and see whether that works. If we
  1873. // decide that we cannot reflow, we will later reset the state to the
  1874. // start of the next line.
  1875. Reflow = false;
  1876. // As we did not continue breaking the line, RemainingTokenColumns is
  1877. // known to fit after ContentStartColumn. Adapt ContentStartColumn to
  1878. // the position at which we want to format the next line if we do
  1879. // actually reflow.
  1880. // When we reflow, we need to add a space between the end of the current
  1881. // line and the next line's start column.
  1882. ContentStartColumn += RemainingTokenColumns + 1;
  1883. // Get the split that we need to reflow next logical line into the end
  1884. // of the current one; the split will include any leading whitespace of
  1885. // the next logical line.
  1886. BreakableToken::Split SplitBeforeNext =
  1887. Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
  1888. LLVM_DEBUG(llvm::dbgs()
  1889. << " Size of reflown text: " << ContentStartColumn
  1890. << "\n Potential reflow split: ");
  1891. if (SplitBeforeNext.first != StringRef::npos) {
  1892. LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
  1893. << SplitBeforeNext.second << "\n");
  1894. TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
  1895. // If the rest of the next line fits into the current line below the
  1896. // column limit, we can safely reflow.
  1897. RemainingTokenColumns = Token->getRemainingLength(
  1898. NextLineIndex, TailOffset, ContentStartColumn);
  1899. Reflow = true;
  1900. if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
  1901. LLVM_DEBUG(llvm::dbgs()
  1902. << " Over limit after reflow, need: "
  1903. << (ContentStartColumn + RemainingTokenColumns)
  1904. << ", space: " << ColumnLimit
  1905. << ", reflown prefix: " << ContentStartColumn
  1906. << ", offset in line: " << TailOffset << "\n");
  1907. // If the whole next line does not fit, try to find a point in
  1908. // the next line at which we can break so that attaching the part
  1909. // of the next line to that break point onto the current line is
  1910. // below the column limit.
  1911. BreakableToken::Split Split =
  1912. Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
  1913. ContentStartColumn, CommentPragmasRegex);
  1914. if (Split.first == StringRef::npos) {
  1915. LLVM_DEBUG(llvm::dbgs() << " Did not find later break\n");
  1916. Reflow = false;
  1917. } else {
  1918. // Check whether the first split point gets us below the column
  1919. // limit. Note that we will execute this split below as part of
  1920. // the normal token breaking and reflow logic within the line.
  1921. unsigned ToSplitColumns = Token->getRangeLength(
  1922. NextLineIndex, TailOffset, Split.first, ContentStartColumn);
  1923. if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
  1924. LLVM_DEBUG(llvm::dbgs() << " Next split protrudes, need: "
  1925. << (ContentStartColumn + ToSplitColumns)
  1926. << ", space: " << ColumnLimit);
  1927. unsigned ExcessCharactersPenalty =
  1928. (ContentStartColumn + ToSplitColumns - ColumnLimit) *
  1929. Style.PenaltyExcessCharacter;
  1930. if (NewBreakPenalty < ExcessCharactersPenalty) {
  1931. Reflow = false;
  1932. }
  1933. }
  1934. }
  1935. }
  1936. } else {
  1937. LLVM_DEBUG(llvm::dbgs() << "not found.\n");
  1938. }
  1939. }
  1940. if (!Reflow) {
  1941. // If we didn't reflow into the next line, the only space to consider is
  1942. // the next logical line. Reset our state to match the start of the next
  1943. // line.
  1944. TailOffset = 0;
  1945. ContentStartColumn =
  1946. Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
  1947. RemainingTokenColumns = Token->getRemainingLength(
  1948. NextLineIndex, TailOffset, ContentStartColumn);
  1949. // Adapt the start of the token, for example indent.
  1950. if (!DryRun)
  1951. Token->adaptStartOfLine(NextLineIndex, Whitespaces);
  1952. } else {
  1953. // If we found a reflow split and have added a new break before the next
  1954. // line, we are going to remove the line break at the start of the next
  1955. // logical line. For example, here we'll add a new line break after
  1956. // 'text', and subsequently delete the line break between 'that' and
  1957. // 'reflows'.
  1958. // // some text that
  1959. // // reflows
  1960. // ->
  1961. // // some text
  1962. // // that reflows
  1963. // When adding the line break, we also added the penalty for it, so we
  1964. // need to subtract that penalty again when we remove the line break due
  1965. // to reflowing.
  1966. if (NewBreakBefore) {
  1967. assert(Penalty >= NewBreakPenalty);
  1968. Penalty -= NewBreakPenalty;
  1969. }
  1970. if (!DryRun)
  1971. Token->reflow(NextLineIndex, Whitespaces);
  1972. }
  1973. }
  1974. }
  1975. BreakableToken::Split SplitAfterLastLine =
  1976. Token->getSplitAfterLastLine(TailOffset);
  1977. if (SplitAfterLastLine.first != StringRef::npos) {
  1978. LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
  1979. // We add the last line's penalty here, since that line is going to be split
  1980. // now.
  1981. Penalty += Style.PenaltyExcessCharacter *
  1982. (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
  1983. if (!DryRun)
  1984. Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
  1985. Whitespaces);
  1986. ContentStartColumn =
  1987. Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
  1988. RemainingTokenColumns = Token->getRemainingLength(
  1989. Token->getLineCount() - 1,
  1990. TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
  1991. ContentStartColumn);
  1992. }
  1993. State.Column = ContentStartColumn + RemainingTokenColumns -
  1994. Current.UnbreakableTailLength;
  1995. if (BreakInserted) {
  1996. // If we break the token inside a parameter list, we need to break before
  1997. // the next parameter on all levels, so that the next parameter is clearly
  1998. // visible. Line comments already introduce a break.
  1999. if (Current.isNot(TT_LineComment)) {
  2000. for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
  2001. State.Stack[i].BreakBeforeParameter = true;
  2002. }
  2003. if (Current.is(TT_BlockComment))
  2004. State.NoContinuation = true;
  2005. State.Stack.back().LastSpace = StartColumn;
  2006. }
  2007. Token->updateNextToken(State);
  2008. return {Penalty, Exceeded};
  2009. }
  2010. unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
  2011. // In preprocessor directives reserve two chars for trailing " \"
  2012. return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
  2013. }
  2014. bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
  2015. const FormatToken &Current = *State.NextToken;
  2016. if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
  2017. return false;
  2018. // We never consider raw string literals "multiline" for the purpose of
  2019. // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
  2020. // (see TokenAnnotator::mustBreakBefore().
  2021. if (Current.TokenText.startswith("R\""))
  2022. return false;
  2023. if (Current.IsMultiline)
  2024. return true;
  2025. if (Current.getNextNonComment() &&
  2026. Current.getNextNonComment()->isStringLiteral())
  2027. return true; // Implicit concatenation.
  2028. if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
  2029. State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
  2030. Style.ColumnLimit)
  2031. return true; // String will be split.
  2032. return false;
  2033. }
  2034. } // namespace format
  2035. } // namespace clang