ContinuationIndenter.cpp 100 KB

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