ContinuationIndenter.cpp 113 KB

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