File: | clang/lib/Format/ContinuationIndenter.cpp |
Warning: | line 595, column 9 Access to field 'PartOfMultiVariableDeclStmt' results in a dereference of a null pointer (loaded from variable 'Previous') |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- ContinuationIndenter.cpp - Format C++ code -----------------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | /// | |||
9 | /// \file | |||
10 | /// This file implements the continuation indenter. | |||
11 | /// | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "ContinuationIndenter.h" | |||
15 | #include "BreakableToken.h" | |||
16 | #include "FormatInternal.h" | |||
17 | #include "FormatToken.h" | |||
18 | #include "WhitespaceManager.h" | |||
19 | #include "clang/Basic/OperatorPrecedence.h" | |||
20 | #include "clang/Basic/SourceManager.h" | |||
21 | #include "clang/Format/Format.h" | |||
22 | #include "llvm/ADT/StringSet.h" | |||
23 | #include "llvm/Support/Debug.h" | |||
24 | ||||
25 | #define DEBUG_TYPE"format-indenter" "format-indenter" | |||
26 | ||||
27 | namespace clang { | |||
28 | namespace format { | |||
29 | ||||
30 | // Returns true if a TT_SelectorName should be indented when wrapped, | |||
31 | // false otherwise. | |||
32 | static bool shouldIndentWrappedSelectorName(const FormatStyle &Style, | |||
33 | LineType LineType) { | |||
34 | return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl; | |||
35 | } | |||
36 | ||||
37 | // Returns the length of everything up to the first possible line break after | |||
38 | // the ), ], } or > matching \c Tok. | |||
39 | static unsigned getLengthToMatchingParen(const FormatToken &Tok, | |||
40 | const std::vector<ParenState> &Stack) { | |||
41 | // Normally whether or not a break before T is possible is calculated and | |||
42 | // stored in T.CanBreakBefore. Braces, array initializers and text proto | |||
43 | // messages like `key: < ... >` are an exception: a break is possible | |||
44 | // before a closing brace R if a break was inserted after the corresponding | |||
45 | // opening brace. The information about whether or not a break is needed | |||
46 | // before a closing brace R is stored in the ParenState field | |||
47 | // S.BreakBeforeClosingBrace where S is the state that R closes. | |||
48 | // | |||
49 | // In order to decide whether there can be a break before encountered right | |||
50 | // braces, this implementation iterates over the sequence of tokens and over | |||
51 | // the paren stack in lockstep, keeping track of the stack level which visited | |||
52 | // right braces correspond to in MatchingStackIndex. | |||
53 | // | |||
54 | // For example, consider: | |||
55 | // L. <- line number | |||
56 | // 1. { | |||
57 | // 2. {1}, | |||
58 | // 3. {2}, | |||
59 | // 4. {{3}}} | |||
60 | // ^ where we call this method with this token. | |||
61 | // The paren stack at this point contains 3 brace levels: | |||
62 | // 0. { at line 1, BreakBeforeClosingBrace: true | |||
63 | // 1. first { at line 4, BreakBeforeClosingBrace: false | |||
64 | // 2. second { at line 4, BreakBeforeClosingBrace: false, | |||
65 | // where there might be fake parens levels in-between these levels. | |||
66 | // The algorithm will start at the first } on line 4, which is the matching | |||
67 | // brace of the initial left brace and at level 2 of the stack. Then, | |||
68 | // examining BreakBeforeClosingBrace: false at level 2, it will continue to | |||
69 | // the second } on line 4, and will traverse the stack downwards until it | |||
70 | // finds the matching { on level 1. Then, examining BreakBeforeClosingBrace: | |||
71 | // false at level 1, it will continue to the third } on line 4 and will | |||
72 | // traverse the stack downwards until it finds the matching { on level 0. | |||
73 | // Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm | |||
74 | // will stop and will use the second } on line 4 to determine the length to | |||
75 | // return, as in this example the range will include the tokens: {3}} | |||
76 | // | |||
77 | // The algorithm will only traverse the stack if it encounters braces, array | |||
78 | // initializer squares or text proto angle brackets. | |||
79 | if (!Tok.MatchingParen) | |||
80 | return 0; | |||
81 | FormatToken *End = Tok.MatchingParen; | |||
82 | // Maintains a stack level corresponding to the current End token. | |||
83 | int MatchingStackIndex = Stack.size() - 1; | |||
84 | // Traverses the stack downwards, looking for the level to which LBrace | |||
85 | // corresponds. Returns either a pointer to the matching level or nullptr if | |||
86 | // LParen is not found in the initial portion of the stack up to | |||
87 | // MatchingStackIndex. | |||
88 | auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * { | |||
89 | while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace) | |||
90 | --MatchingStackIndex; | |||
91 | return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr; | |||
92 | }; | |||
93 | for (; End->Next; End = End->Next) { | |||
94 | if (End->Next->CanBreakBefore) | |||
95 | break; | |||
96 | if (!End->Next->closesScope()) | |||
97 | continue; | |||
98 | if (End->Next->MatchingParen && | |||
99 | End->Next->MatchingParen->isOneOf( | |||
100 | tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) { | |||
101 | const ParenState *State = FindParenState(End->Next->MatchingParen); | |||
102 | if (State && State->BreakBeforeClosingBrace) | |||
103 | break; | |||
104 | } | |||
105 | } | |||
106 | return End->TotalLength - Tok.TotalLength + 1; | |||
107 | } | |||
108 | ||||
109 | static unsigned getLengthToNextOperator(const FormatToken &Tok) { | |||
110 | if (!Tok.NextOperator) | |||
111 | return 0; | |||
112 | return Tok.NextOperator->TotalLength - Tok.TotalLength; | |||
113 | } | |||
114 | ||||
115 | // Returns \c true if \c Tok is the "." or "->" of a call and starts the next | |||
116 | // segment of a builder type call. | |||
117 | static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) { | |||
118 | return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope(); | |||
119 | } | |||
120 | ||||
121 | // Returns \c true if \c Current starts a new parameter. | |||
122 | static bool startsNextParameter(const FormatToken &Current, | |||
123 | const FormatStyle &Style) { | |||
124 | const FormatToken &Previous = *Current.Previous; | |||
125 | if (Current.is(TT_CtorInitializerComma) && | |||
126 | Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) | |||
127 | return true; | |||
128 | if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName)) | |||
129 | return true; | |||
130 | return Previous.is(tok::comma) && !Current.isTrailingComment() && | |||
131 | ((Previous.isNot(TT_CtorInitializerComma) || | |||
132 | Style.BreakConstructorInitializers != | |||
133 | FormatStyle::BCIS_BeforeComma) && | |||
134 | (Previous.isNot(TT_InheritanceComma) || | |||
135 | Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma)); | |||
136 | } | |||
137 | ||||
138 | static bool opensProtoMessageField(const FormatToken &LessTok, | |||
139 | const FormatStyle &Style) { | |||
140 | if (LessTok.isNot(tok::less)) | |||
141 | return false; | |||
142 | return Style.Language == FormatStyle::LK_TextProto || | |||
143 | (Style.Language == FormatStyle::LK_Proto && | |||
144 | (LessTok.NestingLevel > 0 || | |||
145 | (LessTok.Previous && LessTok.Previous->is(tok::equal)))); | |||
146 | } | |||
147 | ||||
148 | // Returns the delimiter of a raw string literal, or None if TokenText is not | |||
149 | // the text of a raw string literal. The delimiter could be the empty string. | |||
150 | // For example, the delimiter of R"deli(cont)deli" is deli. | |||
151 | static llvm::Optional<StringRef> getRawStringDelimiter(StringRef TokenText) { | |||
152 | if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'. | |||
153 | || !TokenText.startswith("R\"") || !TokenText.endswith("\"")) | |||
154 | return None; | |||
155 | ||||
156 | // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has | |||
157 | // size at most 16 by the standard, so the first '(' must be among the first | |||
158 | // 19 bytes. | |||
159 | size_t LParenPos = TokenText.substr(0, 19).find_first_of('('); | |||
160 | if (LParenPos == StringRef::npos) | |||
161 | return None; | |||
162 | StringRef Delimiter = TokenText.substr(2, LParenPos - 2); | |||
163 | ||||
164 | // Check that the string ends in ')Delimiter"'. | |||
165 | size_t RParenPos = TokenText.size() - Delimiter.size() - 2; | |||
166 | if (TokenText[RParenPos] != ')') | |||
167 | return None; | |||
168 | if (!TokenText.substr(RParenPos + 1).startswith(Delimiter)) | |||
169 | return None; | |||
170 | return Delimiter; | |||
171 | } | |||
172 | ||||
173 | // Returns the canonical delimiter for \p Language, or the empty string if no | |||
174 | // canonical delimiter is specified. | |||
175 | static StringRef | |||
176 | getCanonicalRawStringDelimiter(const FormatStyle &Style, | |||
177 | FormatStyle::LanguageKind Language) { | |||
178 | for (const auto &Format : Style.RawStringFormats) { | |||
179 | if (Format.Language == Language) | |||
180 | return StringRef(Format.CanonicalDelimiter); | |||
181 | } | |||
182 | return ""; | |||
183 | } | |||
184 | ||||
185 | RawStringFormatStyleManager::RawStringFormatStyleManager( | |||
186 | const FormatStyle &CodeStyle) { | |||
187 | for (const auto &RawStringFormat : CodeStyle.RawStringFormats) { | |||
188 | llvm::Optional<FormatStyle> LanguageStyle = | |||
189 | CodeStyle.GetLanguageStyle(RawStringFormat.Language); | |||
190 | if (!LanguageStyle) { | |||
191 | FormatStyle PredefinedStyle; | |||
192 | if (!getPredefinedStyle(RawStringFormat.BasedOnStyle, | |||
193 | RawStringFormat.Language, &PredefinedStyle)) { | |||
194 | PredefinedStyle = getLLVMStyle(); | |||
195 | PredefinedStyle.Language = RawStringFormat.Language; | |||
196 | } | |||
197 | LanguageStyle = PredefinedStyle; | |||
198 | } | |||
199 | LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit; | |||
200 | for (StringRef Delimiter : RawStringFormat.Delimiters) { | |||
201 | DelimiterStyle.insert({Delimiter, *LanguageStyle}); | |||
202 | } | |||
203 | for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions) { | |||
204 | EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle}); | |||
205 | } | |||
206 | } | |||
207 | } | |||
208 | ||||
209 | llvm::Optional<FormatStyle> | |||
210 | RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const { | |||
211 | auto It = DelimiterStyle.find(Delimiter); | |||
212 | if (It == DelimiterStyle.end()) | |||
213 | return None; | |||
214 | return It->second; | |||
215 | } | |||
216 | ||||
217 | llvm::Optional<FormatStyle> | |||
218 | RawStringFormatStyleManager::getEnclosingFunctionStyle( | |||
219 | StringRef EnclosingFunction) const { | |||
220 | auto It = EnclosingFunctionStyle.find(EnclosingFunction); | |||
221 | if (It == EnclosingFunctionStyle.end()) | |||
222 | return None; | |||
223 | return It->second; | |||
224 | } | |||
225 | ||||
226 | ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style, | |||
227 | const AdditionalKeywords &Keywords, | |||
228 | const SourceManager &SourceMgr, | |||
229 | WhitespaceManager &Whitespaces, | |||
230 | encoding::Encoding Encoding, | |||
231 | bool BinPackInconclusiveFunctions) | |||
232 | : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr), | |||
233 | Whitespaces(Whitespaces), Encoding(Encoding), | |||
234 | BinPackInconclusiveFunctions(BinPackInconclusiveFunctions), | |||
235 | CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {} | |||
236 | ||||
237 | LineState ContinuationIndenter::getInitialState(unsigned FirstIndent, | |||
238 | unsigned FirstStartColumn, | |||
239 | const AnnotatedLine *Line, | |||
240 | bool DryRun) { | |||
241 | LineState State; | |||
242 | State.FirstIndent = FirstIndent; | |||
243 | if (FirstStartColumn && Line->First->NewlinesBefore == 0) | |||
244 | State.Column = FirstStartColumn; | |||
245 | else | |||
246 | State.Column = FirstIndent; | |||
247 | // With preprocessor directive indentation, the line starts on column 0 | |||
248 | // since it's indented after the hash, but FirstIndent is set to the | |||
249 | // preprocessor indent. | |||
250 | if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash && | |||
251 | (Line->Type == LT_PreprocessorDirective || | |||
252 | Line->Type == LT_ImportStatement)) | |||
253 | State.Column = 0; | |||
254 | State.Line = Line; | |||
255 | State.NextToken = Line->First; | |||
256 | State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent, | |||
257 | /*AvoidBinPacking=*/false, | |||
258 | /*NoLineBreak=*/false)); | |||
259 | State.LineContainsContinuedForLoopSection = false; | |||
260 | State.NoContinuation = false; | |||
261 | State.StartOfStringLiteral = 0; | |||
262 | State.StartOfLineLevel = 0; | |||
263 | State.LowestLevelOnLine = 0; | |||
264 | State.IgnoreStackForComparison = false; | |||
265 | ||||
266 | if (Style.Language == FormatStyle::LK_TextProto) { | |||
267 | // We need this in order to deal with the bin packing of text fields at | |||
268 | // global scope. | |||
269 | State.Stack.back().AvoidBinPacking = true; | |||
270 | State.Stack.back().BreakBeforeParameter = true; | |||
271 | State.Stack.back().AlignColons = false; | |||
272 | } | |||
273 | ||||
274 | // The first token has already been indented and thus consumed. | |||
275 | moveStateToNextToken(State, DryRun, /*Newline=*/false); | |||
276 | return State; | |||
277 | } | |||
278 | ||||
279 | bool ContinuationIndenter::canBreak(const LineState &State) { | |||
280 | const FormatToken &Current = *State.NextToken; | |||
281 | const FormatToken &Previous = *Current.Previous; | |||
282 | assert(&Previous == Current.Previous)(static_cast <bool> (&Previous == Current.Previous) ? void (0) : __assert_fail ("&Previous == Current.Previous" , "clang/lib/Format/ContinuationIndenter.cpp", 282, __extension__ __PRETTY_FUNCTION__)); | |||
283 | if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace && | |||
284 | Current.closesBlockOrBlockTypeList(Style))) | |||
285 | return false; | |||
286 | // The opening "{" of a braced list has to be on the same line as the first | |||
287 | // element if it is nested in another braced init list or function call. | |||
288 | if (!Current.MustBreakBefore && Previous.is(tok::l_brace) && | |||
289 | Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) && | |||
290 | Previous.Previous && | |||
291 | Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) | |||
292 | return false; | |||
293 | // This prevents breaks like: | |||
294 | // ... | |||
295 | // SomeParameter, OtherParameter).DoSomething( | |||
296 | // ... | |||
297 | // As they hide "DoSomething" and are generally bad for readability. | |||
298 | if (Previous.opensScope() && Previous.isNot(tok::l_brace) && | |||
299 | State.LowestLevelOnLine < State.StartOfLineLevel && | |||
300 | State.LowestLevelOnLine < Current.NestingLevel) | |||
301 | return false; | |||
302 | if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder) | |||
303 | return false; | |||
304 | ||||
305 | // Don't create a 'hanging' indent if there are multiple blocks in a single | |||
306 | // statement. | |||
307 | if (Previous.is(tok::l_brace) && State.Stack.size() > 1 && | |||
308 | State.Stack[State.Stack.size() - 2].NestedBlockInlined && | |||
309 | State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks) | |||
310 | return false; | |||
311 | ||||
312 | // Don't break after very short return types (e.g. "void") as that is often | |||
313 | // unexpected. | |||
314 | if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) { | |||
315 | if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) | |||
316 | return false; | |||
317 | } | |||
318 | ||||
319 | // If binary operators are moved to the next line (including commas for some | |||
320 | // styles of constructor initializers), that's always ok. | |||
321 | if (!Current.isOneOf(TT_BinaryOperator, tok::comma) && | |||
322 | State.Stack.back().NoLineBreakInOperand) | |||
323 | return false; | |||
324 | ||||
325 | if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr)) | |||
326 | return false; | |||
327 | ||||
328 | return !State.Stack.back().NoLineBreak; | |||
329 | } | |||
330 | ||||
331 | bool ContinuationIndenter::mustBreak(const LineState &State) { | |||
332 | const FormatToken &Current = *State.NextToken; | |||
333 | const FormatToken &Previous = *Current.Previous; | |||
334 | if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore && | |||
335 | Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) { | |||
336 | auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack); | |||
337 | return (LambdaBodyLength > getColumnLimit(State)); | |||
338 | } | |||
339 | if (Current.MustBreakBefore || Current.is(TT_InlineASMColon)) | |||
340 | return true; | |||
341 | if (State.Stack.back().BreakBeforeClosingBrace && | |||
342 | Current.closesBlockOrBlockTypeList(Style)) | |||
343 | return true; | |||
344 | if (State.Stack.back().BreakBeforeClosingParen && Current.is(tok::r_paren)) | |||
345 | return true; | |||
346 | if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection) | |||
347 | return true; | |||
348 | if (Style.Language == FormatStyle::LK_ObjC && | |||
349 | Style.ObjCBreakBeforeNestedBlockParam && | |||
350 | Current.ObjCSelectorNameParts > 1 && | |||
351 | Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) { | |||
352 | return true; | |||
353 | } | |||
354 | // Avoid producing inconsistent states by requiring breaks where they are not | |||
355 | // permitted for C# generic type constraints. | |||
356 | if (State.Stack.back().IsCSharpGenericTypeConstraint && | |||
357 | Previous.isNot(TT_CSharpGenericTypeConstraintComma)) | |||
358 | return false; | |||
359 | if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) || | |||
360 | (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) && | |||
361 | Style.isCpp() && | |||
362 | // FIXME: This is a temporary workaround for the case where clang-format | |||
363 | // sets BreakBeforeParameter to avoid bin packing and this creates a | |||
364 | // completely unnecessary line break after a template type that isn't | |||
365 | // line-wrapped. | |||
366 | (Previous.NestingLevel == 1 || Style.BinPackParameters)) || | |||
367 | (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) && | |||
368 | Previous.isNot(tok::question)) || | |||
369 | (!Style.BreakBeforeTernaryOperators && | |||
370 | Previous.is(TT_ConditionalExpr))) && | |||
371 | State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() && | |||
372 | !Current.isOneOf(tok::r_paren, tok::r_brace)) | |||
373 | return true; | |||
374 | if (State.Stack.back().IsChainedConditional && | |||
375 | ((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) && | |||
376 | Current.is(tok::colon)) || | |||
377 | (!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) && | |||
378 | Previous.is(tok::colon)))) | |||
379 | return true; | |||
380 | if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) || | |||
381 | (Previous.is(TT_ArrayInitializerLSquare) && | |||
382 | Previous.ParameterCount > 1) || | |||
383 | opensProtoMessageField(Previous, Style)) && | |||
384 | Style.ColumnLimit > 0 && | |||
385 | getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 > | |||
386 | getColumnLimit(State)) | |||
387 | return true; | |||
388 | ||||
389 | const FormatToken &BreakConstructorInitializersToken = | |||
390 | Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon | |||
391 | ? Previous | |||
392 | : Current; | |||
393 | if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) && | |||
394 | (State.Column + State.Line->Last->TotalLength - Previous.TotalLength > | |||
395 | getColumnLimit(State) || | |||
396 | State.Stack.back().BreakBeforeParameter) && | |||
397 | (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All || | |||
398 | Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon || | |||
399 | Style.ColumnLimit != 0)) | |||
400 | return true; | |||
401 | ||||
402 | if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) && | |||
403 | State.Line->startsWith(TT_ObjCMethodSpecifier)) | |||
404 | return true; | |||
405 | if (Current.is(TT_SelectorName) && !Previous.is(tok::at) && | |||
406 | State.Stack.back().ObjCSelectorNameFound && | |||
407 | State.Stack.back().BreakBeforeParameter && | |||
408 | (Style.ObjCBreakBeforeNestedBlockParam || | |||
409 | !Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) | |||
410 | return true; | |||
411 | ||||
412 | unsigned NewLineColumn = getNewLineColumn(State); | |||
413 | if (Current.isMemberAccess() && Style.ColumnLimit != 0 && | |||
414 | State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit && | |||
415 | (State.Column > NewLineColumn || | |||
416 | Current.NestingLevel < State.StartOfLineLevel)) | |||
417 | return true; | |||
418 | ||||
419 | if (startsSegmentOfBuilderTypeCall(Current) && | |||
420 | (State.Stack.back().CallContinuation != 0 || | |||
421 | State.Stack.back().BreakBeforeParameter) && | |||
422 | // JavaScript is treated different here as there is a frequent pattern: | |||
423 | // SomeFunction(function() { | |||
424 | // ... | |||
425 | // }.bind(...)); | |||
426 | // FIXME: We should find a more generic solution to this problem. | |||
427 | !(State.Column <= NewLineColumn && Style.isJavaScript()) && | |||
428 | !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) | |||
429 | return true; | |||
430 | ||||
431 | // If the template declaration spans multiple lines, force wrap before the | |||
432 | // function/class declaration | |||
433 | if (Previous.ClosesTemplateDeclaration && | |||
434 | State.Stack.back().BreakBeforeParameter && Current.CanBreakBefore) | |||
435 | return true; | |||
436 | ||||
437 | if (!State.Line->First->is(tok::kw_enum) && State.Column <= NewLineColumn) | |||
438 | return false; | |||
439 | ||||
440 | if (Style.AlwaysBreakBeforeMultilineStrings && | |||
441 | (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth || | |||
442 | Previous.is(tok::comma) || Current.NestingLevel < 2) && | |||
443 | !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at, | |||
444 | Keywords.kw_dollar) && | |||
445 | !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) && | |||
446 | nextIsMultilineString(State)) | |||
447 | return true; | |||
448 | ||||
449 | // Using CanBreakBefore here and below takes care of the decision whether the | |||
450 | // current style uses wrapping before or after operators for the given | |||
451 | // operator. | |||
452 | if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) { | |||
453 | // If we need to break somewhere inside the LHS of a binary expression, we | |||
454 | // should also break after the operator. Otherwise, the formatting would | |||
455 | // hide the operator precedence, e.g. in: | |||
456 | // if (aaaaaaaaaaaaaa == | |||
457 | // bbbbbbbbbbbbbb && c) {.. | |||
458 | // For comparisons, we only apply this rule, if the LHS is a binary | |||
459 | // expression itself as otherwise, the line breaks seem superfluous. | |||
460 | // We need special cases for ">>" which we have split into two ">" while | |||
461 | // lexing in order to make template parsing easier. | |||
462 | bool IsComparison = (Previous.getPrecedence() == prec::Relational || | |||
463 | Previous.getPrecedence() == prec::Equality || | |||
464 | Previous.getPrecedence() == prec::Spaceship) && | |||
465 | Previous.Previous && | |||
466 | Previous.Previous->isNot(TT_BinaryOperator); // For >>. | |||
467 | bool LHSIsBinaryExpr = | |||
468 | Previous.Previous && Previous.Previous->EndsBinaryExpression; | |||
469 | if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() && | |||
470 | Previous.getPrecedence() != prec::Assignment && | |||
471 | State.Stack.back().BreakBeforeParameter) | |||
472 | return true; | |||
473 | } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore && | |||
474 | State.Stack.back().BreakBeforeParameter) { | |||
475 | return true; | |||
476 | } | |||
477 | ||||
478 | // Same as above, but for the first "<<" operator. | |||
479 | if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) && | |||
480 | State.Stack.back().BreakBeforeParameter && | |||
481 | State.Stack.back().FirstLessLess == 0) | |||
482 | return true; | |||
483 | ||||
484 | if (Current.NestingLevel == 0 && !Current.isTrailingComment()) { | |||
485 | // Always break after "template <...>" and leading annotations. This is only | |||
486 | // for cases where the entire line does not fit on a single line as a | |||
487 | // different LineFormatter would be used otherwise. | |||
488 | if (Previous.ClosesTemplateDeclaration) | |||
489 | return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No; | |||
490 | if (Previous.is(TT_FunctionAnnotationRParen) && | |||
491 | State.Line->Type != LT_PreprocessorDirective) | |||
492 | return true; | |||
493 | if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) && | |||
494 | Current.isNot(TT_LeadingJavaAnnotation)) | |||
495 | return true; | |||
496 | } | |||
497 | ||||
498 | if (Style.isJavaScript() && Previous.is(tok::r_paren) && | |||
499 | Previous.is(TT_JavaAnnotation)) { | |||
500 | // Break after the closing parenthesis of TypeScript decorators before | |||
501 | // functions, getters and setters. | |||
502 | static const llvm::StringSet<> BreakBeforeDecoratedTokens = {"get", "set", | |||
503 | "function"}; | |||
504 | if (BreakBeforeDecoratedTokens.contains(Current.TokenText)) | |||
505 | return true; | |||
506 | } | |||
507 | ||||
508 | // If the return type spans multiple lines, wrap before the function name. | |||
509 | if (((Current.is(TT_FunctionDeclarationName) && | |||
510 | // Don't break before a C# function when no break after return type | |||
511 | (!Style.isCSharp() || | |||
512 | Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) && | |||
513 | // Don't always break between a JavaScript `function` and the function | |||
514 | // name. | |||
515 | !Style.isJavaScript()) || | |||
516 | (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) && | |||
517 | !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter) | |||
518 | return true; | |||
519 | ||||
520 | // The following could be precomputed as they do not depend on the state. | |||
521 | // However, as they should take effect only if the UnwrappedLine does not fit | |||
522 | // into the ColumnLimit, they are checked here in the ContinuationIndenter. | |||
523 | if (Style.ColumnLimit != 0 && Previous.is(BK_Block) && | |||
524 | Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment)) | |||
525 | return true; | |||
526 | ||||
527 | if (Current.is(tok::lessless) && | |||
528 | ((Previous.is(tok::identifier) && Previous.TokenText == "endl") || | |||
529 | (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") || | |||
530 | Previous.TokenText == "\'\\n\'")))) | |||
531 | return true; | |||
532 | ||||
533 | if (Previous.is(TT_BlockComment) && Previous.IsMultiline) | |||
534 | return true; | |||
535 | ||||
536 | if (State.NoContinuation) | |||
537 | return true; | |||
538 | ||||
539 | return false; | |||
540 | } | |||
541 | ||||
542 | unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline, | |||
543 | bool DryRun, | |||
544 | unsigned ExtraSpaces) { | |||
545 | const FormatToken &Current = *State.NextToken; | |||
546 | ||||
547 | assert(!State.Stack.empty())(static_cast <bool> (!State.Stack.empty()) ? void (0) : __assert_fail ("!State.Stack.empty()", "clang/lib/Format/ContinuationIndenter.cpp" , 547, __extension__ __PRETTY_FUNCTION__)); | |||
548 | State.NoContinuation = false; | |||
549 | ||||
550 | if ((Current.is(TT_ImplicitStringLiteral) && | |||
551 | (Current.Previous->Tok.getIdentifierInfo() == nullptr || | |||
552 | Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() == | |||
553 | tok::pp_not_keyword))) { | |||
554 | unsigned EndColumn = | |||
555 | SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd()); | |||
556 | if (Current.LastNewlineOffset != 0) { | |||
557 | // If there is a newline within this token, the final column will solely | |||
558 | // determined by the current end column. | |||
559 | State.Column = EndColumn; | |||
560 | } else { | |||
561 | unsigned StartColumn = | |||
562 | SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin()); | |||
563 | assert(EndColumn >= StartColumn)(static_cast <bool> (EndColumn >= StartColumn) ? void (0) : __assert_fail ("EndColumn >= StartColumn", "clang/lib/Format/ContinuationIndenter.cpp" , 563, __extension__ __PRETTY_FUNCTION__)); | |||
564 | State.Column += EndColumn - StartColumn; | |||
565 | } | |||
566 | moveStateToNextToken(State, DryRun, /*Newline=*/false); | |||
567 | return 0; | |||
568 | } | |||
569 | ||||
570 | unsigned Penalty = 0; | |||
571 | if (Newline) | |||
572 | Penalty = addTokenOnNewLine(State, DryRun); | |||
573 | else | |||
574 | addTokenOnCurrentLine(State, DryRun, ExtraSpaces); | |||
575 | ||||
576 | return moveStateToNextToken(State, DryRun, Newline) + Penalty; | |||
577 | } | |||
578 | ||||
579 | void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, | |||
580 | unsigned ExtraSpaces) { | |||
581 | FormatToken &Current = *State.NextToken; | |||
582 | const FormatToken &Previous = *State.NextToken->Previous; | |||
| ||||
583 | if (Current.is(tok::equal) && | |||
584 | (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) && | |||
585 | State.Stack.back().VariablePos == 0) { | |||
586 | State.Stack.back().VariablePos = State.Column; | |||
587 | // Move over * and & if they are bound to the variable name. | |||
588 | const FormatToken *Tok = &Previous; | |||
589 | while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) { | |||
590 | State.Stack.back().VariablePos -= Tok->ColumnWidth; | |||
591 | if (Tok->SpacesRequiredBefore != 0) | |||
592 | break; | |||
593 | Tok = Tok->Previous; | |||
594 | } | |||
595 | if (Previous.PartOfMultiVariableDeclStmt) | |||
| ||||
596 | State.Stack.back().LastSpace = State.Stack.back().VariablePos; | |||
597 | } | |||
598 | ||||
599 | unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces; | |||
600 | ||||
601 | // Indent preprocessor directives after the hash if required. | |||
602 | int PPColumnCorrection = 0; | |||
603 | if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash && | |||
604 | Previous.is(tok::hash) && State.FirstIndent > 0 && | |||
605 | (State.Line->Type == LT_PreprocessorDirective || | |||
606 | State.Line->Type == LT_ImportStatement)) { | |||
607 | Spaces += State.FirstIndent; | |||
608 | ||||
609 | // For preprocessor indent with tabs, State.Column will be 1 because of the | |||
610 | // hash. This causes second-level indents onward to have an extra space | |||
611 | // after the tabs. We avoid this misalignment by subtracting 1 from the | |||
612 | // column value passed to replaceWhitespace(). | |||
613 | if (Style.UseTab != FormatStyle::UT_Never) | |||
614 | PPColumnCorrection = -1; | |||
615 | } | |||
616 | ||||
617 | if (!DryRun) | |||
618 | Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces, | |||
619 | State.Column + Spaces + PPColumnCorrection); | |||
620 | ||||
621 | // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance | |||
622 | // declaration unless there is multiple inheritance. | |||
623 | if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma && | |||
624 | Current.is(TT_InheritanceColon)) | |||
625 | State.Stack.back().NoLineBreak = true; | |||
626 | if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon && | |||
627 | Previous.is(TT_InheritanceColon)) | |||
628 | State.Stack.back().NoLineBreak = true; | |||
629 | ||||
630 | if (Current.is(TT_SelectorName) && | |||
631 | !State.Stack.back().ObjCSelectorNameFound) { | |||
632 | unsigned MinIndent = | |||
633 | std::max(State.FirstIndent + Style.ContinuationIndentWidth, | |||
634 | State.Stack.back().Indent); | |||
635 | unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth; | |||
636 | if (Current.LongestObjCSelectorName == 0) | |||
637 | State.Stack.back().AlignColons = false; | |||
638 | else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos) | |||
639 | State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName; | |||
640 | else | |||
641 | State.Stack.back().ColonPos = FirstColonPos; | |||
642 | } | |||
643 | ||||
644 | // In "AlwaysBreak" or "BlockIndent" mode, enforce wrapping directly after the | |||
645 | // parenthesis by disallowing any further line breaks if there is no line | |||
646 | // break after the opening parenthesis. Don't break if it doesn't conserve | |||
647 | // columns. | |||
648 | if ((Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak || | |||
649 | Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) && | |||
650 | (Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) || | |||
651 | (Previous.is(tok::l_brace) && Previous.isNot(BK_Block) && | |||
652 | Style.Cpp11BracedListStyle)) && | |||
653 | State.Column > getNewLineColumn(State) && | |||
654 | (!Previous.Previous || !Previous.Previous->isOneOf( | |||
655 | tok::kw_for, tok::kw_while, tok::kw_switch)) && | |||
656 | // Don't do this for simple (no expressions) one-argument function calls | |||
657 | // as that feels like needlessly wasting whitespace, e.g.: | |||
658 | // | |||
659 | // caaaaaaaaaaaall( | |||
660 | // caaaaaaaaaaaall( | |||
661 | // caaaaaaaaaaaall( | |||
662 | // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa)))); | |||
663 | Current.FakeLParens.size() > 0 && | |||
664 | Current.FakeLParens.back() > prec::Unknown) | |||
665 | State.Stack.back().NoLineBreak = true; | |||
666 | if (Previous.is(TT_TemplateString) && Previous.opensScope()) | |||
667 | State.Stack.back().NoLineBreak = true; | |||
668 | ||||
669 | if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign && | |||
670 | !State.Stack.back().IsCSharpGenericTypeConstraint && | |||
671 | Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) && | |||
672 | (Current.isNot(TT_LineComment) || Previous.is(BK_BracedInit))) { | |||
673 | State.Stack.back().Indent = State.Column + Spaces; | |||
674 | State.Stack.back().IsAligned = true; | |||
675 | } | |||
676 | if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style)) | |||
677 | State.Stack.back().NoLineBreak = true; | |||
678 | if (startsSegmentOfBuilderTypeCall(Current) && | |||
679 | State.Column > getNewLineColumn(State)) | |||
680 | State.Stack.back().ContainsUnwrappedBuilder = true; | |||
681 | ||||
682 | if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java) | |||
683 | State.Stack.back().NoLineBreak = true; | |||
684 | if (Current.isMemberAccess() && Previous.is(tok::r_paren) && | |||
685 | (Previous.MatchingParen && | |||
686 | (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) | |||
687 | // If there is a function call with long parameters, break before trailing | |||
688 | // calls. This prevents things like: | |||
689 | // EXPECT_CALL(SomeLongParameter).Times( | |||
690 | // 2); | |||
691 | // We don't want to do this for short parameters as they can just be | |||
692 | // indexes. | |||
693 | State.Stack.back().NoLineBreak = true; | |||
694 | ||||
695 | // Don't allow the RHS of an operator to be split over multiple lines unless | |||
696 | // there is a line-break right after the operator. | |||
697 | // Exclude relational operators, as there, it is always more desirable to | |||
698 | // have the LHS 'left' of the RHS. | |||
699 | const FormatToken *P = Current.getPreviousNonComment(); | |||
700 | if (!Current.is(tok::comment) && P && | |||
701 | (P->isOneOf(TT_BinaryOperator, tok::comma) || | |||
702 | (P->is(TT_ConditionalExpr) && P->is(tok::colon))) && | |||
703 | !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) && | |||
704 | P->getPrecedence() != prec::Assignment && | |||
705 | P->getPrecedence() != prec::Relational && | |||
706 | P->getPrecedence() != prec::Spaceship) { | |||
707 | bool BreakBeforeOperator = | |||
708 | P->MustBreakBefore || P->is(tok::lessless) || | |||
709 | (P->is(TT_BinaryOperator) && | |||
710 | Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) || | |||
711 | (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators); | |||
712 | // Don't do this if there are only two operands. In these cases, there is | |||
713 | // always a nice vertical separation between them and the extra line break | |||
714 | // does not help. | |||
715 | bool HasTwoOperands = | |||
716 | P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr); | |||
717 | if ((!BreakBeforeOperator && | |||
718 | !(HasTwoOperands && | |||
719 | Style.AlignOperands != FormatStyle::OAS_DontAlign)) || | |||
720 | (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator)) | |||
721 | State.Stack.back().NoLineBreakInOperand = true; | |||
722 | } | |||
723 | ||||
724 | State.Column += Spaces; | |||
725 | if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) && | |||
726 | Previous.Previous && | |||
727 | (Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) { | |||
728 | // Treat the condition inside an if as if it was a second function | |||
729 | // parameter, i.e. let nested calls have a continuation indent. | |||
730 | State.Stack.back().LastSpace = State.Column; | |||
731 | State.Stack.back().NestedBlockIndent = State.Column; | |||
732 | } else if (!Current.isOneOf(tok::comment, tok::caret) && | |||
733 | ((Previous.is(tok::comma) && | |||
734 | !Previous.is(TT_OverloadedOperator)) || | |||
735 | (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) { | |||
736 | State.Stack.back().LastSpace = State.Column; | |||
737 | } else if (Previous.is(TT_CtorInitializerColon) && | |||
738 | Style.BreakConstructorInitializers == | |||
739 | FormatStyle::BCIS_AfterColon) { | |||
740 | State.Stack.back().Indent = State.Column; | |||
741 | State.Stack.back().LastSpace = State.Column; | |||
742 | } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr, | |||
743 | TT_CtorInitializerColon)) && | |||
744 | ((Previous.getPrecedence() != prec::Assignment && | |||
745 | (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 || | |||
746 | Previous.NextOperator)) || | |||
747 | Current.StartsBinaryExpression)) { | |||
748 | // Indent relative to the RHS of the expression unless this is a simple | |||
749 | // assignment without binary expression on the RHS. Also indent relative to | |||
750 | // unary operators and the colons of constructor initializers. | |||
751 | if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None) | |||
752 | State.Stack.back().LastSpace = State.Column; | |||
753 | } else if (Previous.is(TT_InheritanceColon)) { | |||
754 | State.Stack.back().Indent = State.Column; | |||
755 | State.Stack.back().LastSpace = State.Column; | |||
756 | } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) { | |||
757 | State.Stack.back().ColonPos = State.Column; | |||
758 | } else if (Previous.opensScope()) { | |||
759 | // If a function has a trailing call, indent all parameters from the | |||
760 | // opening parenthesis. This avoids confusing indents like: | |||
761 | // OuterFunction(InnerFunctionCall( // break | |||
762 | // ParameterToInnerFunction)) // break | |||
763 | // .SecondInnerFunctionCall(); | |||
764 | bool HasTrailingCall = false; | |||
765 | if (Previous.MatchingParen) { | |||
766 | const FormatToken *Next = Previous.MatchingParen->getNextNonComment(); | |||
767 | HasTrailingCall = Next && Next->isMemberAccess(); | |||
768 | } | |||
769 | if (HasTrailingCall && State.Stack.size() > 1 && | |||
770 | State.Stack[State.Stack.size() - 2].CallContinuation == 0) | |||
771 | State.Stack.back().LastSpace = State.Column; | |||
772 | } | |||
773 | } | |||
774 | ||||
775 | unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State, | |||
776 | bool DryRun) { | |||
777 | FormatToken &Current = *State.NextToken; | |||
778 | const FormatToken &Previous = *State.NextToken->Previous; | |||
779 | ||||
780 | // Extra penalty that needs to be added because of the way certain line | |||
781 | // breaks are chosen. | |||
782 | unsigned Penalty = 0; | |||
783 | ||||
784 | const FormatToken *PreviousNonComment = Current.getPreviousNonComment(); | |||
785 | const FormatToken *NextNonComment = Previous.getNextNonComment(); | |||
786 | if (!NextNonComment) | |||
787 | NextNonComment = &Current; | |||
788 | // The first line break on any NestingLevel causes an extra penalty in order | |||
789 | // prefer similar line breaks. | |||
790 | if (!State.Stack.back().ContainsLineBreak) | |||
791 | Penalty += 15; | |||
792 | State.Stack.back().ContainsLineBreak = true; | |||
793 | ||||
794 | Penalty += State.NextToken->SplitPenalty; | |||
795 | ||||
796 | // Breaking before the first "<<" is generally not desirable if the LHS is | |||
797 | // short. Also always add the penalty if the LHS is split over multiple lines | |||
798 | // to avoid unnecessary line breaks that just work around this penalty. | |||
799 | if (NextNonComment->is(tok::lessless) && | |||
800 | State.Stack.back().FirstLessLess == 0 && | |||
801 | (State.Column <= Style.ColumnLimit / 3 || | |||
802 | State.Stack.back().BreakBeforeParameter)) | |||
803 | Penalty += Style.PenaltyBreakFirstLessLess; | |||
804 | ||||
805 | State.Column = getNewLineColumn(State); | |||
806 | ||||
807 | // Add Penalty proportional to amount of whitespace away from FirstColumn | |||
808 | // This tends to penalize several lines that are far-right indented, | |||
809 | // and prefers a line-break prior to such a block, e.g: | |||
810 | // | |||
811 | // Constructor() : | |||
812 | // member(value), looooooooooooooooong_member( | |||
813 | // looooooooooong_call(param_1, param_2, param_3)) | |||
814 | // would then become | |||
815 | // Constructor() : | |||
816 | // member(value), | |||
817 | // looooooooooooooooong_member( | |||
818 | // looooooooooong_call(param_1, param_2, param_3)) | |||
819 | if (State.Column > State.FirstIndent) | |||
820 | Penalty += | |||
821 | Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent); | |||
822 | ||||
823 | // Indent nested blocks relative to this column, unless in a very specific | |||
824 | // JavaScript special case where: | |||
825 | // | |||
826 | // var loooooong_name = | |||
827 | // function() { | |||
828 | // // code | |||
829 | // } | |||
830 | // | |||
831 | // is common and should be formatted like a free-standing function. The same | |||
832 | // goes for wrapping before the lambda return type arrow. | |||
833 | if (!Current.is(TT_LambdaArrow) && | |||
834 | (!Style.isJavaScript() || Current.NestingLevel != 0 || | |||
835 | !PreviousNonComment || !PreviousNonComment->is(tok::equal) || | |||
836 | !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) | |||
837 | State.Stack.back().NestedBlockIndent = State.Column; | |||
838 | ||||
839 | if (NextNonComment->isMemberAccess()) { | |||
840 | if (State.Stack.back().CallContinuation == 0) | |||
841 | State.Stack.back().CallContinuation = State.Column; | |||
842 | } else if (NextNonComment->is(TT_SelectorName)) { | |||
843 | if (!State.Stack.back().ObjCSelectorNameFound) { | |||
844 | if (NextNonComment->LongestObjCSelectorName == 0) { | |||
845 | State.Stack.back().AlignColons = false; | |||
846 | } else { | |||
847 | State.Stack.back().ColonPos = | |||
848 | (shouldIndentWrappedSelectorName(Style, State.Line->Type) | |||
849 | ? std::max(State.Stack.back().Indent, | |||
850 | State.FirstIndent + Style.ContinuationIndentWidth) | |||
851 | : State.Stack.back().Indent) + | |||
852 | std::max(NextNonComment->LongestObjCSelectorName, | |||
853 | NextNonComment->ColumnWidth); | |||
854 | } | |||
855 | } else if (State.Stack.back().AlignColons && | |||
856 | State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) { | |||
857 | State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth; | |||
858 | } | |||
859 | } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) && | |||
860 | PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) { | |||
861 | // FIXME: This is hacky, find a better way. The problem is that in an ObjC | |||
862 | // method expression, the block should be aligned to the line starting it, | |||
863 | // e.g.: | |||
864 | // [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason | |||
865 | // ^(int *i) { | |||
866 | // // ... | |||
867 | // }]; | |||
868 | // Thus, we set LastSpace of the next higher NestingLevel, to which we move | |||
869 | // when we consume all of the "}"'s FakeRParens at the "{". | |||
870 | if (State.Stack.size() > 1) | |||
871 | State.Stack[State.Stack.size() - 2].LastSpace = | |||
872 | std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + | |||
873 | Style.ContinuationIndentWidth; | |||
874 | } | |||
875 | ||||
876 | if ((PreviousNonComment && | |||
877 | PreviousNonComment->isOneOf(tok::comma, tok::semi) && | |||
878 | !State.Stack.back().AvoidBinPacking) || | |||
879 | Previous.is(TT_BinaryOperator)) | |||
880 | State.Stack.back().BreakBeforeParameter = false; | |||
881 | if (PreviousNonComment && | |||
882 | PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) && | |||
883 | Current.NestingLevel == 0) | |||
884 | State.Stack.back().BreakBeforeParameter = false; | |||
885 | if (NextNonComment->is(tok::question) || | |||
886 | (PreviousNonComment && PreviousNonComment->is(tok::question))) | |||
887 | State.Stack.back().BreakBeforeParameter = true; | |||
888 | if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore) | |||
889 | State.Stack.back().BreakBeforeParameter = false; | |||
890 | ||||
891 | if (!DryRun) { | |||
892 | unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1; | |||
893 | if (Current.is(tok::r_brace) && Current.MatchingParen && | |||
894 | // Only strip trailing empty lines for l_braces that have children, i.e. | |||
895 | // for function expressions (lambdas, arrows, etc). | |||
896 | !Current.MatchingParen->Children.empty()) { | |||
897 | // lambdas and arrow functions are expressions, thus their r_brace is not | |||
898 | // on its own line, and thus not covered by UnwrappedLineFormatter's logic | |||
899 | // about removing empty lines on closing blocks. Special case them here. | |||
900 | MaxEmptyLinesToKeep = 1; | |||
901 | } | |||
902 | unsigned Newlines = | |||
903 | std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep)); | |||
904 | bool ContinuePPDirective = | |||
905 | State.Line->InPPDirective && State.Line->Type != LT_ImportStatement; | |||
906 | Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column, | |||
907 | State.Stack.back().IsAligned, | |||
908 | ContinuePPDirective); | |||
909 | } | |||
910 | ||||
911 | if (!Current.isTrailingComment()) | |||
912 | State.Stack.back().LastSpace = State.Column; | |||
913 | if (Current.is(tok::lessless)) | |||
914 | // If we are breaking before a "<<", we always want to indent relative to | |||
915 | // RHS. This is necessary only for "<<", as we special-case it and don't | |||
916 | // always indent relative to the RHS. | |||
917 | State.Stack.back().LastSpace += 3; // 3 -> width of "<< ". | |||
918 | ||||
919 | State.StartOfLineLevel = Current.NestingLevel; | |||
920 | State.LowestLevelOnLine = Current.NestingLevel; | |||
921 | ||||
922 | // Any break on this level means that the parent level has been broken | |||
923 | // and we need to avoid bin packing there. | |||
924 | bool NestedBlockSpecialCase = | |||
925 | (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 && | |||
926 | State.Stack[State.Stack.size() - 2].NestedBlockInlined) || | |||
927 | (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) && | |||
928 | State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam); | |||
929 | if (!NestedBlockSpecialCase) | |||
930 | for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) | |||
931 | State.Stack[i].BreakBeforeParameter = true; | |||
932 | ||||
933 | if (PreviousNonComment && | |||
934 | !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) && | |||
935 | (PreviousNonComment->isNot(TT_TemplateCloser) || | |||
936 | Current.NestingLevel != 0) && | |||
937 | !PreviousNonComment->isOneOf( | |||
938 | TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation, | |||
939 | TT_LeadingJavaAnnotation) && | |||
940 | Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) | |||
941 | State.Stack.back().BreakBeforeParameter = true; | |||
942 | ||||
943 | // If we break after { or the [ of an array initializer, we should also break | |||
944 | // before the corresponding } or ]. | |||
945 | if (PreviousNonComment && | |||
946 | (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || | |||
947 | opensProtoMessageField(*PreviousNonComment, Style))) | |||
948 | State.Stack.back().BreakBeforeClosingBrace = true; | |||
949 | ||||
950 | if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) | |||
951 | State.Stack.back().BreakBeforeClosingParen = | |||
952 | Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent; | |||
953 | ||||
954 | if (State.Stack.back().AvoidBinPacking) { | |||
955 | // If we are breaking after '(', '{', '<', or this is the break after a ':' | |||
956 | // to start a member initializater list in a constructor, this should not | |||
957 | // be considered bin packing unless the relevant AllowAll option is false or | |||
958 | // this is a dict/object literal. | |||
959 | bool PreviousIsBreakingCtorInitializerColon = | |||
960 | Previous.is(TT_CtorInitializerColon) && | |||
961 | Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon; | |||
962 | if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) || | |||
963 | PreviousIsBreakingCtorInitializerColon) || | |||
964 | (!Style.AllowAllParametersOfDeclarationOnNextLine && | |||
965 | State.Line->MustBeDeclaration) || | |||
966 | (!Style.AllowAllArgumentsOnNextLine && | |||
967 | !State.Line->MustBeDeclaration) || | |||
968 | (Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine && | |||
969 | PreviousIsBreakingCtorInitializerColon) || | |||
970 | Previous.is(TT_DictLiteral)) | |||
971 | State.Stack.back().BreakBeforeParameter = true; | |||
972 | ||||
973 | // If we are breaking after a ':' to start a member initializer list, | |||
974 | // and we allow all arguments on the next line, we should not break | |||
975 | // before the next parameter. | |||
976 | if (PreviousIsBreakingCtorInitializerColon && | |||
977 | Style.PackConstructorInitializers == FormatStyle::PCIS_NextLine) | |||
978 | State.Stack.back().BreakBeforeParameter = false; | |||
979 | } | |||
980 | ||||
981 | return Penalty; | |||
982 | } | |||
983 | ||||
984 | unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) { | |||
985 | if (!State.NextToken || !State.NextToken->Previous) | |||
986 | return 0; | |||
987 | ||||
988 | FormatToken &Current = *State.NextToken; | |||
989 | ||||
990 | if (State.Stack.back().IsCSharpGenericTypeConstraint && | |||
991 | Current.isNot(TT_CSharpGenericTypeConstraint)) | |||
992 | return State.Stack.back().ColonPos + 2; | |||
993 | ||||
994 | const FormatToken &Previous = *Current.Previous; | |||
995 | // If we are continuing an expression, we want to use the continuation indent. | |||
996 | unsigned ContinuationIndent = | |||
997 | std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + | |||
998 | Style.ContinuationIndentWidth; | |||
999 | const FormatToken *PreviousNonComment = Current.getPreviousNonComment(); | |||
1000 | const FormatToken *NextNonComment = Previous.getNextNonComment(); | |||
1001 | if (!NextNonComment) | |||
1002 | NextNonComment = &Current; | |||
1003 | ||||
1004 | // Java specific bits. | |||
1005 | if (Style.Language == FormatStyle::LK_Java && | |||
1006 | Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) | |||
1007 | return std::max(State.Stack.back().LastSpace, | |||
1008 | State.Stack.back().Indent + Style.ContinuationIndentWidth); | |||
1009 | ||||
1010 | if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths && | |||
1011 | State.Line->First->is(tok::kw_enum)) | |||
1012 | return (Style.IndentWidth * State.Line->First->IndentLevel) + | |||
1013 | Style.IndentWidth; | |||
1014 | ||||
1015 | if (NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block)) | |||
1016 | return Current.NestingLevel == 0 ? State.FirstIndent | |||
1017 | : State.Stack.back().Indent; | |||
1018 | if ((Current.isOneOf(tok::r_brace, tok::r_square) || | |||
1019 | (Current.is(tok::greater) && | |||
1020 | (Style.Language == FormatStyle::LK_Proto || | |||
1021 | Style.Language == FormatStyle::LK_TextProto))) && | |||
1022 | State.Stack.size() > 1) { | |||
1023 | if (Current.closesBlockOrBlockTypeList(Style)) | |||
1024 | return State.Stack[State.Stack.size() - 2].NestedBlockIndent; | |||
1025 | if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit)) | |||
1026 | return State.Stack[State.Stack.size() - 2].LastSpace; | |||
1027 | return State.FirstIndent; | |||
1028 | } | |||
1029 | // Indent a closing parenthesis at the previous level if followed by a semi, | |||
1030 | // const, or opening brace. This allows indentations such as: | |||
1031 | // foo( | |||
1032 | // a, | |||
1033 | // ); | |||
1034 | // int Foo::getter( | |||
1035 | // // | |||
1036 | // ) const { | |||
1037 | // return foo; | |||
1038 | // } | |||
1039 | // function foo( | |||
1040 | // a, | |||
1041 | // ) { | |||
1042 | // code(); // | |||
1043 | // } | |||
1044 | if (Current.is(tok::r_paren) && State.Stack.size() > 1 && | |||
1045 | (!Current.Next || | |||
1046 | Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) | |||
1047 | return State.Stack[State.Stack.size() - 2].LastSpace; | |||
1048 | if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent && | |||
1049 | Current.is(tok::r_paren) && State.Stack.size() > 1) | |||
1050 | return State.Stack[State.Stack.size() - 2].LastSpace; | |||
1051 | if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope()) | |||
1052 | return State.Stack[State.Stack.size() - 2].LastSpace; | |||
1053 | if (Current.is(tok::identifier) && Current.Next && | |||
1054 | (Current.Next->is(TT_DictLiteral) || | |||
1055 | ((Style.Language == FormatStyle::LK_Proto || | |||
1056 | Style.Language == FormatStyle::LK_TextProto) && | |||
1057 | Current.Next->isOneOf(tok::less, tok::l_brace)))) | |||
1058 | return State.Stack.back().Indent; | |||
1059 | if (NextNonComment->is(TT_ObjCStringLiteral) && | |||
1060 | State.StartOfStringLiteral != 0) | |||
1061 | return State.StartOfStringLiteral - 1; | |||
1062 | if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0) | |||
1063 | return State.StartOfStringLiteral; | |||
1064 | if (NextNonComment->is(tok::lessless) && | |||
1065 | State.Stack.back().FirstLessLess != 0) | |||
1066 | return State.Stack.back().FirstLessLess; | |||
1067 | if (NextNonComment->isMemberAccess()) { | |||
1068 | if (State.Stack.back().CallContinuation == 0) | |||
1069 | return ContinuationIndent; | |||
1070 | return State.Stack.back().CallContinuation; | |||
1071 | } | |||
1072 | if (State.Stack.back().QuestionColumn != 0 && | |||
1073 | ((NextNonComment->is(tok::colon) && | |||
1074 | NextNonComment->is(TT_ConditionalExpr)) || | |||
1075 | Previous.is(TT_ConditionalExpr))) { | |||
1076 | if (((NextNonComment->is(tok::colon) && NextNonComment->Next && | |||
1077 | !NextNonComment->Next->FakeLParens.empty() && | |||
1078 | NextNonComment->Next->FakeLParens.back() == prec::Conditional) || | |||
1079 | (Previous.is(tok::colon) && !Current.FakeLParens.empty() && | |||
1080 | Current.FakeLParens.back() == prec::Conditional)) && | |||
1081 | !State.Stack.back().IsWrappedConditional) { | |||
1082 | // NOTE: we may tweak this slightly: | |||
1083 | // * not remove the 'lead' ContinuationIndentWidth | |||
1084 | // * always un-indent by the operator when | |||
1085 | // BreakBeforeTernaryOperators=true | |||
1086 | unsigned Indent = State.Stack.back().Indent; | |||
1087 | if (Style.AlignOperands != FormatStyle::OAS_DontAlign) { | |||
1088 | Indent -= Style.ContinuationIndentWidth; | |||
1089 | } | |||
1090 | if (Style.BreakBeforeTernaryOperators && | |||
1091 | State.Stack.back().UnindentOperator) | |||
1092 | Indent -= 2; | |||
1093 | return Indent; | |||
1094 | } | |||
1095 | return State.Stack.back().QuestionColumn; | |||
1096 | } | |||
1097 | if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0) | |||
1098 | return State.Stack.back().VariablePos; | |||
1099 | if ((PreviousNonComment && | |||
1100 | (PreviousNonComment->ClosesTemplateDeclaration || | |||
1101 | PreviousNonComment->isOneOf( | |||
1102 | TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen, | |||
1103 | TT_JavaAnnotation, TT_LeadingJavaAnnotation))) || | |||
1104 | (!Style.IndentWrappedFunctionNames && | |||
1105 | NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) | |||
1106 | return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent); | |||
1107 | if (NextNonComment->is(TT_SelectorName)) { | |||
1108 | if (!State.Stack.back().ObjCSelectorNameFound) { | |||
1109 | unsigned MinIndent = State.Stack.back().Indent; | |||
1110 | if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) | |||
1111 | MinIndent = std::max(MinIndent, | |||
1112 | State.FirstIndent + Style.ContinuationIndentWidth); | |||
1113 | // If LongestObjCSelectorName is 0, we are indenting the first | |||
1114 | // part of an ObjC selector (or a selector component which is | |||
1115 | // not colon-aligned due to block formatting). | |||
1116 | // | |||
1117 | // Otherwise, we are indenting a subsequent part of an ObjC | |||
1118 | // selector which should be colon-aligned to the longest | |||
1119 | // component of the ObjC selector. | |||
1120 | // | |||
1121 | // In either case, we want to respect Style.IndentWrappedFunctionNames. | |||
1122 | return MinIndent + | |||
1123 | std::max(NextNonComment->LongestObjCSelectorName, | |||
1124 | NextNonComment->ColumnWidth) - | |||
1125 | NextNonComment->ColumnWidth; | |||
1126 | } | |||
1127 | if (!State.Stack.back().AlignColons) | |||
1128 | return State.Stack.back().Indent; | |||
1129 | if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth) | |||
1130 | return State.Stack.back().ColonPos - NextNonComment->ColumnWidth; | |||
1131 | return State.Stack.back().Indent; | |||
1132 | } | |||
1133 | if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr)) | |||
1134 | return State.Stack.back().ColonPos; | |||
1135 | if (NextNonComment->is(TT_ArraySubscriptLSquare)) { | |||
1136 | if (State.Stack.back().StartOfArraySubscripts != 0) | |||
1137 | return State.Stack.back().StartOfArraySubscripts; | |||
1138 | else if (Style.isCSharp()) // C# allows `["key"] = value` inside object | |||
1139 | // initializers. | |||
1140 | return State.Stack.back().Indent; | |||
1141 | return ContinuationIndent; | |||
1142 | } | |||
1143 | ||||
1144 | // This ensure that we correctly format ObjC methods calls without inputs, | |||
1145 | // i.e. where the last element isn't selector like: [callee method]; | |||
1146 | if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 && | |||
1147 | NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) | |||
1148 | return State.Stack.back().Indent; | |||
1149 | ||||
1150 | if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) || | |||
1151 | Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) | |||
1152 | return ContinuationIndent; | |||
1153 | if (PreviousNonComment && PreviousNonComment->is(tok::colon) && | |||
1154 | PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) | |||
1155 | return ContinuationIndent; | |||
1156 | if (NextNonComment->is(TT_CtorInitializerComma)) | |||
1157 | return State.Stack.back().Indent; | |||
1158 | if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) && | |||
1159 | Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) | |||
1160 | return State.Stack.back().Indent; | |||
1161 | if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) && | |||
1162 | Style.BreakInheritanceList == FormatStyle::BILS_AfterColon) | |||
1163 | return State.Stack.back().Indent; | |||
1164 | if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon, | |||
1165 | TT_InheritanceComma)) | |||
1166 | return State.FirstIndent + Style.ConstructorInitializerIndentWidth; | |||
1167 | if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() && | |||
1168 | !Current.isOneOf(tok::colon, tok::comment)) | |||
1169 | return ContinuationIndent; | |||
1170 | if (Current.is(TT_ProtoExtensionLSquare)) | |||
1171 | return State.Stack.back().Indent; | |||
1172 | if (Current.isBinaryOperator() && State.Stack.back().UnindentOperator) | |||
1173 | return State.Stack.back().Indent - Current.Tok.getLength() - | |||
1174 | Current.SpacesRequiredBefore; | |||
1175 | if (Current.isOneOf(tok::comment, TT_BlockComment, TT_LineComment) && | |||
1176 | NextNonComment->isBinaryOperator() && State.Stack.back().UnindentOperator) | |||
1177 | return State.Stack.back().Indent - NextNonComment->Tok.getLength() - | |||
1178 | NextNonComment->SpacesRequiredBefore; | |||
1179 | if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment && | |||
1180 | !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) | |||
1181 | // Ensure that we fall back to the continuation indent width instead of | |||
1182 | // just flushing continuations left. | |||
1183 | return State.Stack.back().Indent + Style.ContinuationIndentWidth; | |||
1184 | return State.Stack.back().Indent; | |||
1185 | } | |||
1186 | ||||
1187 | static bool hasNestedBlockInlined(const FormatToken *Previous, | |||
1188 | const FormatToken &Current, | |||
1189 | const FormatStyle &Style) { | |||
1190 | if (Previous->isNot(tok::l_paren)) | |||
1191 | return true; | |||
1192 | if (Previous->ParameterCount > 1) | |||
1193 | return true; | |||
1194 | ||||
1195 | // Also a nested block if contains a lambda inside function with 1 parameter | |||
1196 | return (Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare)); | |||
1197 | } | |||
1198 | ||||
1199 | unsigned ContinuationIndenter::moveStateToNextToken(LineState &State, | |||
1200 | bool DryRun, bool Newline) { | |||
1201 | assert(State.Stack.size())(static_cast <bool> (State.Stack.size()) ? void (0) : __assert_fail ("State.Stack.size()", "clang/lib/Format/ContinuationIndenter.cpp" , 1201, __extension__ __PRETTY_FUNCTION__)); | |||
1202 | const FormatToken &Current = *State.NextToken; | |||
1203 | ||||
1204 | if (Current.is(TT_CSharpGenericTypeConstraint)) | |||
1205 | State.Stack.back().IsCSharpGenericTypeConstraint = true; | |||
1206 | if (Current.isOneOf(tok::comma, TT_BinaryOperator)) | |||
1207 | State.Stack.back().NoLineBreakInOperand = false; | |||
1208 | if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon)) | |||
1209 | State.Stack.back().AvoidBinPacking = true; | |||
1210 | if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) { | |||
1211 | if (State.Stack.back().FirstLessLess == 0) | |||
1212 | State.Stack.back().FirstLessLess = State.Column; | |||
1213 | else | |||
1214 | State.Stack.back().LastOperatorWrapped = Newline; | |||
1215 | } | |||
1216 | if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) | |||
1217 | State.Stack.back().LastOperatorWrapped = Newline; | |||
1218 | if (Current.is(TT_ConditionalExpr) && Current.Previous && | |||
1219 | !Current.Previous->is(TT_ConditionalExpr)) | |||
1220 | State.Stack.back().LastOperatorWrapped = Newline; | |||
1221 | if (Current.is(TT_ArraySubscriptLSquare) && | |||
1222 | State.Stack.back().StartOfArraySubscripts == 0) | |||
1223 | State.Stack.back().StartOfArraySubscripts = State.Column; | |||
1224 | if (Current.is(TT_ConditionalExpr) && Current.is(tok::question) && | |||
1225 | ((Current.MustBreakBefore) || | |||
1226 | (Current.getNextNonComment() && | |||
1227 | Current.getNextNonComment()->MustBreakBefore))) | |||
1228 | State.Stack.back().IsWrappedConditional = true; | |||
1229 | if (Style.BreakBeforeTernaryOperators && Current.is(tok::question)) | |||
1230 | State.Stack.back().QuestionColumn = State.Column; | |||
1231 | if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) { | |||
1232 | const FormatToken *Previous = Current.Previous; | |||
1233 | while (Previous && Previous->isTrailingComment()) | |||
1234 | Previous = Previous->Previous; | |||
1235 | if (Previous && Previous->is(tok::question)) | |||
1236 | State.Stack.back().QuestionColumn = State.Column; | |||
1237 | } | |||
1238 | if (!Current.opensScope() && !Current.closesScope() && | |||
1239 | !Current.is(TT_PointerOrReference)) | |||
1240 | State.LowestLevelOnLine = | |||
1241 | std::min(State.LowestLevelOnLine, Current.NestingLevel); | |||
1242 | if (Current.isMemberAccess()) | |||
1243 | State.Stack.back().StartOfFunctionCall = | |||
1244 | !Current.NextOperator ? 0 : State.Column; | |||
1245 | if (Current.is(TT_SelectorName)) | |||
1246 | State.Stack.back().ObjCSelectorNameFound = true; | |||
1247 | if (Current.is(TT_CtorInitializerColon) && | |||
1248 | Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) { | |||
1249 | // Indent 2 from the column, so: | |||
1250 | // SomeClass::SomeClass() | |||
1251 | // : First(...), ... | |||
1252 | // Next(...) | |||
1253 | // ^ line up here. | |||
1254 | State.Stack.back().Indent = | |||
1255 | State.Column + | |||
1256 | (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma | |||
1257 | ? 0 | |||
1258 | : 2); | |||
1259 | State.Stack.back().NestedBlockIndent = State.Stack.back().Indent; | |||
1260 | if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack) { | |||
1261 | State.Stack.back().AvoidBinPacking = true; | |||
1262 | State.Stack.back().BreakBeforeParameter = | |||
1263 | Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine; | |||
1264 | } else { | |||
1265 | State.Stack.back().BreakBeforeParameter = false; | |||
1266 | } | |||
1267 | } | |||
1268 | if (Current.is(TT_CtorInitializerColon) && | |||
1269 | Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) { | |||
1270 | State.Stack.back().Indent = | |||
1271 | State.FirstIndent + Style.ConstructorInitializerIndentWidth; | |||
1272 | State.Stack.back().NestedBlockIndent = State.Stack.back().Indent; | |||
1273 | if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack) | |||
1274 | State.Stack.back().AvoidBinPacking = true; | |||
1275 | } | |||
1276 | if (Current.is(TT_InheritanceColon)) | |||
1277 | State.Stack.back().Indent = | |||
1278 | State.FirstIndent + Style.ConstructorInitializerIndentWidth; | |||
1279 | if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline) | |||
1280 | State.Stack.back().NestedBlockIndent = | |||
1281 | State.Column + Current.ColumnWidth + 1; | |||
1282 | if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow)) | |||
1283 | State.Stack.back().LastSpace = State.Column; | |||
1284 | ||||
1285 | // Insert scopes created by fake parenthesis. | |||
1286 | const FormatToken *Previous = Current.getPreviousNonComment(); | |||
1287 | ||||
1288 | // Add special behavior to support a format commonly used for JavaScript | |||
1289 | // closures: | |||
1290 | // SomeFunction(function() { | |||
1291 | // foo(); | |||
1292 | // bar(); | |||
1293 | // }, a, b, c); | |||
1294 | if (Current.isNot(tok::comment) && Previous && | |||
1295 | Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) && | |||
1296 | !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 && | |||
1297 | !State.Stack.back().HasMultipleNestedBlocks) { | |||
1298 | if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline) | |||
1299 | for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) | |||
1300 | State.Stack[i].NoLineBreak = true; | |||
1301 | State.Stack[State.Stack.size() - 2].NestedBlockInlined = false; | |||
1302 | } | |||
1303 | if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) || | |||
1304 | (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) && | |||
1305 | !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))) { | |||
1306 | State.Stack.back().NestedBlockInlined = | |||
1307 | !Newline && hasNestedBlockInlined(Previous, Current, Style); | |||
1308 | } | |||
1309 | ||||
1310 | moveStatePastFakeLParens(State, Newline); | |||
1311 | moveStatePastScopeCloser(State); | |||
1312 | bool AllowBreak = !State.Stack.back().NoLineBreak && | |||
1313 | !State.Stack.back().NoLineBreakInOperand; | |||
1314 | moveStatePastScopeOpener(State, Newline); | |||
1315 | moveStatePastFakeRParens(State); | |||
1316 | ||||
1317 | if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0) | |||
1318 | State.StartOfStringLiteral = State.Column + 1; | |||
1319 | if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) | |||
1320 | State.StartOfStringLiteral = State.Column + 1; | |||
1321 | else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) | |||
1322 | State.StartOfStringLiteral = State.Column; | |||
1323 | else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) && | |||
1324 | !Current.isStringLiteral()) | |||
1325 | State.StartOfStringLiteral = 0; | |||
1326 | ||||
1327 | State.Column += Current.ColumnWidth; | |||
1328 | State.NextToken = State.NextToken->Next; | |||
1329 | ||||
1330 | unsigned Penalty = | |||
1331 | handleEndOfLine(Current, State, DryRun, AllowBreak, Newline); | |||
1332 | ||||
1333 | if (Current.Role) | |||
1334 | Current.Role->formatFromToken(State, this, DryRun); | |||
1335 | // If the previous has a special role, let it consume tokens as appropriate. | |||
1336 | // It is necessary to start at the previous token for the only implemented | |||
1337 | // role (comma separated list). That way, the decision whether or not to break | |||
1338 | // after the "{" is already done and both options are tried and evaluated. | |||
1339 | // FIXME: This is ugly, find a better way. | |||
1340 | if (Previous && Previous->Role) | |||
1341 | Penalty += Previous->Role->formatAfterToken(State, this, DryRun); | |||
1342 | ||||
1343 | return Penalty; | |||
1344 | } | |||
1345 | ||||
1346 | void ContinuationIndenter::moveStatePastFakeLParens(LineState &State, | |||
1347 | bool Newline) { | |||
1348 | const FormatToken &Current = *State.NextToken; | |||
1349 | if (Current.FakeLParens.empty()) | |||
1350 | return; | |||
1351 | ||||
1352 | const FormatToken *Previous = Current.getPreviousNonComment(); | |||
1353 | ||||
1354 | // Don't add extra indentation for the first fake parenthesis after | |||
1355 | // 'return', assignments or opening <({[. The indentation for these cases | |||
1356 | // is special cased. | |||
1357 | bool SkipFirstExtraIndent = | |||
1358 | (Previous && (Previous->opensScope() || | |||
1359 | Previous->isOneOf(tok::semi, tok::kw_return) || | |||
1360 | (Previous->getPrecedence() == prec::Assignment && | |||
1361 | Style.AlignOperands != FormatStyle::OAS_DontAlign) || | |||
1362 | Previous->is(TT_ObjCMethodExpr))); | |||
1363 | for (const auto &PrecedenceLevel : llvm::reverse(Current.FakeLParens)) { | |||
1364 | ParenState NewParenState = State.Stack.back(); | |||
1365 | NewParenState.Tok = nullptr; | |||
1366 | NewParenState.ContainsLineBreak = false; | |||
1367 | NewParenState.LastOperatorWrapped = true; | |||
1368 | NewParenState.IsChainedConditional = false; | |||
1369 | NewParenState.IsWrappedConditional = false; | |||
1370 | NewParenState.UnindentOperator = false; | |||
1371 | NewParenState.NoLineBreak = | |||
1372 | NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand; | |||
1373 | ||||
1374 | // Don't propagate AvoidBinPacking into subexpressions of arg/param lists. | |||
1375 | if (PrecedenceLevel > prec::Comma) | |||
1376 | NewParenState.AvoidBinPacking = false; | |||
1377 | ||||
1378 | // Indent from 'LastSpace' unless these are fake parentheses encapsulating | |||
1379 | // a builder type call after 'return' or, if the alignment after opening | |||
1380 | // brackets is disabled. | |||
1381 | if (!Current.isTrailingComment() && | |||
1382 | (Style.AlignOperands != FormatStyle::OAS_DontAlign || | |||
1383 | PrecedenceLevel < prec::Assignment) && | |||
1384 | (!Previous || Previous->isNot(tok::kw_return) || | |||
1385 | (Style.Language != FormatStyle::LK_Java && PrecedenceLevel > 0)) && | |||
1386 | (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign || | |||
1387 | PrecedenceLevel != prec::Comma || Current.NestingLevel == 0)) { | |||
1388 | NewParenState.Indent = | |||
1389 | std::max(std::max(State.Column, NewParenState.Indent), | |||
1390 | State.Stack.back().LastSpace); | |||
1391 | } | |||
1392 | ||||
1393 | if (Previous && | |||
1394 | (Previous->getPrecedence() == prec::Assignment || | |||
1395 | Previous->is(tok::kw_return) || | |||
1396 | (PrecedenceLevel == prec::Conditional && Previous->is(tok::question) && | |||
1397 | Previous->is(TT_ConditionalExpr))) && | |||
1398 | !Newline) { | |||
1399 | // If BreakBeforeBinaryOperators is set, un-indent a bit to account for | |||
1400 | // the operator and keep the operands aligned | |||
1401 | if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator) | |||
1402 | NewParenState.UnindentOperator = true; | |||
1403 | // Mark indentation as alignment if the expression is aligned. | |||
1404 | if (Style.AlignOperands != FormatStyle::OAS_DontAlign) | |||
1405 | NewParenState.IsAligned = true; | |||
1406 | } | |||
1407 | ||||
1408 | // Do not indent relative to the fake parentheses inserted for "." or "->". | |||
1409 | // This is a special case to make the following to statements consistent: | |||
1410 | // OuterFunction(InnerFunctionCall( // break | |||
1411 | // ParameterToInnerFunction)); | |||
1412 | // OuterFunction(SomeObject.InnerFunctionCall( // break | |||
1413 | // ParameterToInnerFunction)); | |||
1414 | if (PrecedenceLevel > prec::Unknown) | |||
1415 | NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column); | |||
1416 | if (PrecedenceLevel != prec::Conditional && !Current.is(TT_UnaryOperator) && | |||
1417 | Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) | |||
1418 | NewParenState.StartOfFunctionCall = State.Column; | |||
1419 | ||||
1420 | // Indent conditional expressions, unless they are chained "else-if" | |||
1421 | // conditionals. Never indent expression where the 'operator' is ',', ';' or | |||
1422 | // an assignment (i.e. *I <= prec::Assignment) as those have different | |||
1423 | // indentation rules. Indent other expression, unless the indentation needs | |||
1424 | // to be skipped. | |||
1425 | if (PrecedenceLevel == prec::Conditional && Previous && | |||
1426 | Previous->is(tok::colon) && Previous->is(TT_ConditionalExpr) && | |||
1427 | &PrecedenceLevel == &Current.FakeLParens.back() && | |||
1428 | !State.Stack.back().IsWrappedConditional) { | |||
1429 | NewParenState.IsChainedConditional = true; | |||
1430 | NewParenState.UnindentOperator = State.Stack.back().UnindentOperator; | |||
1431 | } else if (PrecedenceLevel == prec::Conditional || | |||
1432 | (!SkipFirstExtraIndent && PrecedenceLevel > prec::Assignment && | |||
1433 | !Current.isTrailingComment())) { | |||
1434 | NewParenState.Indent += Style.ContinuationIndentWidth; | |||
1435 | } | |||
1436 | if ((Previous && !Previous->opensScope()) || PrecedenceLevel != prec::Comma) | |||
1437 | NewParenState.BreakBeforeParameter = false; | |||
1438 | State.Stack.push_back(NewParenState); | |||
1439 | SkipFirstExtraIndent = false; | |||
1440 | } | |||
1441 | } | |||
1442 | ||||
1443 | void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) { | |||
1444 | for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) { | |||
1445 | unsigned VariablePos = State.Stack.back().VariablePos; | |||
1446 | if (State.Stack.size() == 1) { | |||
1447 | // Do not pop the last element. | |||
1448 | break; | |||
1449 | } | |||
1450 | State.Stack.pop_back(); | |||
1451 | State.Stack.back().VariablePos = VariablePos; | |||
1452 | } | |||
1453 | } | |||
1454 | ||||
1455 | void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, | |||
1456 | bool Newline) { | |||
1457 | const FormatToken &Current = *State.NextToken; | |||
1458 | if (!Current.opensScope()) | |||
1459 | return; | |||
1460 | ||||
1461 | // Don't allow '<' or '(' in C# generic type constraints to start new scopes. | |||
1462 | if (Current.isOneOf(tok::less, tok::l_paren) && | |||
1463 | State.Stack.back().IsCSharpGenericTypeConstraint) | |||
1464 | return; | |||
1465 | ||||
1466 | if (Current.MatchingParen && Current.is(BK_Block)) { | |||
1467 | moveStateToNewBlock(State); | |||
1468 | return; | |||
1469 | } | |||
1470 | ||||
1471 | unsigned NewIndent; | |||
1472 | unsigned LastSpace = State.Stack.back().LastSpace; | |||
1473 | bool AvoidBinPacking; | |||
1474 | bool BreakBeforeParameter = false; | |||
1475 | unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall, | |||
1476 | State.Stack.back().NestedBlockIndent); | |||
1477 | if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || | |||
1478 | opensProtoMessageField(Current, Style)) { | |||
1479 | if (Current.opensBlockOrBlockTypeList(Style)) { | |||
1480 | NewIndent = Style.IndentWidth + | |||
1481 | std::min(State.Column, State.Stack.back().NestedBlockIndent); | |||
1482 | } else { | |||
1483 | NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth; | |||
1484 | } | |||
1485 | const FormatToken *NextNoComment = Current.getNextNonComment(); | |||
1486 | bool EndsInComma = Current.MatchingParen && | |||
1487 | Current.MatchingParen->Previous && | |||
1488 | Current.MatchingParen->Previous->is(tok::comma); | |||
1489 | AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) || | |||
1490 | Style.Language == FormatStyle::LK_Proto || | |||
1491 | Style.Language == FormatStyle::LK_TextProto || | |||
1492 | !Style.BinPackArguments || | |||
1493 | (NextNoComment && | |||
1494 | NextNoComment->isOneOf(TT_DesignatedInitializerPeriod, | |||
1495 | TT_DesignatedInitializerLSquare)); | |||
1496 | BreakBeforeParameter = EndsInComma; | |||
1497 | if (Current.ParameterCount > 1) | |||
1498 | NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1); | |||
1499 | } else { | |||
1500 | NewIndent = Style.ContinuationIndentWidth + | |||
1501 | std::max(State.Stack.back().LastSpace, | |||
1502 | State.Stack.back().StartOfFunctionCall); | |||
1503 | ||||
1504 | // Ensure that different different brackets force relative alignment, e.g.: | |||
1505 | // void SomeFunction(vector< // break | |||
1506 | // int> v); | |||
1507 | // FIXME: We likely want to do this for more combinations of brackets. | |||
1508 | if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) { | |||
1509 | NewIndent = std::max(NewIndent, State.Stack.back().Indent); | |||
1510 | LastSpace = std::max(LastSpace, State.Stack.back().Indent); | |||
1511 | } | |||
1512 | ||||
1513 | bool EndsInComma = | |||
1514 | Current.MatchingParen && | |||
1515 | Current.MatchingParen->getPreviousNonComment() && | |||
1516 | Current.MatchingParen->getPreviousNonComment()->is(tok::comma); | |||
1517 | ||||
1518 | // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters | |||
1519 | // for backwards compatibility. | |||
1520 | bool ObjCBinPackProtocolList = | |||
1521 | (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto && | |||
1522 | Style.BinPackParameters) || | |||
1523 | Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always; | |||
1524 | ||||
1525 | bool BinPackDeclaration = | |||
1526 | (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) || | |||
1527 | (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList); | |||
1528 | ||||
1529 | AvoidBinPacking = | |||
1530 | (State.Stack.back().IsCSharpGenericTypeConstraint) || | |||
1531 | (Style.isJavaScript() && EndsInComma) || | |||
1532 | (State.Line->MustBeDeclaration && !BinPackDeclaration) || | |||
1533 | (!State.Line->MustBeDeclaration && !Style.BinPackArguments) || | |||
1534 | (Style.ExperimentalAutoDetectBinPacking && | |||
1535 | (Current.is(PPK_OnePerLine) || | |||
1536 | (!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive)))); | |||
1537 | ||||
1538 | if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen && | |||
1539 | Style.ObjCBreakBeforeNestedBlockParam) { | |||
1540 | if (Style.ColumnLimit) { | |||
1541 | // If this '[' opens an ObjC call, determine whether all parameters fit | |||
1542 | // into one line and put one per line if they don't. | |||
1543 | if (getLengthToMatchingParen(Current, State.Stack) + State.Column > | |||
1544 | getColumnLimit(State)) | |||
1545 | BreakBeforeParameter = true; | |||
1546 | } else { | |||
1547 | // For ColumnLimit = 0, we have to figure out whether there is or has to | |||
1548 | // be a line break within this call. | |||
1549 | for (const FormatToken *Tok = &Current; | |||
1550 | Tok && Tok != Current.MatchingParen; Tok = Tok->Next) { | |||
1551 | if (Tok->MustBreakBefore || | |||
1552 | (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) { | |||
1553 | BreakBeforeParameter = true; | |||
1554 | break; | |||
1555 | } | |||
1556 | } | |||
1557 | } | |||
1558 | } | |||
1559 | ||||
1560 | if (Style.isJavaScript() && EndsInComma) | |||
1561 | BreakBeforeParameter = true; | |||
1562 | } | |||
1563 | // Generally inherit NoLineBreak from the current scope to nested scope. | |||
1564 | // However, don't do this for non-empty nested blocks, dict literals and | |||
1565 | // array literals as these follow different indentation rules. | |||
1566 | bool NoLineBreak = | |||
1567 | Current.Children.empty() && | |||
1568 | !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) && | |||
1569 | (State.Stack.back().NoLineBreak || | |||
1570 | State.Stack.back().NoLineBreakInOperand || | |||
1571 | (Current.is(TT_TemplateOpener) && | |||
1572 | State.Stack.back().ContainsUnwrappedBuilder)); | |||
1573 | State.Stack.push_back( | |||
1574 | ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak)); | |||
1575 | State.Stack.back().NestedBlockIndent = NestedBlockIndent; | |||
1576 | State.Stack.back().BreakBeforeParameter = BreakBeforeParameter; | |||
1577 | State.Stack.back().HasMultipleNestedBlocks = | |||
1578 | (Current.BlockParameterCount > 1); | |||
1579 | ||||
1580 | if (Style.BraceWrapping.BeforeLambdaBody && Current.Next != nullptr && | |||
1581 | Current.Tok.is(tok::l_paren)) { | |||
1582 | // Search for any parameter that is a lambda | |||
1583 | FormatToken const *next = Current.Next; | |||
1584 | while (next != nullptr) { | |||
1585 | if (next->is(TT_LambdaLSquare)) { | |||
1586 | State.Stack.back().HasMultipleNestedBlocks = true; | |||
1587 | break; | |||
1588 | } | |||
1589 | next = next->Next; | |||
1590 | } | |||
1591 | } | |||
1592 | ||||
1593 | State.Stack.back().IsInsideObjCArrayLiteral = | |||
1594 | Current.is(TT_ArrayInitializerLSquare) && Current.Previous && | |||
1595 | Current.Previous->is(tok::at); | |||
1596 | } | |||
1597 | ||||
1598 | void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) { | |||
1599 | const FormatToken &Current = *State.NextToken; | |||
1600 | if (!Current.closesScope()) | |||
1601 | return; | |||
1602 | ||||
1603 | // If we encounter a closing ), ], } or >, we can remove a level from our | |||
1604 | // stacks. | |||
1605 | if (State.Stack.size() > 1 && | |||
1606 | (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) || | |||
1607 | (Current.is(tok::r_brace) && State.NextToken != State.Line->First) || | |||
1608 | State.NextToken->is(TT_TemplateCloser) || | |||
1609 | (Current.is(tok::greater) && Current.is(TT_DictLiteral)))) | |||
1610 | State.Stack.pop_back(); | |||
1611 | ||||
1612 | // Reevaluate whether ObjC message arguments fit into one line. | |||
1613 | // If a receiver spans multiple lines, e.g.: | |||
1614 | // [[object block:^{ | |||
1615 | // return 42; | |||
1616 | // }] a:42 b:42]; | |||
1617 | // BreakBeforeParameter is calculated based on an incorrect assumption | |||
1618 | // (it is checked whether the whole expression fits into one line without | |||
1619 | // considering a line break inside a message receiver). | |||
1620 | // We check whether arguments fit after receiver scope closer (into the same | |||
1621 | // line). | |||
1622 | if (State.Stack.back().BreakBeforeParameter && Current.MatchingParen && | |||
1623 | Current.MatchingParen->Previous) { | |||
1624 | const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous; | |||
1625 | if (CurrentScopeOpener.is(TT_ObjCMethodExpr) && | |||
1626 | CurrentScopeOpener.MatchingParen) { | |||
1627 | int NecessarySpaceInLine = | |||
1628 | getLengthToMatchingParen(CurrentScopeOpener, State.Stack) + | |||
1629 | CurrentScopeOpener.TotalLength - Current.TotalLength - 1; | |||
1630 | if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <= | |||
1631 | Style.ColumnLimit) | |||
1632 | State.Stack.back().BreakBeforeParameter = false; | |||
1633 | } | |||
1634 | } | |||
1635 | ||||
1636 | if (Current.is(tok::r_square)) { | |||
1637 | // If this ends the array subscript expr, reset the corresponding value. | |||
1638 | const FormatToken *NextNonComment = Current.getNextNonComment(); | |||
1639 | if (NextNonComment && NextNonComment->isNot(tok::l_square)) | |||
1640 | State.Stack.back().StartOfArraySubscripts = 0; | |||
1641 | } | |||
1642 | } | |||
1643 | ||||
1644 | void ContinuationIndenter::moveStateToNewBlock(LineState &State) { | |||
1645 | unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent; | |||
1646 | // ObjC block sometimes follow special indentation rules. | |||
1647 | unsigned NewIndent = | |||
1648 | NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace) | |||
1649 | ? Style.ObjCBlockIndentWidth | |||
1650 | : Style.IndentWidth); | |||
1651 | State.Stack.push_back(ParenState(State.NextToken, NewIndent, | |||
1652 | State.Stack.back().LastSpace, | |||
1653 | /*AvoidBinPacking=*/true, | |||
1654 | /*NoLineBreak=*/false)); | |||
1655 | State.Stack.back().NestedBlockIndent = NestedBlockIndent; | |||
1656 | State.Stack.back().BreakBeforeParameter = true; | |||
1657 | } | |||
1658 | ||||
1659 | static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn, | |||
1660 | unsigned TabWidth, | |||
1661 | encoding::Encoding Encoding) { | |||
1662 | size_t LastNewlinePos = Text.find_last_of("\n"); | |||
1663 | if (LastNewlinePos == StringRef::npos) { | |||
1664 | return StartColumn + | |||
1665 | encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding); | |||
1666 | } else { | |||
1667 | return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos), | |||
1668 | /*StartColumn=*/0, TabWidth, Encoding); | |||
1669 | } | |||
1670 | } | |||
1671 | ||||
1672 | unsigned ContinuationIndenter::reformatRawStringLiteral( | |||
1673 | const FormatToken &Current, LineState &State, | |||
1674 | const FormatStyle &RawStringStyle, bool DryRun, bool Newline) { | |||
1675 | unsigned StartColumn = State.Column - Current.ColumnWidth; | |||
1676 | StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText); | |||
1677 | StringRef NewDelimiter = | |||
1678 | getCanonicalRawStringDelimiter(Style, RawStringStyle.Language); | |||
1679 | if (NewDelimiter.empty()) | |||
1680 | NewDelimiter = OldDelimiter; | |||
1681 | // The text of a raw string is between the leading 'R"delimiter(' and the | |||
1682 | // trailing 'delimiter)"'. | |||
1683 | unsigned OldPrefixSize = 3 + OldDelimiter.size(); | |||
1684 | unsigned OldSuffixSize = 2 + OldDelimiter.size(); | |||
1685 | // We create a virtual text environment which expects a null-terminated | |||
1686 | // string, so we cannot use StringRef. | |||
1687 | std::string RawText = std::string( | |||
1688 | Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize)); | |||
1689 | if (NewDelimiter != OldDelimiter) { | |||
1690 | // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the | |||
1691 | // raw string. | |||
1692 | std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str(); | |||
1693 | if (StringRef(RawText).contains(CanonicalDelimiterSuffix)) | |||
1694 | NewDelimiter = OldDelimiter; | |||
1695 | } | |||
1696 | ||||
1697 | unsigned NewPrefixSize = 3 + NewDelimiter.size(); | |||
1698 | unsigned NewSuffixSize = 2 + NewDelimiter.size(); | |||
1699 | ||||
1700 | // The first start column is the column the raw text starts after formatting. | |||
1701 | unsigned FirstStartColumn = StartColumn + NewPrefixSize; | |||
1702 | ||||
1703 | // The next start column is the intended indentation a line break inside | |||
1704 | // the raw string at level 0. It is determined by the following rules: | |||
1705 | // - if the content starts on newline, it is one level more than the current | |||
1706 | // indent, and | |||
1707 | // - if the content does not start on a newline, it is the first start | |||
1708 | // column. | |||
1709 | // These rules have the advantage that the formatted content both does not | |||
1710 | // violate the rectangle rule and visually flows within the surrounding | |||
1711 | // source. | |||
1712 | bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n'; | |||
1713 | // If this token is the last parameter (checked by looking if it's followed by | |||
1714 | // `)` and is not on a newline, the base the indent off the line's nested | |||
1715 | // block indent. Otherwise, base the indent off the arguments indent, so we | |||
1716 | // can achieve: | |||
1717 | // | |||
1718 | // fffffffffff(1, 2, 3, R"pb( | |||
1719 | // key1: 1 # | |||
1720 | // key2: 2)pb"); | |||
1721 | // | |||
1722 | // fffffffffff(1, 2, 3, | |||
1723 | // R"pb( | |||
1724 | // key1: 1 # | |||
1725 | // key2: 2 | |||
1726 | // )pb"); | |||
1727 | // | |||
1728 | // fffffffffff(1, 2, 3, | |||
1729 | // R"pb( | |||
1730 | // key1: 1 # | |||
1731 | // key2: 2 | |||
1732 | // )pb", | |||
1733 | // 5); | |||
1734 | unsigned CurrentIndent = | |||
1735 | (!Newline && Current.Next && Current.Next->is(tok::r_paren)) | |||
1736 | ? State.Stack.back().NestedBlockIndent | |||
1737 | : State.Stack.back().Indent; | |||
1738 | unsigned NextStartColumn = ContentStartsOnNewline | |||
1739 | ? CurrentIndent + Style.IndentWidth | |||
1740 | : FirstStartColumn; | |||
1741 | ||||
1742 | // The last start column is the column the raw string suffix starts if it is | |||
1743 | // put on a newline. | |||
1744 | // The last start column is the intended indentation of the raw string postfix | |||
1745 | // if it is put on a newline. It is determined by the following rules: | |||
1746 | // - if the raw string prefix starts on a newline, it is the column where | |||
1747 | // that raw string prefix starts, and | |||
1748 | // - if the raw string prefix does not start on a newline, it is the current | |||
1749 | // indent. | |||
1750 | unsigned LastStartColumn = | |||
1751 | Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent; | |||
1752 | ||||
1753 | std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat( | |||
1754 | RawStringStyle, RawText, {tooling::Range(0, RawText.size())}, | |||
1755 | FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>", | |||
1756 | /*Status=*/nullptr); | |||
1757 | ||||
1758 | auto NewCode = applyAllReplacements(RawText, Fixes.first); | |||
1759 | tooling::Replacements NoFixes; | |||
1760 | if (!NewCode) { | |||
1761 | return addMultilineToken(Current, State); | |||
1762 | } | |||
1763 | if (!DryRun) { | |||
1764 | if (NewDelimiter != OldDelimiter) { | |||
1765 | // In 'R"delimiter(...', the delimiter starts 2 characters after the start | |||
1766 | // of the token. | |||
1767 | SourceLocation PrefixDelimiterStart = | |||
1768 | Current.Tok.getLocation().getLocWithOffset(2); | |||
1769 | auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement( | |||
1770 | SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter)); | |||
1771 | if (PrefixErr) { | |||
1772 | llvm::errs() | |||
1773 | << "Failed to update the prefix delimiter of a raw string: " | |||
1774 | << llvm::toString(std::move(PrefixErr)) << "\n"; | |||
1775 | } | |||
1776 | // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at | |||
1777 | // position length - 1 - |delimiter|. | |||
1778 | SourceLocation SuffixDelimiterStart = | |||
1779 | Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() - | |||
1780 | 1 - OldDelimiter.size()); | |||
1781 | auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement( | |||
1782 | SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter)); | |||
1783 | if (SuffixErr) { | |||
1784 | llvm::errs() | |||
1785 | << "Failed to update the suffix delimiter of a raw string: " | |||
1786 | << llvm::toString(std::move(SuffixErr)) << "\n"; | |||
1787 | } | |||
1788 | } | |||
1789 | SourceLocation OriginLoc = | |||
1790 | Current.Tok.getLocation().getLocWithOffset(OldPrefixSize); | |||
1791 | for (const tooling::Replacement &Fix : Fixes.first) { | |||
1792 | auto Err = Whitespaces.addReplacement(tooling::Replacement( | |||
1793 | SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()), | |||
1794 | Fix.getLength(), Fix.getReplacementText())); | |||
1795 | if (Err) { | |||
1796 | llvm::errs() << "Failed to reformat raw string: " | |||
1797 | << llvm::toString(std::move(Err)) << "\n"; | |||
1798 | } | |||
1799 | } | |||
1800 | } | |||
1801 | unsigned RawLastLineEndColumn = getLastLineEndColumn( | |||
1802 | *NewCode, FirstStartColumn, Style.TabWidth, Encoding); | |||
1803 | State.Column = RawLastLineEndColumn + NewSuffixSize; | |||
1804 | // Since we're updating the column to after the raw string literal here, we | |||
1805 | // have to manually add the penalty for the prefix R"delim( over the column | |||
1806 | // limit. | |||
1807 | unsigned PrefixExcessCharacters = | |||
1808 | StartColumn + NewPrefixSize > Style.ColumnLimit | |||
1809 | ? StartColumn + NewPrefixSize - Style.ColumnLimit | |||
1810 | : 0; | |||
1811 | bool IsMultiline = | |||
1812 | ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos); | |||
1813 | if (IsMultiline) { | |||
1814 | // Break before further function parameters on all levels. | |||
1815 | for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) | |||
1816 | State.Stack[i].BreakBeforeParameter = true; | |||
1817 | } | |||
1818 | return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter; | |||
1819 | } | |||
1820 | ||||
1821 | unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current, | |||
1822 | LineState &State) { | |||
1823 | // Break before further function parameters on all levels. | |||
1824 | for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) | |||
1825 | State.Stack[i].BreakBeforeParameter = true; | |||
1826 | ||||
1827 | unsigned ColumnsUsed = State.Column; | |||
1828 | // We can only affect layout of the first and the last line, so the penalty | |||
1829 | // for all other lines is constant, and we ignore it. | |||
1830 | State.Column = Current.LastLineColumnWidth; | |||
1831 | ||||
1832 | if (ColumnsUsed > getColumnLimit(State)) | |||
1833 | return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State)); | |||
1834 | return 0; | |||
1835 | } | |||
1836 | ||||
1837 | unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current, | |||
1838 | LineState &State, bool DryRun, | |||
1839 | bool AllowBreak, bool Newline) { | |||
1840 | unsigned Penalty = 0; | |||
1841 | // Compute the raw string style to use in case this is a raw string literal | |||
1842 | // that can be reformatted. | |||
1843 | auto RawStringStyle = getRawStringStyle(Current, State); | |||
1844 | if (RawStringStyle && !Current.Finalized) { | |||
1845 | Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun, | |||
1846 | Newline); | |||
1847 | } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) { | |||
1848 | // Don't break multi-line tokens other than block comments and raw string | |||
1849 | // literals. Instead, just update the state. | |||
1850 | Penalty = addMultilineToken(Current, State); | |||
1851 | } else if (State.Line->Type != LT_ImportStatement) { | |||
1852 | // We generally don't break import statements. | |||
1853 | LineState OriginalState = State; | |||
1854 | ||||
1855 | // Whether we force the reflowing algorithm to stay strictly within the | |||
1856 | // column limit. | |||
1857 | bool Strict = false; | |||
1858 | // Whether the first non-strict attempt at reflowing did intentionally | |||
1859 | // exceed the column limit. | |||
1860 | bool Exceeded = false; | |||
1861 | std::tie(Penalty, Exceeded) = breakProtrudingToken( | |||
1862 | Current, State, AllowBreak, /*DryRun=*/true, Strict); | |||
1863 | if (Exceeded) { | |||
1864 | // If non-strict reflowing exceeds the column limit, try whether strict | |||
1865 | // reflowing leads to an overall lower penalty. | |||
1866 | LineState StrictState = OriginalState; | |||
1867 | unsigned StrictPenalty = | |||
1868 | breakProtrudingToken(Current, StrictState, AllowBreak, | |||
1869 | /*DryRun=*/true, /*Strict=*/true) | |||
1870 | .first; | |||
1871 | Strict = StrictPenalty <= Penalty; | |||
1872 | if (Strict) { | |||
1873 | Penalty = StrictPenalty; | |||
1874 | State = StrictState; | |||
1875 | } | |||
1876 | } | |||
1877 | if (!DryRun) { | |||
1878 | // If we're not in dry-run mode, apply the changes with the decision on | |||
1879 | // strictness made above. | |||
1880 | breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false, | |||
1881 | Strict); | |||
1882 | } | |||
1883 | } | |||
1884 | if (State.Column > getColumnLimit(State)) { | |||
1885 | unsigned ExcessCharacters = State.Column - getColumnLimit(State); | |||
1886 | Penalty += Style.PenaltyExcessCharacter * ExcessCharacters; | |||
1887 | } | |||
1888 | return Penalty; | |||
1889 | } | |||
1890 | ||||
1891 | // Returns the enclosing function name of a token, or the empty string if not | |||
1892 | // found. | |||
1893 | static StringRef getEnclosingFunctionName(const FormatToken &Current) { | |||
1894 | // Look for: 'function(' or 'function<templates>(' before Current. | |||
1895 | auto Tok = Current.getPreviousNonComment(); | |||
1896 | if (!Tok || !Tok->is(tok::l_paren)) | |||
1897 | return ""; | |||
1898 | Tok = Tok->getPreviousNonComment(); | |||
1899 | if (!Tok) | |||
1900 | return ""; | |||
1901 | if (Tok->is(TT_TemplateCloser)) { | |||
1902 | Tok = Tok->MatchingParen; | |||
1903 | if (Tok) | |||
1904 | Tok = Tok->getPreviousNonComment(); | |||
1905 | } | |||
1906 | if (!Tok || !Tok->is(tok::identifier)) | |||
1907 | return ""; | |||
1908 | return Tok->TokenText; | |||
1909 | } | |||
1910 | ||||
1911 | llvm::Optional<FormatStyle> | |||
1912 | ContinuationIndenter::getRawStringStyle(const FormatToken &Current, | |||
1913 | const LineState &State) { | |||
1914 | if (!Current.isStringLiteral()) | |||
1915 | return None; | |||
1916 | auto Delimiter = getRawStringDelimiter(Current.TokenText); | |||
1917 | if (!Delimiter) | |||
1918 | return None; | |||
1919 | auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter); | |||
1920 | if (!RawStringStyle && Delimiter->empty()) | |||
1921 | RawStringStyle = RawStringFormats.getEnclosingFunctionStyle( | |||
1922 | getEnclosingFunctionName(Current)); | |||
1923 | if (!RawStringStyle) | |||
1924 | return None; | |||
1925 | RawStringStyle->ColumnLimit = getColumnLimit(State); | |||
1926 | return RawStringStyle; | |||
1927 | } | |||
1928 | ||||
1929 | std::unique_ptr<BreakableToken> | |||
1930 | ContinuationIndenter::createBreakableToken(const FormatToken &Current, | |||
1931 | LineState &State, bool AllowBreak) { | |||
1932 | unsigned StartColumn = State.Column - Current.ColumnWidth; | |||
1933 | if (Current.isStringLiteral()) { | |||
1934 | // FIXME: String literal breaking is currently disabled for C#, Java, Json | |||
1935 | // and JavaScript, as it requires strings to be merged using "+" which we | |||
1936 | // don't support. | |||
1937 | if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() || | |||
1938 | Style.isCSharp() || Style.isJson() || !Style.BreakStringLiterals || | |||
1939 | !AllowBreak) | |||
1940 | return nullptr; | |||
1941 | ||||
1942 | // Don't break string literals inside preprocessor directives (except for | |||
1943 | // #define directives, as their contents are stored in separate lines and | |||
1944 | // are not affected by this check). | |||
1945 | // This way we avoid breaking code with line directives and unknown | |||
1946 | // preprocessor directives that contain long string literals. | |||
1947 | if (State.Line->Type == LT_PreprocessorDirective) | |||
1948 | return nullptr; | |||
1949 | // Exempts unterminated string literals from line breaking. The user will | |||
1950 | // likely want to terminate the string before any line breaking is done. | |||
1951 | if (Current.IsUnterminatedLiteral) | |||
1952 | return nullptr; | |||
1953 | // Don't break string literals inside Objective-C array literals (doing so | |||
1954 | // raises the warning -Wobjc-string-concatenation). | |||
1955 | if (State.Stack.back().IsInsideObjCArrayLiteral) { | |||
1956 | return nullptr; | |||
1957 | } | |||
1958 | ||||
1959 | StringRef Text = Current.TokenText; | |||
1960 | StringRef Prefix; | |||
1961 | StringRef Postfix; | |||
1962 | // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'. | |||
1963 | // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to | |||
1964 | // reduce the overhead) for each FormatToken, which is a string, so that we | |||
1965 | // don't run multiple checks here on the hot path. | |||
1966 | if ((Text.endswith(Postfix = "\"") && | |||
1967 | (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") || | |||
1968 | Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") || | |||
1969 | Text.startswith(Prefix = "u8\"") || | |||
1970 | Text.startswith(Prefix = "L\""))) || | |||
1971 | (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) { | |||
1972 | // We need this to address the case where there is an unbreakable tail | |||
1973 | // only if certain other formatting decisions have been taken. The | |||
1974 | // UnbreakableTailLength of Current is an overapproximation is that case | |||
1975 | // and we need to be correct here. | |||
1976 | unsigned UnbreakableTailLength = (State.NextToken && canBreak(State)) | |||
1977 | ? 0 | |||
1978 | : Current.UnbreakableTailLength; | |||
1979 | return std::make_unique<BreakableStringLiteral>( | |||
1980 | Current, StartColumn, Prefix, Postfix, UnbreakableTailLength, | |||
1981 | State.Line->InPPDirective, Encoding, Style); | |||
1982 | } | |||
1983 | } else if (Current.is(TT_BlockComment)) { | |||
1984 | if (!Style.ReflowComments || | |||
1985 | // If a comment token switches formatting, like | |||
1986 | // /* clang-format on */, we don't want to break it further, | |||
1987 | // but we may still want to adjust its indentation. | |||
1988 | switchesFormatting(Current)) { | |||
1989 | return nullptr; | |||
1990 | } | |||
1991 | return std::make_unique<BreakableBlockComment>( | |||
1992 | Current, StartColumn, Current.OriginalColumn, !Current.Previous, | |||
1993 | State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF()); | |||
1994 | } else if (Current.is(TT_LineComment) && | |||
1995 | (Current.Previous == nullptr || | |||
1996 | Current.Previous->isNot(TT_ImplicitStringLiteral))) { | |||
1997 | bool RegularComments = [&]() { | |||
1998 | for (const FormatToken *T = &Current; T && T->is(TT_LineComment); | |||
1999 | T = T->Next) { | |||
2000 | if (!(T->TokenText.startswith("//") || T->TokenText.startswith("#"))) | |||
2001 | return false; | |||
2002 | } | |||
2003 | return true; | |||
2004 | }(); | |||
2005 | if (!Style.ReflowComments || | |||
2006 | CommentPragmasRegex.match(Current.TokenText.substr(2)) || | |||
2007 | switchesFormatting(Current) || !RegularComments) | |||
2008 | return nullptr; | |||
2009 | return std::make_unique<BreakableLineCommentSection>( | |||
2010 | Current, StartColumn, /*InPPDirective=*/false, Encoding, Style); | |||
2011 | } | |||
2012 | return nullptr; | |||
2013 | } | |||
2014 | ||||
2015 | std::pair<unsigned, bool> | |||
2016 | ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, | |||
2017 | LineState &State, bool AllowBreak, | |||
2018 | bool DryRun, bool Strict) { | |||
2019 | std::unique_ptr<const BreakableToken> Token = | |||
2020 | createBreakableToken(Current, State, AllowBreak); | |||
2021 | if (!Token) | |||
2022 | return {0, false}; | |||
2023 | assert(Token->getLineCount() > 0)(static_cast <bool> (Token->getLineCount() > 0) ? void (0) : __assert_fail ("Token->getLineCount() > 0", "clang/lib/Format/ContinuationIndenter.cpp", 2023, __extension__ __PRETTY_FUNCTION__)); | |||
2024 | unsigned ColumnLimit = getColumnLimit(State); | |||
2025 | if (Current.is(TT_LineComment)) { | |||
2026 | // We don't insert backslashes when breaking line comments. | |||
2027 | ColumnLimit = Style.ColumnLimit; | |||
2028 | } | |||
2029 | if (ColumnLimit == 0) { | |||
2030 | // To make the rest of the function easier set the column limit to the | |||
2031 | // maximum, if there should be no limit. | |||
2032 | ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max(); | |||
2033 | } | |||
2034 | if (Current.UnbreakableTailLength >= ColumnLimit) | |||
2035 | return {0, false}; | |||
2036 | // ColumnWidth was already accounted into State.Column before calling | |||
2037 | // breakProtrudingToken. | |||
2038 | unsigned StartColumn = State.Column - Current.ColumnWidth; | |||
2039 | unsigned NewBreakPenalty = Current.isStringLiteral() | |||
2040 | ? Style.PenaltyBreakString | |||
2041 | : Style.PenaltyBreakComment; | |||
2042 | // Stores whether we intentionally decide to let a line exceed the column | |||
2043 | // limit. | |||
2044 | bool Exceeded = false; | |||
2045 | // Stores whether we introduce a break anywhere in the token. | |||
2046 | bool BreakInserted = Token->introducesBreakBeforeToken(); | |||
2047 | // Store whether we inserted a new line break at the end of the previous | |||
2048 | // logical line. | |||
2049 | bool NewBreakBefore = false; | |||
2050 | // We use a conservative reflowing strategy. Reflow starts after a line is | |||
2051 | // broken or the corresponding whitespace compressed. Reflow ends as soon as a | |||
2052 | // line that doesn't get reflown with the previous line is reached. | |||
2053 | bool Reflow = false; | |||
2054 | // Keep track of where we are in the token: | |||
2055 | // Where we are in the content of the current logical line. | |||
2056 | unsigned TailOffset = 0; | |||
2057 | // The column number we're currently at. | |||
2058 | unsigned ContentStartColumn = | |||
2059 | Token->getContentStartColumn(0, /*Break=*/false); | |||
2060 | // The number of columns left in the current logical line after TailOffset. | |||
2061 | unsigned RemainingTokenColumns = | |||
2062 | Token->getRemainingLength(0, TailOffset, ContentStartColumn); | |||
2063 | // Adapt the start of the token, for example indent. | |||
2064 | if (!DryRun) | |||
2065 | Token->adaptStartOfLine(0, Whitespaces); | |||
2066 | ||||
2067 | unsigned ContentIndent = 0; | |||
2068 | unsigned Penalty = 0; | |||
2069 | LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << "Breaking protruding token at column " << StartColumn << ".\n"; } } while (false) | |||
2070 | << StartColumn << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << "Breaking protruding token at column " << StartColumn << ".\n"; } } while (false); | |||
2071 | for (unsigned LineIndex = 0, EndIndex = Token->getLineCount(); | |||
2072 | LineIndex != EndIndex; ++LineIndex) { | |||
2073 | LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n" ; } } while (false) | |||
2074 | << " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Line: " << LineIndex << " (Reflow: " << Reflow << ")\n" ; } } while (false); | |||
2075 | NewBreakBefore = false; | |||
2076 | // If we did reflow the previous line, we'll try reflowing again. Otherwise | |||
2077 | // we'll start reflowing if the current line is broken or whitespace is | |||
2078 | // compressed. | |||
2079 | bool TryReflow = Reflow; | |||
2080 | // Break the current token until we can fit the rest of the line. | |||
2081 | while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) { | |||
2082 | LLVM_DEBUG(llvm::dbgs() << " Over limit, need: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false) | |||
2083 | << (ContentStartColumn + RemainingTokenColumns)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false) | |||
2084 | << ", space: " << ColumnLimitdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false) | |||
2085 | << ", reflown prefix: " << ContentStartColumndo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false) | |||
2086 | << ", offset in line: " << TailOffset << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false); | |||
2087 | // If the current token doesn't fit, find the latest possible split in the | |||
2088 | // current line so that breaking at it will be under the column limit. | |||
2089 | // FIXME: Use the earliest possible split while reflowing to correctly | |||
2090 | // compress whitespace within a line. | |||
2091 | BreakableToken::Split Split = | |||
2092 | Token->getSplit(LineIndex, TailOffset, ColumnLimit, | |||
2093 | ContentStartColumn, CommentPragmasRegex); | |||
2094 | if (Split.first == StringRef::npos) { | |||
2095 | // No break opportunity - update the penalty and continue with the next | |||
2096 | // logical line. | |||
2097 | if (LineIndex < EndIndex - 1) | |||
2098 | // The last line's penalty is handled in addNextStateToQueue() or when | |||
2099 | // calling replaceWhitespaceAfterLastLine below. | |||
2100 | Penalty += Style.PenaltyExcessCharacter * | |||
2101 | (ContentStartColumn + RemainingTokenColumns - ColumnLimit); | |||
2102 | LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " No break opportunity.\n" ; } } while (false); | |||
2103 | break; | |||
2104 | } | |||
2105 | assert(Split.first != 0)(static_cast <bool> (Split.first != 0) ? void (0) : __assert_fail ("Split.first != 0", "clang/lib/Format/ContinuationIndenter.cpp" , 2105, __extension__ __PRETTY_FUNCTION__)); | |||
2106 | ||||
2107 | if (Token->supportsReflow()) { | |||
2108 | // Check whether the next natural split point after the current one can | |||
2109 | // still fit the line, either because we can compress away whitespace, | |||
2110 | // or because the penalty the excess characters introduce is lower than | |||
2111 | // the break penalty. | |||
2112 | // We only do this for tokens that support reflowing, and thus allow us | |||
2113 | // to change the whitespace arbitrarily (e.g. comments). | |||
2114 | // Other tokens, like string literals, can be broken on arbitrary | |||
2115 | // positions. | |||
2116 | ||||
2117 | // First, compute the columns from TailOffset to the next possible split | |||
2118 | // position. | |||
2119 | // For example: | |||
2120 | // ColumnLimit: | | |||
2121 | // // Some text that breaks | |||
2122 | // ^ tail offset | |||
2123 | // ^-- split | |||
2124 | // ^-------- to split columns | |||
2125 | // ^--- next split | |||
2126 | // ^--------------- to next split columns | |||
2127 | unsigned ToSplitColumns = Token->getRangeLength( | |||
2128 | LineIndex, TailOffset, Split.first, ContentStartColumn); | |||
2129 | LLVM_DEBUG(llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " ToSplit: " << ToSplitColumns << "\n"; } } while (false); | |||
2130 | ||||
2131 | BreakableToken::Split NextSplit = Token->getSplit( | |||
2132 | LineIndex, TailOffset + Split.first + Split.second, ColumnLimit, | |||
2133 | ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex); | |||
2134 | // Compute the columns necessary to fit the next non-breakable sequence | |||
2135 | // into the current line. | |||
2136 | unsigned ToNextSplitColumns = 0; | |||
2137 | if (NextSplit.first == StringRef::npos) { | |||
2138 | ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset, | |||
2139 | ContentStartColumn); | |||
2140 | } else { | |||
2141 | ToNextSplitColumns = Token->getRangeLength( | |||
2142 | LineIndex, TailOffset, | |||
2143 | Split.first + Split.second + NextSplit.first, ContentStartColumn); | |||
2144 | } | |||
2145 | // Compress the whitespace between the break and the start of the next | |||
2146 | // unbreakable sequence. | |||
2147 | ToNextSplitColumns = | |||
2148 | Token->getLengthAfterCompression(ToNextSplitColumns, Split); | |||
2149 | LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " ContentStartColumn: " << ContentStartColumn << "\n"; } } while (false) | |||
2150 | << " ContentStartColumn: " << ContentStartColumn << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " ContentStartColumn: " << ContentStartColumn << "\n"; } } while (false); | |||
2151 | LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " ToNextSplit: " << ToNextSplitColumns << "\n"; } } while (false) | |||
2152 | << " ToNextSplit: " << ToNextSplitColumns << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " ToNextSplit: " << ToNextSplitColumns << "\n"; } } while (false); | |||
2153 | // If the whitespace compression makes us fit, continue on the current | |||
2154 | // line. | |||
2155 | bool ContinueOnLine = | |||
2156 | ContentStartColumn + ToNextSplitColumns <= ColumnLimit; | |||
2157 | unsigned ExcessCharactersPenalty = 0; | |||
2158 | if (!ContinueOnLine && !Strict) { | |||
2159 | // Similarly, if the excess characters' penalty is lower than the | |||
2160 | // penalty of introducing a new break, continue on the current line. | |||
2161 | ExcessCharactersPenalty = | |||
2162 | (ContentStartColumn + ToNextSplitColumns - ColumnLimit) * | |||
2163 | Style.PenaltyExcessCharacter; | |||
2164 | LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Penalty excess: " << ExcessCharactersPenalty << "\n break : " << NewBreakPenalty << "\n"; } } while (false) | |||
2165 | << " Penalty excess: " << ExcessCharactersPenaltydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Penalty excess: " << ExcessCharactersPenalty << "\n break : " << NewBreakPenalty << "\n"; } } while (false) | |||
2166 | << "\n break : " << NewBreakPenalty << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Penalty excess: " << ExcessCharactersPenalty << "\n break : " << NewBreakPenalty << "\n"; } } while (false); | |||
2167 | if (ExcessCharactersPenalty < NewBreakPenalty) { | |||
2168 | Exceeded = true; | |||
2169 | ContinueOnLine = true; | |||
2170 | } | |||
2171 | } | |||
2172 | if (ContinueOnLine) { | |||
2173 | LLVM_DEBUG(llvm::dbgs() << " Continuing on line...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Continuing on line...\n" ; } } while (false); | |||
2174 | // The current line fits after compressing the whitespace - reflow | |||
2175 | // the next line into it if possible. | |||
2176 | TryReflow = true; | |||
2177 | if (!DryRun) | |||
2178 | Token->compressWhitespace(LineIndex, TailOffset, Split, | |||
2179 | Whitespaces); | |||
2180 | // When we continue on the same line, leave one space between content. | |||
2181 | ContentStartColumn += ToSplitColumns + 1; | |||
2182 | Penalty += ExcessCharactersPenalty; | |||
2183 | TailOffset += Split.first + Split.second; | |||
2184 | RemainingTokenColumns = Token->getRemainingLength( | |||
2185 | LineIndex, TailOffset, ContentStartColumn); | |||
2186 | continue; | |||
2187 | } | |||
2188 | } | |||
2189 | LLVM_DEBUG(llvm::dbgs() << " Breaking...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Breaking...\n" ; } } while (false); | |||
2190 | // Update the ContentIndent only if the current line was not reflown with | |||
2191 | // the previous line, since in that case the previous line should still | |||
2192 | // determine the ContentIndent. Also never intent the last line. | |||
2193 | if (!Reflow) | |||
2194 | ContentIndent = Token->getContentIndent(LineIndex); | |||
2195 | LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " ContentIndent: " << ContentIndent << "\n"; } } while (false) | |||
2196 | << " ContentIndent: " << ContentIndent << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " ContentIndent: " << ContentIndent << "\n"; } } while (false); | |||
2197 | ContentStartColumn = ContentIndent + Token->getContentStartColumn( | |||
2198 | LineIndex, /*Break=*/true); | |||
2199 | ||||
2200 | unsigned NewRemainingTokenColumns = Token->getRemainingLength( | |||
2201 | LineIndex, TailOffset + Split.first + Split.second, | |||
2202 | ContentStartColumn); | |||
2203 | if (NewRemainingTokenColumns == 0) { | |||
2204 | // No content to indent. | |||
2205 | ContentIndent = 0; | |||
2206 | ContentStartColumn = | |||
2207 | Token->getContentStartColumn(LineIndex, /*Break=*/true); | |||
2208 | NewRemainingTokenColumns = Token->getRemainingLength( | |||
2209 | LineIndex, TailOffset + Split.first + Split.second, | |||
2210 | ContentStartColumn); | |||
2211 | } | |||
2212 | ||||
2213 | // When breaking before a tab character, it may be moved by a few columns, | |||
2214 | // but will still be expanded to the next tab stop, so we don't save any | |||
2215 | // columns. | |||
2216 | if (NewRemainingTokenColumns >= RemainingTokenColumns) { | |||
2217 | // FIXME: Do we need to adjust the penalty? | |||
2218 | break; | |||
2219 | } | |||
2220 | ||||
2221 | LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.firstdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Breaking at: " << TailOffset + Split.first << ", " << Split .second << "\n"; } } while (false) | |||
2222 | << ", " << Split.second << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Breaking at: " << TailOffset + Split.first << ", " << Split .second << "\n"; } } while (false); | |||
2223 | if (!DryRun) | |||
2224 | Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent, | |||
2225 | Whitespaces); | |||
2226 | ||||
2227 | Penalty += NewBreakPenalty; | |||
2228 | TailOffset += Split.first + Split.second; | |||
2229 | RemainingTokenColumns = NewRemainingTokenColumns; | |||
2230 | BreakInserted = true; | |||
2231 | NewBreakBefore = true; | |||
2232 | } | |||
2233 | // In case there's another line, prepare the state for the start of the next | |||
2234 | // line. | |||
2235 | if (LineIndex + 1 != EndIndex) { | |||
2236 | unsigned NextLineIndex = LineIndex + 1; | |||
2237 | if (NewBreakBefore) | |||
2238 | // After breaking a line, try to reflow the next line into the current | |||
2239 | // one once RemainingTokenColumns fits. | |||
2240 | TryReflow = true; | |||
2241 | if (TryReflow) { | |||
2242 | // We decided that we want to try reflowing the next line into the | |||
2243 | // current one. | |||
2244 | // We will now adjust the state as if the reflow is successful (in | |||
2245 | // preparation for the next line), and see whether that works. If we | |||
2246 | // decide that we cannot reflow, we will later reset the state to the | |||
2247 | // start of the next line. | |||
2248 | Reflow = false; | |||
2249 | // As we did not continue breaking the line, RemainingTokenColumns is | |||
2250 | // known to fit after ContentStartColumn. Adapt ContentStartColumn to | |||
2251 | // the position at which we want to format the next line if we do | |||
2252 | // actually reflow. | |||
2253 | // When we reflow, we need to add a space between the end of the current | |||
2254 | // line and the next line's start column. | |||
2255 | ContentStartColumn += RemainingTokenColumns + 1; | |||
2256 | // Get the split that we need to reflow next logical line into the end | |||
2257 | // of the current one; the split will include any leading whitespace of | |||
2258 | // the next logical line. | |||
2259 | BreakableToken::Split SplitBeforeNext = | |||
2260 | Token->getReflowSplit(NextLineIndex, CommentPragmasRegex); | |||
2261 | LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Size of reflown text: " << ContentStartColumn << "\n Potential reflow split: " ; } } while (false) | |||
2262 | << " Size of reflown text: " << ContentStartColumndo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Size of reflown text: " << ContentStartColumn << "\n Potential reflow split: " ; } } while (false) | |||
2263 | << "\n Potential reflow split: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Size of reflown text: " << ContentStartColumn << "\n Potential reflow split: " ; } } while (false); | |||
2264 | if (SplitBeforeNext.first != StringRef::npos) { | |||
2265 | LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << SplitBeforeNext. first << ", " << SplitBeforeNext.second << "\n" ; } } while (false) | |||
2266 | << SplitBeforeNext.second << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << SplitBeforeNext. first << ", " << SplitBeforeNext.second << "\n" ; } } while (false); | |||
2267 | TailOffset = SplitBeforeNext.first + SplitBeforeNext.second; | |||
2268 | // If the rest of the next line fits into the current line below the | |||
2269 | // column limit, we can safely reflow. | |||
2270 | RemainingTokenColumns = Token->getRemainingLength( | |||
2271 | NextLineIndex, TailOffset, ContentStartColumn); | |||
2272 | Reflow = true; | |||
2273 | if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) { | |||
2274 | LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false) | |||
2275 | << " Over limit after reflow, need: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false) | |||
2276 | << (ContentStartColumn + RemainingTokenColumns)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false) | |||
2277 | << ", space: " << ColumnLimitdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false) | |||
2278 | << ", reflown prefix: " << ContentStartColumndo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false) | |||
2279 | << ", offset in line: " << TailOffset << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Over limit after reflow, need: " << (ContentStartColumn + RemainingTokenColumns) << ", space: " << ColumnLimit << ", reflown prefix: " << ContentStartColumn << ", offset in line: " << TailOffset << "\n"; } } while (false); | |||
2280 | // If the whole next line does not fit, try to find a point in | |||
2281 | // the next line at which we can break so that attaching the part | |||
2282 | // of the next line to that break point onto the current line is | |||
2283 | // below the column limit. | |||
2284 | BreakableToken::Split Split = | |||
2285 | Token->getSplit(NextLineIndex, TailOffset, ColumnLimit, | |||
2286 | ContentStartColumn, CommentPragmasRegex); | |||
2287 | if (Split.first == StringRef::npos) { | |||
2288 | LLVM_DEBUG(llvm::dbgs() << " Did not find later break\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Did not find later break\n" ; } } while (false); | |||
2289 | Reflow = false; | |||
2290 | } else { | |||
2291 | // Check whether the first split point gets us below the column | |||
2292 | // limit. Note that we will execute this split below as part of | |||
2293 | // the normal token breaking and reflow logic within the line. | |||
2294 | unsigned ToSplitColumns = Token->getRangeLength( | |||
2295 | NextLineIndex, TailOffset, Split.first, ContentStartColumn); | |||
2296 | if (ContentStartColumn + ToSplitColumns > ColumnLimit) { | |||
2297 | LLVM_DEBUG(llvm::dbgs() << " Next split protrudes, need: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Next split protrudes, need: " << (ContentStartColumn + ToSplitColumns) << ", space: " << ColumnLimit; } } while (false) | |||
2298 | << (ContentStartColumn + ToSplitColumns)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Next split protrudes, need: " << (ContentStartColumn + ToSplitColumns) << ", space: " << ColumnLimit; } } while (false) | |||
2299 | << ", space: " << ColumnLimit)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << " Next split protrudes, need: " << (ContentStartColumn + ToSplitColumns) << ", space: " << ColumnLimit; } } while (false); | |||
2300 | unsigned ExcessCharactersPenalty = | |||
2301 | (ContentStartColumn + ToSplitColumns - ColumnLimit) * | |||
2302 | Style.PenaltyExcessCharacter; | |||
2303 | if (NewBreakPenalty < ExcessCharactersPenalty) { | |||
2304 | Reflow = false; | |||
2305 | } | |||
2306 | } | |||
2307 | } | |||
2308 | } | |||
2309 | } else { | |||
2310 | LLVM_DEBUG(llvm::dbgs() << "not found.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << "not found.\n"; } } while (false); | |||
2311 | } | |||
2312 | } | |||
2313 | if (!Reflow) { | |||
2314 | // If we didn't reflow into the next line, the only space to consider is | |||
2315 | // the next logical line. Reset our state to match the start of the next | |||
2316 | // line. | |||
2317 | TailOffset = 0; | |||
2318 | ContentStartColumn = | |||
2319 | Token->getContentStartColumn(NextLineIndex, /*Break=*/false); | |||
2320 | RemainingTokenColumns = Token->getRemainingLength( | |||
2321 | NextLineIndex, TailOffset, ContentStartColumn); | |||
2322 | // Adapt the start of the token, for example indent. | |||
2323 | if (!DryRun) | |||
2324 | Token->adaptStartOfLine(NextLineIndex, Whitespaces); | |||
2325 | } else { | |||
2326 | // If we found a reflow split and have added a new break before the next | |||
2327 | // line, we are going to remove the line break at the start of the next | |||
2328 | // logical line. For example, here we'll add a new line break after | |||
2329 | // 'text', and subsequently delete the line break between 'that' and | |||
2330 | // 'reflows'. | |||
2331 | // // some text that | |||
2332 | // // reflows | |||
2333 | // -> | |||
2334 | // // some text | |||
2335 | // // that reflows | |||
2336 | // When adding the line break, we also added the penalty for it, so we | |||
2337 | // need to subtract that penalty again when we remove the line break due | |||
2338 | // to reflowing. | |||
2339 | if (NewBreakBefore) { | |||
2340 | assert(Penalty >= NewBreakPenalty)(static_cast <bool> (Penalty >= NewBreakPenalty) ? void (0) : __assert_fail ("Penalty >= NewBreakPenalty", "clang/lib/Format/ContinuationIndenter.cpp" , 2340, __extension__ __PRETTY_FUNCTION__)); | |||
2341 | Penalty -= NewBreakPenalty; | |||
2342 | } | |||
2343 | if (!DryRun) | |||
2344 | Token->reflow(NextLineIndex, Whitespaces); | |||
2345 | } | |||
2346 | } | |||
2347 | } | |||
2348 | ||||
2349 | BreakableToken::Split SplitAfterLastLine = | |||
2350 | Token->getSplitAfterLastLine(TailOffset); | |||
2351 | if (SplitAfterLastLine.first != StringRef::npos) { | |||
2352 | LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("format-indenter")) { llvm::dbgs() << "Replacing whitespace after last line.\n" ; } } while (false); | |||
2353 | ||||
2354 | // We add the last line's penalty here, since that line is going to be split | |||
2355 | // now. | |||
2356 | Penalty += Style.PenaltyExcessCharacter * | |||
2357 | (ContentStartColumn + RemainingTokenColumns - ColumnLimit); | |||
2358 | ||||
2359 | if (!DryRun) | |||
2360 | Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine, | |||
2361 | Whitespaces); | |||
2362 | ContentStartColumn = | |||
2363 | Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true); | |||
2364 | RemainingTokenColumns = Token->getRemainingLength( | |||
2365 | Token->getLineCount() - 1, | |||
2366 | TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second, | |||
2367 | ContentStartColumn); | |||
2368 | } | |||
2369 | ||||
2370 | State.Column = ContentStartColumn + RemainingTokenColumns - | |||
2371 | Current.UnbreakableTailLength; | |||
2372 | ||||
2373 | if (BreakInserted) { | |||
2374 | // If we break the token inside a parameter list, we need to break before | |||
2375 | // the next parameter on all levels, so that the next parameter is clearly | |||
2376 | // visible. Line comments already introduce a break. | |||
2377 | if (Current.isNot(TT_LineComment)) { | |||
2378 | for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) | |||
2379 | State.Stack[i].BreakBeforeParameter = true; | |||
2380 | } | |||
2381 | ||||
2382 | if (Current.is(TT_BlockComment)) | |||
2383 | State.NoContinuation = true; | |||
2384 | ||||
2385 | State.Stack.back().LastSpace = StartColumn; | |||
2386 | } | |||
2387 | ||||
2388 | Token->updateNextToken(State); | |||
2389 | ||||
2390 | return {Penalty, Exceeded}; | |||
2391 | } | |||
2392 | ||||
2393 | unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const { | |||
2394 | // In preprocessor directives reserve two chars for trailing " \" | |||
2395 | return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0); | |||
2396 | } | |||
2397 | ||||
2398 | bool ContinuationIndenter::nextIsMultilineString(const LineState &State) { | |||
2399 | const FormatToken &Current = *State.NextToken; | |||
2400 | if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral)) | |||
2401 | return false; | |||
2402 | // We never consider raw string literals "multiline" for the purpose of | |||
2403 | // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased | |||
2404 | // (see TokenAnnotator::mustBreakBefore(). | |||
2405 | if (Current.TokenText.startswith("R\"")) | |||
2406 | return false; | |||
2407 | if (Current.IsMultiline) | |||
2408 | return true; | |||
2409 | if (Current.getNextNonComment() && | |||
2410 | Current.getNextNonComment()->isStringLiteral()) | |||
2411 | return true; // Implicit concatenation. | |||
2412 | if (Style.ColumnLimit != 0 && Style.BreakStringLiterals && | |||
2413 | State.Column + Current.ColumnWidth + Current.UnbreakableTailLength > | |||
2414 | Style.ColumnLimit) | |||
2415 | return true; // String will be split. | |||
2416 | return false; | |||
2417 | } | |||
2418 | ||||
2419 | } // namespace format | |||
2420 | } // namespace clang |
1 | //===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | /// |
9 | /// \file |
10 | /// This file contains the declaration of the FormatToken, a wrapper |
11 | /// around Token with additional information related to formatting. |
12 | /// |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H |
16 | #define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H |
17 | |
18 | #include "clang/Basic/IdentifierTable.h" |
19 | #include "clang/Basic/OperatorPrecedence.h" |
20 | #include "clang/Format/Format.h" |
21 | #include "clang/Lex/Lexer.h" |
22 | #include <memory> |
23 | #include <unordered_set> |
24 | |
25 | namespace clang { |
26 | namespace format { |
27 | |
28 | #define LIST_TOKEN_TYPESTYPE(ArrayInitializerLSquare) TYPE(ArraySubscriptLSquare) TYPE (AttributeColon) TYPE(AttributeMacro) TYPE(AttributeParen) TYPE (AttributeSquare) TYPE(BinaryOperator) TYPE(BitFieldColon) TYPE (BlockComment) TYPE(CastRParen) TYPE(ConditionalExpr) TYPE(ConflictAlternative ) TYPE(ConflictEnd) TYPE(ConflictStart) TYPE(ConstraintJunctions ) TYPE(CtorInitializerColon) TYPE(CtorInitializerComma) TYPE( DesignatedInitializerLSquare) TYPE(DesignatedInitializerPeriod ) TYPE(DictLiteral) TYPE(FatArrow) TYPE(ForEachMacro) TYPE(FunctionAnnotationRParen ) TYPE(FunctionDeclarationName) TYPE(FunctionLBrace) TYPE(FunctionTypeLParen ) TYPE(IfMacro) TYPE(ImplicitStringLiteral) TYPE(InheritanceColon ) TYPE(InheritanceComma) TYPE(InlineASMBrace) TYPE(InlineASMColon ) TYPE(InlineASMSymbolicNameLSquare) TYPE(JavaAnnotation) TYPE (JsComputedPropertyName) TYPE(JsExponentiation) TYPE(JsExponentiationEqual ) TYPE(JsPipePipeEqual) TYPE(JsPrivateIdentifier) TYPE(JsTypeColon ) TYPE(JsTypeOperator) TYPE(JsTypeOptionalQuestion) TYPE(JsAndAndEqual ) TYPE(LambdaArrow) TYPE(LambdaLBrace) TYPE(LambdaLSquare) TYPE (LeadingJavaAnnotation) TYPE(LineComment) TYPE(MacroBlockBegin ) TYPE(MacroBlockEnd) TYPE(ModulePartitionColon) TYPE(NamespaceMacro ) TYPE(NonNullAssertion) TYPE(NullCoalescingEqual) TYPE(NullCoalescingOperator ) TYPE(NullPropagatingOperator) TYPE(ObjCBlockLBrace) TYPE(ObjCBlockLParen ) TYPE(ObjCDecl) TYPE(ObjCForIn) TYPE(ObjCMethodExpr) TYPE(ObjCMethodSpecifier ) TYPE(ObjCProperty) TYPE(ObjCStringLiteral) TYPE(OverloadedOperator ) TYPE(OverloadedOperatorLParen) TYPE(PointerOrReference) TYPE (PureVirtualSpecifier) TYPE(RangeBasedForLoopColon) TYPE(RegexLiteral ) TYPE(SelectorName) TYPE(StartOfName) TYPE(StatementAttributeLikeMacro ) TYPE(StatementMacro) TYPE(StructuredBindingLSquare) TYPE(TemplateCloser ) TYPE(TemplateOpener) TYPE(TemplateString) TYPE(ProtoExtensionLSquare ) TYPE(TrailingAnnotation) TYPE(TrailingReturnArrow) TYPE(TrailingUnaryOperator ) TYPE(TypeDeclarationParen) TYPE(TypenameMacro) TYPE(UnaryOperator ) TYPE(UntouchableMacroFunc) TYPE(CSharpStringLiteral) TYPE(CSharpNamedArgumentColon ) TYPE(CSharpNullable) TYPE(CSharpNullConditionalLSquare) TYPE (CSharpGenericTypeConstraint) TYPE(CSharpGenericTypeConstraintColon ) TYPE(CSharpGenericTypeConstraintComma) TYPE(Unknown) \ |
29 | TYPE(ArrayInitializerLSquare) \ |
30 | TYPE(ArraySubscriptLSquare) \ |
31 | TYPE(AttributeColon) \ |
32 | TYPE(AttributeMacro) \ |
33 | TYPE(AttributeParen) \ |
34 | TYPE(AttributeSquare) \ |
35 | TYPE(BinaryOperator) \ |
36 | TYPE(BitFieldColon) \ |
37 | TYPE(BlockComment) \ |
38 | TYPE(CastRParen) \ |
39 | TYPE(ConditionalExpr) \ |
40 | TYPE(ConflictAlternative) \ |
41 | TYPE(ConflictEnd) \ |
42 | TYPE(ConflictStart) \ |
43 | TYPE(ConstraintJunctions) \ |
44 | TYPE(CtorInitializerColon) \ |
45 | TYPE(CtorInitializerComma) \ |
46 | TYPE(DesignatedInitializerLSquare) \ |
47 | TYPE(DesignatedInitializerPeriod) \ |
48 | TYPE(DictLiteral) \ |
49 | TYPE(FatArrow) \ |
50 | TYPE(ForEachMacro) \ |
51 | TYPE(FunctionAnnotationRParen) \ |
52 | TYPE(FunctionDeclarationName) \ |
53 | TYPE(FunctionLBrace) \ |
54 | TYPE(FunctionTypeLParen) \ |
55 | TYPE(IfMacro) \ |
56 | TYPE(ImplicitStringLiteral) \ |
57 | TYPE(InheritanceColon) \ |
58 | TYPE(InheritanceComma) \ |
59 | TYPE(InlineASMBrace) \ |
60 | TYPE(InlineASMColon) \ |
61 | TYPE(InlineASMSymbolicNameLSquare) \ |
62 | TYPE(JavaAnnotation) \ |
63 | TYPE(JsComputedPropertyName) \ |
64 | TYPE(JsExponentiation) \ |
65 | TYPE(JsExponentiationEqual) \ |
66 | TYPE(JsPipePipeEqual) \ |
67 | TYPE(JsPrivateIdentifier) \ |
68 | TYPE(JsTypeColon) \ |
69 | TYPE(JsTypeOperator) \ |
70 | TYPE(JsTypeOptionalQuestion) \ |
71 | TYPE(JsAndAndEqual) \ |
72 | TYPE(LambdaArrow) \ |
73 | TYPE(LambdaLBrace) \ |
74 | TYPE(LambdaLSquare) \ |
75 | TYPE(LeadingJavaAnnotation) \ |
76 | TYPE(LineComment) \ |
77 | TYPE(MacroBlockBegin) \ |
78 | TYPE(MacroBlockEnd) \ |
79 | TYPE(ModulePartitionColon) \ |
80 | TYPE(NamespaceMacro) \ |
81 | TYPE(NonNullAssertion) \ |
82 | TYPE(NullCoalescingEqual) \ |
83 | TYPE(NullCoalescingOperator) \ |
84 | TYPE(NullPropagatingOperator) \ |
85 | TYPE(ObjCBlockLBrace) \ |
86 | TYPE(ObjCBlockLParen) \ |
87 | TYPE(ObjCDecl) \ |
88 | TYPE(ObjCForIn) \ |
89 | TYPE(ObjCMethodExpr) \ |
90 | TYPE(ObjCMethodSpecifier) \ |
91 | TYPE(ObjCProperty) \ |
92 | TYPE(ObjCStringLiteral) \ |
93 | TYPE(OverloadedOperator) \ |
94 | TYPE(OverloadedOperatorLParen) \ |
95 | TYPE(PointerOrReference) \ |
96 | TYPE(PureVirtualSpecifier) \ |
97 | TYPE(RangeBasedForLoopColon) \ |
98 | TYPE(RegexLiteral) \ |
99 | TYPE(SelectorName) \ |
100 | TYPE(StartOfName) \ |
101 | TYPE(StatementAttributeLikeMacro) \ |
102 | TYPE(StatementMacro) \ |
103 | TYPE(StructuredBindingLSquare) \ |
104 | TYPE(TemplateCloser) \ |
105 | TYPE(TemplateOpener) \ |
106 | TYPE(TemplateString) \ |
107 | TYPE(ProtoExtensionLSquare) \ |
108 | TYPE(TrailingAnnotation) \ |
109 | TYPE(TrailingReturnArrow) \ |
110 | TYPE(TrailingUnaryOperator) \ |
111 | TYPE(TypeDeclarationParen) \ |
112 | TYPE(TypenameMacro) \ |
113 | TYPE(UnaryOperator) \ |
114 | TYPE(UntouchableMacroFunc) \ |
115 | TYPE(CSharpStringLiteral) \ |
116 | TYPE(CSharpNamedArgumentColon) \ |
117 | TYPE(CSharpNullable) \ |
118 | TYPE(CSharpNullConditionalLSquare) \ |
119 | TYPE(CSharpGenericTypeConstraint) \ |
120 | TYPE(CSharpGenericTypeConstraintColon) \ |
121 | TYPE(CSharpGenericTypeConstraintComma) \ |
122 | TYPE(Unknown) |
123 | |
124 | /// Determines the semantic type of a syntactic token, e.g. whether "<" is a |
125 | /// template opener or binary operator. |
126 | enum TokenType : uint8_t { |
127 | #define TYPE(X) TT_##X, |
128 | LIST_TOKEN_TYPESTYPE(ArrayInitializerLSquare) TYPE(ArraySubscriptLSquare) TYPE (AttributeColon) TYPE(AttributeMacro) TYPE(AttributeParen) TYPE (AttributeSquare) TYPE(BinaryOperator) TYPE(BitFieldColon) TYPE (BlockComment) TYPE(CastRParen) TYPE(ConditionalExpr) TYPE(ConflictAlternative ) TYPE(ConflictEnd) TYPE(ConflictStart) TYPE(ConstraintJunctions ) TYPE(CtorInitializerColon) TYPE(CtorInitializerComma) TYPE( DesignatedInitializerLSquare) TYPE(DesignatedInitializerPeriod ) TYPE(DictLiteral) TYPE(FatArrow) TYPE(ForEachMacro) TYPE(FunctionAnnotationRParen ) TYPE(FunctionDeclarationName) TYPE(FunctionLBrace) TYPE(FunctionTypeLParen ) TYPE(IfMacro) TYPE(ImplicitStringLiteral) TYPE(InheritanceColon ) TYPE(InheritanceComma) TYPE(InlineASMBrace) TYPE(InlineASMColon ) TYPE(InlineASMSymbolicNameLSquare) TYPE(JavaAnnotation) TYPE (JsComputedPropertyName) TYPE(JsExponentiation) TYPE(JsExponentiationEqual ) TYPE(JsPipePipeEqual) TYPE(JsPrivateIdentifier) TYPE(JsTypeColon ) TYPE(JsTypeOperator) TYPE(JsTypeOptionalQuestion) TYPE(JsAndAndEqual ) TYPE(LambdaArrow) TYPE(LambdaLBrace) TYPE(LambdaLSquare) TYPE (LeadingJavaAnnotation) TYPE(LineComment) TYPE(MacroBlockBegin ) TYPE(MacroBlockEnd) TYPE(ModulePartitionColon) TYPE(NamespaceMacro ) TYPE(NonNullAssertion) TYPE(NullCoalescingEqual) TYPE(NullCoalescingOperator ) TYPE(NullPropagatingOperator) TYPE(ObjCBlockLBrace) TYPE(ObjCBlockLParen ) TYPE(ObjCDecl) TYPE(ObjCForIn) TYPE(ObjCMethodExpr) TYPE(ObjCMethodSpecifier ) TYPE(ObjCProperty) TYPE(ObjCStringLiteral) TYPE(OverloadedOperator ) TYPE(OverloadedOperatorLParen) TYPE(PointerOrReference) TYPE (PureVirtualSpecifier) TYPE(RangeBasedForLoopColon) TYPE(RegexLiteral ) TYPE(SelectorName) TYPE(StartOfName) TYPE(StatementAttributeLikeMacro ) TYPE(StatementMacro) TYPE(StructuredBindingLSquare) TYPE(TemplateCloser ) TYPE(TemplateOpener) TYPE(TemplateString) TYPE(ProtoExtensionLSquare ) TYPE(TrailingAnnotation) TYPE(TrailingReturnArrow) TYPE(TrailingUnaryOperator ) TYPE(TypeDeclarationParen) TYPE(TypenameMacro) TYPE(UnaryOperator ) TYPE(UntouchableMacroFunc) TYPE(CSharpStringLiteral) TYPE(CSharpNamedArgumentColon ) TYPE(CSharpNullable) TYPE(CSharpNullConditionalLSquare) TYPE (CSharpGenericTypeConstraint) TYPE(CSharpGenericTypeConstraintColon ) TYPE(CSharpGenericTypeConstraintComma) TYPE(Unknown) |
129 | #undef TYPE |
130 | NUM_TOKEN_TYPES |
131 | }; |
132 | |
133 | /// Determines the name of a token type. |
134 | const char *getTokenTypeName(TokenType Type); |
135 | |
136 | // Represents what type of block a set of braces open. |
137 | enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit }; |
138 | |
139 | // The packing kind of a function's parameters. |
140 | enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive }; |
141 | |
142 | enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break }; |
143 | |
144 | /// Roles a token can take in a configured macro expansion. |
145 | enum MacroRole { |
146 | /// The token was expanded from a macro argument when formatting the expanded |
147 | /// token sequence. |
148 | MR_ExpandedArg, |
149 | /// The token is part of a macro argument that was previously formatted as |
150 | /// expansion when formatting the unexpanded macro call. |
151 | MR_UnexpandedArg, |
152 | /// The token was expanded from a macro definition, and is not visible as part |
153 | /// of the macro call. |
154 | MR_Hidden, |
155 | }; |
156 | |
157 | struct FormatToken; |
158 | |
159 | /// Contains information on the token's role in a macro expansion. |
160 | /// |
161 | /// Given the following definitions: |
162 | /// A(X) = [ X ] |
163 | /// B(X) = < X > |
164 | /// C(X) = X |
165 | /// |
166 | /// Consider the macro call: |
167 | /// A({B(C(C(x)))}) -> [{<x>}] |
168 | /// |
169 | /// In this case, the tokens of the unexpanded macro call will have the |
170 | /// following relevant entries in their macro context (note that formatting |
171 | /// the unexpanded macro call happens *after* formatting the expanded macro |
172 | /// call): |
173 | /// A( { B( C( C(x) ) ) } ) |
174 | /// Role: NN U NN NN NNUN N N U N (N=None, U=UnexpandedArg) |
175 | /// |
176 | /// [ { < x > } ] |
177 | /// Role: H E H E H E H (H=Hidden, E=ExpandedArg) |
178 | /// ExpandedFrom[0]: A A A A A A A |
179 | /// ExpandedFrom[1]: B B B |
180 | /// ExpandedFrom[2]: C |
181 | /// ExpandedFrom[3]: C |
182 | /// StartOfExpansion: 1 0 1 2 0 0 0 |
183 | /// EndOfExpansion: 0 0 0 2 1 0 1 |
184 | struct MacroExpansion { |
185 | MacroExpansion(MacroRole Role) : Role(Role) {} |
186 | |
187 | /// The token's role in the macro expansion. |
188 | /// When formatting an expanded macro, all tokens that are part of macro |
189 | /// arguments will be MR_ExpandedArg, while all tokens that are not visible in |
190 | /// the macro call will be MR_Hidden. |
191 | /// When formatting an unexpanded macro call, all tokens that are part of |
192 | /// macro arguments will be MR_UnexpandedArg. |
193 | MacroRole Role; |
194 | |
195 | /// The stack of macro call identifier tokens this token was expanded from. |
196 | llvm::SmallVector<FormatToken *, 1> ExpandedFrom; |
197 | |
198 | /// The number of expansions of which this macro is the first entry. |
199 | unsigned StartOfExpansion = 0; |
200 | |
201 | /// The number of currently open expansions in \c ExpandedFrom this macro is |
202 | /// the last token in. |
203 | unsigned EndOfExpansion = 0; |
204 | }; |
205 | |
206 | class TokenRole; |
207 | class AnnotatedLine; |
208 | |
209 | /// A wrapper around a \c Token storing information about the |
210 | /// whitespace characters preceding it. |
211 | struct FormatToken { |
212 | FormatToken() |
213 | : HasUnescapedNewline(false), IsMultiline(false), IsFirst(false), |
214 | MustBreakBefore(false), IsUnterminatedLiteral(false), |
215 | CanBreakBefore(false), ClosesTemplateDeclaration(false), |
216 | StartsBinaryExpression(false), EndsBinaryExpression(false), |
217 | PartOfMultiVariableDeclStmt(false), ContinuesLineCommentSection(false), |
218 | Finalized(false), BlockKind(BK_Unknown), Decision(FD_Unformatted), |
219 | PackingKind(PPK_Inconclusive), Type(TT_Unknown) {} |
220 | |
221 | /// The \c Token. |
222 | Token Tok; |
223 | |
224 | /// The raw text of the token. |
225 | /// |
226 | /// Contains the raw token text without leading whitespace and without leading |
227 | /// escaped newlines. |
228 | StringRef TokenText; |
229 | |
230 | /// A token can have a special role that can carry extra information |
231 | /// about the token's formatting. |
232 | /// FIXME: Make FormatToken for parsing and AnnotatedToken two different |
233 | /// classes and make this a unique_ptr in the AnnotatedToken class. |
234 | std::shared_ptr<TokenRole> Role; |
235 | |
236 | /// The range of the whitespace immediately preceding the \c Token. |
237 | SourceRange WhitespaceRange; |
238 | |
239 | /// Whether there is at least one unescaped newline before the \c |
240 | /// Token. |
241 | unsigned HasUnescapedNewline : 1; |
242 | |
243 | /// Whether the token text contains newlines (escaped or not). |
244 | unsigned IsMultiline : 1; |
245 | |
246 | /// Indicates that this is the first token of the file. |
247 | unsigned IsFirst : 1; |
248 | |
249 | /// Whether there must be a line break before this token. |
250 | /// |
251 | /// This happens for example when a preprocessor directive ended directly |
252 | /// before the token. |
253 | unsigned MustBreakBefore : 1; |
254 | |
255 | /// Set to \c true if this token is an unterminated literal. |
256 | unsigned IsUnterminatedLiteral : 1; |
257 | |
258 | /// \c true if it is allowed to break before this token. |
259 | unsigned CanBreakBefore : 1; |
260 | |
261 | /// \c true if this is the ">" of "template<..>". |
262 | unsigned ClosesTemplateDeclaration : 1; |
263 | |
264 | /// \c true if this token starts a binary expression, i.e. has at least |
265 | /// one fake l_paren with a precedence greater than prec::Unknown. |
266 | unsigned StartsBinaryExpression : 1; |
267 | /// \c true if this token ends a binary expression. |
268 | unsigned EndsBinaryExpression : 1; |
269 | |
270 | /// Is this token part of a \c DeclStmt defining multiple variables? |
271 | /// |
272 | /// Only set if \c Type == \c TT_StartOfName. |
273 | unsigned PartOfMultiVariableDeclStmt : 1; |
274 | |
275 | /// Does this line comment continue a line comment section? |
276 | /// |
277 | /// Only set to true if \c Type == \c TT_LineComment. |
278 | unsigned ContinuesLineCommentSection : 1; |
279 | |
280 | /// If \c true, this token has been fully formatted (indented and |
281 | /// potentially re-formatted inside), and we do not allow further formatting |
282 | /// changes. |
283 | unsigned Finalized : 1; |
284 | |
285 | private: |
286 | /// Contains the kind of block if this token is a brace. |
287 | unsigned BlockKind : 2; |
288 | |
289 | public: |
290 | BraceBlockKind getBlockKind() const { |
291 | return static_cast<BraceBlockKind>(BlockKind); |
292 | } |
293 | void setBlockKind(BraceBlockKind BBK) { |
294 | BlockKind = BBK; |
295 | assert(getBlockKind() == BBK && "BraceBlockKind overflow!")(static_cast <bool> (getBlockKind() == BBK && "BraceBlockKind overflow!" ) ? void (0) : __assert_fail ("getBlockKind() == BBK && \"BraceBlockKind overflow!\"" , "clang/lib/Format/FormatToken.h", 295, __extension__ __PRETTY_FUNCTION__ )); |
296 | } |
297 | |
298 | private: |
299 | /// Stores the formatting decision for the token once it was made. |
300 | unsigned Decision : 2; |
301 | |
302 | public: |
303 | FormatDecision getDecision() const { |
304 | return static_cast<FormatDecision>(Decision); |
305 | } |
306 | void setDecision(FormatDecision D) { |
307 | Decision = D; |
308 | assert(getDecision() == D && "FormatDecision overflow!")(static_cast <bool> (getDecision() == D && "FormatDecision overflow!" ) ? void (0) : __assert_fail ("getDecision() == D && \"FormatDecision overflow!\"" , "clang/lib/Format/FormatToken.h", 308, __extension__ __PRETTY_FUNCTION__ )); |
309 | } |
310 | |
311 | private: |
312 | /// If this is an opening parenthesis, how are the parameters packed? |
313 | unsigned PackingKind : 2; |
314 | |
315 | public: |
316 | ParameterPackingKind getPackingKind() const { |
317 | return static_cast<ParameterPackingKind>(PackingKind); |
318 | } |
319 | void setPackingKind(ParameterPackingKind K) { |
320 | PackingKind = K; |
321 | assert(getPackingKind() == K && "ParameterPackingKind overflow!")(static_cast <bool> (getPackingKind() == K && "ParameterPackingKind overflow!" ) ? void (0) : __assert_fail ("getPackingKind() == K && \"ParameterPackingKind overflow!\"" , "clang/lib/Format/FormatToken.h", 321, __extension__ __PRETTY_FUNCTION__ )); |
322 | } |
323 | |
324 | private: |
325 | TokenType Type; |
326 | |
327 | public: |
328 | /// Returns the token's type, e.g. whether "<" is a template opener or |
329 | /// binary operator. |
330 | TokenType getType() const { return Type; } |
331 | void setType(TokenType T) { Type = T; } |
332 | |
333 | /// The number of newlines immediately before the \c Token. |
334 | /// |
335 | /// This can be used to determine what the user wrote in the original code |
336 | /// and thereby e.g. leave an empty line between two function definitions. |
337 | unsigned NewlinesBefore = 0; |
338 | |
339 | /// The offset just past the last '\n' in this token's leading |
340 | /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'. |
341 | unsigned LastNewlineOffset = 0; |
342 | |
343 | /// The width of the non-whitespace parts of the token (or its first |
344 | /// line for multi-line tokens) in columns. |
345 | /// We need this to correctly measure number of columns a token spans. |
346 | unsigned ColumnWidth = 0; |
347 | |
348 | /// Contains the width in columns of the last line of a multi-line |
349 | /// token. |
350 | unsigned LastLineColumnWidth = 0; |
351 | |
352 | /// The number of spaces that should be inserted before this token. |
353 | unsigned SpacesRequiredBefore = 0; |
354 | |
355 | /// Number of parameters, if this is "(", "[" or "<". |
356 | unsigned ParameterCount = 0; |
357 | |
358 | /// Number of parameters that are nested blocks, |
359 | /// if this is "(", "[" or "<". |
360 | unsigned BlockParameterCount = 0; |
361 | |
362 | /// If this is a bracket ("<", "(", "[" or "{"), contains the kind of |
363 | /// the surrounding bracket. |
364 | tok::TokenKind ParentBracket = tok::unknown; |
365 | |
366 | /// The total length of the unwrapped line up to and including this |
367 | /// token. |
368 | unsigned TotalLength = 0; |
369 | |
370 | /// The original 0-based column of this token, including expanded tabs. |
371 | /// The configured TabWidth is used as tab width. |
372 | unsigned OriginalColumn = 0; |
373 | |
374 | /// The length of following tokens until the next natural split point, |
375 | /// or the next token that can be broken. |
376 | unsigned UnbreakableTailLength = 0; |
377 | |
378 | // FIXME: Come up with a 'cleaner' concept. |
379 | /// The binding strength of a token. This is a combined value of |
380 | /// operator precedence, parenthesis nesting, etc. |
381 | unsigned BindingStrength = 0; |
382 | |
383 | /// The nesting level of this token, i.e. the number of surrounding (), |
384 | /// [], {} or <>. |
385 | unsigned NestingLevel = 0; |
386 | |
387 | /// The indent level of this token. Copied from the surrounding line. |
388 | unsigned IndentLevel = 0; |
389 | |
390 | /// Penalty for inserting a line break before this token. |
391 | unsigned SplitPenalty = 0; |
392 | |
393 | /// If this is the first ObjC selector name in an ObjC method |
394 | /// definition or call, this contains the length of the longest name. |
395 | /// |
396 | /// This being set to 0 means that the selectors should not be colon-aligned, |
397 | /// e.g. because several of them are block-type. |
398 | unsigned LongestObjCSelectorName = 0; |
399 | |
400 | /// If this is the first ObjC selector name in an ObjC method |
401 | /// definition or call, this contains the number of parts that the whole |
402 | /// selector consist of. |
403 | unsigned ObjCSelectorNameParts = 0; |
404 | |
405 | /// The 0-based index of the parameter/argument. For ObjC it is set |
406 | /// for the selector name token. |
407 | /// For now calculated only for ObjC. |
408 | unsigned ParameterIndex = 0; |
409 | |
410 | /// Stores the number of required fake parentheses and the |
411 | /// corresponding operator precedence. |
412 | /// |
413 | /// If multiple fake parentheses start at a token, this vector stores them in |
414 | /// reverse order, i.e. inner fake parenthesis first. |
415 | SmallVector<prec::Level, 4> FakeLParens; |
416 | /// Insert this many fake ) after this token for correct indentation. |
417 | unsigned FakeRParens = 0; |
418 | |
419 | /// If this is an operator (or "."/"->") in a sequence of operators |
420 | /// with the same precedence, contains the 0-based operator index. |
421 | unsigned OperatorIndex = 0; |
422 | |
423 | /// If this is an operator (or "."/"->") in a sequence of operators |
424 | /// with the same precedence, points to the next operator. |
425 | FormatToken *NextOperator = nullptr; |
426 | |
427 | /// If this is a bracket, this points to the matching one. |
428 | FormatToken *MatchingParen = nullptr; |
429 | |
430 | /// The previous token in the unwrapped line. |
431 | FormatToken *Previous = nullptr; |
432 | |
433 | /// The next token in the unwrapped line. |
434 | FormatToken *Next = nullptr; |
435 | |
436 | /// The first token in set of column elements. |
437 | bool StartsColumn = false; |
438 | |
439 | /// This notes the start of the line of an array initializer. |
440 | bool ArrayInitializerLineStart = false; |
441 | |
442 | /// This starts an array initializer. |
443 | bool IsArrayInitializer = false; |
444 | |
445 | /// Is optional and can be removed. |
446 | bool Optional = false; |
447 | |
448 | /// If this token starts a block, this contains all the unwrapped lines |
449 | /// in it. |
450 | SmallVector<AnnotatedLine *, 1> Children; |
451 | |
452 | // Contains all attributes related to how this token takes part |
453 | // in a configured macro expansion. |
454 | llvm::Optional<MacroExpansion> MacroCtx; |
455 | |
456 | bool is(tok::TokenKind Kind) const { return Tok.is(Kind); } |
457 | bool is(TokenType TT) const { return getType() == TT; } |
458 | bool is(const IdentifierInfo *II) const { |
459 | return II && II == Tok.getIdentifierInfo(); |
460 | } |
461 | bool is(tok::PPKeywordKind Kind) const { |
462 | return Tok.getIdentifierInfo() && |
463 | Tok.getIdentifierInfo()->getPPKeywordID() == Kind; |
464 | } |
465 | bool is(BraceBlockKind BBK) const { return getBlockKind() == BBK; } |
466 | bool is(ParameterPackingKind PPK) const { return getPackingKind() == PPK; } |
467 | |
468 | template <typename A, typename B> bool isOneOf(A K1, B K2) const { |
469 | return is(K1) || is(K2); |
470 | } |
471 | template <typename A, typename B, typename... Ts> |
472 | bool isOneOf(A K1, B K2, Ts... Ks) const { |
473 | return is(K1) || isOneOf(K2, Ks...); |
474 | } |
475 | template <typename T> bool isNot(T Kind) const { return !is(Kind); } |
476 | |
477 | bool isIf(bool AllowConstexprMacro = true) const { |
478 | return is(tok::kw_if) || endsSequence(tok::kw_constexpr, tok::kw_if) || |
479 | (endsSequence(tok::identifier, tok::kw_if) && AllowConstexprMacro); |
480 | } |
481 | |
482 | bool closesScopeAfterBlock() const { |
483 | if (getBlockKind() == BK_Block) |
484 | return true; |
485 | if (closesScope()) |
486 | return Previous->closesScopeAfterBlock(); |
487 | return false; |
488 | } |
489 | |
490 | /// \c true if this token starts a sequence with the given tokens in order, |
491 | /// following the ``Next`` pointers, ignoring comments. |
492 | template <typename A, typename... Ts> |
493 | bool startsSequence(A K1, Ts... Tokens) const { |
494 | return startsSequenceInternal(K1, Tokens...); |
495 | } |
496 | |
497 | /// \c true if this token ends a sequence with the given tokens in order, |
498 | /// following the ``Previous`` pointers, ignoring comments. |
499 | /// For example, given tokens [T1, T2, T3], the function returns true if |
500 | /// 3 tokens ending at this (ignoring comments) are [T3, T2, T1]. In other |
501 | /// words, the tokens passed to this function need to the reverse of the |
502 | /// order the tokens appear in code. |
503 | template <typename A, typename... Ts> |
504 | bool endsSequence(A K1, Ts... Tokens) const { |
505 | return endsSequenceInternal(K1, Tokens...); |
506 | } |
507 | |
508 | bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } |
509 | |
510 | bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const { |
511 | return Tok.isObjCAtKeyword(Kind); |
512 | } |
513 | |
514 | bool isAccessSpecifier(bool ColonRequired = true) const { |
515 | return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) && |
516 | (!ColonRequired || (Next && Next->is(tok::colon))); |
517 | } |
518 | |
519 | bool canBePointerOrReferenceQualifier() const { |
520 | return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile, |
521 | tok::kw___attribute, tok::kw__Nonnull, tok::kw__Nullable, |
522 | tok::kw__Null_unspecified, tok::kw___ptr32, tok::kw___ptr64, |
523 | TT_AttributeMacro); |
524 | } |
525 | |
526 | /// Determine whether the token is a simple-type-specifier. |
527 | LLVM_NODISCARD[[clang::warn_unused_result]] bool isSimpleTypeSpecifier() const; |
528 | |
529 | LLVM_NODISCARD[[clang::warn_unused_result]] bool isTypeOrIdentifier() const; |
530 | |
531 | bool isObjCAccessSpecifier() const { |
532 | return is(tok::at) && Next && |
533 | (Next->isObjCAtKeyword(tok::objc_public) || |
534 | Next->isObjCAtKeyword(tok::objc_protected) || |
535 | Next->isObjCAtKeyword(tok::objc_package) || |
536 | Next->isObjCAtKeyword(tok::objc_private)); |
537 | } |
538 | |
539 | /// Returns whether \p Tok is ([{ or an opening < of a template or in |
540 | /// protos. |
541 | bool opensScope() const { |
542 | if (is(TT_TemplateString) && TokenText.endswith("${")) |
543 | return true; |
544 | if (is(TT_DictLiteral) && is(tok::less)) |
545 | return true; |
546 | return isOneOf(tok::l_paren, tok::l_brace, tok::l_square, |
547 | TT_TemplateOpener); |
548 | } |
549 | /// Returns whether \p Tok is )]} or a closing > of a template or in |
550 | /// protos. |
551 | bool closesScope() const { |
552 | if (is(TT_TemplateString) && TokenText.startswith("}")) |
553 | return true; |
554 | if (is(TT_DictLiteral) && is(tok::greater)) |
555 | return true; |
556 | return isOneOf(tok::r_paren, tok::r_brace, tok::r_square, |
557 | TT_TemplateCloser); |
558 | } |
559 | |
560 | /// Returns \c true if this is a "." or "->" accessing a member. |
561 | bool isMemberAccess() const { |
562 | return isOneOf(tok::arrow, tok::period, tok::arrowstar) && |
563 | !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow, |
564 | TT_LambdaArrow, TT_LeadingJavaAnnotation); |
565 | } |
566 | |
567 | bool isUnaryOperator() const { |
568 | switch (Tok.getKind()) { |
569 | case tok::plus: |
570 | case tok::plusplus: |
571 | case tok::minus: |
572 | case tok::minusminus: |
573 | case tok::exclaim: |
574 | case tok::tilde: |
575 | case tok::kw_sizeof: |
576 | case tok::kw_alignof: |
577 | return true; |
578 | default: |
579 | return false; |
580 | } |
581 | } |
582 | |
583 | bool isBinaryOperator() const { |
584 | // Comma is a binary operator, but does not behave as such wrt. formatting. |
585 | return getPrecedence() > prec::Comma; |
586 | } |
587 | |
588 | bool isTrailingComment() const { |
589 | return is(tok::comment) && |
590 | (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0); |
591 | } |
592 | |
593 | /// Returns \c true if this is a keyword that can be used |
594 | /// like a function call (e.g. sizeof, typeid, ...). |
595 | bool isFunctionLikeKeyword() const { |
596 | switch (Tok.getKind()) { |
597 | case tok::kw_throw: |
598 | case tok::kw_typeid: |
599 | case tok::kw_return: |
600 | case tok::kw_sizeof: |
601 | case tok::kw_alignof: |
602 | case tok::kw_alignas: |
603 | case tok::kw_decltype: |
604 | case tok::kw_noexcept: |
605 | case tok::kw_static_assert: |
606 | case tok::kw__Atomic: |
607 | case tok::kw___attribute: |
608 | case tok::kw___underlying_type: |
609 | case tok::kw_requires: |
610 | return true; |
611 | default: |
612 | return false; |
613 | } |
614 | } |
615 | |
616 | /// Returns \c true if this is a string literal that's like a label, |
617 | /// e.g. ends with "=" or ":". |
618 | bool isLabelString() const { |
619 | if (!is(tok::string_literal)) |
620 | return false; |
621 | StringRef Content = TokenText; |
622 | if (Content.startswith("\"") || Content.startswith("'")) |
623 | Content = Content.drop_front(1); |
624 | if (Content.endswith("\"") || Content.endswith("'")) |
625 | Content = Content.drop_back(1); |
626 | Content = Content.trim(); |
627 | return Content.size() > 1 && |
628 | (Content.back() == ':' || Content.back() == '='); |
629 | } |
630 | |
631 | /// Returns actual token start location without leading escaped |
632 | /// newlines and whitespace. |
633 | /// |
634 | /// This can be different to Tok.getLocation(), which includes leading escaped |
635 | /// newlines. |
636 | SourceLocation getStartOfNonWhitespace() const { |
637 | return WhitespaceRange.getEnd(); |
638 | } |
639 | |
640 | prec::Level getPrecedence() const { |
641 | return getBinOpPrecedence(Tok.getKind(), /*GreaterThanIsOperator=*/true, |
642 | /*CPlusPlus11=*/true); |
643 | } |
644 | |
645 | /// Returns the previous token ignoring comments. |
646 | FormatToken *getPreviousNonComment() const { |
647 | FormatToken *Tok = Previous; |
648 | while (Tok && Tok->is(tok::comment)) |
649 | Tok = Tok->Previous; |
650 | return Tok; |
651 | } |
652 | |
653 | /// Returns the next token ignoring comments. |
654 | const FormatToken *getNextNonComment() const { |
655 | const FormatToken *Tok = Next; |
656 | while (Tok && Tok->is(tok::comment)) |
657 | Tok = Tok->Next; |
658 | return Tok; |
659 | } |
660 | |
661 | /// Returns \c true if this tokens starts a block-type list, i.e. a |
662 | /// list that should be indented with a block indent. |
663 | bool opensBlockOrBlockTypeList(const FormatStyle &Style) const { |
664 | // C# Does not indent object initialisers as continuations. |
665 | if (is(tok::l_brace) && getBlockKind() == BK_BracedInit && Style.isCSharp()) |
666 | return true; |
667 | if (is(TT_TemplateString) && opensScope()) |
668 | return true; |
669 | return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) || |
670 | (is(tok::l_brace) && |
671 | (getBlockKind() == BK_Block || is(TT_DictLiteral) || |
672 | (!Style.Cpp11BracedListStyle && NestingLevel == 0))) || |
673 | (is(tok::less) && (Style.Language == FormatStyle::LK_Proto || |
674 | Style.Language == FormatStyle::LK_TextProto)); |
675 | } |
676 | |
677 | /// Returns whether the token is the left square bracket of a C++ |
678 | /// structured binding declaration. |
679 | bool isCppStructuredBinding(const FormatStyle &Style) const { |
680 | if (!Style.isCpp() || isNot(tok::l_square)) |
681 | return false; |
682 | const FormatToken *T = this; |
683 | do { |
684 | T = T->getPreviousNonComment(); |
685 | } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp, |
686 | tok::ampamp)); |
687 | return T && T->is(tok::kw_auto); |
688 | } |
689 | |
690 | /// Same as opensBlockOrBlockTypeList, but for the closing token. |
691 | bool closesBlockOrBlockTypeList(const FormatStyle &Style) const { |
692 | if (is(TT_TemplateString) && closesScope()) |
693 | return true; |
694 | return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style); |
695 | } |
696 | |
697 | /// Return the actual namespace token, if this token starts a namespace |
698 | /// block. |
699 | const FormatToken *getNamespaceToken() const { |
700 | const FormatToken *NamespaceTok = this; |
701 | if (is(tok::comment)) |
702 | NamespaceTok = NamespaceTok->getNextNonComment(); |
703 | // Detect "(inline|export)? namespace" in the beginning of a line. |
704 | if (NamespaceTok && NamespaceTok->isOneOf(tok::kw_inline, tok::kw_export)) |
705 | NamespaceTok = NamespaceTok->getNextNonComment(); |
706 | return NamespaceTok && |
707 | NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) |
708 | ? NamespaceTok |
709 | : nullptr; |
710 | } |
711 | |
712 | void copyFrom(const FormatToken &Tok) { *this = Tok; } |
713 | |
714 | private: |
715 | // Only allow copying via the explicit copyFrom method. |
716 | FormatToken(const FormatToken &) = delete; |
717 | FormatToken &operator=(const FormatToken &) = default; |
718 | |
719 | template <typename A, typename... Ts> |
720 | bool startsSequenceInternal(A K1, Ts... Tokens) const { |
721 | if (is(tok::comment) && Next) |
722 | return Next->startsSequenceInternal(K1, Tokens...); |
723 | return is(K1) && Next && Next->startsSequenceInternal(Tokens...); |
724 | } |
725 | |
726 | template <typename A> bool startsSequenceInternal(A K1) const { |
727 | if (is(tok::comment) && Next) |
728 | return Next->startsSequenceInternal(K1); |
729 | return is(K1); |
730 | } |
731 | |
732 | template <typename A, typename... Ts> bool endsSequenceInternal(A K1) const { |
733 | if (is(tok::comment) && Previous) |
734 | return Previous->endsSequenceInternal(K1); |
735 | return is(K1); |
736 | } |
737 | |
738 | template <typename A, typename... Ts> |
739 | bool endsSequenceInternal(A K1, Ts... Tokens) const { |
740 | if (is(tok::comment) && Previous) |
741 | return Previous->endsSequenceInternal(K1, Tokens...); |
742 | return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...); |
743 | } |
744 | }; |
745 | |
746 | class ContinuationIndenter; |
747 | struct LineState; |
748 | |
749 | class TokenRole { |
750 | public: |
751 | TokenRole(const FormatStyle &Style) : Style(Style) {} |
752 | virtual ~TokenRole(); |
753 | |
754 | /// After the \c TokenAnnotator has finished annotating all the tokens, |
755 | /// this function precomputes required information for formatting. |
756 | virtual void precomputeFormattingInfos(const FormatToken *Token); |
757 | |
758 | /// Apply the special formatting that the given role demands. |
759 | /// |
760 | /// Assumes that the token having this role is already formatted. |
761 | /// |
762 | /// Continues formatting from \p State leaving indentation to \p Indenter and |
763 | /// returns the total penalty that this formatting incurs. |
764 | virtual unsigned formatFromToken(LineState &State, |
765 | ContinuationIndenter *Indenter, |
766 | bool DryRun) { |
767 | return 0; |
768 | } |
769 | |
770 | /// Same as \c formatFromToken, but assumes that the first token has |
771 | /// already been set thereby deciding on the first line break. |
772 | virtual unsigned formatAfterToken(LineState &State, |
773 | ContinuationIndenter *Indenter, |
774 | bool DryRun) { |
775 | return 0; |
776 | } |
777 | |
778 | /// Notifies the \c Role that a comma was found. |
779 | virtual void CommaFound(const FormatToken *Token) {} |
780 | |
781 | virtual const FormatToken *lastComma() { return nullptr; } |
782 | |
783 | protected: |
784 | const FormatStyle &Style; |
785 | }; |
786 | |
787 | class CommaSeparatedList : public TokenRole { |
788 | public: |
789 | CommaSeparatedList(const FormatStyle &Style) |
790 | : TokenRole(Style), HasNestedBracedList(false) {} |
791 | |
792 | void precomputeFormattingInfos(const FormatToken *Token) override; |
793 | |
794 | unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, |
795 | bool DryRun) override; |
796 | |
797 | unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, |
798 | bool DryRun) override; |
799 | |
800 | /// Adds \p Token as the next comma to the \c CommaSeparated list. |
801 | void CommaFound(const FormatToken *Token) override { |
802 | Commas.push_back(Token); |
803 | } |
804 | |
805 | const FormatToken *lastComma() override { |
806 | if (Commas.empty()) |
807 | return nullptr; |
808 | return Commas.back(); |
809 | } |
810 | |
811 | private: |
812 | /// A struct that holds information on how to format a given list with |
813 | /// a specific number of columns. |
814 | struct ColumnFormat { |
815 | /// The number of columns to use. |
816 | unsigned Columns; |
817 | |
818 | /// The total width in characters. |
819 | unsigned TotalWidth; |
820 | |
821 | /// The number of lines required for this format. |
822 | unsigned LineCount; |
823 | |
824 | /// The size of each column in characters. |
825 | SmallVector<unsigned, 8> ColumnSizes; |
826 | }; |
827 | |
828 | /// Calculate which \c ColumnFormat fits best into |
829 | /// \p RemainingCharacters. |
830 | const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const; |
831 | |
832 | /// The ordered \c FormatTokens making up the commas of this list. |
833 | SmallVector<const FormatToken *, 8> Commas; |
834 | |
835 | /// The length of each of the list's items in characters including the |
836 | /// trailing comma. |
837 | SmallVector<unsigned, 8> ItemLengths; |
838 | |
839 | /// Precomputed formats that can be used for this list. |
840 | SmallVector<ColumnFormat, 4> Formats; |
841 | |
842 | bool HasNestedBracedList; |
843 | }; |
844 | |
845 | /// Encapsulates keywords that are context sensitive or for languages not |
846 | /// properly supported by Clang's lexer. |
847 | struct AdditionalKeywords { |
848 | AdditionalKeywords(IdentifierTable &IdentTable) { |
849 | kw_final = &IdentTable.get("final"); |
850 | kw_override = &IdentTable.get("override"); |
851 | kw_in = &IdentTable.get("in"); |
852 | kw_of = &IdentTable.get("of"); |
853 | kw_CF_CLOSED_ENUM = &IdentTable.get("CF_CLOSED_ENUM"); |
854 | kw_CF_ENUM = &IdentTable.get("CF_ENUM"); |
855 | kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS"); |
856 | kw_NS_CLOSED_ENUM = &IdentTable.get("NS_CLOSED_ENUM"); |
857 | kw_NS_ENUM = &IdentTable.get("NS_ENUM"); |
858 | kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS"); |
859 | |
860 | kw_as = &IdentTable.get("as"); |
861 | kw_async = &IdentTable.get("async"); |
862 | kw_await = &IdentTable.get("await"); |
863 | kw_declare = &IdentTable.get("declare"); |
864 | kw_finally = &IdentTable.get("finally"); |
865 | kw_from = &IdentTable.get("from"); |
866 | kw_function = &IdentTable.get("function"); |
867 | kw_get = &IdentTable.get("get"); |
868 | kw_import = &IdentTable.get("import"); |
869 | kw_infer = &IdentTable.get("infer"); |
870 | kw_is = &IdentTable.get("is"); |
871 | kw_let = &IdentTable.get("let"); |
872 | kw_module = &IdentTable.get("module"); |
873 | kw_readonly = &IdentTable.get("readonly"); |
874 | kw_set = &IdentTable.get("set"); |
875 | kw_type = &IdentTable.get("type"); |
876 | kw_typeof = &IdentTable.get("typeof"); |
877 | kw_var = &IdentTable.get("var"); |
878 | kw_yield = &IdentTable.get("yield"); |
879 | |
880 | kw_abstract = &IdentTable.get("abstract"); |
881 | kw_assert = &IdentTable.get("assert"); |
882 | kw_extends = &IdentTable.get("extends"); |
883 | kw_implements = &IdentTable.get("implements"); |
884 | kw_instanceof = &IdentTable.get("instanceof"); |
885 | kw_interface = &IdentTable.get("interface"); |
886 | kw_native = &IdentTable.get("native"); |
887 | kw_package = &IdentTable.get("package"); |
888 | kw_synchronized = &IdentTable.get("synchronized"); |
889 | kw_throws = &IdentTable.get("throws"); |
890 | kw___except = &IdentTable.get("__except"); |
891 | kw___has_include = &IdentTable.get("__has_include"); |
892 | kw___has_include_next = &IdentTable.get("__has_include_next"); |
893 | |
894 | kw_mark = &IdentTable.get("mark"); |
895 | |
896 | kw_extend = &IdentTable.get("extend"); |
897 | kw_option = &IdentTable.get("option"); |
898 | kw_optional = &IdentTable.get("optional"); |
899 | kw_repeated = &IdentTable.get("repeated"); |
900 | kw_required = &IdentTable.get("required"); |
901 | kw_returns = &IdentTable.get("returns"); |
902 | |
903 | kw_signals = &IdentTable.get("signals"); |
904 | kw_qsignals = &IdentTable.get("Q_SIGNALS"); |
905 | kw_slots = &IdentTable.get("slots"); |
906 | kw_qslots = &IdentTable.get("Q_SLOTS"); |
907 | |
908 | // C# keywords |
909 | kw_dollar = &IdentTable.get("dollar"); |
910 | kw_base = &IdentTable.get("base"); |
911 | kw_byte = &IdentTable.get("byte"); |
912 | kw_checked = &IdentTable.get("checked"); |
913 | kw_decimal = &IdentTable.get("decimal"); |
914 | kw_delegate = &IdentTable.get("delegate"); |
915 | kw_event = &IdentTable.get("event"); |
916 | kw_fixed = &IdentTable.get("fixed"); |
917 | kw_foreach = &IdentTable.get("foreach"); |
918 | kw_implicit = &IdentTable.get("implicit"); |
919 | kw_internal = &IdentTable.get("internal"); |
920 | kw_lock = &IdentTable.get("lock"); |
921 | kw_null = &IdentTable.get("null"); |
922 | kw_object = &IdentTable.get("object"); |
923 | kw_out = &IdentTable.get("out"); |
924 | kw_params = &IdentTable.get("params"); |
925 | kw_ref = &IdentTable.get("ref"); |
926 | kw_string = &IdentTable.get("string"); |
927 | kw_stackalloc = &IdentTable.get("stackalloc"); |
928 | kw_sbyte = &IdentTable.get("sbyte"); |
929 | kw_sealed = &IdentTable.get("sealed"); |
930 | kw_uint = &IdentTable.get("uint"); |
931 | kw_ulong = &IdentTable.get("ulong"); |
932 | kw_unchecked = &IdentTable.get("unchecked"); |
933 | kw_unsafe = &IdentTable.get("unsafe"); |
934 | kw_ushort = &IdentTable.get("ushort"); |
935 | kw_when = &IdentTable.get("when"); |
936 | kw_where = &IdentTable.get("where"); |
937 | |
938 | // Keep this at the end of the constructor to make sure everything here |
939 | // is |
940 | // already initialized. |
941 | JsExtraKeywords = std::unordered_set<IdentifierInfo *>( |
942 | {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from, |
943 | kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_override, |
944 | kw_readonly, kw_set, kw_type, kw_typeof, kw_var, kw_yield, |
945 | // Keywords from the Java section. |
946 | kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface}); |
947 | |
948 | CSharpExtraKeywords = std::unordered_set<IdentifierInfo *>( |
949 | {kw_base, kw_byte, kw_checked, kw_decimal, kw_delegate, kw_event, |
950 | kw_fixed, kw_foreach, kw_implicit, kw_in, kw_interface, kw_internal, |
951 | kw_is, kw_lock, kw_null, kw_object, kw_out, kw_override, kw_params, |
952 | kw_readonly, kw_ref, kw_string, kw_stackalloc, kw_sbyte, kw_sealed, |
953 | kw_uint, kw_ulong, kw_unchecked, kw_unsafe, kw_ushort, kw_when, |
954 | kw_where, |
955 | // Keywords from the JavaScript section. |
956 | kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from, |
957 | kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly, |
958 | kw_set, kw_type, kw_typeof, kw_var, kw_yield, |
959 | // Keywords from the Java section. |
960 | kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface}); |
961 | } |
962 | |
963 | // Context sensitive keywords. |
964 | IdentifierInfo *kw_final; |
965 | IdentifierInfo *kw_override; |
966 | IdentifierInfo *kw_in; |
967 | IdentifierInfo *kw_of; |
968 | IdentifierInfo *kw_CF_CLOSED_ENUM; |
969 | IdentifierInfo *kw_CF_ENUM; |
970 | IdentifierInfo *kw_CF_OPTIONS; |
971 | IdentifierInfo *kw_NS_CLOSED_ENUM; |
972 | IdentifierInfo *kw_NS_ENUM; |
973 | IdentifierInfo *kw_NS_OPTIONS; |
974 | IdentifierInfo *kw___except; |
975 | IdentifierInfo *kw___has_include; |
976 | IdentifierInfo *kw___has_include_next; |
977 | |
978 | // JavaScript keywords. |
979 | IdentifierInfo *kw_as; |
980 | IdentifierInfo *kw_async; |
981 | IdentifierInfo *kw_await; |
982 | IdentifierInfo *kw_declare; |
983 | IdentifierInfo *kw_finally; |
984 | IdentifierInfo *kw_from; |
985 | IdentifierInfo *kw_function; |
986 | IdentifierInfo *kw_get; |
987 | IdentifierInfo *kw_import; |
988 | IdentifierInfo *kw_infer; |
989 | IdentifierInfo *kw_is; |
990 | IdentifierInfo *kw_let; |
991 | IdentifierInfo *kw_module; |
992 | IdentifierInfo *kw_readonly; |
993 | IdentifierInfo *kw_set; |
994 | IdentifierInfo *kw_type; |
995 | IdentifierInfo *kw_typeof; |
996 | IdentifierInfo *kw_var; |
997 | IdentifierInfo *kw_yield; |
998 | |
999 | // Java keywords. |
1000 | IdentifierInfo *kw_abstract; |
1001 | IdentifierInfo *kw_assert; |
1002 | IdentifierInfo *kw_extends; |
1003 | IdentifierInfo *kw_implements; |
1004 | IdentifierInfo *kw_instanceof; |
1005 | IdentifierInfo *kw_interface; |
1006 | IdentifierInfo *kw_native; |
1007 | IdentifierInfo *kw_package; |
1008 | IdentifierInfo *kw_synchronized; |
1009 | IdentifierInfo *kw_throws; |
1010 | |
1011 | // Pragma keywords. |
1012 | IdentifierInfo *kw_mark; |
1013 | |
1014 | // Proto keywords. |
1015 | IdentifierInfo *kw_extend; |
1016 | IdentifierInfo *kw_option; |
1017 | IdentifierInfo *kw_optional; |
1018 | IdentifierInfo *kw_repeated; |
1019 | IdentifierInfo *kw_required; |
1020 | IdentifierInfo *kw_returns; |
1021 | |
1022 | // QT keywords. |
1023 | IdentifierInfo *kw_signals; |
1024 | IdentifierInfo *kw_qsignals; |
1025 | IdentifierInfo *kw_slots; |
1026 | IdentifierInfo *kw_qslots; |
1027 | |
1028 | // C# keywords |
1029 | IdentifierInfo *kw_dollar; |
1030 | IdentifierInfo *kw_base; |
1031 | IdentifierInfo *kw_byte; |
1032 | IdentifierInfo *kw_checked; |
1033 | IdentifierInfo *kw_decimal; |
1034 | IdentifierInfo *kw_delegate; |
1035 | IdentifierInfo *kw_event; |
1036 | IdentifierInfo *kw_fixed; |
1037 | IdentifierInfo *kw_foreach; |
1038 | IdentifierInfo *kw_implicit; |
1039 | IdentifierInfo *kw_internal; |
1040 | |
1041 | IdentifierInfo *kw_lock; |
1042 | IdentifierInfo *kw_null; |
1043 | IdentifierInfo *kw_object; |
1044 | IdentifierInfo *kw_out; |
1045 | |
1046 | IdentifierInfo *kw_params; |
1047 | |
1048 | IdentifierInfo *kw_ref; |
1049 | IdentifierInfo *kw_string; |
1050 | IdentifierInfo *kw_stackalloc; |
1051 | IdentifierInfo *kw_sbyte; |
1052 | IdentifierInfo *kw_sealed; |
1053 | IdentifierInfo *kw_uint; |
1054 | IdentifierInfo *kw_ulong; |
1055 | IdentifierInfo *kw_unchecked; |
1056 | IdentifierInfo *kw_unsafe; |
1057 | IdentifierInfo *kw_ushort; |
1058 | IdentifierInfo *kw_when; |
1059 | IdentifierInfo *kw_where; |
1060 | |
1061 | /// Returns \c true if \p Tok is a true JavaScript identifier, returns |
1062 | /// \c false if it is a keyword or a pseudo keyword. |
1063 | /// If \c AcceptIdentifierName is true, returns true not only for keywords, |
1064 | // but also for IdentifierName tokens (aka pseudo-keywords), such as |
1065 | // ``yield``. |
1066 | bool IsJavaScriptIdentifier(const FormatToken &Tok, |
1067 | bool AcceptIdentifierName = true) const { |
1068 | // Based on the list of JavaScript & TypeScript keywords here: |
1069 | // https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74 |
1070 | switch (Tok.Tok.getKind()) { |
1071 | case tok::kw_break: |
1072 | case tok::kw_case: |
1073 | case tok::kw_catch: |
1074 | case tok::kw_class: |
1075 | case tok::kw_continue: |
1076 | case tok::kw_const: |
1077 | case tok::kw_default: |
1078 | case tok::kw_delete: |
1079 | case tok::kw_do: |
1080 | case tok::kw_else: |
1081 | case tok::kw_enum: |
1082 | case tok::kw_export: |
1083 | case tok::kw_false: |
1084 | case tok::kw_for: |
1085 | case tok::kw_if: |
1086 | case tok::kw_import: |
1087 | case tok::kw_module: |
1088 | case tok::kw_new: |
1089 | case tok::kw_private: |
1090 | case tok::kw_protected: |
1091 | case tok::kw_public: |
1092 | case tok::kw_return: |
1093 | case tok::kw_static: |
1094 | case tok::kw_switch: |
1095 | case tok::kw_this: |
1096 | case tok::kw_throw: |
1097 | case tok::kw_true: |
1098 | case tok::kw_try: |
1099 | case tok::kw_typeof: |
1100 | case tok::kw_void: |
1101 | case tok::kw_while: |
1102 | // These are JS keywords that are lexed by LLVM/clang as keywords. |
1103 | return false; |
1104 | case tok::identifier: { |
1105 | // For identifiers, make sure they are true identifiers, excluding the |
1106 | // JavaScript pseudo-keywords (not lexed by LLVM/clang as keywords). |
1107 | bool IsPseudoKeyword = |
1108 | JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) != |
1109 | JsExtraKeywords.end(); |
1110 | return AcceptIdentifierName || !IsPseudoKeyword; |
1111 | } |
1112 | default: |
1113 | // Other keywords are handled in the switch below, to avoid problems due |
1114 | // to duplicate case labels when using the #include trick. |
1115 | break; |
1116 | } |
1117 | |
1118 | switch (Tok.Tok.getKind()) { |
1119 | // Handle C++ keywords not included above: these are all JS identifiers. |
1120 | #define KEYWORD(X, Y) case tok::kw_##X: |
1121 | #include "clang/Basic/TokenKinds.def" |
1122 | // #undef KEYWORD is not needed -- it's #undef-ed at the end of |
1123 | // TokenKinds.def |
1124 | return true; |
1125 | default: |
1126 | // All other tokens (punctuation etc) are not JS identifiers. |
1127 | return false; |
1128 | } |
1129 | } |
1130 | |
1131 | /// Returns \c true if \p Tok is a C# keyword, returns |
1132 | /// \c false if it is a anything else. |
1133 | bool isCSharpKeyword(const FormatToken &Tok) const { |
1134 | switch (Tok.Tok.getKind()) { |
1135 | case tok::kw_bool: |
1136 | case tok::kw_break: |
1137 | case tok::kw_case: |
1138 | case tok::kw_catch: |
1139 | case tok::kw_char: |
1140 | case tok::kw_class: |
1141 | case tok::kw_const: |
1142 | case tok::kw_continue: |
1143 | case tok::kw_default: |
1144 | case tok::kw_do: |
1145 | case tok::kw_double: |
1146 | case tok::kw_else: |
1147 | case tok::kw_enum: |
1148 | case tok::kw_explicit: |
1149 | case tok::kw_extern: |
1150 | case tok::kw_false: |
1151 | case tok::kw_float: |
1152 | case tok::kw_for: |
1153 | case tok::kw_goto: |
1154 | case tok::kw_if: |
1155 | case tok::kw_int: |
1156 | case tok::kw_long: |
1157 | case tok::kw_namespace: |
1158 | case tok::kw_new: |
1159 | case tok::kw_operator: |
1160 | case tok::kw_private: |
1161 | case tok::kw_protected: |
1162 | case tok::kw_public: |
1163 | case tok::kw_return: |
1164 | case tok::kw_short: |
1165 | case tok::kw_sizeof: |
1166 | case tok::kw_static: |
1167 | case tok::kw_struct: |
1168 | case tok::kw_switch: |
1169 | case tok::kw_this: |
1170 | case tok::kw_throw: |
1171 | case tok::kw_true: |
1172 | case tok::kw_try: |
1173 | case tok::kw_typeof: |
1174 | case tok::kw_using: |
1175 | case tok::kw_virtual: |
1176 | case tok::kw_void: |
1177 | case tok::kw_volatile: |
1178 | case tok::kw_while: |
1179 | return true; |
1180 | default: |
1181 | return Tok.is(tok::identifier) && |
1182 | CSharpExtraKeywords.find(Tok.Tok.getIdentifierInfo()) == |
1183 | CSharpExtraKeywords.end(); |
1184 | } |
1185 | } |
1186 | |
1187 | private: |
1188 | /// The JavaScript keywords beyond the C++ keyword set. |
1189 | std::unordered_set<IdentifierInfo *> JsExtraKeywords; |
1190 | |
1191 | /// The C# keywords beyond the C++ keyword set |
1192 | std::unordered_set<IdentifierInfo *> CSharpExtraKeywords; |
1193 | }; |
1194 | |
1195 | } // namespace format |
1196 | } // namespace clang |
1197 | |
1198 | #endif |
1 | //===--- Token.h - Token interface ------------------------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines the Token interface. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_LEX_TOKEN_H |
14 | #define LLVM_CLANG_LEX_TOKEN_H |
15 | |
16 | #include "clang/Basic/SourceLocation.h" |
17 | #include "clang/Basic/TokenKinds.h" |
18 | #include "llvm/ADT/StringRef.h" |
19 | #include <cassert> |
20 | |
21 | namespace clang { |
22 | |
23 | class IdentifierInfo; |
24 | |
25 | /// Token - This structure provides full information about a lexed token. |
26 | /// It is not intended to be space efficient, it is intended to return as much |
27 | /// information as possible about each returned token. This is expected to be |
28 | /// compressed into a smaller form if memory footprint is important. |
29 | /// |
30 | /// The parser can create a special "annotation token" representing a stream of |
31 | /// tokens that were parsed and semantically resolved, e.g.: "foo::MyClass<int>" |
32 | /// can be represented by a single typename annotation token that carries |
33 | /// information about the SourceRange of the tokens and the type object. |
34 | class Token { |
35 | /// The location of the token. This is actually a SourceLocation. |
36 | SourceLocation::UIntTy Loc; |
37 | |
38 | // Conceptually these next two fields could be in a union. However, this |
39 | // causes gcc 4.2 to pessimize LexTokenInternal, a very performance critical |
40 | // routine. Keeping as separate members with casts until a more beautiful fix |
41 | // presents itself. |
42 | |
43 | /// UintData - This holds either the length of the token text, when |
44 | /// a normal token, or the end of the SourceRange when an annotation |
45 | /// token. |
46 | SourceLocation::UIntTy UintData; |
47 | |
48 | /// PtrData - This is a union of four different pointer types, which depends |
49 | /// on what type of token this is: |
50 | /// Identifiers, keywords, etc: |
51 | /// This is an IdentifierInfo*, which contains the uniqued identifier |
52 | /// spelling. |
53 | /// Literals: isLiteral() returns true. |
54 | /// This is a pointer to the start of the token in a text buffer, which |
55 | /// may be dirty (have trigraphs / escaped newlines). |
56 | /// Annotations (resolved type names, C++ scopes, etc): isAnnotation(). |
57 | /// This is a pointer to sema-specific data for the annotation token. |
58 | /// Eof: |
59 | // This is a pointer to a Decl. |
60 | /// Other: |
61 | /// This is null. |
62 | void *PtrData; |
63 | |
64 | /// Kind - The actual flavor of token this is. |
65 | tok::TokenKind Kind; |
66 | |
67 | /// Flags - Bits we track about this token, members of the TokenFlags enum. |
68 | unsigned short Flags; |
69 | |
70 | public: |
71 | // Various flags set per token: |
72 | enum TokenFlags { |
73 | StartOfLine = 0x01, // At start of line or only after whitespace |
74 | // (considering the line after macro expansion). |
75 | LeadingSpace = 0x02, // Whitespace exists before this token (considering |
76 | // whitespace after macro expansion). |
77 | DisableExpand = 0x04, // This identifier may never be macro expanded. |
78 | NeedsCleaning = 0x08, // Contained an escaped newline or trigraph. |
79 | LeadingEmptyMacro = 0x10, // Empty macro exists before this token. |
80 | HasUDSuffix = 0x20, // This string or character literal has a ud-suffix. |
81 | HasUCN = 0x40, // This identifier contains a UCN. |
82 | IgnoredComma = 0x80, // This comma is not a macro argument separator (MS). |
83 | StringifiedInMacro = 0x100, // This string or character literal is formed by |
84 | // macro stringizing or charizing operator. |
85 | CommaAfterElided = 0x200, // The comma following this token was elided (MS). |
86 | IsEditorPlaceholder = 0x400, // This identifier is a placeholder. |
87 | IsReinjected = 0x800, // A phase 4 token that was produced before and |
88 | // re-added, e.g. via EnterTokenStream. Annotation |
89 | // tokens are *not* reinjected. |
90 | }; |
91 | |
92 | tok::TokenKind getKind() const { return Kind; } |
93 | void setKind(tok::TokenKind K) { Kind = K; } |
94 | |
95 | /// is/isNot - Predicates to check if this token is a specific kind, as in |
96 | /// "if (Tok.is(tok::l_brace)) {...}". |
97 | bool is(tok::TokenKind K) const { return Kind == K; } |
98 | bool isNot(tok::TokenKind K) const { return Kind != K; } |
99 | bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const { |
100 | return is(K1) || is(K2); |
101 | } |
102 | template <typename... Ts> |
103 | bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, Ts... Ks) const { |
104 | return is(K1) || isOneOf(K2, Ks...); |
105 | } |
106 | |
107 | /// Return true if this is a raw identifier (when lexing |
108 | /// in raw mode) or a non-keyword identifier (when lexing in non-raw mode). |
109 | bool isAnyIdentifier() const { |
110 | return tok::isAnyIdentifier(getKind()); |
111 | } |
112 | |
113 | /// Return true if this is a "literal", like a numeric |
114 | /// constant, string, etc. |
115 | bool isLiteral() const { |
116 | return tok::isLiteral(getKind()); |
117 | } |
118 | |
119 | /// Return true if this is any of tok::annot_* kind tokens. |
120 | bool isAnnotation() const { |
121 | return tok::isAnnotation(getKind()); |
122 | } |
123 | |
124 | /// Return a source location identifier for the specified |
125 | /// offset in the current file. |
126 | SourceLocation getLocation() const { |
127 | return SourceLocation::getFromRawEncoding(Loc); |
128 | } |
129 | unsigned getLength() const { |
130 | assert(!isAnnotation() && "Annotation tokens have no length field")(static_cast <bool> (!isAnnotation() && "Annotation tokens have no length field" ) ? void (0) : __assert_fail ("!isAnnotation() && \"Annotation tokens have no length field\"" , "clang/include/clang/Lex/Token.h", 130, __extension__ __PRETTY_FUNCTION__ )); |
131 | return UintData; |
132 | } |
133 | |
134 | void setLocation(SourceLocation L) { Loc = L.getRawEncoding(); } |
135 | void setLength(unsigned Len) { |
136 | assert(!isAnnotation() && "Annotation tokens have no length field")(static_cast <bool> (!isAnnotation() && "Annotation tokens have no length field" ) ? void (0) : __assert_fail ("!isAnnotation() && \"Annotation tokens have no length field\"" , "clang/include/clang/Lex/Token.h", 136, __extension__ __PRETTY_FUNCTION__ )); |
137 | UintData = Len; |
138 | } |
139 | |
140 | SourceLocation getAnnotationEndLoc() const { |
141 | assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")(static_cast <bool> (isAnnotation() && "Used AnnotEndLocID on non-annotation token" ) ? void (0) : __assert_fail ("isAnnotation() && \"Used AnnotEndLocID on non-annotation token\"" , "clang/include/clang/Lex/Token.h", 141, __extension__ __PRETTY_FUNCTION__ )); |
142 | return SourceLocation::getFromRawEncoding(UintData ? UintData : Loc); |
143 | } |
144 | void setAnnotationEndLoc(SourceLocation L) { |
145 | assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token")(static_cast <bool> (isAnnotation() && "Used AnnotEndLocID on non-annotation token" ) ? void (0) : __assert_fail ("isAnnotation() && \"Used AnnotEndLocID on non-annotation token\"" , "clang/include/clang/Lex/Token.h", 145, __extension__ __PRETTY_FUNCTION__ )); |
146 | UintData = L.getRawEncoding(); |
147 | } |
148 | |
149 | SourceLocation getLastLoc() const { |
150 | return isAnnotation() ? getAnnotationEndLoc() : getLocation(); |
151 | } |
152 | |
153 | SourceLocation getEndLoc() const { |
154 | return isAnnotation() ? getAnnotationEndLoc() |
155 | : getLocation().getLocWithOffset(getLength()); |
156 | } |
157 | |
158 | /// SourceRange of the group of tokens that this annotation token |
159 | /// represents. |
160 | SourceRange getAnnotationRange() const { |
161 | return SourceRange(getLocation(), getAnnotationEndLoc()); |
162 | } |
163 | void setAnnotationRange(SourceRange R) { |
164 | setLocation(R.getBegin()); |
165 | setAnnotationEndLoc(R.getEnd()); |
166 | } |
167 | |
168 | const char *getName() const { return tok::getTokenName(Kind); } |
169 | |
170 | /// Reset all flags to cleared. |
171 | void startToken() { |
172 | Kind = tok::unknown; |
173 | Flags = 0; |
174 | PtrData = nullptr; |
175 | UintData = 0; |
176 | Loc = SourceLocation().getRawEncoding(); |
177 | } |
178 | |
179 | IdentifierInfo *getIdentifierInfo() const { |
180 | assert(isNot(tok::raw_identifier) &&(static_cast <bool> (isNot(tok::raw_identifier) && "getIdentifierInfo() on a tok::raw_identifier token!") ? void (0) : __assert_fail ("isNot(tok::raw_identifier) && \"getIdentifierInfo() on a tok::raw_identifier token!\"" , "clang/include/clang/Lex/Token.h", 181, __extension__ __PRETTY_FUNCTION__ )) |
181 | "getIdentifierInfo() on a tok::raw_identifier token!")(static_cast <bool> (isNot(tok::raw_identifier) && "getIdentifierInfo() on a tok::raw_identifier token!") ? void (0) : __assert_fail ("isNot(tok::raw_identifier) && \"getIdentifierInfo() on a tok::raw_identifier token!\"" , "clang/include/clang/Lex/Token.h", 181, __extension__ __PRETTY_FUNCTION__ )); |
182 | assert(!isAnnotation() &&(static_cast <bool> (!isAnnotation() && "getIdentifierInfo() on an annotation token!" ) ? void (0) : __assert_fail ("!isAnnotation() && \"getIdentifierInfo() on an annotation token!\"" , "clang/include/clang/Lex/Token.h", 183, __extension__ __PRETTY_FUNCTION__ )) |
183 | "getIdentifierInfo() on an annotation token!")(static_cast <bool> (!isAnnotation() && "getIdentifierInfo() on an annotation token!" ) ? void (0) : __assert_fail ("!isAnnotation() && \"getIdentifierInfo() on an annotation token!\"" , "clang/include/clang/Lex/Token.h", 183, __extension__ __PRETTY_FUNCTION__ )); |
184 | if (isLiteral()) return nullptr; |
185 | if (is(tok::eof)) return nullptr; |
186 | return (IdentifierInfo*) PtrData; |
187 | } |
188 | void setIdentifierInfo(IdentifierInfo *II) { |
189 | PtrData = (void*) II; |
190 | } |
191 | |
192 | const void *getEofData() const { |
193 | assert(is(tok::eof))(static_cast <bool> (is(tok::eof)) ? void (0) : __assert_fail ("is(tok::eof)", "clang/include/clang/Lex/Token.h", 193, __extension__ __PRETTY_FUNCTION__)); |
194 | return reinterpret_cast<const void *>(PtrData); |
195 | } |
196 | void setEofData(const void *D) { |
197 | assert(is(tok::eof))(static_cast <bool> (is(tok::eof)) ? void (0) : __assert_fail ("is(tok::eof)", "clang/include/clang/Lex/Token.h", 197, __extension__ __PRETTY_FUNCTION__)); |
198 | assert(!PtrData)(static_cast <bool> (!PtrData) ? void (0) : __assert_fail ("!PtrData", "clang/include/clang/Lex/Token.h", 198, __extension__ __PRETTY_FUNCTION__)); |
199 | PtrData = const_cast<void *>(D); |
200 | } |
201 | |
202 | /// getRawIdentifier - For a raw identifier token (i.e., an identifier |
203 | /// lexed in raw mode), returns a reference to the text substring in the |
204 | /// buffer if known. |
205 | StringRef getRawIdentifier() const { |
206 | assert(is(tok::raw_identifier))(static_cast <bool> (is(tok::raw_identifier)) ? void (0 ) : __assert_fail ("is(tok::raw_identifier)", "clang/include/clang/Lex/Token.h" , 206, __extension__ __PRETTY_FUNCTION__)); |
207 | return StringRef(reinterpret_cast<const char *>(PtrData), getLength()); |
208 | } |
209 | void setRawIdentifierData(const char *Ptr) { |
210 | assert(is(tok::raw_identifier))(static_cast <bool> (is(tok::raw_identifier)) ? void (0 ) : __assert_fail ("is(tok::raw_identifier)", "clang/include/clang/Lex/Token.h" , 210, __extension__ __PRETTY_FUNCTION__)); |
211 | PtrData = const_cast<char*>(Ptr); |
212 | } |
213 | |
214 | /// getLiteralData - For a literal token (numeric constant, string, etc), this |
215 | /// returns a pointer to the start of it in the text buffer if known, null |
216 | /// otherwise. |
217 | const char *getLiteralData() const { |
218 | assert(isLiteral() && "Cannot get literal data of non-literal")(static_cast <bool> (isLiteral() && "Cannot get literal data of non-literal" ) ? void (0) : __assert_fail ("isLiteral() && \"Cannot get literal data of non-literal\"" , "clang/include/clang/Lex/Token.h", 218, __extension__ __PRETTY_FUNCTION__ )); |
219 | return reinterpret_cast<const char*>(PtrData); |
220 | } |
221 | void setLiteralData(const char *Ptr) { |
222 | assert(isLiteral() && "Cannot set literal data of non-literal")(static_cast <bool> (isLiteral() && "Cannot set literal data of non-literal" ) ? void (0) : __assert_fail ("isLiteral() && \"Cannot set literal data of non-literal\"" , "clang/include/clang/Lex/Token.h", 222, __extension__ __PRETTY_FUNCTION__ )); |
223 | PtrData = const_cast<char*>(Ptr); |
224 | } |
225 | |
226 | void *getAnnotationValue() const { |
227 | assert(isAnnotation() && "Used AnnotVal on non-annotation token")(static_cast <bool> (isAnnotation() && "Used AnnotVal on non-annotation token" ) ? void (0) : __assert_fail ("isAnnotation() && \"Used AnnotVal on non-annotation token\"" , "clang/include/clang/Lex/Token.h", 227, __extension__ __PRETTY_FUNCTION__ )); |
228 | return PtrData; |
229 | } |
230 | void setAnnotationValue(void *val) { |
231 | assert(isAnnotation() && "Used AnnotVal on non-annotation token")(static_cast <bool> (isAnnotation() && "Used AnnotVal on non-annotation token" ) ? void (0) : __assert_fail ("isAnnotation() && \"Used AnnotVal on non-annotation token\"" , "clang/include/clang/Lex/Token.h", 231, __extension__ __PRETTY_FUNCTION__ )); |
232 | PtrData = val; |
233 | } |
234 | |
235 | /// Set the specified flag. |
236 | void setFlag(TokenFlags Flag) { |
237 | Flags |= Flag; |
238 | } |
239 | |
240 | /// Get the specified flag. |
241 | bool getFlag(TokenFlags Flag) const { |
242 | return (Flags & Flag) != 0; |
243 | } |
244 | |
245 | /// Unset the specified flag. |
246 | void clearFlag(TokenFlags Flag) { |
247 | Flags &= ~Flag; |
248 | } |
249 | |
250 | /// Return the internal represtation of the flags. |
251 | /// |
252 | /// This is only intended for low-level operations such as writing tokens to |
253 | /// disk. |
254 | unsigned getFlags() const { |
255 | return Flags; |
256 | } |
257 | |
258 | /// Set a flag to either true or false. |
259 | void setFlagValue(TokenFlags Flag, bool Val) { |
260 | if (Val) |
261 | setFlag(Flag); |
262 | else |
263 | clearFlag(Flag); |
264 | } |
265 | |
266 | /// isAtStartOfLine - Return true if this token is at the start of a line. |
267 | /// |
268 | bool isAtStartOfLine() const { return getFlag(StartOfLine); } |
269 | |
270 | /// Return true if this token has whitespace before it. |
271 | /// |
272 | bool hasLeadingSpace() const { return getFlag(LeadingSpace); } |
273 | |
274 | /// Return true if this identifier token should never |
275 | /// be expanded in the future, due to C99 6.10.3.4p2. |
276 | bool isExpandDisabled() const { return getFlag(DisableExpand); } |
277 | |
278 | /// Return true if we have an ObjC keyword identifier. |
279 | bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const; |
280 | |
281 | /// Return the ObjC keyword kind. |
282 | tok::ObjCKeywordKind getObjCKeywordID() const; |
283 | |
284 | /// Return true if this token has trigraphs or escaped newlines in it. |
285 | bool needsCleaning() const { return getFlag(NeedsCleaning); } |
286 | |
287 | /// Return true if this token has an empty macro before it. |
288 | /// |
289 | bool hasLeadingEmptyMacro() const { return getFlag(LeadingEmptyMacro); } |
290 | |
291 | /// Return true if this token is a string or character literal which |
292 | /// has a ud-suffix. |
293 | bool hasUDSuffix() const { return getFlag(HasUDSuffix); } |
294 | |
295 | /// Returns true if this token contains a universal character name. |
296 | bool hasUCN() const { return getFlag(HasUCN); } |
297 | |
298 | /// Returns true if this token is formed by macro by stringizing or charizing |
299 | /// operator. |
300 | bool stringifiedInMacro() const { return getFlag(StringifiedInMacro); } |
301 | |
302 | /// Returns true if the comma after this token was elided. |
303 | bool commaAfterElided() const { return getFlag(CommaAfterElided); } |
304 | |
305 | /// Returns true if this token is an editor placeholder. |
306 | /// |
307 | /// Editor placeholders are produced by the code-completion engine and are |
308 | /// represented as characters between '<#' and '#>' in the source code. The |
309 | /// lexer uses identifier tokens to represent placeholders. |
310 | bool isEditorPlaceholder() const { return getFlag(IsEditorPlaceholder); } |
311 | }; |
312 | |
313 | /// Information about the conditional stack (\#if directives) |
314 | /// currently active. |
315 | struct PPConditionalInfo { |
316 | /// Location where the conditional started. |
317 | SourceLocation IfLoc; |
318 | |
319 | /// True if this was contained in a skipping directive, e.g., |
320 | /// in a "\#if 0" block. |
321 | bool WasSkipping; |
322 | |
323 | /// True if we have emitted tokens already, and now we're in |
324 | /// an \#else block or something. Only useful in Skipping blocks. |
325 | bool FoundNonSkip; |
326 | |
327 | /// True if we've seen a \#else in this block. If so, |
328 | /// \#elif/\#else directives are not allowed. |
329 | bool FoundElse; |
330 | }; |
331 | |
332 | } // end namespace clang |
333 | |
334 | #endif // LLVM_CLANG_LEX_TOKEN_H |