ContinuationIndenter.cpp 99 KB

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