ContinuationIndenter.cpp 83 KB

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