ContinuationIndenter.cpp 94 KB

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