1//===--- TokenAnnotator.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 a token annotator, i.e. creates
11/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
12///
13//===----------------------------------------------------------------------===//
14
15#include "TokenAnnotator.h"
16#include "FormatToken.h"
17#include "clang/Basic/TokenKinds.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/Support/Debug.h"
20
21#define DEBUG_TYPE "format-token-annotator"
22
23namespace clang {
24namespace format {
25
26static bool mustBreakAfterAttributes(const FormatToken &Tok,
27 const FormatStyle &Style) {
28 switch (Style.BreakAfterAttributes) {
29 case FormatStyle::ABS_Always:
30 return true;
31 case FormatStyle::ABS_Never:
32 return false;
33 default: // ABS_Leave and ABS_LeaveAll
34 return Tok.NewlinesBefore > 0;
35 }
36}
37
38namespace {
39
40/// Returns \c true if the line starts with a token that can start a statement
41/// with an initializer.
42static bool startsWithInitStatement(const AnnotatedLine &Line) {
43 return Line.startsWith(Tokens: tok::kw_for) || Line.startsWith(Tokens: tok::kw_if) ||
44 Line.startsWith(Tokens: tok::kw_switch);
45}
46
47/// Returns \c true if the token can be used as an identifier in
48/// an Objective-C \c \@selector, \c false otherwise.
49///
50/// Because getFormattingLangOpts() always lexes source code as
51/// Objective-C++, C++ keywords like \c new and \c delete are
52/// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
53///
54/// For Objective-C and Objective-C++, both identifiers and keywords
55/// are valid inside @selector(...) (or a macro which
56/// invokes @selector(...)). So, we allow treat any identifier or
57/// keyword as a potential Objective-C selector component.
58static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
59 return Tok.Tok.getIdentifierInfo();
60}
61
62/// With `Left` being '(', check if we're at either `[...](` or
63/// `[...]<...>(`, where the [ opens a lambda capture list.
64// FIXME: this doesn't cover attributes/constraints before the l_paren.
65static bool isLambdaParameterList(const FormatToken *Left) {
66 // Skip <...> if present.
67 if (Left->Previous && Left->Previous->is(Kind: tok::greater) &&
68 Left->Previous->MatchingParen &&
69 Left->Previous->MatchingParen->is(TT: TT_TemplateOpener)) {
70 Left = Left->Previous->MatchingParen;
71 }
72
73 // Check for `[...]`.
74 return Left->Previous && Left->Previous->is(Kind: tok::r_square) &&
75 Left->Previous->MatchingParen &&
76 Left->Previous->MatchingParen->is(TT: TT_LambdaLSquare);
77}
78
79/// Returns \c true if the token is followed by a boolean condition, \c false
80/// otherwise.
81static bool isKeywordWithCondition(const FormatToken &Tok) {
82 return Tok.isOneOf(K1: tok::kw_if, K2: tok::kw_for, Ks: tok::kw_while, Ks: tok::kw_switch,
83 Ks: tok::kw_constexpr, Ks: tok::kw_catch);
84}
85
86/// Returns \c true if the token starts a C++ attribute, \c false otherwise.
87static bool isCppAttribute(bool IsCpp, const FormatToken &Tok) {
88 if (!IsCpp || !Tok.startsSequence(K1: tok::l_square, Tokens: tok::l_square))
89 return false;
90 // The first square bracket belongs to an ObjC array literal or malformed
91 // nested-bracket input.
92 if (Tok.Previous && Tok.Previous->isOneOf(K1: tok::at, K2: tok::l_square))
93 return false;
94 const FormatToken *AttrTok = Tok.Next->Next;
95 if (!AttrTok)
96 return false;
97 // C++17 '[[using ns: foo, bar(baz, blech)]]'
98 // We assume nobody will name an ObjC variable 'using'.
99 if (AttrTok->startsSequence(K1: tok::kw_using, Tokens: tok::identifier, Tokens: tok::colon))
100 return true;
101 if (AttrTok->isNot(Kind: tok::identifier))
102 return false;
103 while (AttrTok && !AttrTok->startsSequence(K1: tok::r_square, Tokens: tok::r_square)) {
104 // ObjC message send. We assume nobody will use : in a C++11 attribute
105 // specifier parameter, although this is technically valid:
106 // [[foo(:)]].
107 if (AttrTok->is(Kind: tok::colon) ||
108 AttrTok->startsSequence(K1: tok::identifier, Tokens: tok::identifier) ||
109 AttrTok->startsSequence(K1: tok::r_paren, Tokens: tok::identifier)) {
110 return false;
111 }
112 if (AttrTok->is(Kind: tok::ellipsis))
113 return true;
114 AttrTok = AttrTok->Next;
115 }
116 return AttrTok && AttrTok->startsSequence(K1: tok::r_square, Tokens: tok::r_square);
117}
118
119/// A parser that gathers additional information about tokens.
120///
121/// The \c TokenAnnotator tries to match parenthesis and square brakets and
122/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
123/// into template parameter lists.
124class AnnotatingParser {
125public:
126 AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
127 const AdditionalKeywords &Keywords,
128 SmallVector<ScopeType> &Scopes)
129 : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
130 IsCpp(Style.isCpp()), LangOpts(getFormattingLangOpts(Style)),
131 Keywords(Keywords), Scopes(Scopes), TemplateDeclarationDepth(0) {
132 Contexts.push_back(Elt: Context(tok::unknown, 1, /*IsExpression=*/false));
133 resetTokenMetadata();
134 }
135
136private:
137 ScopeType getScopeType(const FormatToken &Token) const {
138 switch (Token.getType()) {
139 case TT_ClassLBrace:
140 case TT_StructLBrace:
141 case TT_UnionLBrace:
142 return ST_Class;
143 case TT_EnumLBrace:
144 return ST_Enum;
145 case TT_CompoundRequirementLBrace:
146 return ST_CompoundRequirement;
147 default:
148 return ST_Other;
149 }
150 }
151
152 bool parseAngle() {
153 if (!CurrentToken)
154 return false;
155
156 auto *Left = CurrentToken->Previous; // The '<'.
157 if (!Left)
158 return false;
159
160 if (NonTemplateLess.count(Ptr: Left) > 0)
161 return false;
162
163 const auto *BeforeLess = Left->Previous;
164
165 if (BeforeLess) {
166 if (BeforeLess->Tok.isLiteral())
167 return false;
168 if (BeforeLess->is(Kind: tok::r_brace))
169 return false;
170 if (BeforeLess->is(Kind: tok::r_paren) && Contexts.size() > 1 &&
171 !(BeforeLess->MatchingParen &&
172 BeforeLess->MatchingParen->is(TT: TT_OverloadedOperatorLParen))) {
173 return false;
174 }
175 if (BeforeLess->is(Kind: tok::kw_operator) && CurrentToken->is(Kind: tok::l_paren))
176 return false;
177 }
178
179 Left->ParentBracket = Contexts.back().ContextKind;
180 ScopedContextCreator ContextCreator(*this, tok::less, 12);
181 Contexts.back().IsExpression = false;
182
183 // If there's a template keyword before the opening angle bracket, this is a
184 // template parameter, not an argument.
185 if (BeforeLess && BeforeLess->isNot(Kind: tok::kw_template))
186 Contexts.back().ContextType = Context::TemplateArgument;
187
188 if (Style.isJava() && CurrentToken->is(Kind: tok::question))
189 next();
190
191 for (bool SeenTernaryOperator = false, MaybeAngles = true; CurrentToken;) {
192 const auto &ParentContext = Contexts[Contexts.size() - 2];
193 const bool InExpr = ParentContext.IsExpression;
194 if (CurrentToken->is(Kind: tok::greater)) {
195 const auto *Next = CurrentToken->Next;
196 if (CurrentToken->isNot(Kind: TT_TemplateCloser)) {
197 // Try to do a better job at looking for ">>" within the condition of
198 // a statement. Conservatively insert spaces between consecutive ">"
199 // tokens to prevent splitting right shift operators and potentially
200 // altering program semantics. This check is overly conservative and
201 // will prevent spaces from being inserted in select nested template
202 // parameter cases, but should not alter program semantics.
203 if (Next && Next->is(Kind: tok::greater) &&
204 Left->ParentBracket != tok::less &&
205 CurrentToken->getStartOfNonWhitespace() ==
206 Next->getStartOfNonWhitespace().getLocWithOffset(Offset: -1)) {
207 return false;
208 }
209 if (InExpr && SeenTernaryOperator &&
210 (!Next || Next->isNoneOf(Ks: tok::l_paren, Ks: tok::l_brace))) {
211 return false;
212 }
213 if (!MaybeAngles)
214 return false;
215 if (ParentContext.InStaticAssertFirstArgument && Next &&
216 Next->isOneOf(K1: tok::minus, K2: tok::identifier)) {
217 return false;
218 }
219 }
220 Left->MatchingParen = CurrentToken;
221 CurrentToken->MatchingParen = Left;
222 // In TT_Proto, we must distignuish between:
223 // map<key, value>
224 // msg < item: data >
225 // msg: < item: data >
226 // In TT_TextProto, map<key, value> does not occur.
227 if (Style.isTextProto() ||
228 (Style.Language == FormatStyle::LK_Proto && BeforeLess &&
229 BeforeLess->isOneOf(K1: TT_SelectorName, K2: TT_DictLiteral))) {
230 CurrentToken->setType(TT_DictLiteral);
231 } else {
232 CurrentToken->setType(TT_TemplateCloser);
233 CurrentToken->Tok.setLength(1);
234 }
235 if (Next && Next->Tok.isLiteral())
236 return false;
237 next();
238 return true;
239 }
240 if (BeforeLess && BeforeLess->is(TT: TT_TemplateName)) {
241 next();
242 continue;
243 }
244 if (CurrentToken->is(Kind: tok::question) && Style.isJava()) {
245 next();
246 continue;
247 }
248 if (CurrentToken->isOneOf(K1: tok::r_paren, K2: tok::r_square, Ks: tok::r_brace))
249 return false;
250 const auto &Prev = *CurrentToken->Previous;
251 // If a && or || is found and interpreted as a binary operator, this set
252 // of angles is likely part of something like "a < b && c > d". If the
253 // angles are inside an expression, the ||/&& might also be a binary
254 // operator that was misinterpreted because we are parsing template
255 // parameters.
256 // FIXME: This is getting out of hand, write a decent parser.
257 if (MaybeAngles && InExpr && !Line.startsWith(Tokens: tok::kw_template) &&
258 Prev.is(TT: TT_BinaryOperator) &&
259 Prev.isOneOf(K1: tok::pipepipe, K2: tok::ampamp)) {
260 MaybeAngles = false;
261 }
262 if (Prev.isOneOf(K1: tok::question, K2: tok::colon) && !Style.isProto())
263 SeenTernaryOperator = true;
264 updateParameterCount(Left, Current: CurrentToken);
265 if (Style.Language == FormatStyle::LK_Proto) {
266 if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
267 if (CurrentToken->is(Kind: tok::colon) ||
268 (CurrentToken->isOneOf(K1: tok::l_brace, K2: tok::less) &&
269 Previous->isNot(Kind: tok::colon))) {
270 Previous->setType(TT_SelectorName);
271 }
272 }
273 } else if (Style.isTableGen()) {
274 if (CurrentToken->isOneOf(K1: tok::comma, K2: tok::equal)) {
275 // They appear as separators. Unless they are not in class definition.
276 next();
277 continue;
278 }
279 // In angle, there must be Value like tokens. Types are also able to be
280 // parsed in the same way with Values.
281 if (!parseTableGenValue())
282 return false;
283 continue;
284 }
285 if (!consumeToken())
286 return false;
287 }
288 return false;
289 }
290
291 bool parseUntouchableParens() {
292 while (CurrentToken) {
293 CurrentToken->Finalized = true;
294 switch (CurrentToken->Tok.getKind()) {
295 case tok::l_paren:
296 next();
297 if (!parseUntouchableParens())
298 return false;
299 continue;
300 case tok::r_paren:
301 next();
302 return true;
303 default:
304 // no-op
305 break;
306 }
307 next();
308 }
309 return false;
310 }
311
312 bool parseParens(bool IsIf = false) {
313 if (!CurrentToken)
314 return false;
315 assert(CurrentToken->Previous && "Unknown previous token");
316 FormatToken &OpeningParen = *CurrentToken->Previous;
317 assert(OpeningParen.is(tok::l_paren));
318 FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment();
319 OpeningParen.ParentBracket = Contexts.back().ContextKind;
320 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
321
322 // FIXME: This is a bit of a hack. Do better.
323 Contexts.back().ColonIsForRangeExpr =
324 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
325
326 if (OpeningParen.Previous &&
327 OpeningParen.Previous->is(TT: TT_UntouchableMacroFunc)) {
328 OpeningParen.Finalized = true;
329 return parseUntouchableParens();
330 }
331
332 bool StartsObjCSelector = false;
333 if (!Style.isVerilog()) {
334 if (FormatToken *MaybeSel = OpeningParen.Previous) {
335 // @selector( starts a selector.
336 if (MaybeSel->is(Kind: tok::objc_selector) && MaybeSel->Previous &&
337 MaybeSel->Previous->is(Kind: tok::at)) {
338 StartsObjCSelector = true;
339 }
340 }
341 }
342
343 if (OpeningParen.is(TT: TT_OverloadedOperatorLParen)) {
344 // Find the previous kw_operator token.
345 FormatToken *Prev = &OpeningParen;
346 while (Prev->isNot(Kind: tok::kw_operator)) {
347 Prev = Prev->Previous;
348 assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
349 }
350
351 // If faced with "a.operator*(argument)" or "a->operator*(argument)",
352 // i.e. the operator is called as a member function,
353 // then the argument must be an expression.
354 bool OperatorCalledAsMemberFunction =
355 Prev->Previous && Prev->Previous->isOneOf(K1: tok::period, K2: tok::arrow);
356 Contexts.back().IsExpression = OperatorCalledAsMemberFunction;
357 } else if (OpeningParen.is(TT: TT_VerilogInstancePortLParen)) {
358 Contexts.back().IsExpression = true;
359 Contexts.back().ContextType = Context::VerilogInstancePortList;
360 } else if (Style.isJavaScript() &&
361 (Line.startsWith(Tokens: Keywords.kw_type, Tokens: tok::identifier) ||
362 Line.startsWith(Tokens: tok::kw_export, Tokens: Keywords.kw_type,
363 Tokens: tok::identifier))) {
364 // type X = (...);
365 // export type X = (...);
366 Contexts.back().IsExpression = false;
367 } else if (OpeningParen.Previous &&
368 (OpeningParen.Previous->isOneOf(
369 K1: tok::kw_noexcept, K2: tok::kw_explicit, Ks: tok::kw_while,
370 Ks: tok::l_paren, Ks: tok::comma, Ks: TT_CastRParen,
371 Ks: TT_BinaryOperator) ||
372 OpeningParen.Previous->isIf())) {
373 // if and while usually contain expressions.
374 Contexts.back().IsExpression = true;
375 } else if (Style.isJavaScript() && OpeningParen.Previous &&
376 (OpeningParen.Previous->is(II: Keywords.kw_function) ||
377 (OpeningParen.Previous->endsSequence(K1: tok::identifier,
378 Tokens: Keywords.kw_function)))) {
379 // function(...) or function f(...)
380 Contexts.back().IsExpression = false;
381 } else if (Style.isJavaScript() && OpeningParen.Previous &&
382 OpeningParen.Previous->is(TT: TT_JsTypeColon)) {
383 // let x: (SomeType);
384 Contexts.back().IsExpression = false;
385 } else if (isLambdaParameterList(Left: &OpeningParen)) {
386 // This is a parameter list of a lambda expression.
387 OpeningParen.setType(TT_LambdaDefinitionLParen);
388 Contexts.back().IsExpression = false;
389 } else if (OpeningParen.is(TT: TT_RequiresExpressionLParen)) {
390 Contexts.back().IsExpression = false;
391 } else if (OpeningParen.Previous &&
392 OpeningParen.Previous->is(Kind: tok::kw__Generic)) {
393 Contexts.back().ContextType = Context::C11GenericSelection;
394 Contexts.back().IsExpression = true;
395 } else if (OpeningParen.Previous &&
396 OpeningParen.Previous->TokenText == "Q_PROPERTY") {
397 Contexts.back().ContextType = Context::QtProperty;
398 Contexts.back().IsExpression = false;
399 } else if (Line.InPPDirective &&
400 (!OpeningParen.Previous ||
401 OpeningParen.Previous->isNot(Kind: tok::identifier))) {
402 Contexts.back().IsExpression = true;
403 } else if (Contexts[Contexts.size() - 2].CaretFound) {
404 // This is the parameter list of an ObjC block.
405 Contexts.back().IsExpression = false;
406 } else if (OpeningParen.Previous &&
407 OpeningParen.Previous->is(TT: TT_ForEachMacro)) {
408 // The first argument to a foreach macro is a declaration.
409 Contexts.back().ContextType = Context::ForEachMacro;
410 Contexts.back().IsExpression = false;
411 } else if (OpeningParen.Previous && OpeningParen.Previous->MatchingParen &&
412 OpeningParen.Previous->MatchingParen->isOneOf(
413 K1: TT_ObjCBlockLParen, K2: TT_FunctionTypeLParen)) {
414 Contexts.back().IsExpression = false;
415 } else if (!Line.MustBeDeclaration &&
416 (!Line.InPPDirective || (Line.InMacroBody && !Scopes.empty()))) {
417 bool IsForOrCatch =
418 OpeningParen.Previous &&
419 OpeningParen.Previous->isOneOf(K1: tok::kw_for, K2: tok::kw_catch);
420 Contexts.back().IsExpression = !IsForOrCatch;
421 }
422
423 if (Style.isTableGen()) {
424 if (FormatToken *Prev = OpeningParen.Previous) {
425 if (Prev->is(TT: TT_TableGenCondOperator)) {
426 Contexts.back().IsTableGenCondOpe = true;
427 Contexts.back().IsExpression = true;
428 } else if (Contexts.size() > 1 &&
429 Contexts[Contexts.size() - 2].IsTableGenBangOpe) {
430 // Hack to handle bang operators. The parent context's flag
431 // was set by parseTableGenSimpleValue().
432 // We have to specify the context outside because the prev of "(" may
433 // be ">", not the bang operator in this case.
434 Contexts.back().IsTableGenBangOpe = true;
435 Contexts.back().IsExpression = true;
436 } else {
437 // Otherwise, this paren seems DAGArg.
438 if (!parseTableGenDAGArg())
439 return false;
440 return parseTableGenDAGArgAndList(Opener: &OpeningParen);
441 }
442 }
443 }
444
445 // Infer the role of the l_paren based on the previous token if we haven't
446 // detected one yet.
447 if (PrevNonComment && OpeningParen.is(TT: TT_Unknown)) {
448 if (PrevNonComment->isAttribute()) {
449 OpeningParen.setType(TT_AttributeLParen);
450 } else if (PrevNonComment->isOneOf(K1: TT_TypenameMacro, K2: tok::kw_decltype,
451 Ks: tok::kw_typeof,
452#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
453#include "clang/Basic/BuiltinTraits.inc"
454 Ks: tok::kw__Atomic)) {
455 OpeningParen.setType(TT_TypeDeclarationParen);
456 // decltype() and typeof() usually contain expressions.
457 if (PrevNonComment->isOneOf(K1: tok::kw_decltype, K2: tok::kw_typeof))
458 Contexts.back().IsExpression = true;
459 }
460 }
461
462 if (StartsObjCSelector)
463 OpeningParen.setType(TT_ObjCSelector);
464
465 const bool IsStaticAssert =
466 PrevNonComment && PrevNonComment->is(Kind: tok::kw_static_assert);
467 if (IsStaticAssert)
468 Contexts.back().InStaticAssertFirstArgument = true;
469
470 // MightBeFunctionType and ProbablyFunctionType are used for
471 // function pointer and reference types as well as Objective-C
472 // block types:
473 //
474 // void (*FunctionPointer)(void);
475 // void (&FunctionReference)(void);
476 // void (&&FunctionReference)(void);
477 // void (^ObjCBlock)(void);
478 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
479 bool ProbablyFunctionType =
480 CurrentToken->isPointerOrReference() || CurrentToken->is(Kind: tok::caret);
481 bool HasMultipleLines = false;
482 bool HasMultipleParametersOnALine = false;
483 bool MightBeObjCForRangeLoop =
484 OpeningParen.Previous && OpeningParen.Previous->is(Kind: tok::kw_for);
485 FormatToken *PossibleObjCForInToken = nullptr;
486 while (CurrentToken) {
487 const auto &Prev = *CurrentToken->Previous;
488 const auto *PrevPrev = Prev.Previous;
489 if (Prev.is(TT: TT_PointerOrReference) &&
490 PrevPrev->isOneOf(K1: tok::l_paren, K2: tok::coloncolon)) {
491 ProbablyFunctionType = true;
492 }
493 if (CurrentToken->is(Kind: tok::comma))
494 MightBeFunctionType = false;
495 if (Prev.is(TT: TT_BinaryOperator))
496 Contexts.back().IsExpression = true;
497 if (CurrentToken->is(Kind: tok::r_paren)) {
498 if (Prev.is(TT: TT_PointerOrReference) &&
499 (PrevPrev == &OpeningParen || PrevPrev->is(Kind: tok::coloncolon))) {
500 MightBeFunctionType = true;
501 }
502 if (OpeningParen.isNot(Kind: TT_CppCastLParen) && MightBeFunctionType &&
503 ProbablyFunctionType && CurrentToken->Next &&
504 (CurrentToken->Next->is(Kind: tok::l_paren) ||
505 (CurrentToken->Next->is(Kind: tok::l_square) &&
506 (Line.MustBeDeclaration ||
507 (PrevNonComment && PrevNonComment->isTypeName(LangOpts)))))) {
508 OpeningParen.setType(OpeningParen.Next->is(Kind: tok::caret)
509 ? TT_ObjCBlockLParen
510 : TT_FunctionTypeLParen);
511 }
512 OpeningParen.MatchingParen = CurrentToken;
513 CurrentToken->MatchingParen = &OpeningParen;
514
515 if (CurrentToken->Next && CurrentToken->Next->is(Kind: tok::l_brace) &&
516 OpeningParen.Previous && OpeningParen.Previous->is(Kind: tok::l_paren)) {
517 // Detect the case where macros are used to generate lambdas or
518 // function bodies, e.g.:
519 // auto my_lambda = MACRO((Type *type, int i) { .. body .. });
520 for (FormatToken *Tok = &OpeningParen; Tok != CurrentToken;
521 Tok = Tok->Next) {
522 if (Tok->is(TT: TT_BinaryOperator) && Tok->isPointerOrReference())
523 Tok->setType(TT_PointerOrReference);
524 }
525 }
526
527 if (StartsObjCSelector) {
528 CurrentToken->setType(TT_ObjCSelector);
529 if (Contexts.back().FirstObjCSelectorName) {
530 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
531 Contexts.back().LongestObjCSelectorName;
532 }
533 }
534
535 if (OpeningParen.is(TT: TT_AttributeLParen))
536 CurrentToken->setType(TT_AttributeRParen);
537 if (OpeningParen.is(TT: TT_TypeDeclarationParen))
538 CurrentToken->setType(TT_TypeDeclarationParen);
539 if (OpeningParen.Previous &&
540 OpeningParen.Previous->is(TT: TT_JavaAnnotation)) {
541 CurrentToken->setType(TT_JavaAnnotation);
542 }
543 if (OpeningParen.Previous &&
544 OpeningParen.Previous->is(TT: TT_LeadingJavaAnnotation)) {
545 CurrentToken->setType(TT_LeadingJavaAnnotation);
546 }
547
548 if (!HasMultipleLines)
549 OpeningParen.setPackingKind(PPK_Inconclusive);
550 else if (HasMultipleParametersOnALine)
551 OpeningParen.setPackingKind(PPK_BinPacked);
552 else
553 OpeningParen.setPackingKind(PPK_OnePerLine);
554
555 next();
556 return true;
557 }
558 if (CurrentToken->isOneOf(K1: tok::r_square, K2: tok::r_brace))
559 return false;
560
561 if (CurrentToken->is(Kind: tok::l_brace) && OpeningParen.is(TT: TT_ObjCBlockLParen))
562 OpeningParen.setType(TT_Unknown);
563 if (CurrentToken->is(Kind: tok::comma) && CurrentToken->Next &&
564 !CurrentToken->Next->HasUnescapedNewline &&
565 !CurrentToken->Next->isTrailingComment()) {
566 HasMultipleParametersOnALine = true;
567 }
568 bool ProbablyFunctionTypeLParen =
569 (CurrentToken->is(Kind: tok::l_paren) && CurrentToken->Next &&
570 CurrentToken->Next->isOneOf(K1: tok::star, K2: tok::amp, Ks: tok::caret));
571 if ((Prev.isOneOf(K1: tok::kw_const, K2: tok::kw_auto) ||
572 Prev.isTypeName(LangOpts)) &&
573 !(CurrentToken->is(Kind: tok::l_brace) ||
574 (CurrentToken->is(Kind: tok::l_paren) && !ProbablyFunctionTypeLParen))) {
575 Contexts.back().IsExpression = false;
576 }
577 if (CurrentToken->isOneOf(K1: tok::semi, K2: tok::colon)) {
578 MightBeObjCForRangeLoop = false;
579 if (PossibleObjCForInToken) {
580 PossibleObjCForInToken->setType(TT_Unknown);
581 PossibleObjCForInToken = nullptr;
582 }
583 }
584 if (IsIf && CurrentToken->is(Kind: tok::semi)) {
585 for (auto *Tok = OpeningParen.Next;
586 Tok != CurrentToken &&
587 Tok->isNoneOf(Ks: tok::equal, Ks: tok::l_paren, Ks: tok::l_brace);
588 Tok = Tok->Next) {
589 if (Tok->isPointerOrReference())
590 Tok->setFinalizedType(TT_PointerOrReference);
591 }
592 }
593 if (MightBeObjCForRangeLoop && CurrentToken->is(II: Keywords.kw_in)) {
594 PossibleObjCForInToken = CurrentToken;
595 PossibleObjCForInToken->setType(TT_ObjCForIn);
596 }
597 // When we discover a 'new', we set CanBeExpression to 'false' in order to
598 // parse the type correctly. Reset that after a comma.
599 if (CurrentToken->is(Kind: tok::comma)) {
600 if (IsStaticAssert)
601 Contexts.back().InStaticAssertFirstArgument = false;
602 else
603 Contexts.back().CanBeExpression = true;
604 }
605
606 if (Style.isTableGen()) {
607 if (CurrentToken->is(Kind: tok::comma)) {
608 if (Contexts.back().IsTableGenCondOpe)
609 CurrentToken->setType(TT_TableGenCondOperatorComma);
610 next();
611 } else if (CurrentToken->is(Kind: tok::colon)) {
612 if (Contexts.back().IsTableGenCondOpe)
613 CurrentToken->setType(TT_TableGenCondOperatorColon);
614 next();
615 }
616 // In TableGen there must be Values in parens.
617 if (!parseTableGenValue())
618 return false;
619 continue;
620 }
621
622 FormatToken *Tok = CurrentToken;
623 if (!consumeToken())
624 return false;
625 updateParameterCount(Left: &OpeningParen, Current: Tok);
626 if (CurrentToken && CurrentToken->HasUnescapedNewline)
627 HasMultipleLines = true;
628 }
629 return false;
630 }
631
632 bool isCSharpAttributeSpecifier(const FormatToken &Tok) {
633 if (!Style.isCSharp())
634 return false;
635
636 // `identifier[i]` is not an attribute.
637 if (Tok.Previous && Tok.Previous->is(Kind: tok::identifier))
638 return false;
639
640 // Chains of [] in `identifier[i][j][k]` are not attributes.
641 if (Tok.Previous && Tok.Previous->is(Kind: tok::r_square)) {
642 auto *MatchingParen = Tok.Previous->MatchingParen;
643 if (!MatchingParen || MatchingParen->is(TT: TT_ArraySubscriptLSquare))
644 return false;
645 }
646
647 const FormatToken *AttrTok = Tok.Next;
648 if (!AttrTok)
649 return false;
650
651 // Just an empty declaration e.g. string [].
652 if (AttrTok->is(Kind: tok::r_square))
653 return false;
654
655 // Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
656 while (AttrTok && AttrTok->isNot(Kind: tok::r_square))
657 AttrTok = AttrTok->Next;
658
659 if (!AttrTok)
660 return false;
661
662 // Allow an attribute to be the only content of a file.
663 AttrTok = AttrTok->Next;
664 if (!AttrTok)
665 return true;
666
667 // Limit this to being an access modifier that follows.
668 if (AttrTok->isAccessSpecifierKeyword() ||
669 AttrTok->isOneOf(K1: tok::comment, K2: tok::kw_class, Ks: tok::kw_static,
670 Ks: tok::l_square, Ks: Keywords.kw_internal)) {
671 return true;
672 }
673
674 // incase its a [XXX] retval func(....
675 if (AttrTok->Next &&
676 AttrTok->Next->startsSequence(K1: tok::identifier, Tokens: tok::l_paren)) {
677 return true;
678 }
679
680 return false;
681 }
682
683 bool parseSquare() {
684 if (!CurrentToken)
685 return false;
686
687 // A '[' could be an index subscript (after an identifier or after
688 // ')' or ']'), it could be the start of an Objective-C method
689 // expression, it could the start of an Objective-C array literal,
690 // or it could be a C++ attribute specifier [[foo::bar]].
691 FormatToken *Left = CurrentToken->Previous;
692 Left->ParentBracket = Contexts.back().ContextKind;
693 FormatToken *Parent = Left->getPreviousNonComment();
694
695 // Cases where '>' is followed by '['.
696 // In C++, this can happen either in array of templates (foo<int>[10])
697 // or when array is a nested template type (unique_ptr<type1<type2>[]>).
698 bool CppArrayTemplates =
699 IsCpp && Parent && Parent->is(TT: TT_TemplateCloser) &&
700 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
701 Contexts.back().ContextType == Context::TemplateArgument);
702
703 const bool IsInnerSquare = Contexts.back().InCpp11AttributeSpecifier;
704 const bool IsCpp11AttributeSpecifier =
705 isCppAttribute(IsCpp, Tok: *Left) || IsInnerSquare;
706
707 // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
708 bool IsCSharpAttributeSpecifier =
709 isCSharpAttributeSpecifier(Tok: *Left) ||
710 Contexts.back().InCSharpAttributeSpecifier;
711
712 bool InsideInlineASM = Line.startsWith(Tokens: tok::kw_asm);
713 bool IsCppStructuredBinding = Left->isCppStructuredBinding(IsCpp);
714 bool StartsObjCMethodExpr =
715 !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
716 IsCpp && !IsCpp11AttributeSpecifier && !IsCSharpAttributeSpecifier &&
717 Contexts.back().CanBeExpression && Left->isNot(Kind: TT_LambdaLSquare) &&
718 CurrentToken->isNoneOf(Ks: tok::l_brace, Ks: tok::r_square) &&
719 // Do not consider '[' after a comma inside a braced initializer the
720 // start of an ObjC method expression. In braced initializer lists,
721 // commas are list separators and should not trigger ObjC parsing.
722 (!Parent || !Parent->is(Kind: tok::comma) ||
723 Contexts.back().ContextKind != tok::l_brace) &&
724 (!Parent ||
725 Parent->isOneOf(K1: tok::colon, K2: tok::l_square, Ks: tok::l_paren,
726 Ks: tok::kw_return, Ks: tok::kw_throw) ||
727 Parent->isUnaryOperator() ||
728 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
729 Parent->isOneOf(K1: TT_ObjCForIn, K2: TT_CastRParen) ||
730 (getBinOpPrecedence(Kind: Parent->Tok.getKind(), GreaterThanIsOperator: true, CPlusPlus11: true) >
731 prec::Unknown));
732 bool ColonFound = false;
733
734 unsigned BindingIncrease = 1;
735 if (IsCppStructuredBinding) {
736 Left->setType(TT_StructuredBindingLSquare);
737 } else if (Left->is(TT: TT_Unknown)) {
738 if (StartsObjCMethodExpr) {
739 Left->setType(TT_ObjCMethodExpr);
740 } else if (InsideInlineASM) {
741 Left->setType(TT_InlineASMSymbolicNameLSquare);
742 } else if (IsCpp11AttributeSpecifier) {
743 if (!IsInnerSquare) {
744 Left->setType(TT_AttributeLSquare);
745 if (Left->Previous)
746 Left->Previous->EndsCppAttributeGroup = false;
747 }
748 } else if (Style.isJavaScript() && Parent &&
749 Contexts.back().ContextKind == tok::l_brace &&
750 Parent->isOneOf(K1: tok::l_brace, K2: tok::comma)) {
751 Left->setType(TT_JsComputedPropertyName);
752 } else if (IsCpp && Contexts.back().ContextKind == tok::l_brace &&
753 Parent && Parent->isOneOf(K1: tok::l_brace, K2: tok::comma)) {
754 Left->setType(TT_DesignatedInitializerLSquare);
755 } else if (IsCSharpAttributeSpecifier) {
756 Left->setType(TT_AttributeLSquare);
757 } else if (CurrentToken->is(Kind: tok::r_square) && Parent &&
758 Parent->is(TT: TT_TemplateCloser)) {
759 Left->setType(TT_ArraySubscriptLSquare);
760 } else if (Style.isProto()) {
761 // Square braces in LK_Proto can either be message field attributes:
762 //
763 // optional Aaa aaa = 1 [
764 // (aaa) = aaa
765 // ];
766 //
767 // extensions 123 [
768 // (aaa) = aaa
769 // ];
770 //
771 // or text proto extensions (in options):
772 //
773 // option (Aaa.options) = {
774 // [type.type/type] {
775 // key: value
776 // }
777 // }
778 //
779 // or repeated fields (in options):
780 //
781 // option (Aaa.options) = {
782 // keys: [ 1, 2, 3 ]
783 // }
784 //
785 // In the first and the third case we want to spread the contents inside
786 // the square braces; in the second we want to keep them inline.
787 Left->setType(TT_ArrayInitializerLSquare);
788 if (!Left->endsSequence(K1: tok::l_square, Tokens: tok::numeric_constant,
789 Tokens: tok::equal) &&
790 !Left->endsSequence(K1: tok::l_square, Tokens: tok::numeric_constant,
791 Tokens: tok::identifier) &&
792 !Left->endsSequence(K1: tok::l_square, Tokens: tok::colon, Tokens: TT_SelectorName)) {
793 Left->setType(TT_ProtoExtensionLSquare);
794 BindingIncrease = 10;
795 }
796 } else if (!CppArrayTemplates && Parent &&
797 Parent->isOneOf(K1: TT_BinaryOperator, K2: TT_TemplateCloser, Ks: tok::at,
798 Ks: tok::comma, Ks: tok::l_paren, Ks: tok::l_square,
799 Ks: tok::question, Ks: tok::colon, Ks: tok::kw_return,
800 // Should only be relevant to JavaScript:
801 Ks: tok::kw_default)) {
802 Left->setType(TT_ArrayInitializerLSquare);
803 } else {
804 BindingIncrease = 10;
805 Left->setType(TT_ArraySubscriptLSquare);
806 }
807 }
808
809 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
810 Contexts.back().IsExpression = true;
811 if (Style.isJavaScript() && Parent && Parent->is(TT: TT_JsTypeColon))
812 Contexts.back().IsExpression = false;
813
814 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
815 Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
816 Contexts.back().InCSharpAttributeSpecifier = IsCSharpAttributeSpecifier;
817
818 while (CurrentToken) {
819 if (CurrentToken->is(Kind: tok::r_square)) {
820 if (IsCpp11AttributeSpecifier && !IsInnerSquare) {
821 CurrentToken->setType(TT_AttributeRSquare);
822 CurrentToken->EndsCppAttributeGroup = true;
823 }
824 if (IsCSharpAttributeSpecifier) {
825 CurrentToken->setType(TT_AttributeRSquare);
826 } else if (((CurrentToken->Next &&
827 CurrentToken->Next->is(Kind: tok::l_paren)) ||
828 (CurrentToken->Previous &&
829 CurrentToken->Previous->Previous == Left)) &&
830 Left->is(TT: TT_ObjCMethodExpr)) {
831 // An ObjC method call is rarely followed by an open parenthesis. It
832 // also can't be composed of just one token, unless it's a macro that
833 // will be expanded to more tokens.
834 // FIXME: Do we incorrectly label ":" with this?
835 StartsObjCMethodExpr = false;
836 Left->setType(TT_Unknown);
837 }
838 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
839 CurrentToken->setType(TT_ObjCMethodExpr);
840 // If we haven't seen a colon yet, make sure the last identifier
841 // before the r_square is tagged as a selector name component.
842 if (!ColonFound && CurrentToken->Previous &&
843 CurrentToken->Previous->is(TT: TT_Unknown) &&
844 canBeObjCSelectorComponent(Tok: *CurrentToken->Previous)) {
845 CurrentToken->Previous->setType(TT_SelectorName);
846 }
847 // determineStarAmpUsage() thinks that '*' '[' is allocating an
848 // array of pointers, but if '[' starts a selector then '*' is a
849 // binary operator.
850 if (Parent && Parent->is(TT: TT_PointerOrReference))
851 Parent->overwriteFixedType(T: TT_BinaryOperator);
852 }
853 Left->MatchingParen = CurrentToken;
854 CurrentToken->MatchingParen = Left;
855 // FirstObjCSelectorName is set when a colon is found. This does
856 // not work, however, when the method has no parameters.
857 // Here, we set FirstObjCSelectorName when the end of the method call is
858 // reached, in case it was not set already.
859 if (!Contexts.back().FirstObjCSelectorName) {
860 FormatToken *Previous = CurrentToken->getPreviousNonComment();
861 if (Previous && Previous->is(TT: TT_SelectorName)) {
862 Previous->ObjCSelectorNameParts = 1;
863 Contexts.back().FirstObjCSelectorName = Previous;
864 }
865 } else {
866 Left->ParameterCount =
867 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
868 }
869 if (Contexts.back().FirstObjCSelectorName) {
870 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
871 Contexts.back().LongestObjCSelectorName;
872 if (Left->BlockParameterCount > 1)
873 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
874 }
875 if (Style.isTableGen() && Left->is(TT: TT_TableGenListOpener))
876 CurrentToken->setType(TT_TableGenListCloser);
877 next();
878 return true;
879 }
880 if (CurrentToken->isOneOf(K1: tok::r_paren, K2: tok::r_brace))
881 return false;
882 if (CurrentToken->is(Kind: tok::colon)) {
883 if (IsCpp11AttributeSpecifier &&
884 CurrentToken->endsSequence(K1: tok::colon, Tokens: tok::identifier,
885 Tokens: tok::kw_using)) {
886 // Remember that this is a [[using ns: foo]] C++ attribute, so we
887 // don't add a space before the colon (unlike other colons).
888 CurrentToken->setType(TT_AttributeColon);
889 } else if (!Style.isVerilog() && !Line.InPragmaDirective &&
890 Left->isOneOf(K1: TT_ArraySubscriptLSquare,
891 K2: TT_DesignatedInitializerLSquare)) {
892 Left->setType(TT_ObjCMethodExpr);
893 StartsObjCMethodExpr = true;
894 Contexts.back().ColonIsObjCMethodExpr = true;
895 if (Parent && Parent->is(Kind: tok::r_paren)) {
896 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
897 Parent->setType(TT_CastRParen);
898 }
899 }
900 ColonFound = true;
901 }
902 if (CurrentToken->is(Kind: tok::comma) && Left->is(TT: TT_ObjCMethodExpr) &&
903 !ColonFound) {
904 Left->setType(TT_ArrayInitializerLSquare);
905 }
906 FormatToken *Tok = CurrentToken;
907 if (Style.isTableGen()) {
908 if (CurrentToken->isOneOf(K1: tok::comma, K2: tok::minus, Ks: tok::ellipsis)) {
909 // '-' and '...' appears as a separator in slice.
910 next();
911 } else {
912 // In TableGen there must be a list of Values in square brackets.
913 // It must be ValueList or SliceElements.
914 if (!parseTableGenValue())
915 return false;
916 }
917 updateParameterCount(Left, Current: Tok);
918 continue;
919 }
920 if (!consumeToken())
921 return false;
922 updateParameterCount(Left, Current: Tok);
923 }
924 return false;
925 }
926
927 void skipToNextNonComment() {
928 next();
929 while (CurrentToken && CurrentToken->is(Kind: tok::comment))
930 next();
931 }
932
933 // Simplified parser for TableGen Value. Returns true on success.
934 // It consists of SimpleValues, SimpleValues with Suffixes, and Value followed
935 // by '#', paste operator.
936 // There also exists the case the Value is parsed as NameValue.
937 // In this case, the Value ends if '{' is found.
938 bool parseTableGenValue(bool ParseNameMode = false) {
939 if (!CurrentToken)
940 return false;
941 while (CurrentToken->is(Kind: tok::comment))
942 next();
943 if (!parseTableGenSimpleValue())
944 return false;
945 if (!CurrentToken)
946 return true;
947 // Value "#" [Value]
948 if (CurrentToken->is(Kind: tok::hash)) {
949 if (CurrentToken->Next &&
950 CurrentToken->Next->isOneOf(K1: tok::colon, K2: tok::semi, Ks: tok::l_brace)) {
951 // Trailing paste operator.
952 // These are only the allowed cases in TGParser::ParseValue().
953 CurrentToken->setType(TT_TableGenTrailingPasteOperator);
954 next();
955 return true;
956 }
957 FormatToken *HashTok = CurrentToken;
958 skipToNextNonComment();
959 HashTok->setType(TT_Unknown);
960 if (!parseTableGenValue(ParseNameMode))
961 return false;
962 if (!CurrentToken)
963 return true;
964 }
965 // In name mode, '{' is regarded as the end of the value.
966 // See TGParser::ParseValue in TGParser.cpp
967 if (ParseNameMode && CurrentToken->is(Kind: tok::l_brace))
968 return true;
969 // These tokens indicates this is a value with suffixes.
970 if (CurrentToken->isOneOf(K1: tok::l_brace, K2: tok::l_square, Ks: tok::period)) {
971 CurrentToken->setType(TT_TableGenValueSuffix);
972 FormatToken *Suffix = CurrentToken;
973 skipToNextNonComment();
974 if (Suffix->is(Kind: tok::l_square))
975 return parseSquare();
976 if (Suffix->is(Kind: tok::l_brace)) {
977 Scopes.push_back(Elt: getScopeType(Token: *Suffix));
978 return parseBrace();
979 }
980 }
981 return true;
982 }
983
984 // TokVarName ::= "$" ualpha (ualpha | "0"..."9")*
985 // Appears as a part of DagArg.
986 // This does not change the current token on fail.
987 bool tryToParseTableGenTokVar() {
988 if (!CurrentToken)
989 return false;
990 if (CurrentToken->is(Kind: tok::identifier) &&
991 CurrentToken->TokenText.front() == '$') {
992 skipToNextNonComment();
993 return true;
994 }
995 return false;
996 }
997
998 // DagArg ::= Value [":" TokVarName] | TokVarName
999 // Appears as a part of SimpleValue6.
1000 bool parseTableGenDAGArg(bool AlignColon = false) {
1001 if (tryToParseTableGenTokVar())
1002 return true;
1003 if (parseTableGenValue()) {
1004 if (CurrentToken && CurrentToken->is(Kind: tok::colon)) {
1005 if (AlignColon)
1006 CurrentToken->setType(TT_TableGenDAGArgListColonToAlign);
1007 else
1008 CurrentToken->setType(TT_TableGenDAGArgListColon);
1009 skipToNextNonComment();
1010 return tryToParseTableGenTokVar();
1011 }
1012 return true;
1013 }
1014 return false;
1015 }
1016
1017 // Judge if the token is a operator ID to insert line break in DAGArg.
1018 // That is, TableGenBreakingDAGArgOperators is empty (by the definition of the
1019 // option) or the token is in the list.
1020 bool isTableGenDAGArgBreakingOperator(const FormatToken &Tok) {
1021 auto &Opes = Style.TableGenBreakingDAGArgOperators;
1022 // If the list is empty, all operators are breaking operators.
1023 if (Opes.empty())
1024 return true;
1025 // Otherwise, the operator is limited to normal identifiers.
1026 if (Tok.isNot(Kind: tok::identifier) ||
1027 Tok.isOneOf(K1: TT_TableGenBangOperator, K2: TT_TableGenCondOperator)) {
1028 return false;
1029 }
1030 // The case next is colon, it is not a operator of identifier.
1031 if (!Tok.Next || Tok.Next->is(Kind: tok::colon))
1032 return false;
1033 return llvm::is_contained(Range: Opes, Element: Tok.TokenText.str());
1034 }
1035
1036 // SimpleValue6 ::= "(" DagArg [DagArgList] ")"
1037 // This parses SimpleValue 6's inside part of "(" ")"
1038 bool parseTableGenDAGArgAndList(FormatToken *Opener) {
1039 FormatToken *FirstTok = CurrentToken;
1040 if (!parseTableGenDAGArg())
1041 return false;
1042 bool BreakInside = false;
1043 if (Style.TableGenBreakInsideDAGArg != FormatStyle::DAS_DontBreak) {
1044 // Specialized detection for DAGArgOperator, that determines the way of
1045 // line break for this DAGArg elements.
1046 if (isTableGenDAGArgBreakingOperator(Tok: *FirstTok)) {
1047 // Special case for identifier DAGArg operator.
1048 BreakInside = true;
1049 Opener->setType(TT_TableGenDAGArgOpenerToBreak);
1050 if (FirstTok->isOneOf(K1: TT_TableGenBangOperator,
1051 K2: TT_TableGenCondOperator)) {
1052 // Special case for bang/cond operators. Set the whole operator as
1053 // the DAGArg operator. Always break after it.
1054 CurrentToken->Previous->setType(TT_TableGenDAGArgOperatorToBreak);
1055 } else if (FirstTok->is(Kind: tok::identifier)) {
1056 if (Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakAll)
1057 FirstTok->setType(TT_TableGenDAGArgOperatorToBreak);
1058 else
1059 FirstTok->setType(TT_TableGenDAGArgOperatorID);
1060 }
1061 }
1062 }
1063 // Parse the [DagArgList] part
1064 return parseTableGenDAGArgList(Opener, BreakInside);
1065 }
1066
1067 // DagArgList ::= "," DagArg [DagArgList]
1068 // This parses SimpleValue 6's [DagArgList] part.
1069 bool parseTableGenDAGArgList(FormatToken *Opener, bool BreakInside) {
1070 ScopedContextCreator ContextCreator(*this, tok::l_paren, 0);
1071 Contexts.back().IsTableGenDAGArgList = true;
1072 bool FirstDAGArgListElm = true;
1073 while (CurrentToken) {
1074 if (!FirstDAGArgListElm && CurrentToken->is(Kind: tok::comma)) {
1075 CurrentToken->setType(BreakInside ? TT_TableGenDAGArgListCommaToBreak
1076 : TT_TableGenDAGArgListComma);
1077 skipToNextNonComment();
1078 }
1079 if (CurrentToken && CurrentToken->is(Kind: tok::r_paren)) {
1080 CurrentToken->setType(TT_TableGenDAGArgCloser);
1081 Opener->MatchingParen = CurrentToken;
1082 CurrentToken->MatchingParen = Opener;
1083 skipToNextNonComment();
1084 return true;
1085 }
1086 if (!parseTableGenDAGArg(
1087 AlignColon: BreakInside &&
1088 Style.AlignConsecutiveTableGenBreakingDAGArgColons.Enabled)) {
1089 return false;
1090 }
1091 FirstDAGArgListElm = false;
1092 }
1093 return false;
1094 }
1095
1096 bool parseTableGenSimpleValue() {
1097 assert(Style.isTableGen());
1098 if (!CurrentToken)
1099 return false;
1100 FormatToken *Tok = CurrentToken;
1101 skipToNextNonComment();
1102 // SimpleValue 1, 2, 3: Literals
1103 if (Tok->isOneOf(K1: tok::numeric_constant, K2: tok::string_literal,
1104 Ks: TT_TableGenMultiLineString, Ks: tok::kw_true, Ks: tok::kw_false,
1105 Ks: tok::question, Ks: tok::kw_int)) {
1106 return true;
1107 }
1108 // SimpleValue 4: ValueList, Type
1109 if (Tok->is(Kind: tok::l_brace)) {
1110 Scopes.push_back(Elt: getScopeType(Token: *Tok));
1111 return parseBrace();
1112 }
1113 // SimpleValue 5: List initializer
1114 if (Tok->is(Kind: tok::l_square)) {
1115 Tok->setType(TT_TableGenListOpener);
1116 if (!parseSquare())
1117 return false;
1118 if (Tok->is(Kind: tok::less)) {
1119 CurrentToken->setType(TT_TemplateOpener);
1120 return parseAngle();
1121 }
1122 return true;
1123 }
1124 // SimpleValue 6: DAGArg [DAGArgList]
1125 // SimpleValue6 ::= "(" DagArg [DagArgList] ")"
1126 if (Tok->is(Kind: tok::l_paren)) {
1127 Tok->setType(TT_TableGenDAGArgOpener);
1128 // Nested DAGArg requires space before '(' as separator.
1129 if (Contexts.back().IsTableGenDAGArgList)
1130 Tok->SpacesRequiredBefore = 1;
1131 return parseTableGenDAGArgAndList(Opener: Tok);
1132 }
1133 // SimpleValue 9: Bang operator
1134 if (Tok->is(TT: TT_TableGenBangOperator)) {
1135 if (CurrentToken && CurrentToken->is(Kind: tok::less)) {
1136 CurrentToken->setType(TT_TemplateOpener);
1137 skipToNextNonComment();
1138 if (!parseAngle())
1139 return false;
1140 }
1141 if (!CurrentToken || CurrentToken->isNot(Kind: tok::l_paren))
1142 return false;
1143 next();
1144 // FIXME: Hack using inheritance to child context
1145 Contexts.back().IsTableGenBangOpe = true;
1146 bool Result = parseParens();
1147 Contexts.back().IsTableGenBangOpe = false;
1148 return Result;
1149 }
1150 // SimpleValue 9: Cond operator
1151 if (Tok->is(TT: TT_TableGenCondOperator)) {
1152 if (!CurrentToken || CurrentToken->isNot(Kind: tok::l_paren))
1153 return false;
1154 next();
1155 return parseParens();
1156 }
1157 // We have to check identifier at the last because the kind of bang/cond
1158 // operators are also identifier.
1159 // SimpleValue 7: Identifiers
1160 if (Tok->is(Kind: tok::identifier)) {
1161 // SimpleValue 8: Anonymous record
1162 if (CurrentToken && CurrentToken->is(Kind: tok::less)) {
1163 CurrentToken->setType(TT_TemplateOpener);
1164 skipToNextNonComment();
1165 return parseAngle();
1166 }
1167 return true;
1168 }
1169
1170 return false;
1171 }
1172
1173 bool couldBeInStructArrayInitializer() const {
1174 if (Contexts.size() < 2)
1175 return false;
1176 // We want to back up no more then 2 context levels i.e.
1177 // . { { <-
1178 const auto End = std::next(x: Contexts.rbegin(), n: 2);
1179 auto Last = Contexts.rbegin();
1180 unsigned Depth = 0;
1181 for (; Last != End; ++Last)
1182 if (Last->ContextKind == tok::l_brace)
1183 ++Depth;
1184 return Depth == 2 && Last->ContextKind != tok::l_brace;
1185 }
1186
1187 bool parseBrace() {
1188 if (!CurrentToken)
1189 return true;
1190
1191 assert(CurrentToken->Previous);
1192 FormatToken &OpeningBrace = *CurrentToken->Previous;
1193 assert(OpeningBrace.is(tok::l_brace));
1194 OpeningBrace.ParentBracket = Contexts.back().ContextKind;
1195
1196 if (Contexts.back().CaretFound)
1197 OpeningBrace.overwriteFixedType(T: TT_ObjCBlockLBrace);
1198 Contexts.back().CaretFound = false;
1199
1200 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
1201 Contexts.back().ColonIsDictLiteral = true;
1202 if (OpeningBrace.is(BBK: BK_BracedInit))
1203 Contexts.back().IsExpression = true;
1204 if (Style.isJavaScript() && OpeningBrace.Previous &&
1205 OpeningBrace.Previous->is(TT: TT_JsTypeColon)) {
1206 Contexts.back().IsExpression = false;
1207 }
1208 if (Style.isVerilog() &&
1209 (!OpeningBrace.getPreviousNonComment() ||
1210 OpeningBrace.getPreviousNonComment()->isNot(Kind: Keywords.kw_apostrophe))) {
1211 Contexts.back().VerilogMayBeConcatenation = true;
1212 }
1213 if (Style.isTableGen())
1214 Contexts.back().ColonIsDictLiteral = false;
1215
1216 unsigned CommaCount = 0;
1217 while (CurrentToken) {
1218 assert(!Scopes.empty());
1219 if (CurrentToken->is(Kind: tok::r_brace)) {
1220 assert(Scopes.back() == getScopeType(OpeningBrace));
1221 Scopes.pop_back();
1222 assert(OpeningBrace.Optional == CurrentToken->Optional);
1223 OpeningBrace.MatchingParen = CurrentToken;
1224 CurrentToken->MatchingParen = &OpeningBrace;
1225 if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
1226 if (OpeningBrace.ParentBracket == tok::l_brace &&
1227 couldBeInStructArrayInitializer() && CommaCount > 0) {
1228 Contexts.back().ContextType = Context::StructArrayInitializer;
1229 }
1230 }
1231 next();
1232 return true;
1233 }
1234 if (CurrentToken->isOneOf(K1: tok::r_paren, K2: tok::r_square))
1235 return false;
1236 updateParameterCount(Left: &OpeningBrace, Current: CurrentToken);
1237 if (CurrentToken->isOneOf(K1: tok::colon, K2: tok::l_brace, Ks: tok::less)) {
1238 FormatToken *Previous = CurrentToken->getPreviousNonComment();
1239 if (Previous->is(TT: TT_JsTypeOptionalQuestion))
1240 Previous = Previous->getPreviousNonComment();
1241 if ((CurrentToken->is(Kind: tok::colon) && !Style.isTableGen() &&
1242 (!Contexts.back().ColonIsDictLiteral || !IsCpp)) ||
1243 Style.isProto()) {
1244 OpeningBrace.setType(TT_DictLiteral);
1245 Scopes.back() = getScopeType(Token: OpeningBrace);
1246 if (Previous->Tok.getIdentifierInfo() ||
1247 Previous->is(Kind: tok::string_literal)) {
1248 Previous->setType(TT_SelectorName);
1249 }
1250 }
1251 if (CurrentToken->is(Kind: tok::colon) && OpeningBrace.is(TT: TT_Unknown) &&
1252 !Style.isTableGen()) {
1253 OpeningBrace.setType(TT_DictLiteral);
1254 Scopes.back() = getScopeType(Token: OpeningBrace);
1255 } else if (Style.isJavaScript()) {
1256 OpeningBrace.overwriteFixedType(T: TT_DictLiteral);
1257 Scopes.back() = getScopeType(Token: OpeningBrace);
1258 }
1259 }
1260 bool IsBracedListComma = false;
1261 if (CurrentToken->is(Kind: tok::comma)) {
1262 if (Style.isJavaScript()) {
1263 OpeningBrace.overwriteFixedType(T: TT_DictLiteral);
1264 Scopes.back() = getScopeType(Token: OpeningBrace);
1265 } else {
1266 IsBracedListComma = OpeningBrace.is(BBK: BK_BracedInit);
1267 }
1268 ++CommaCount;
1269 }
1270 if (!consumeToken())
1271 return false;
1272 if (IsBracedListComma)
1273 Contexts.back().IsExpression = true;
1274 }
1275 return true;
1276 }
1277
1278 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
1279 // For ObjC methods, the number of parameters is calculated differently as
1280 // method declarations have a different structure (the parameters are not
1281 // inside a bracket scope).
1282 if (Current->is(Kind: tok::l_brace) && Current->is(BBK: BK_Block))
1283 ++Left->BlockParameterCount;
1284 if (Current->is(Kind: tok::comma)) {
1285 ++Left->ParameterCount;
1286 if (!Left->Role)
1287 Left->Role.reset(p: new CommaSeparatedList(Style));
1288 Left->Role->CommaFound(Token: Current);
1289 } else if (Left->ParameterCount == 0 && Current->isNot(Kind: tok::comment)) {
1290 Left->ParameterCount = 1;
1291 }
1292 }
1293
1294 bool parseConditional() {
1295 while (CurrentToken) {
1296 if (CurrentToken->is(Kind: tok::colon) && CurrentToken->is(TT: TT_Unknown)) {
1297 CurrentToken->setType(TT_ConditionalExpr);
1298 next();
1299 return true;
1300 }
1301 // An unmatched `}` belongs to an enclosing parseBrace call, consuming it
1302 // here would pop that call's Scopes frame and trigger its assertion.
1303 // Return early instead.
1304 if (CurrentToken->is(Kind: tok::r_brace))
1305 return false;
1306 if (!consumeToken())
1307 return false;
1308 }
1309 return false;
1310 }
1311
1312 bool parseTemplateDeclaration() {
1313 if (!CurrentToken || CurrentToken->isNot(Kind: tok::less))
1314 return false;
1315
1316 CurrentToken->setType(TT_TemplateOpener);
1317 next();
1318
1319 TemplateDeclarationDepth++;
1320 const bool WellFormed = parseAngle();
1321 TemplateDeclarationDepth--;
1322 if (!WellFormed)
1323 return false;
1324
1325 if (CurrentToken && TemplateDeclarationDepth == 0)
1326 CurrentToken->Previous->ClosesTemplateDeclaration = true;
1327
1328 return true;
1329 }
1330
1331 bool consumeToken() {
1332 if (IsCpp) {
1333 const auto *Prev = CurrentToken->getPreviousNonComment();
1334 if (Prev && Prev->is(TT: TT_AttributeRSquare) &&
1335 CurrentToken->isOneOf(K1: tok::kw_if, K2: tok::kw_switch, Ks: tok::kw_case,
1336 Ks: tok::kw_default, Ks: tok::kw_for, Ks: tok::kw_while) &&
1337 mustBreakAfterAttributes(Tok: *CurrentToken, Style)) {
1338 CurrentToken->MustBreakBefore = true;
1339 }
1340 }
1341 FormatToken *Tok = CurrentToken;
1342 next();
1343 // In Verilog primitives' state tables, `:`, `?`, and `-` aren't normal
1344 // operators.
1345 if (Tok->is(TT: TT_VerilogTableItem))
1346 return true;
1347 // Multi-line string itself is a single annotated token.
1348 if (Tok->is(TT: TT_TableGenMultiLineString))
1349 return true;
1350 auto *Prev = Tok->getPreviousNonComment();
1351 auto *Next = Tok->getNextNonComment();
1352 switch (bool IsIf = false; Tok->Tok.getKind()) {
1353 case tok::plus:
1354 case tok::minus:
1355 if (!Prev && Line.MustBeDeclaration)
1356 Tok->setType(TT_ObjCMethodSpecifier);
1357 break;
1358 case tok::colon:
1359 if (!Prev)
1360 return false;
1361 // Goto labels and case labels are already identified in
1362 // UnwrappedLineParser.
1363 if (Tok->isTypeFinalized())
1364 break;
1365 // Colons from ?: are handled in parseConditional().
1366 if (Style.isJavaScript()) {
1367 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
1368 (Contexts.size() == 1 && // switch/case labels
1369 Line.First->isNoneOf(Ks: tok::kw_enum, Ks: tok::kw_case)) ||
1370 Contexts.back().ContextKind == tok::l_paren || // function params
1371 Contexts.back().ContextKind == tok::l_square || // array type
1372 (!Contexts.back().IsExpression &&
1373 Contexts.back().ContextKind == tok::l_brace) || // object type
1374 (Contexts.size() == 1 &&
1375 Line.MustBeDeclaration)) { // method/property declaration
1376 Contexts.back().IsExpression = false;
1377 Tok->setType(TT_JsTypeColon);
1378 break;
1379 }
1380 } else if (Style.isCSharp()) {
1381 if (Contexts.back().InCSharpAttributeSpecifier) {
1382 Tok->setType(TT_AttributeColon);
1383 break;
1384 }
1385 if (Contexts.back().ContextKind == tok::l_paren) {
1386 Tok->setType(TT_CSharpNamedArgumentColon);
1387 break;
1388 }
1389 } else if (Style.isVerilog() && Tok->isNot(Kind: TT_BinaryOperator)) {
1390 // The distribution weight operators are labeled
1391 // TT_BinaryOperator by the lexer.
1392 if (Keywords.isVerilogEnd(Tok: *Prev) || Keywords.isVerilogBegin(Tok: *Prev)) {
1393 Tok->setType(TT_VerilogBlockLabelColon);
1394 } else if (Contexts.back().ContextKind == tok::l_square) {
1395 Tok->setType(TT_BitFieldColon);
1396 } else if (Contexts.back().ColonIsDictLiteral) {
1397 Tok->setType(TT_DictLiteral);
1398 } else if (Contexts.size() == 1) {
1399 // In Verilog a case label doesn't have the case keyword. We
1400 // assume a colon following an expression is a case label.
1401 // Colons from ?: are annotated in parseConditional().
1402 Tok->setType(TT_CaseLabelColon);
1403 if (Line.Level > 1 || (!Line.InPPDirective && Line.Level > 0))
1404 --Line.Level;
1405 }
1406 break;
1407 }
1408 if (Line.First->is(Kind: tok::kw_asm)) {
1409 Tok->setType(TT_InlineASMColon);
1410 } else if (Contexts.back().ColonIsDictLiteral || Style.isProto()) {
1411 Tok->setType(TT_DictLiteral);
1412 if (Style.isTextProto())
1413 Prev->setType(TT_SelectorName);
1414 } else if (Contexts.back().ColonIsObjCMethodExpr ||
1415 Line.startsWith(Tokens: TT_ObjCMethodSpecifier)) {
1416 Tok->setType(TT_ObjCMethodExpr);
1417 const auto *PrevPrev = Prev->Previous;
1418 // Ensure we tag all identifiers in method declarations as
1419 // TT_SelectorName.
1420 bool UnknownIdentifierInMethodDeclaration =
1421 Line.startsWith(Tokens: TT_ObjCMethodSpecifier) &&
1422 Prev->is(Kind: tok::identifier) && Prev->is(TT: TT_Unknown);
1423 if (!PrevPrev ||
1424 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
1425 !(PrevPrev->is(TT: TT_CastRParen) ||
1426 (PrevPrev->is(TT: TT_ObjCMethodExpr) && PrevPrev->is(Kind: tok::colon))) ||
1427 PrevPrev->is(Kind: tok::r_square) ||
1428 Contexts.back().LongestObjCSelectorName == 0 ||
1429 UnknownIdentifierInMethodDeclaration) {
1430 Prev->setType(TT_SelectorName);
1431 if (!Contexts.back().FirstObjCSelectorName)
1432 Contexts.back().FirstObjCSelectorName = Prev;
1433 else if (Prev->ColumnWidth > Contexts.back().LongestObjCSelectorName)
1434 Contexts.back().LongestObjCSelectorName = Prev->ColumnWidth;
1435 Prev->ParameterIndex =
1436 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
1437 ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
1438 }
1439 } else if (Contexts.back().ColonIsForRangeExpr) {
1440 Tok->setType(TT_RangeBasedForLoopColon);
1441 for (auto *Token = Prev;
1442 Token && Token->isNoneOf(Ks: tok::semi, Ks: tok::l_paren);
1443 Token = Token->Previous) {
1444 if (Token->isPointerOrReference())
1445 Token->setFinalizedType(TT_PointerOrReference);
1446 }
1447 } else if (Contexts.back().ContextType == Context::C11GenericSelection) {
1448 Tok->setType(TT_GenericSelectionColon);
1449 if (Prev->isPointerOrReference())
1450 Prev->setFinalizedType(TT_PointerOrReference);
1451 } else if ((CurrentToken && CurrentToken->is(Kind: tok::numeric_constant)) ||
1452 (Prev->is(TT: TT_StartOfName) && !Scopes.empty() &&
1453 Scopes.back() == ST_Class)) {
1454 Tok->setType(TT_BitFieldColon);
1455 } else if (Contexts.size() == 1 &&
1456 Line.getFirstNonComment()->isNoneOf(Ks: tok::kw_enum, Ks: tok::kw_case,
1457 Ks: tok::kw_default) &&
1458 !Line.startsWith(Tokens: tok::kw_typedef, Tokens: tok::kw_enum)) {
1459 if (Prev->isOneOf(K1: tok::r_paren, K2: tok::kw_noexcept) ||
1460 Prev->ClosesRequiresClause) {
1461 Tok->setType(TT_CtorInitializerColon);
1462 } else if (Prev->is(Kind: tok::kw_try)) {
1463 // Member initializer list within function try block.
1464 FormatToken *PrevPrev = Prev->getPreviousNonComment();
1465 if (!PrevPrev)
1466 break;
1467 if (PrevPrev && PrevPrev->isOneOf(K1: tok::r_paren, K2: tok::kw_noexcept))
1468 Tok->setType(TT_CtorInitializerColon);
1469 } else {
1470 Tok->setType(TT_InheritanceColon);
1471 if (Prev->isAccessSpecifierKeyword())
1472 Line.Type = LT_AccessModifier;
1473 }
1474 } else if (canBeObjCSelectorComponent(Tok: *Prev) && Next &&
1475 (Next->isOneOf(K1: tok::r_paren, K2: tok::comma) ||
1476 (canBeObjCSelectorComponent(Tok: *Next) && Next->Next &&
1477 Next->Next->is(Kind: tok::colon)))) {
1478 // This handles a special macro in ObjC code where selectors including
1479 // the colon are passed as macro arguments.
1480 Tok->setType(TT_ObjCSelector);
1481 }
1482 break;
1483 case tok::pipe:
1484 case tok::amp:
1485 // | and & in declarations/type expressions represent union and
1486 // intersection types, respectively.
1487 if (Style.isJavaScript() && !Contexts.back().IsExpression)
1488 Tok->setType(TT_JsTypeOperator);
1489 break;
1490 case tok::kw_if:
1491 if (Style.isTableGen()) {
1492 // In TableGen it has the form 'if' <value> 'then'.
1493 if (!parseTableGenValue())
1494 return false;
1495 if (CurrentToken && CurrentToken->is(II: Keywords.kw_then))
1496 next(); // skip then
1497 break;
1498 }
1499 if (CurrentToken &&
1500 CurrentToken->isOneOf(K1: tok::kw_constexpr, K2: tok::identifier)) {
1501 next();
1502 }
1503 IsIf = true;
1504 [[fallthrough]];
1505 case tok::kw_while:
1506 if (CurrentToken && CurrentToken->is(Kind: tok::l_paren)) {
1507 next();
1508 if (!parseParens(IsIf))
1509 return false;
1510 }
1511 break;
1512 case tok::kw_for:
1513 if (Style.isJavaScript()) {
1514 // x.for and {for: ...}
1515 if ((Prev && Prev->is(Kind: tok::period)) || (Next && Next->is(Kind: tok::colon)))
1516 break;
1517 // JS' for await ( ...
1518 if (CurrentToken && CurrentToken->is(II: Keywords.kw_await))
1519 next();
1520 }
1521 if (IsCpp && CurrentToken && CurrentToken->is(Kind: tok::kw_co_await))
1522 next();
1523 Contexts.back().ColonIsForRangeExpr = true;
1524 if (!CurrentToken || CurrentToken->isNot(Kind: tok::l_paren))
1525 return false;
1526 next();
1527 if (!parseParens())
1528 return false;
1529 break;
1530 case tok::l_paren:
1531 // When faced with 'operator()()', the kw_operator handler incorrectly
1532 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
1533 // the first two parens OverloadedOperators and the second l_paren an
1534 // OverloadedOperatorLParen.
1535 if (Prev && Prev->is(Kind: tok::r_paren) && Prev->MatchingParen &&
1536 Prev->MatchingParen->is(TT: TT_OverloadedOperatorLParen)) {
1537 Prev->setType(TT_OverloadedOperator);
1538 Prev->MatchingParen->setType(TT_OverloadedOperator);
1539 Tok->setType(TT_OverloadedOperatorLParen);
1540 }
1541
1542 if (Style.isVerilog()) {
1543 // Identify the parameter list and port list in a module instantiation.
1544 // This is still needed when we already have
1545 // UnwrappedLineParser::parseVerilogHierarchyHeader because that
1546 // function is only responsible for the definition, not the
1547 // instantiation.
1548 auto IsInstancePort = [&]() {
1549 const FormatToken *PrevPrev;
1550 // In the following example all 4 left parentheses will be treated as
1551 // 'TT_VerilogInstancePortLParen'.
1552 //
1553 // module_x instance_1(port_1); // Case A.
1554 // module_x #(parameter_1) // Case B.
1555 // instance_2(port_1), // Case C.
1556 // instance_3(port_1); // Case D.
1557 if (!Prev || !(PrevPrev = Prev->getPreviousNonComment()))
1558 return false;
1559 // Case A.
1560 if (Keywords.isVerilogIdentifier(Tok: *Prev) &&
1561 Keywords.isVerilogIdentifier(Tok: *PrevPrev)) {
1562 return true;
1563 }
1564 // Case B.
1565 if (Prev->is(II: Keywords.kw_verilogHash) &&
1566 Keywords.isVerilogIdentifier(Tok: *PrevPrev)) {
1567 return true;
1568 }
1569 // Case C.
1570 if (Keywords.isVerilogIdentifier(Tok: *Prev) && PrevPrev->is(Kind: tok::r_paren))
1571 return true;
1572 // Case D.
1573 if (Keywords.isVerilogIdentifier(Tok: *Prev) && PrevPrev->is(Kind: tok::comma)) {
1574 const FormatToken *PrevParen = PrevPrev->getPreviousNonComment();
1575 if (PrevParen && PrevParen->is(Kind: tok::r_paren) &&
1576 PrevParen->MatchingParen &&
1577 PrevParen->MatchingParen->is(TT: TT_VerilogInstancePortLParen)) {
1578 return true;
1579 }
1580 }
1581 return false;
1582 };
1583
1584 if (IsInstancePort())
1585 Tok->setType(TT_VerilogInstancePortLParen);
1586 }
1587
1588 if (!parseParens())
1589 return false;
1590 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
1591 !Contexts.back().IsExpression && !Line.startsWith(Tokens: TT_ObjCProperty) &&
1592 !Line.startsWith(Tokens: tok::l_paren) &&
1593 Tok->isNoneOf(Ks: TT_TypeDeclarationParen, Ks: TT_RequiresExpressionLParen)) {
1594 if (!Prev ||
1595 (!Prev->isAttribute() &&
1596 Prev->isNoneOf(Ks: TT_RequiresClause, Ks: TT_LeadingJavaAnnotation,
1597 Ks: TT_BinaryOperator))) {
1598 Line.MightBeFunctionDecl = true;
1599 Tok->MightBeFunctionDeclParen = true;
1600 }
1601 }
1602 break;
1603 case tok::l_square:
1604 if (Style.isTableGen())
1605 Tok->setType(TT_TableGenListOpener);
1606 if (!parseSquare())
1607 return false;
1608 break;
1609 case tok::l_brace:
1610 if (IsCpp) {
1611 if (Tok->is(TT: TT_RequiresExpressionLBrace))
1612 Line.Type = LT_RequiresExpression;
1613 } else if (Style.isTextProto()) {
1614 if (Prev && Prev->isNot(Kind: TT_DictLiteral))
1615 Prev->setType(TT_SelectorName);
1616 }
1617 Scopes.push_back(Elt: getScopeType(Token: *Tok));
1618 if (!parseBrace())
1619 return false;
1620 break;
1621 case tok::less:
1622 if (parseAngle()) {
1623 Tok->setType(TT_TemplateOpener);
1624 // In TT_Proto, we must distignuish between:
1625 // map<key, value>
1626 // msg < item: data >
1627 // msg: < item: data >
1628 // In TT_TextProto, map<key, value> does not occur.
1629 if (Style.isTextProto() ||
1630 (Style.Language == FormatStyle::LK_Proto && Prev &&
1631 Prev->isOneOf(K1: TT_SelectorName, K2: TT_DictLiteral))) {
1632 Tok->setType(TT_DictLiteral);
1633 if (Prev && Prev->isNot(Kind: TT_DictLiteral))
1634 Prev->setType(TT_SelectorName);
1635 }
1636 if (Style.isTableGen())
1637 Tok->setType(TT_TemplateOpener);
1638 } else {
1639 Tok->setType(TT_BinaryOperator);
1640 NonTemplateLess.insert(Ptr: Tok);
1641 CurrentToken = Tok;
1642 next();
1643 }
1644 break;
1645 case tok::r_paren:
1646 case tok::r_square:
1647 return false;
1648 case tok::r_brace:
1649 // Don't pop scope when encountering unbalanced r_brace.
1650 if (!Scopes.empty())
1651 Scopes.pop_back();
1652 // Lines can start with '}'.
1653 if (Prev)
1654 return false;
1655 break;
1656 case tok::greater:
1657 if (!Style.isTextProto() && Tok->is(TT: TT_Unknown))
1658 Tok->setType(TT_BinaryOperator);
1659 if (Prev && Prev->is(TT: TT_TemplateCloser))
1660 Tok->SpacesRequiredBefore = 1;
1661 break;
1662 case tok::kw_operator:
1663 if (Style.isProto())
1664 break;
1665 // Handle C++ user-defined conversion function.
1666 if (IsCpp && CurrentToken) {
1667 const auto *Info = CurrentToken->Tok.getIdentifierInfo();
1668 // What follows Tok is an identifier or a non-operator keyword.
1669 if (Info && !(CurrentToken->isPlacementOperator() ||
1670 CurrentToken->is(Kind: tok::kw_co_await) ||
1671 Info->isCPlusPlusOperatorKeyword())) {
1672 FormatToken *LParen;
1673 if (CurrentToken->startsSequence(K1: tok::kw_decltype, Tokens: tok::l_paren,
1674 Tokens: tok::kw_auto, Tokens: tok::r_paren)) {
1675 // Skip `decltype(auto)`.
1676 LParen = CurrentToken->Next->Next->Next->Next;
1677 } else {
1678 // Skip to l_paren.
1679 for (LParen = CurrentToken->Next;
1680 LParen && LParen->isNot(Kind: tok::l_paren); LParen = LParen->Next) {
1681 if (LParen->isPointerOrReference())
1682 LParen->setFinalizedType(TT_PointerOrReference);
1683 }
1684 }
1685 if (LParen && LParen->is(Kind: tok::l_paren)) {
1686 if (!Contexts.back().IsExpression) {
1687 Tok->setFinalizedType(TT_FunctionDeclarationName);
1688 LParen->setFinalizedType(TT_FunctionDeclarationLParen);
1689 }
1690 break;
1691 }
1692 }
1693 }
1694 while (CurrentToken &&
1695 CurrentToken->isNoneOf(Ks: tok::l_paren, Ks: tok::semi, Ks: tok::r_paren,
1696 Ks: tok::r_brace)) {
1697 if (CurrentToken->isOneOf(K1: tok::star, K2: tok::amp))
1698 CurrentToken->setType(TT_PointerOrReference);
1699 auto Next = CurrentToken->getNextNonComment();
1700 if (!Next)
1701 break;
1702 if (Next->is(Kind: tok::less))
1703 next();
1704 else
1705 consumeToken();
1706 if (!CurrentToken)
1707 break;
1708 auto Previous = CurrentToken->getPreviousNonComment();
1709 assert(Previous);
1710 if (CurrentToken->is(Kind: tok::comma) && Previous->isNot(Kind: tok::kw_operator))
1711 break;
1712 if (Previous->isOneOf(K1: TT_BinaryOperator, K2: TT_UnaryOperator, Ks: tok::comma,
1713 Ks: tok::arrow) ||
1714 (!Previous->isTypeFinalized() &&
1715 Previous->isPointerOrReference()) ||
1716 // User defined literal.
1717 Previous->TokenText.starts_with(Prefix: "\"\"")) {
1718 Previous->setType(TT_OverloadedOperator);
1719 if (CurrentToken->isOneOf(K1: tok::less, K2: tok::greater))
1720 break;
1721 }
1722 }
1723 if (CurrentToken && CurrentToken->is(Kind: tok::l_paren))
1724 CurrentToken->setType(TT_OverloadedOperatorLParen);
1725 if (CurrentToken && CurrentToken->Previous->is(TT: TT_BinaryOperator))
1726 CurrentToken->Previous->setType(TT_OverloadedOperator);
1727 break;
1728 case tok::question:
1729 if (Style.isJavaScript() && Next &&
1730 Next->isOneOf(K1: tok::semi, K2: tok::comma, Ks: tok::colon, Ks: tok::r_paren,
1731 Ks: tok::r_brace, Ks: tok::r_square)) {
1732 // Question marks before semicolons, colons, etc. indicate optional
1733 // types (fields, parameters), e.g.
1734 // function(x?: string, y?) {...}
1735 // class X { y?; }
1736 Tok->setType(TT_JsTypeOptionalQuestion);
1737 break;
1738 }
1739 // Declarations cannot be conditional expressions, this can only be part
1740 // of a type declaration.
1741 if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
1742 Style.isJavaScript()) {
1743 break;
1744 }
1745 if (Style.isCSharp()) {
1746 // `Type?)`, `Type?>`, `Type? name;`, and `Type? name =` can only be
1747 // nullable types.
1748 if (Next && (Next->isOneOf(K1: tok::r_paren, K2: tok::greater) ||
1749 Next->startsSequence(K1: tok::identifier, Tokens: tok::semi) ||
1750 Next->startsSequence(K1: tok::identifier, Tokens: tok::equal))) {
1751 Tok->setType(TT_CSharpNullable);
1752 break;
1753 }
1754
1755 // Line.MustBeDeclaration will be true for `Type? name;`.
1756 // But not
1757 // cond ? "A" : "B";
1758 // cond ? id : "B";
1759 // cond ? cond2 ? "A" : "B" : "C";
1760 if (!Contexts.back().IsExpression && Line.MustBeDeclaration &&
1761 (!Next || Next->isNoneOf(Ks: tok::identifier, Ks: tok::string_literal) ||
1762 !Next->Next || Next->Next->isNoneOf(Ks: tok::colon, Ks: tok::question))) {
1763 Tok->setType(TT_CSharpNullable);
1764 break;
1765 }
1766 }
1767 parseConditional();
1768 break;
1769 case tok::kw_template:
1770 parseTemplateDeclaration();
1771 break;
1772 case tok::comma:
1773 switch (Contexts.back().ContextType) {
1774 case Context::CtorInitializer:
1775 Tok->setType(TT_CtorInitializerComma);
1776 break;
1777 case Context::InheritanceList:
1778 Tok->setType(TT_InheritanceComma);
1779 break;
1780 case Context::VerilogInstancePortList:
1781 Tok->setType(TT_VerilogInstancePortComma);
1782 break;
1783 default:
1784 if (Style.isVerilog() && Contexts.size() == 1 &&
1785 Line.startsWith(Tokens: Keywords.kw_assign)) {
1786 Tok->setFinalizedType(TT_VerilogAssignComma);
1787 } else if (Contexts.back().FirstStartOfName &&
1788 (Contexts.size() == 1 || startsWithInitStatement(Line))) {
1789 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
1790 Line.IsMultiVariableDeclStmt = true;
1791 }
1792 break;
1793 }
1794 if (Contexts.back().ContextType == Context::ForEachMacro)
1795 Contexts.back().IsExpression = true;
1796 break;
1797 case tok::kw_default:
1798 // Unindent case labels.
1799 if (Style.isVerilog() && Keywords.isVerilogEndOfLabel(Tok: *Tok) &&
1800 (Line.Level > 1 || (!Line.InPPDirective && Line.Level > 0))) {
1801 --Line.Level;
1802 }
1803 break;
1804 case tok::identifier:
1805 if (Tok->isOneOf(K1: Keywords.kw___has_include,
1806 K2: Keywords.kw___has_include_next)) {
1807 parseHasInclude();
1808 }
1809 if (IsCpp) {
1810 if (Next && Next->is(Kind: tok::l_paren) && Prev &&
1811 Prev->isOneOf(K1: tok::kw___cdecl, K2: tok::kw___stdcall,
1812 Ks: tok::kw___fastcall, Ks: tok::kw___thiscall,
1813 Ks: tok::kw___regcall, Ks: tok::kw___vectorcall)) {
1814 Tok->setFinalizedType(TT_FunctionDeclarationName);
1815 Next->setFinalizedType(TT_FunctionDeclarationLParen);
1816 }
1817 } else if (Style.isCSharp()) {
1818 if (Tok->is(II: Keywords.kw_where) && Next && Next->isNot(Kind: tok::l_paren)) {
1819 Tok->setType(TT_CSharpGenericTypeConstraint);
1820 parseCSharpGenericTypeConstraint();
1821 if (!Prev)
1822 Line.IsContinuation = true;
1823 }
1824 } else if (Style.isTableGen()) {
1825 if (Tok->is(II: Keywords.kw_assert)) {
1826 if (!parseTableGenValue())
1827 return false;
1828 } else if (Tok->isOneOf(K1: Keywords.kw_def, K2: Keywords.kw_defm) &&
1829 (!Next || Next->isNoneOf(Ks: tok::colon, Ks: tok::l_brace))) {
1830 // The case NameValue appears.
1831 if (!parseTableGenValue(ParseNameMode: true))
1832 return false;
1833 }
1834 }
1835 if (Style.AllowBreakBeforeQtProperty &&
1836 Contexts.back().ContextType == Context::QtProperty &&
1837 Tok->isQtProperty()) {
1838 Tok->setFinalizedType(TT_QtProperty);
1839 }
1840 break;
1841 case tok::arrow:
1842 if (Tok->isNot(Kind: TT_LambdaArrow) && Prev && Prev->is(Kind: tok::kw_noexcept))
1843 Tok->setType(TT_TrailingReturnArrow);
1844 break;
1845 case tok::equal:
1846 // In TableGen, there must be a value after "=";
1847 if (Style.isTableGen() && !parseTableGenValue())
1848 return false;
1849 if (!Scopes.empty() && Scopes.back() == ST_Enum)
1850 Tok->setFinalizedType(TT_EnumEqual);
1851 break;
1852 default:
1853 break;
1854 }
1855 return true;
1856 }
1857
1858 void parseCSharpGenericTypeConstraint() {
1859 int OpenAngleBracketsCount = 0;
1860 while (CurrentToken) {
1861 if (CurrentToken->is(Kind: tok::less)) {
1862 // parseAngle is too greedy and will consume the whole line.
1863 CurrentToken->setType(TT_TemplateOpener);
1864 ++OpenAngleBracketsCount;
1865 next();
1866 } else if (CurrentToken->is(Kind: tok::greater)) {
1867 CurrentToken->setType(TT_TemplateCloser);
1868 --OpenAngleBracketsCount;
1869 next();
1870 } else if (CurrentToken->is(Kind: tok::comma) && OpenAngleBracketsCount == 0) {
1871 // We allow line breaks after GenericTypeConstraintComma's
1872 // so do not flag commas in Generics as GenericTypeConstraintComma's.
1873 CurrentToken->setType(TT_CSharpGenericTypeConstraintComma);
1874 next();
1875 } else if (CurrentToken->is(II: Keywords.kw_where)) {
1876 CurrentToken->setType(TT_CSharpGenericTypeConstraint);
1877 next();
1878 } else if (CurrentToken->is(Kind: tok::colon)) {
1879 CurrentToken->setType(TT_CSharpGenericTypeConstraintColon);
1880 next();
1881 } else {
1882 next();
1883 }
1884 }
1885 }
1886
1887 void parseIncludeDirective() {
1888 if (CurrentToken && CurrentToken->is(Kind: tok::less)) {
1889 next();
1890 while (CurrentToken) {
1891 // Mark tokens up to the trailing line comments as implicit string
1892 // literals.
1893 if (CurrentToken->isNot(Kind: tok::comment) &&
1894 !CurrentToken->TokenText.starts_with(Prefix: "//")) {
1895 CurrentToken->setType(TT_ImplicitStringLiteral);
1896 }
1897 next();
1898 }
1899 }
1900 }
1901
1902 void parseWarningOrError() {
1903 next();
1904 // We still want to format the whitespace left of the first token of the
1905 // warning or error.
1906 next();
1907 while (CurrentToken) {
1908 CurrentToken->setType(TT_ImplicitStringLiteral);
1909 next();
1910 }
1911 }
1912
1913 void parsePragma() {
1914 next(); // Consume "pragma".
1915 if (CurrentToken &&
1916 CurrentToken->isOneOf(K1: Keywords.kw_mark, K2: Keywords.kw_option,
1917 Ks: Keywords.kw_region)) {
1918 bool IsMarkOrRegion =
1919 CurrentToken->isOneOf(K1: Keywords.kw_mark, K2: Keywords.kw_region);
1920 next();
1921 next(); // Consume first token (so we fix leading whitespace).
1922 while (CurrentToken) {
1923 if (IsMarkOrRegion || CurrentToken->Previous->is(TT: TT_BinaryOperator))
1924 CurrentToken->setType(TT_ImplicitStringLiteral);
1925 next();
1926 }
1927 }
1928 }
1929
1930 void parseHasInclude() {
1931 if (!CurrentToken || CurrentToken->isNot(Kind: tok::l_paren))
1932 return;
1933 next(); // '('
1934 parseIncludeDirective();
1935 next(); // ')'
1936 }
1937
1938 LineType parsePreprocessorDirective() {
1939 bool IsFirstToken = CurrentToken->IsFirst;
1940 LineType Type = LT_PreprocessorDirective;
1941 next();
1942 if (!CurrentToken)
1943 return Type;
1944
1945 if (Style.isJavaScript() && IsFirstToken) {
1946 // JavaScript files can contain shebang lines of the form:
1947 // #!/usr/bin/env node
1948 // Treat these like C++ #include directives.
1949 while (CurrentToken) {
1950 // Tokens cannot be comments here.
1951 CurrentToken->setType(TT_ImplicitStringLiteral);
1952 next();
1953 }
1954 return LT_ImportStatement;
1955 }
1956
1957 if (CurrentToken->is(Kind: tok::numeric_constant)) {
1958 CurrentToken->SpacesRequiredBefore = 1;
1959 return Type;
1960 }
1961 // Hashes in the middle of a line can lead to any strange token
1962 // sequence.
1963 if (!CurrentToken->Tok.getIdentifierInfo())
1964 return Type;
1965 // In Verilog macro expansions start with a backtick just like preprocessor
1966 // directives. Thus we stop if the word is not a preprocessor directive.
1967 if (Style.isVerilog() && !Keywords.isVerilogPPDirective(Tok: *CurrentToken))
1968 return LT_Invalid;
1969 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
1970 case tok::pp_include:
1971 case tok::pp_include_next:
1972 case tok::pp_import:
1973 next();
1974 parseIncludeDirective();
1975 Type = LT_ImportStatement;
1976 break;
1977 case tok::pp_error:
1978 case tok::pp_warning:
1979 parseWarningOrError();
1980 break;
1981 case tok::pp_pragma:
1982 parsePragma();
1983 break;
1984 case tok::pp_if:
1985 case tok::pp_elif:
1986 Contexts.back().IsExpression = true;
1987 next();
1988 if (CurrentToken)
1989 CurrentToken->SpacesRequiredBefore = 1;
1990 parseLine();
1991 break;
1992 default:
1993 break;
1994 }
1995 while (CurrentToken) {
1996 FormatToken *Tok = CurrentToken;
1997 next();
1998 if (Tok->is(Kind: tok::l_paren)) {
1999 parseParens();
2000 } else if (Tok->isOneOf(K1: Keywords.kw___has_include,
2001 K2: Keywords.kw___has_include_next)) {
2002 parseHasInclude();
2003 }
2004 }
2005 return Type;
2006 }
2007
2008public:
2009 LineType parseLine() {
2010 if (!CurrentToken)
2011 return LT_Invalid;
2012 NonTemplateLess.clear();
2013 if (!Line.InMacroBody && CurrentToken->is(Kind: tok::hash)) {
2014 // We were not yet allowed to use C++17 optional when this was being
2015 // written. So we used LT_Invalid to mark that the line is not a
2016 // preprocessor directive.
2017 auto Type = parsePreprocessorDirective();
2018 if (Type != LT_Invalid)
2019 return Type;
2020 }
2021
2022 // Directly allow to 'import <string-literal>' to support protocol buffer
2023 // definitions (github.com/google/protobuf) or missing "#" (either way we
2024 // should not break the line).
2025 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
2026 if ((Style.isJava() && CurrentToken->is(II: Keywords.kw_package)) ||
2027 (!Style.isVerilog() && Info &&
2028 Info->getPPKeywordID() == tok::pp_import && CurrentToken->Next &&
2029 CurrentToken->Next->isOneOf(K1: tok::string_literal, K2: tok::identifier,
2030 Ks: tok::kw_static))) {
2031 next();
2032 parseIncludeDirective();
2033 return LT_ImportStatement;
2034 }
2035
2036 // If this line starts and ends in '<' and '>', respectively, it is likely
2037 // part of "#define <a/b.h>".
2038 if (CurrentToken->is(Kind: tok::less) && Line.Last->is(Kind: tok::greater)) {
2039 parseIncludeDirective();
2040 return LT_ImportStatement;
2041 }
2042
2043 // In .proto files, top-level options and package statements are very
2044 // similar to import statements and should not be line-wrapped.
2045 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
2046 CurrentToken->isOneOf(K1: Keywords.kw_option, K2: Keywords.kw_package)) {
2047 next();
2048 if (CurrentToken && CurrentToken->is(Kind: tok::identifier)) {
2049 while (CurrentToken)
2050 next();
2051 return LT_ImportStatement;
2052 }
2053 }
2054
2055 bool KeywordVirtualFound = false;
2056 bool ImportStatement = false;
2057
2058 // import {...} from '...';
2059 if (Style.isJavaScript() && CurrentToken->is(II: Keywords.kw_import))
2060 ImportStatement = true;
2061
2062 while (CurrentToken) {
2063 if (CurrentToken->is(Kind: tok::kw_virtual))
2064 KeywordVirtualFound = true;
2065 if (Style.isJavaScript()) {
2066 // export {...} from '...';
2067 // An export followed by "from 'some string';" is a re-export from
2068 // another module identified by a URI and is treated as a
2069 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
2070 // Just "export {...};" or "export class ..." should not be treated as
2071 // an import in this sense.
2072 if (Line.First->is(Kind: tok::kw_export) &&
2073 CurrentToken->is(II: Keywords.kw_from) && CurrentToken->Next &&
2074 CurrentToken->Next->isStringLiteral()) {
2075 ImportStatement = true;
2076 }
2077 if (isClosureImportStatement(Tok: *CurrentToken))
2078 ImportStatement = true;
2079 }
2080 if (!consumeToken())
2081 return LT_Invalid;
2082 }
2083 if (const auto Type = Line.Type; Type == LT_AccessModifier ||
2084 Type == LT_RequiresExpression ||
2085 Type == LT_SimpleRequirement) {
2086 return Type;
2087 }
2088 if (KeywordVirtualFound)
2089 return LT_VirtualFunctionDecl;
2090 if (ImportStatement)
2091 return LT_ImportStatement;
2092
2093 if (Line.startsWith(Tokens: TT_ObjCMethodSpecifier)) {
2094 if (Contexts.back().FirstObjCSelectorName) {
2095 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
2096 Contexts.back().LongestObjCSelectorName;
2097 }
2098 return LT_ObjCMethodDecl;
2099 }
2100
2101 for (const auto &ctx : Contexts)
2102 if (ctx.ContextType == Context::StructArrayInitializer)
2103 return LT_ArrayOfStructInitializer;
2104
2105 return LT_Other;
2106 }
2107
2108private:
2109 bool isClosureImportStatement(const FormatToken &Tok) {
2110 // FIXME: Closure-library specific stuff should not be hard-coded but be
2111 // configurable.
2112 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(Kind: tok::period) &&
2113 Tok.Next->Next &&
2114 (Tok.Next->Next->TokenText == "module" ||
2115 Tok.Next->Next->TokenText == "provide" ||
2116 Tok.Next->Next->TokenText == "require" ||
2117 Tok.Next->Next->TokenText == "requireType" ||
2118 Tok.Next->Next->TokenText == "forwardDeclare") &&
2119 Tok.Next->Next->Next && Tok.Next->Next->Next->is(Kind: tok::l_paren);
2120 }
2121
2122 void resetTokenMetadata() {
2123 if (!CurrentToken)
2124 return;
2125
2126 // Reset token type in case we have already looked at it and then
2127 // recovered from an error (e.g. failure to find the matching >).
2128 if (!CurrentToken->isTypeFinalized() &&
2129 CurrentToken->isNoneOf(
2130 Ks: TT_LambdaLSquare, Ks: TT_LambdaLBrace, Ks: TT_AttributeMacro, Ks: TT_IfMacro,
2131 Ks: TT_ForEachMacro, Ks: TT_TypenameMacro, Ks: TT_FunctionLBrace,
2132 Ks: TT_ImplicitStringLiteral, Ks: TT_InlineASMBrace, Ks: TT_FatArrow,
2133 Ks: TT_LambdaArrow, Ks: TT_NamespaceMacro, Ks: TT_OverloadedOperator,
2134 Ks: TT_RegexLiteral, Ks: TT_TemplateString, Ks: TT_ObjCStringLiteral,
2135 Ks: TT_UntouchableMacroFunc, Ks: TT_StatementAttributeLikeMacro,
2136 Ks: TT_FunctionLikeOrFreestandingMacro, Ks: TT_ClassLBrace, Ks: TT_EnumLBrace,
2137 Ks: TT_RecordLBrace, Ks: TT_StructLBrace, Ks: TT_UnionLBrace, Ks: TT_RequiresClause,
2138 Ks: TT_RequiresClauseInARequiresExpression, Ks: TT_RequiresExpression,
2139 Ks: TT_RequiresExpressionLParen, Ks: TT_RequiresExpressionLBrace,
2140 Ks: TT_CompoundRequirementLBrace, Ks: TT_BracedListLBrace,
2141 Ks: TT_FunctionLikeMacro)) {
2142 CurrentToken->setType(TT_Unknown);
2143 }
2144 CurrentToken->Role.reset();
2145 CurrentToken->MatchingParen = nullptr;
2146 CurrentToken->FakeLParens.clear();
2147 CurrentToken->FakeRParens = 0;
2148 }
2149
2150 void next() {
2151 if (!CurrentToken)
2152 return;
2153
2154 CurrentToken->NestingLevel = Contexts.size() - 1;
2155 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
2156 modifyContext(Current: *CurrentToken);
2157 determineTokenType(Current&: *CurrentToken);
2158 CurrentToken = CurrentToken->Next;
2159
2160 resetTokenMetadata();
2161 }
2162
2163 /// A struct to hold information valid in a specific context, e.g.
2164 /// a pair of parenthesis.
2165 struct Context {
2166 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
2167 bool IsExpression)
2168 : ContextKind(ContextKind), BindingStrength(BindingStrength),
2169 IsExpression(IsExpression) {}
2170
2171 tok::TokenKind ContextKind;
2172 unsigned BindingStrength;
2173 bool IsExpression;
2174 unsigned LongestObjCSelectorName = 0;
2175 bool ColonIsForRangeExpr = false;
2176 bool ColonIsDictLiteral = false;
2177 bool ColonIsObjCMethodExpr = false;
2178 FormatToken *FirstObjCSelectorName = nullptr;
2179 FormatToken *FirstStartOfName = nullptr;
2180 bool CanBeExpression = true;
2181 bool CaretFound = false;
2182 bool InCpp11AttributeSpecifier = false;
2183 bool InCSharpAttributeSpecifier = false;
2184 bool InStaticAssertFirstArgument = false;
2185 bool VerilogAssignmentFound = false;
2186 // Whether the braces may mean concatenation instead of structure or array
2187 // literal.
2188 bool VerilogMayBeConcatenation = false;
2189 bool IsTableGenDAGArgList = false;
2190 bool IsTableGenBangOpe = false;
2191 bool IsTableGenCondOpe = false;
2192 enum {
2193 Unknown,
2194 // Like the part after `:` in a constructor.
2195 // Context(...) : IsExpression(IsExpression)
2196 CtorInitializer,
2197 // Like in the parentheses in a foreach.
2198 ForEachMacro,
2199 // Like the inheritance list in a class declaration.
2200 // class Input : public IO
2201 InheritanceList,
2202 // Like in the braced list.
2203 // int x[] = {};
2204 StructArrayInitializer,
2205 // Like in `static_cast<int>`.
2206 TemplateArgument,
2207 // C11 _Generic selection.
2208 C11GenericSelection,
2209 QtProperty,
2210 // Like in the outer parentheses in `ffnand ff1(.q());`.
2211 VerilogInstancePortList,
2212 } ContextType = Unknown;
2213 };
2214
2215 /// Puts a new \c Context onto the stack \c Contexts for the lifetime
2216 /// of each instance.
2217 struct ScopedContextCreator {
2218 AnnotatingParser &P;
2219
2220 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
2221 unsigned Increase)
2222 : P(P) {
2223 P.Contexts.push_back(Elt: Context(ContextKind,
2224 P.Contexts.back().BindingStrength + Increase,
2225 P.Contexts.back().IsExpression));
2226 }
2227
2228 ~ScopedContextCreator() {
2229 if (P.Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
2230 if (P.Contexts.back().ContextType == Context::StructArrayInitializer) {
2231 P.Contexts.pop_back();
2232 P.Contexts.back().ContextType = Context::StructArrayInitializer;
2233 return;
2234 }
2235 }
2236 P.Contexts.pop_back();
2237 }
2238 };
2239
2240 void modifyContext(const FormatToken &Current) {
2241 auto AssignmentStartsExpression = [&]() {
2242 if (Current.getPrecedence() != prec::Assignment)
2243 return false;
2244
2245 if (Line.First->isOneOf(K1: tok::kw_using, K2: tok::kw_return))
2246 return false;
2247 if (Line.First->is(Kind: tok::kw_template)) {
2248 assert(Current.Previous);
2249 if (Current.Previous->is(Kind: tok::kw_operator)) {
2250 // `template ... operator=` cannot be an expression.
2251 return false;
2252 }
2253
2254 // `template` keyword can start a variable template.
2255 const FormatToken *Tok = Line.First->getNextNonComment();
2256 assert(Tok); // Current token is on the same line.
2257 if (Tok->isNot(Kind: TT_TemplateOpener)) {
2258 // Explicit template instantiations do not have `<>`.
2259 return false;
2260 }
2261
2262 // This is the default value of a template parameter, determine if it's
2263 // type or non-type.
2264 if (Contexts.back().ContextKind == tok::less) {
2265 assert(Current.Previous->Previous);
2266 return Current.Previous->Previous->isNoneOf(Ks: tok::kw_typename,
2267 Ks: tok::kw_class);
2268 }
2269
2270 Tok = Tok->MatchingParen;
2271 if (!Tok)
2272 return false;
2273 Tok = Tok->getNextNonComment();
2274 if (!Tok)
2275 return false;
2276
2277 if (Tok->isOneOf(K1: tok::kw_class, K2: tok::kw_enum, Ks: tok::kw_struct,
2278 Ks: tok::kw_using)) {
2279 return false;
2280 }
2281
2282 return true;
2283 }
2284
2285 // Type aliases use `type X = ...;` in TypeScript and can be exported
2286 // using `export type ...`.
2287 if (Style.isJavaScript() &&
2288 (Line.startsWith(Tokens: Keywords.kw_type, Tokens: tok::identifier) ||
2289 Line.startsWith(Tokens: tok::kw_export, Tokens: Keywords.kw_type,
2290 Tokens: tok::identifier))) {
2291 return false;
2292 }
2293
2294 return !Current.Previous || Current.Previous->isNot(Kind: tok::kw_operator);
2295 };
2296
2297 if (AssignmentStartsExpression()) {
2298 Contexts.back().IsExpression = true;
2299 if (!Line.startsWith(Tokens: TT_UnaryOperator)) {
2300 for (FormatToken *Previous = Current.Previous;
2301 Previous && Previous->Previous &&
2302 Previous->Previous->isNoneOf(Ks: tok::comma, Ks: tok::semi);
2303 Previous = Previous->Previous) {
2304 if (Previous->isOneOf(K1: tok::r_square, K2: tok::r_paren, Ks: tok::greater)) {
2305 Previous = Previous->MatchingParen;
2306 if (!Previous)
2307 break;
2308 }
2309 if (Previous->opensScope())
2310 break;
2311 if (!Previous->isTypeFinalized() &&
2312 Previous->isOneOf(K1: TT_BinaryOperator, K2: TT_UnaryOperator) &&
2313 Previous->isPointerOrReference() && Previous->Previous &&
2314 Previous->Previous->isNot(Kind: tok::equal)) {
2315 Previous->setType(TT_PointerOrReference);
2316 }
2317 }
2318 }
2319 } else if (Current.is(Kind: tok::lessless) &&
2320 (!Current.Previous ||
2321 Current.Previous->isNot(Kind: tok::kw_operator))) {
2322 Contexts.back().IsExpression = true;
2323 } else if (Current.isOneOf(K1: tok::kw_return, K2: tok::kw_throw)) {
2324 Contexts.back().IsExpression = true;
2325 } else if (Current.is(TT: TT_TrailingReturnArrow)) {
2326 Contexts.back().IsExpression = false;
2327 } else if (Current.isOneOf(K1: TT_LambdaArrow, K2: Keywords.kw_assert)) {
2328 Contexts.back().IsExpression = Style.isJava();
2329 } else if (Current.Previous &&
2330 Current.Previous->is(TT: TT_CtorInitializerColon)) {
2331 Contexts.back().IsExpression = true;
2332 Contexts.back().ContextType = Context::CtorInitializer;
2333 } else if (Current.Previous && Current.Previous->is(TT: TT_InheritanceColon)) {
2334 Contexts.back().ContextType = Context::InheritanceList;
2335 } else if (Current.isOneOf(K1: tok::r_paren, K2: tok::greater, Ks: tok::comma)) {
2336 for (FormatToken *Previous = Current.Previous;
2337 Previous && Previous->isOneOf(K1: tok::star, K2: tok::amp);
2338 Previous = Previous->Previous) {
2339 Previous->setType(TT_PointerOrReference);
2340 }
2341 if (Line.MustBeDeclaration &&
2342 Contexts.front().ContextType != Context::CtorInitializer) {
2343 Contexts.back().IsExpression = false;
2344 }
2345 } else if (Current.is(Kind: tok::kw_new)) {
2346 Contexts.back().CanBeExpression = false;
2347 } else if (Current.is(Kind: tok::semi) ||
2348 (Current.is(Kind: tok::exclaim) && Current.Previous &&
2349 Current.Previous->isNot(Kind: tok::kw_operator))) {
2350 // This should be the condition or increment in a for-loop.
2351 // But not operator !() (can't use TT_OverloadedOperator here as its not
2352 // been annotated yet).
2353 Contexts.back().IsExpression = true;
2354 }
2355 }
2356
2357 static FormatToken *untilMatchingParen(FormatToken *Current) {
2358 // Used when `MatchingParen` is not yet established.
2359 int ParenLevel = 0;
2360 while (Current) {
2361 if (Current->is(Kind: tok::l_paren))
2362 ++ParenLevel;
2363 if (Current->is(Kind: tok::r_paren))
2364 --ParenLevel;
2365 if (ParenLevel < 1)
2366 break;
2367 Current = Current->Next;
2368 }
2369 return Current;
2370 }
2371
2372 static bool isDeductionGuide(FormatToken &Current) {
2373 // Look for a deduction guide template<T> A(...) -> A<...>;
2374 if (Current.Previous && Current.Previous->is(Kind: tok::r_paren) &&
2375 Current.startsSequence(K1: tok::arrow, Tokens: tok::identifier, Tokens: tok::less)) {
2376 // Find the TemplateCloser.
2377 FormatToken *TemplateCloser = Current.Next->Next;
2378 int NestingLevel = 0;
2379 while (TemplateCloser) {
2380 // Skip over an expressions in parens A<(3 < 2)>;
2381 if (TemplateCloser->is(Kind: tok::l_paren)) {
2382 // No Matching Paren yet so skip to matching paren
2383 TemplateCloser = untilMatchingParen(Current: TemplateCloser);
2384 if (!TemplateCloser)
2385 break;
2386 }
2387 if (TemplateCloser->is(Kind: tok::less))
2388 ++NestingLevel;
2389 if (TemplateCloser->is(Kind: tok::greater))
2390 --NestingLevel;
2391 if (NestingLevel < 1)
2392 break;
2393 TemplateCloser = TemplateCloser->Next;
2394 }
2395 // Assuming we have found the end of the template ensure its followed
2396 // with a semi-colon.
2397 if (TemplateCloser && TemplateCloser->Next &&
2398 TemplateCloser->Next->is(Kind: tok::semi) &&
2399 Current.Previous->MatchingParen) {
2400 // Determine if the identifier `A` prior to the A<..>; is the same as
2401 // prior to the A(..)
2402 FormatToken *LeadingIdentifier =
2403 Current.Previous->MatchingParen->Previous;
2404
2405 return LeadingIdentifier &&
2406 LeadingIdentifier->TokenText == Current.Next->TokenText;
2407 }
2408 }
2409 return false;
2410 }
2411
2412 void determineTokenType(FormatToken &Current) {
2413 if (Current.isNot(Kind: TT_Unknown)) {
2414 // The token type is already known.
2415 return;
2416 }
2417
2418 if ((Style.isJavaScript() || Style.isCSharp()) &&
2419 Current.is(Kind: tok::exclaim)) {
2420 if (Current.Previous) {
2421 bool IsIdentifier =
2422 Style.isJavaScript()
2423 ? Keywords.isJavaScriptIdentifier(
2424 Tok: *Current.Previous, /* AcceptIdentifierName= */ true)
2425 : Current.Previous->is(Kind: tok::identifier);
2426 if (IsIdentifier ||
2427 Current.Previous->isOneOf(
2428 K1: tok::kw_default, K2: tok::kw_namespace, Ks: tok::r_paren, Ks: tok::r_square,
2429 Ks: tok::r_brace, Ks: tok::kw_false, Ks: tok::kw_true, Ks: Keywords.kw_type,
2430 Ks: Keywords.kw_get, Ks: Keywords.kw_init, Ks: Keywords.kw_set) ||
2431 Current.Previous->Tok.isLiteral()) {
2432 Current.setType(TT_NonNullAssertion);
2433 return;
2434 }
2435 }
2436 if (Current.Next &&
2437 Current.Next->isOneOf(K1: TT_BinaryOperator, K2: Keywords.kw_as)) {
2438 Current.setType(TT_NonNullAssertion);
2439 return;
2440 }
2441 }
2442
2443 // Line.MightBeFunctionDecl can only be true after the parentheses of a
2444 // function declaration have been found. In this case, 'Current' is a
2445 // trailing token of this declaration and thus cannot be a name.
2446 if ((Style.isJavaScript() || Style.isJava()) &&
2447 Current.is(II: Keywords.kw_instanceof)) {
2448 Current.setType(TT_BinaryOperator);
2449 } else if (isStartOfName(Tok: Current) &&
2450 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
2451 Contexts.back().FirstStartOfName = &Current;
2452 Current.setType(TT_StartOfName);
2453 } else if (Current.is(Kind: tok::semi)) {
2454 // Reset FirstStartOfName after finding a semicolon so that a for loop
2455 // with multiple increment statements is not confused with a for loop
2456 // having multiple variable declarations.
2457 Contexts.back().FirstStartOfName = nullptr;
2458 } else if (Current.isOneOf(K1: tok::kw_auto, K2: tok::kw___auto_type)) {
2459 AutoFound = true;
2460 } else if (Current.is(Kind: tok::arrow) && Style.isJava()) {
2461 Current.setType(TT_LambdaArrow);
2462 } else if (Current.is(Kind: tok::arrow) && Style.isVerilog()) {
2463 // The implication operator.
2464 Current.setType(TT_BinaryOperator);
2465 } else if (Current.is(Kind: tok::arrow) && AutoFound &&
2466 Line.MightBeFunctionDecl && Current.NestingLevel == 0 &&
2467 Current.Previous->isNoneOf(Ks: tok::kw_operator, Ks: tok::identifier)) {
2468 // not auto operator->() -> xxx;
2469 Current.setType(TT_TrailingReturnArrow);
2470 } else if (Current.is(Kind: tok::arrow) && Current.Previous &&
2471 Current.Previous->is(Kind: tok::r_brace) &&
2472 Current.Previous->is(BBK: BK_Block)) {
2473 // Concept implicit conversion constraint needs to be treated like
2474 // a trailing return type ... } -> <type>.
2475 Current.setType(TT_TrailingReturnArrow);
2476 } else if (isDeductionGuide(Current)) {
2477 // Deduction guides trailing arrow " A(...) -> A<T>;".
2478 Current.setType(TT_TrailingReturnArrow);
2479 } else if (Current.isPointerOrReference()) {
2480 Current.setType(determineStarAmpUsage(
2481 Tok: Current,
2482 IsExpression: (Contexts.back().CanBeExpression && Contexts.back().IsExpression) ||
2483 Contexts.back().InStaticAssertFirstArgument,
2484 InTemplateArgument: Contexts.back().ContextType == Context::TemplateArgument));
2485 } else if (Current.isOneOf(K1: tok::minus, K2: tok::plus, Ks: tok::caret) ||
2486 (Style.isVerilog() && Current.is(Kind: tok::pipe))) {
2487 Current.setType(determinePlusMinusCaretUsage(Tok: Current));
2488 if (Current.is(TT: TT_UnaryOperator) && Current.is(Kind: tok::caret))
2489 Contexts.back().CaretFound = true;
2490 } else if (Current.isOneOf(K1: tok::minusminus, K2: tok::plusplus)) {
2491 Current.setType(determineIncrementUsage(Tok: Current));
2492 } else if (Current.isOneOf(K1: tok::exclaim, K2: tok::tilde)) {
2493 Current.setType(TT_UnaryOperator);
2494 } else if (Current.is(Kind: tok::question)) {
2495 if (Style.isJavaScript() && Line.MustBeDeclaration &&
2496 !Contexts.back().IsExpression) {
2497 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
2498 // on the interface, not a ternary expression.
2499 Current.setType(TT_JsTypeOptionalQuestion);
2500 } else if (Style.isTableGen()) {
2501 // In TableGen, '?' is just an identifier like token.
2502 Current.setType(TT_Unknown);
2503 } else {
2504 Current.setType(TT_ConditionalExpr);
2505 if (IsCpp)
2506 Contexts.back().IsExpression = true;
2507 }
2508 } else if (Current.isBinaryOperator() &&
2509 (!Current.Previous || Current.Previous->isNot(Kind: tok::l_square)) &&
2510 (Current.isNot(Kind: tok::greater) && !Style.isTextProto())) {
2511 if (Style.isVerilog()) {
2512 if (Current.is(Kind: tok::lessequal) && Contexts.size() == 1 &&
2513 !Contexts.back().VerilogAssignmentFound) {
2514 // In Verilog `<=` is assignment if in its own statement. It is a
2515 // statement instead of an expression, that is it can not be chained.
2516 Current.ForcedPrecedence = prec::Assignment;
2517 Current.setFinalizedType(TT_BinaryOperator);
2518 }
2519 if (Current.getPrecedence() == prec::Assignment)
2520 Contexts.back().VerilogAssignmentFound = true;
2521 }
2522 Current.setType(TT_BinaryOperator);
2523 } else if (Current.is(Kind: tok::comment)) {
2524 if (Current.TokenText.starts_with(Prefix: "/*")) {
2525 if (Current.TokenText.ends_with(Suffix: "*/")) {
2526 Current.setType(TT_BlockComment);
2527 } else {
2528 // The lexer has for some reason determined a comment here. But we
2529 // cannot really handle it, if it isn't properly terminated.
2530 Current.Tok.setKind(tok::unknown);
2531 }
2532 } else {
2533 Current.setType(TT_LineComment);
2534 }
2535 } else if (Current.is(Kind: tok::string_literal)) {
2536 if (Style.isVerilog() && Contexts.back().VerilogMayBeConcatenation &&
2537 Current.getPreviousNonComment() &&
2538 Current.getPreviousNonComment()->isOneOf(K1: tok::comma, K2: tok::l_brace) &&
2539 Current.getNextNonComment() &&
2540 Current.getNextNonComment()->isOneOf(K1: tok::comma, K2: tok::r_brace)) {
2541 Current.setType(TT_StringInConcatenation);
2542 }
2543 } else if (Current.is(Kind: tok::l_paren)) {
2544 if (lParenStartsCppCast(Tok: Current))
2545 Current.setType(TT_CppCastLParen);
2546 } else if (Current.is(Kind: tok::r_paren)) {
2547 if (rParenEndsCast(Tok: Current))
2548 Current.setType(TT_CastRParen);
2549 if (Current.MatchingParen && Current.MatchingParen->is(TT: TT_InlineASMParen))
2550 Current.setType(TT_InlineASMParen);
2551 if (Current.MatchingParen && Current.Next &&
2552 !Current.Next->isBinaryOperator() &&
2553 Current.Next->isNoneOf(
2554 Ks: tok::semi, Ks: tok::colon, Ks: tok::l_brace, Ks: tok::l_paren, Ks: tok::comma,
2555 Ks: tok::period, Ks: tok::arrow, Ks: tok::coloncolon, Ks: tok::kw_noexcept)) {
2556 if (FormatToken *AfterParen = Current.MatchingParen->Next;
2557 AfterParen && AfterParen->isNot(Kind: tok::caret)) {
2558 // Make sure this isn't the return type of an Obj-C block declaration.
2559 if (FormatToken *BeforeParen = Current.MatchingParen->Previous;
2560 BeforeParen && BeforeParen->is(Kind: tok::identifier) &&
2561 BeforeParen->isNot(Kind: TT_TypenameMacro) &&
2562 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
2563 (!BeforeParen->Previous ||
2564 BeforeParen->Previous->ClosesTemplateDeclaration ||
2565 BeforeParen->Previous->ClosesRequiresClause)) {
2566 Current.setType(TT_FunctionAnnotationRParen);
2567 }
2568 }
2569 }
2570 } else if (Current.is(Kind: tok::at) && Current.Next && !Style.isJavaScript() &&
2571 !Style.isJava()) {
2572 // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
2573 // marks declarations and properties that need special formatting.
2574 switch (Current.Next->Tok.getObjCKeywordID()) {
2575 case tok::objc_interface:
2576 case tok::objc_implementation:
2577 case tok::objc_protocol:
2578 Current.setType(TT_ObjCDecl);
2579 break;
2580 case tok::objc_property:
2581 Current.setType(TT_ObjCProperty);
2582 break;
2583 default:
2584 break;
2585 }
2586 } else if (Current.is(Kind: tok::period)) {
2587 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
2588 if (PreviousNoComment &&
2589 PreviousNoComment->isOneOf(K1: tok::comma, K2: tok::l_brace)) {
2590 Current.setType(TT_DesignatedInitializerPeriod);
2591 } else if (Style.isJava() && Current.Previous &&
2592 Current.Previous->isOneOf(K1: TT_JavaAnnotation,
2593 K2: TT_LeadingJavaAnnotation)) {
2594 Current.setType(Current.Previous->getType());
2595 }
2596 } else if (canBeObjCSelectorComponent(Tok: Current) &&
2597 // FIXME(bug 36976): ObjC return types shouldn't use
2598 // TT_CastRParen.
2599 Current.Previous && Current.Previous->is(TT: TT_CastRParen) &&
2600 Current.Previous->MatchingParen &&
2601 Current.Previous->MatchingParen->Previous &&
2602 Current.Previous->MatchingParen->Previous->is(
2603 TT: TT_ObjCMethodSpecifier)) {
2604 // This is the first part of an Objective-C selector name. (If there's no
2605 // colon after this, this is the only place which annotates the identifier
2606 // as a selector.)
2607 Current.setType(TT_SelectorName);
2608 } else if (Current.isOneOf(K1: tok::identifier, K2: tok::kw_const, Ks: tok::kw_noexcept,
2609 Ks: tok::kw_requires) &&
2610 Current.Previous &&
2611 Current.Previous->isNoneOf(Ks: tok::equal, Ks: tok::at,
2612 Ks: TT_CtorInitializerComma,
2613 Ks: TT_CtorInitializerColon) &&
2614 Line.MightBeFunctionDecl && Contexts.size() == 1) {
2615 // Line.MightBeFunctionDecl can only be true after the parentheses of a
2616 // function declaration have been found.
2617 Current.setType(TT_TrailingAnnotation);
2618 } else if ((Style.isJava() || Style.isJavaScript()) && Current.Previous) {
2619 if (Current.Previous->is(Kind: tok::at) &&
2620 Current.isNot(Kind: Keywords.kw_interface)) {
2621 const FormatToken &AtToken = *Current.Previous;
2622 const FormatToken *Previous = AtToken.getPreviousNonComment();
2623 if (!Previous || Previous->is(TT: TT_LeadingJavaAnnotation))
2624 Current.setType(TT_LeadingJavaAnnotation);
2625 else
2626 Current.setType(TT_JavaAnnotation);
2627 } else if (Current.Previous->is(Kind: tok::period) &&
2628 Current.Previous->isOneOf(K1: TT_JavaAnnotation,
2629 K2: TT_LeadingJavaAnnotation)) {
2630 Current.setType(Current.Previous->getType());
2631 }
2632 }
2633 }
2634
2635 /// Take a guess at whether \p Tok starts a name of a function or
2636 /// variable declaration.
2637 ///
2638 /// This is a heuristic based on whether \p Tok is an identifier following
2639 /// something that is likely a type.
2640 bool isStartOfName(const FormatToken &Tok) {
2641 // Handled in ExpressionParser for Verilog.
2642 if (Style.isVerilog())
2643 return false;
2644
2645 if (!Tok.Previous || Tok.isNot(Kind: tok::identifier) || Tok.is(TT: TT_ClassHeadName))
2646 return false;
2647
2648 if (Tok.endsSequence(K1: Keywords.kw_final, Tokens: TT_ClassHeadName))
2649 return false;
2650
2651 if ((Style.isJavaScript() || Style.isJava()) && Tok.is(II: Keywords.kw_extends))
2652 return false;
2653
2654 if (const auto *NextNonComment = Tok.getNextNonComment();
2655 (!NextNonComment && !Line.InMacroBody) ||
2656 (NextNonComment &&
2657 (NextNonComment->isPointerOrReference() ||
2658 NextNonComment->isOneOf(K1: TT_ClassHeadName, K2: tok::string_literal) ||
2659 (Line.InPragmaDirective && NextNonComment->is(Kind: tok::identifier))))) {
2660 return false;
2661 }
2662
2663 if (Tok.Previous->isOneOf(K1: TT_LeadingJavaAnnotation, K2: Keywords.kw_instanceof,
2664 Ks: Keywords.kw_as)) {
2665 return false;
2666 }
2667 if (Style.isJavaScript() && Tok.Previous->is(II: Keywords.kw_in))
2668 return false;
2669
2670 // Skip "const" as it does not have an influence on whether this is a name.
2671 FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
2672
2673 // For javascript const can be like "let" or "var"
2674 if (!Style.isJavaScript())
2675 while (PreviousNotConst && PreviousNotConst->is(Kind: tok::kw_const))
2676 PreviousNotConst = PreviousNotConst->getPreviousNonComment();
2677
2678 if (!PreviousNotConst)
2679 return false;
2680
2681 if (PreviousNotConst->ClosesRequiresClause)
2682 return false;
2683
2684 if (Style.isTableGen()) {
2685 // keywords such as let and def* defines names.
2686 if (Keywords.isTableGenDefinition(Tok: *PreviousNotConst))
2687 return true;
2688 // Otherwise C++ style declarations is available only inside the brace.
2689 if (Contexts.back().ContextKind != tok::l_brace)
2690 return false;
2691 }
2692
2693 bool IsPPKeyword = PreviousNotConst->is(Kind: tok::identifier) &&
2694 PreviousNotConst->Previous &&
2695 PreviousNotConst->Previous->is(Kind: tok::hash);
2696
2697 if (PreviousNotConst->is(TT: TT_TemplateCloser)) {
2698 return PreviousNotConst && PreviousNotConst->MatchingParen &&
2699 PreviousNotConst->MatchingParen->Previous &&
2700 PreviousNotConst->MatchingParen->Previous->isNoneOf(
2701 Ks: tok::period, Ks: tok::kw_template);
2702 }
2703
2704 if ((PreviousNotConst->is(Kind: tok::r_paren) &&
2705 PreviousNotConst->is(TT: TT_TypeDeclarationParen)) ||
2706 PreviousNotConst->is(TT: TT_AttributeRParen)) {
2707 return true;
2708 }
2709
2710 // If is a preprocess keyword like #define.
2711 if (IsPPKeyword)
2712 return false;
2713
2714 // int a or auto a.
2715 if (PreviousNotConst->isOneOf(K1: tok::identifier, K2: tok::kw_auto) &&
2716 !PreviousNotConst->endsSequence(K1: Keywords.kw_import, Tokens: tok::kw_export) &&
2717 PreviousNotConst->isNot(Kind: TT_StatementAttributeLikeMacro)) {
2718 return true;
2719 }
2720
2721 // *a or &a or &&a.
2722 if (PreviousNotConst->is(TT: TT_PointerOrReference) ||
2723 PreviousNotConst->endsSequence(K1: tok::coloncolon,
2724 Tokens: TT_PointerOrReference)) {
2725 return true;
2726 }
2727
2728 // MyClass a;
2729 if (PreviousNotConst->isTypeName(LangOpts))
2730 return true;
2731
2732 // type[] a in Java
2733 if (Style.isJava() && PreviousNotConst->is(Kind: tok::r_square))
2734 return true;
2735
2736 // const a = in JavaScript.
2737 return Style.isJavaScript() && PreviousNotConst->is(Kind: tok::kw_const);
2738 }
2739
2740 /// Determine whether '(' is starting a C++ cast.
2741 bool lParenStartsCppCast(const FormatToken &Tok) {
2742 // C-style casts are only used in C++.
2743 if (!IsCpp)
2744 return false;
2745
2746 FormatToken *LeftOfParens = Tok.getPreviousNonComment();
2747 if (LeftOfParens && LeftOfParens->is(TT: TT_TemplateCloser) &&
2748 LeftOfParens->MatchingParen) {
2749 auto *Prev = LeftOfParens->MatchingParen->getPreviousNonComment();
2750 if (Prev &&
2751 Prev->isOneOf(K1: tok::kw_const_cast, K2: tok::kw_dynamic_cast,
2752 Ks: tok::kw_reinterpret_cast, Ks: tok::kw_static_cast)) {
2753 // FIXME: Maybe we should handle identifiers ending with "_cast",
2754 // e.g. any_cast?
2755 return true;
2756 }
2757 }
2758 return false;
2759 }
2760
2761 /// Determine whether ')' is ending a cast.
2762 bool rParenEndsCast(const FormatToken &Tok) {
2763 assert(Tok.is(tok::r_paren));
2764
2765 if (!Tok.MatchingParen || !Tok.Previous)
2766 return false;
2767
2768 // C-style casts are only used in C++, C# and Java.
2769 if (!IsCpp && !Style.isCSharp() && !Style.isJava())
2770 return false;
2771
2772 const auto *LParen = Tok.MatchingParen;
2773 const auto *BeforeRParen = Tok.Previous;
2774 const auto *AfterRParen = Tok.Next;
2775
2776 // Empty parens aren't casts and there are no casts at the end of the line.
2777 if (BeforeRParen == LParen || !AfterRParen)
2778 return false;
2779
2780 if (LParen->isOneOf(K1: TT_OverloadedOperatorLParen, K2: TT_FunctionTypeLParen))
2781 return false;
2782
2783 auto *LeftOfParens = LParen->getPreviousNonComment();
2784 if (LeftOfParens) {
2785 // If there is a closing parenthesis left of the current
2786 // parentheses, look past it as these might be chained casts.
2787 if (LeftOfParens->is(Kind: tok::r_paren) &&
2788 LeftOfParens->isNot(Kind: TT_CastRParen)) {
2789 if (!LeftOfParens->MatchingParen ||
2790 !LeftOfParens->MatchingParen->Previous) {
2791 return false;
2792 }
2793 LeftOfParens = LeftOfParens->MatchingParen->Previous;
2794 }
2795
2796 if (LeftOfParens->is(Kind: tok::r_square)) {
2797 // delete[] (void *)ptr;
2798 auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
2799 if (Tok->isNot(Kind: tok::r_square))
2800 return nullptr;
2801
2802 Tok = Tok->getPreviousNonComment();
2803 if (!Tok || Tok->isNot(Kind: tok::l_square))
2804 return nullptr;
2805
2806 Tok = Tok->getPreviousNonComment();
2807 if (!Tok || Tok->isNot(Kind: tok::kw_delete))
2808 return nullptr;
2809 return Tok;
2810 };
2811 if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens))
2812 LeftOfParens = MaybeDelete;
2813 }
2814
2815 // The Condition directly below this one will see the operator arguments
2816 // as a (void *foo) cast.
2817 // void operator delete(void *foo) ATTRIB;
2818 if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous &&
2819 LeftOfParens->Previous->is(Kind: tok::kw_operator)) {
2820 return false;
2821 }
2822
2823 // If there is an identifier (or with a few exceptions a keyword) right
2824 // before the parentheses, this is unlikely to be a cast.
2825 if (LeftOfParens->Tok.getIdentifierInfo() &&
2826 LeftOfParens->isNoneOf(Ks: TT_ObjCForIn, Ks: tok::kw_return, Ks: tok::kw_case,
2827 Ks: tok::kw_delete, Ks: tok::kw_throw)) {
2828 return false;
2829 }
2830
2831 // Certain other tokens right before the parentheses are also signals that
2832 // this cannot be a cast.
2833 if (LeftOfParens->isOneOf(K1: tok::at, K2: tok::r_square, Ks: TT_OverloadedOperator,
2834 Ks: TT_TemplateCloser, Ks: tok::ellipsis)) {
2835 return false;
2836 }
2837 }
2838
2839 if (AfterRParen->is(Kind: tok::question) ||
2840 (AfterRParen->is(Kind: tok::ampamp) && !BeforeRParen->isTypeName(LangOpts))) {
2841 return false;
2842 }
2843
2844 // `foreach((A a, B b) in someList)` should not be seen as a cast.
2845 if (AfterRParen->is(II: Keywords.kw_in) && Style.isCSharp())
2846 return false;
2847
2848 // Functions which end with decorations like volatile, noexcept are unlikely
2849 // to be casts.
2850 if (AfterRParen->isOneOf(K1: tok::kw_noexcept, K2: tok::kw_volatile, Ks: tok::kw_const,
2851 Ks: tok::kw_requires, Ks: tok::kw_throw, Ks: tok::arrow,
2852 Ks: Keywords.kw_override, Ks: Keywords.kw_final) ||
2853 isCppAttribute(IsCpp, Tok: *AfterRParen)) {
2854 return false;
2855 }
2856
2857 // As Java has no function types, a "(" after the ")" likely means that this
2858 // is a cast.
2859 if (Style.isJava() && AfterRParen->is(Kind: tok::l_paren))
2860 return true;
2861
2862 // If a (non-string) literal follows, this is likely a cast.
2863 if (AfterRParen->isOneOf(K1: tok::kw_sizeof, K2: tok::kw_alignof) ||
2864 (AfterRParen->Tok.isLiteral() &&
2865 AfterRParen->isNot(Kind: tok::string_literal))) {
2866 return true;
2867 }
2868
2869 auto IsNonVariableTemplate = [](const FormatToken &Tok) {
2870 if (Tok.isNot(Kind: TT_TemplateCloser))
2871 return false;
2872 const auto *Less = Tok.MatchingParen;
2873 if (!Less)
2874 return false;
2875 const auto *BeforeLess = Less->getPreviousNonComment();
2876 return BeforeLess && BeforeLess->isNot(Kind: TT_VariableTemplate);
2877 };
2878
2879 // Heuristically try to determine whether the parentheses contain a type.
2880 auto IsQualifiedPointerOrReference = [](const FormatToken *T,
2881 const LangOptions &LangOpts) {
2882 // This is used to handle cases such as x = (foo *const)&y;
2883 assert(!T->isTypeName(LangOpts) && "Should have already been checked");
2884 // Strip trailing qualifiers such as const or volatile when checking
2885 // whether the parens could be a cast to a pointer/reference type.
2886 while (T) {
2887 if (T->is(TT: TT_AttributeRParen)) {
2888 // Handle `x = (foo *__attribute__((foo)))&v;`:
2889 assert(T->is(tok::r_paren));
2890 assert(T->MatchingParen);
2891 assert(T->MatchingParen->is(tok::l_paren));
2892 assert(T->MatchingParen->is(TT_AttributeLParen));
2893 if (const auto *Tok = T->MatchingParen->Previous;
2894 Tok && Tok->isAttribute()) {
2895 T = Tok->Previous;
2896 continue;
2897 }
2898 } else if (T->is(TT: TT_AttributeRSquare)) {
2899 // Handle `x = (foo *[[clang::foo]])&v;`:
2900 if (T->MatchingParen && T->MatchingParen->Previous) {
2901 T = T->MatchingParen->Previous;
2902 continue;
2903 }
2904 } else if (T->canBePointerOrReferenceQualifier()) {
2905 T = T->Previous;
2906 continue;
2907 }
2908 break;
2909 }
2910 return T && T->is(TT: TT_PointerOrReference);
2911 };
2912
2913 bool ParensAreType = IsNonVariableTemplate(*BeforeRParen) ||
2914 BeforeRParen->is(TT: TT_TypeDeclarationParen) ||
2915 BeforeRParen->isTypeName(LangOpts) ||
2916 IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
2917 bool ParensCouldEndDecl =
2918 AfterRParen->isOneOf(K1: tok::equal, K2: tok::semi, Ks: tok::l_brace, Ks: tok::greater);
2919 if (ParensAreType && !ParensCouldEndDecl)
2920 return true;
2921
2922 // At this point, we heuristically assume that there are no casts at the
2923 // start of the line. We assume that we have found most cases where there
2924 // are by the logic above, e.g. "(void)x;".
2925 if (!LeftOfParens)
2926 return false;
2927
2928 // Certain token types inside the parentheses mean that this can't be a
2929 // cast.
2930 for (const auto *Token = LParen->Next; Token != &Tok; Token = Token->Next)
2931 if (Token->is(TT: TT_BinaryOperator))
2932 return false;
2933
2934 // If the following token is an identifier or 'this', this is a cast. All
2935 // cases where this can be something else are handled above.
2936 if (AfterRParen->isOneOf(K1: tok::identifier, K2: tok::kw_this))
2937 return true;
2938
2939 // Look for a cast `( x ) (`, where x may be a qualified identifier.
2940 if (AfterRParen->is(Kind: tok::l_paren)) {
2941 for (const auto *Prev = BeforeRParen; Prev->is(Kind: tok::identifier);) {
2942 Prev = Prev->Previous;
2943 if (Prev->is(Kind: tok::coloncolon))
2944 Prev = Prev->Previous;
2945 if (Prev == LParen)
2946 return true;
2947 }
2948 }
2949
2950 if (!AfterRParen->Next)
2951 return false;
2952
2953 // A pair of parentheses before an l_brace in C starts a compound literal
2954 // and is not a cast.
2955 if (Style.Language != FormatStyle::LK_C && AfterRParen->is(Kind: tok::l_brace) &&
2956 AfterRParen->getBlockKind() == BK_BracedInit) {
2957 return true;
2958 }
2959
2960 // If the next token after the parenthesis is a unary operator, assume
2961 // that this is cast, unless there are unexpected tokens inside the
2962 // parenthesis.
2963 const bool NextIsAmpOrStar = AfterRParen->isOneOf(K1: tok::amp, K2: tok::star);
2964 if (!(AfterRParen->isUnaryOperator() || NextIsAmpOrStar) ||
2965 AfterRParen->is(Kind: tok::plus) ||
2966 AfterRParen->Next->isNoneOf(Ks: tok::identifier, Ks: tok::numeric_constant)) {
2967 return false;
2968 }
2969
2970 if (NextIsAmpOrStar &&
2971 (AfterRParen->Next->is(Kind: tok::numeric_constant) || Line.InPPDirective)) {
2972 return false;
2973 }
2974
2975 if (Line.InPPDirective && AfterRParen->is(Kind: tok::minus))
2976 return false;
2977
2978 const auto *Prev = BeforeRParen;
2979
2980 // Look for a function pointer type, e.g. `(*)()`.
2981 if (Prev->is(Kind: tok::r_paren)) {
2982 if (Prev->is(TT: TT_CastRParen))
2983 return false;
2984 Prev = Prev->MatchingParen;
2985 if (!Prev)
2986 return false;
2987 Prev = Prev->Previous;
2988 if (!Prev || Prev->isNot(Kind: tok::r_paren))
2989 return false;
2990 Prev = Prev->MatchingParen;
2991 return Prev && Prev->is(TT: TT_FunctionTypeLParen);
2992 }
2993
2994 // Search for unexpected tokens.
2995 for (Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous)
2996 if (Prev->isNoneOf(Ks: tok::kw_const, Ks: tok::identifier, Ks: tok::coloncolon))
2997 return false;
2998
2999 return true;
3000 }
3001
3002 /// Returns true if the token is used as a unary operator.
3003 bool determineUnaryOperatorByUsage(const FormatToken &Tok) {
3004 const FormatToken *PrevToken = Tok.getPreviousNonComment();
3005 if (!PrevToken)
3006 return true;
3007
3008 // These keywords are deliberately not included here because they may
3009 // precede only one of unary star/amp and plus/minus but not both. They are
3010 // either included in determineStarAmpUsage or determinePlusMinusCaretUsage.
3011 //
3012 // @ - It may be followed by a unary `-` in Objective-C literals. We don't
3013 // know how they can be followed by a star or amp.
3014 if (PrevToken->isOneOf(
3015 K1: TT_ConditionalExpr, K2: tok::l_paren, Ks: tok::comma, Ks: tok::colon, Ks: tok::semi,
3016 Ks: tok::equal, Ks: tok::question, Ks: tok::l_square, Ks: tok::l_brace,
3017 Ks: tok::kw_case, Ks: tok::kw_co_await, Ks: tok::kw_co_return, Ks: tok::kw_co_yield,
3018 Ks: tok::kw_delete, Ks: tok::kw_return, Ks: tok::kw_throw)) {
3019 return true;
3020 }
3021
3022 // We put sizeof here instead of only in determineStarAmpUsage. In the cases
3023 // where the unary `+` operator is overloaded, it is reasonable to write
3024 // things like `sizeof +x`. Like commit 446d6ec996c6c3.
3025 if (PrevToken->is(Kind: tok::kw_sizeof))
3026 return true;
3027
3028 // A sequence of leading unary operators.
3029 if (PrevToken->isOneOf(K1: TT_CastRParen, K2: TT_UnaryOperator))
3030 return true;
3031
3032 // There can't be two consecutive binary operators.
3033 if (PrevToken->is(TT: TT_BinaryOperator))
3034 return true;
3035
3036 return false;
3037 }
3038
3039 /// Return the type of the given token assuming it is * or &.
3040 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
3041 bool InTemplateArgument) {
3042 if (Style.isJavaScript())
3043 return TT_BinaryOperator;
3044
3045 // && in C# must be a binary operator.
3046 if (Style.isCSharp() && Tok.is(Kind: tok::ampamp))
3047 return TT_BinaryOperator;
3048
3049 if (Style.isVerilog()) {
3050 // In Verilog, `*` can only be a binary operator. `&` can be either unary
3051 // or binary. `*` also includes `*>` in module path declarations in
3052 // specify blocks because merged tokens take the type of the first one by
3053 // default.
3054 if (Tok.is(Kind: tok::star))
3055 return TT_BinaryOperator;
3056 return determineUnaryOperatorByUsage(Tok) ? TT_UnaryOperator
3057 : TT_BinaryOperator;
3058 }
3059
3060 const FormatToken *PrevToken = Tok.getPreviousNonComment();
3061 if (!PrevToken)
3062 return TT_UnaryOperator;
3063 if (PrevToken->isTypeName(LangOpts))
3064 return TT_PointerOrReference;
3065 if (PrevToken->isPlacementOperator() && Tok.is(Kind: tok::ampamp))
3066 return TT_BinaryOperator;
3067
3068 auto *NextToken = Tok.getNextNonComment();
3069 if (!NextToken)
3070 return TT_PointerOrReference;
3071 if (NextToken->is(Kind: tok::greater))
3072 return TT_PointerOrReference;
3073
3074 if (InTemplateArgument && NextToken->is(Kind: tok::kw_noexcept))
3075 return TT_BinaryOperator;
3076
3077 if (NextToken->isOneOf(K1: tok::arrow, K2: tok::equal, Ks: tok::comma, Ks: tok::r_paren,
3078 Ks: tok::semi, Ks: TT_RequiresClause) ||
3079 (NextToken->is(Kind: tok::kw_noexcept) && !IsExpression) ||
3080 NextToken->canBePointerOrReferenceQualifier() ||
3081 (NextToken->is(Kind: tok::l_brace) && !NextToken->getNextNonComment())) {
3082 return TT_PointerOrReference;
3083 }
3084
3085 if (PrevToken->is(Kind: tok::coloncolon))
3086 return TT_PointerOrReference;
3087
3088 if (PrevToken->is(Kind: tok::r_paren) && PrevToken->is(TT: TT_TypeDeclarationParen))
3089 return TT_PointerOrReference;
3090
3091 if (determineUnaryOperatorByUsage(Tok))
3092 return TT_UnaryOperator;
3093
3094 if (NextToken->is(Kind: tok::l_square) && NextToken->isNot(Kind: TT_LambdaLSquare))
3095 return TT_PointerOrReference;
3096 if (NextToken->is(Kind: tok::kw_operator) && !IsExpression)
3097 return TT_PointerOrReference;
3098
3099 // After right braces, star tokens are likely to be pointers to struct,
3100 // union, or class.
3101 // struct {} *ptr;
3102 // This by itself is not sufficient to distinguish from multiplication
3103 // following a brace-initialized expression, as in:
3104 // int i = int{42} * 2;
3105 // In the struct case, the part of the struct declaration until the `{` and
3106 // the `}` are put on separate unwrapped lines; in the brace-initialized
3107 // case, the matching `{` is on the same unwrapped line, so check for the
3108 // presence of the matching brace to distinguish between those.
3109 if (PrevToken->is(Kind: tok::r_brace) && Tok.is(Kind: tok::star) &&
3110 !PrevToken->MatchingParen) {
3111 return TT_PointerOrReference;
3112 }
3113
3114 if (PrevToken->endsSequence(K1: tok::r_square, Tokens: tok::l_square, Tokens: tok::kw_delete))
3115 return TT_UnaryOperator;
3116
3117 if (PrevToken->Tok.isLiteral() ||
3118 PrevToken->isOneOf(K1: tok::r_paren, K2: tok::r_square, Ks: tok::kw_true,
3119 Ks: tok::kw_false, Ks: tok::r_brace)) {
3120 return TT_BinaryOperator;
3121 }
3122
3123 const FormatToken *NextNonParen = NextToken;
3124 while (NextNonParen && NextNonParen->is(Kind: tok::l_paren))
3125 NextNonParen = NextNonParen->getNextNonComment();
3126 if (NextNonParen && (NextNonParen->Tok.isLiteral() ||
3127 NextNonParen->isOneOf(K1: tok::kw_true, K2: tok::kw_false) ||
3128 NextNonParen->isUnaryOperator())) {
3129 return TT_BinaryOperator;
3130 }
3131
3132 // If we know we're in a template argument, there are no named declarations.
3133 // Thus, having an identifier on the right-hand side indicates a binary
3134 // operator.
3135 if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
3136 return TT_BinaryOperator;
3137
3138 // "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
3139 // unary "&".
3140 if (Tok.is(Kind: tok::ampamp) &&
3141 NextToken->isOneOf(K1: tok::l_paren, K2: tok::star, Ks: tok::amp)) {
3142 return TT_BinaryOperator;
3143 }
3144
3145 // This catches some cases where evaluation order is used as control flow:
3146 // aaa && aaa->f();
3147 // Or expressions like:
3148 // width * height * length
3149 if (NextToken->Tok.isAnyIdentifier()) {
3150 auto *NextNextToken = NextToken->getNextNonComment();
3151 if (NextNextToken) {
3152 if (NextNextToken->is(Kind: tok::arrow))
3153 return TT_BinaryOperator;
3154 if (NextNextToken->isPointerOrReference() &&
3155 !NextToken->isObjCLifetimeQualifier(Style)) {
3156 NextNextToken->setFinalizedType(TT_BinaryOperator);
3157 return TT_BinaryOperator;
3158 }
3159 }
3160 }
3161
3162 // It is very unlikely that we are going to find a pointer or reference type
3163 // definition on the RHS of an assignment.
3164 if (IsExpression && !Contexts.back().CaretFound &&
3165 Line.getFirstNonComment()->isNot(
3166 Kind: TT_RequiresClauseInARequiresExpression)) {
3167 return TT_BinaryOperator;
3168 }
3169
3170 // Opeartors at class scope are likely pointer or reference members.
3171 if (!Scopes.empty() && Scopes.back() == ST_Class)
3172 return TT_PointerOrReference;
3173
3174 // Tokens that indicate member access or chained operator& use.
3175 auto IsChainedOperatorAmpOrMember = [](const FormatToken *token) {
3176 return !token || token->isOneOf(K1: tok::amp, K2: tok::period, Ks: tok::arrow,
3177 Ks: tok::arrowstar, Ks: tok::periodstar);
3178 };
3179
3180 // It's more likely that & represents operator& than an uninitialized
3181 // reference.
3182 if (Tok.is(Kind: tok::amp) && PrevToken->Tok.isAnyIdentifier() &&
3183 IsChainedOperatorAmpOrMember(PrevToken->getPreviousNonComment()) &&
3184 NextToken && NextToken->Tok.isAnyIdentifier()) {
3185 if (auto NextNext = NextToken->getNextNonComment();
3186 NextNext &&
3187 (IsChainedOperatorAmpOrMember(NextNext) || NextNext->is(Kind: tok::semi))) {
3188 return TT_BinaryOperator;
3189 }
3190 }
3191
3192 if (Line.Type == LT_SimpleRequirement ||
3193 (!Scopes.empty() && Scopes.back() == ST_CompoundRequirement)) {
3194 return TT_BinaryOperator;
3195 }
3196
3197 return TT_PointerOrReference;
3198 }
3199
3200 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
3201 if (determineUnaryOperatorByUsage(Tok))
3202 return TT_UnaryOperator;
3203
3204 const FormatToken *PrevToken = Tok.getPreviousNonComment();
3205 if (!PrevToken)
3206 return TT_UnaryOperator;
3207
3208 if (PrevToken->is(Kind: tok::at))
3209 return TT_UnaryOperator;
3210
3211 // Fall back to marking the token as binary operator.
3212 return TT_BinaryOperator;
3213 }
3214
3215 /// Determine whether ++/-- are pre- or post-increments/-decrements.
3216 TokenType determineIncrementUsage(const FormatToken &Tok) {
3217 const FormatToken *PrevToken = Tok.getPreviousNonComment();
3218 if (!PrevToken || PrevToken->is(TT: TT_CastRParen))
3219 return TT_UnaryOperator;
3220 if (PrevToken->isOneOf(K1: tok::r_paren, K2: tok::r_square, Ks: tok::identifier))
3221 return TT_TrailingUnaryOperator;
3222
3223 return TT_UnaryOperator;
3224 }
3225
3226 SmallVector<Context, 8> Contexts;
3227
3228 const FormatStyle &Style;
3229 AnnotatedLine &Line;
3230 FormatToken *CurrentToken;
3231 bool AutoFound;
3232 bool IsCpp;
3233 LangOptions LangOpts;
3234 const AdditionalKeywords &Keywords;
3235
3236 SmallVector<ScopeType> &Scopes;
3237
3238 // Set of "<" tokens that do not open a template parameter list. If parseAngle
3239 // determines that a specific token can't be a template opener, it will make
3240 // same decision irrespective of the decisions for tokens leading up to it.
3241 // Store this information to prevent this from causing exponential runtime.
3242 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
3243
3244 int TemplateDeclarationDepth;
3245};
3246
3247static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
3248static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
3249
3250/// Parses binary expressions by inserting fake parenthesis based on
3251/// operator precedence.
3252class ExpressionParser {
3253public:
3254 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
3255 AnnotatedLine &Line)
3256 : Style(Style), Keywords(Keywords), Line(Line), Current(Line.First) {}
3257
3258 /// Parse expressions with the given operator precedence.
3259 void parse(int Precedence = 0) {
3260 // Skip 'return' and ObjC selector colons as they are not part of a binary
3261 // expression.
3262 while (Current && (Current->is(Kind: tok::kw_return) ||
3263 (Current->is(Kind: tok::colon) &&
3264 Current->isOneOf(K1: TT_ObjCMethodExpr, K2: TT_DictLiteral)))) {
3265 next();
3266 }
3267
3268 if (!Current || Precedence > PrecedenceArrowAndPeriod)
3269 return;
3270
3271 // Conditional expressions need to be parsed separately for proper nesting.
3272 if (Precedence == prec::Conditional) {
3273 parseConditionalExpr();
3274 return;
3275 }
3276
3277 // Parse unary operators, which all have a higher precedence than binary
3278 // operators.
3279 if (Precedence == PrecedenceUnaryOperator) {
3280 parseUnaryOperator();
3281 return;
3282 }
3283
3284 FormatToken *Start = Current;
3285 FormatToken *LatestOperator = nullptr;
3286 unsigned OperatorIndex = 0;
3287 // The first name of the current type in a port list.
3288 FormatToken *VerilogFirstOfType = nullptr;
3289
3290 while (Current) {
3291 // In Verilog ports in a module header that don't have a type take the
3292 // type of the previous one. For example,
3293 // module a(output b,
3294 // c,
3295 // output d);
3296 // In this case there need to be fake parentheses around b and c.
3297 if (Style.isVerilog() && Precedence == prec::Comma) {
3298 VerilogFirstOfType =
3299 verilogGroupDecl(FirstOfType: VerilogFirstOfType, PreviousComma: LatestOperator);
3300 }
3301
3302 // Consume operators with higher precedence.
3303 parse(Precedence: Precedence + 1);
3304
3305 int CurrentPrecedence = getCurrentPrecedence();
3306 if (CurrentPrecedence > prec::Conditional &&
3307 CurrentPrecedence < prec::PointerToMember) {
3308 // When BreakBinaryOperations is globally OnePerLine (no per-operator
3309 // rules), flatten all precedence levels so that every operator is
3310 // treated equally for line-breaking purposes. With per-operator rules
3311 // we must preserve natural precedence so that higher-precedence
3312 // sub-expressions (e.g. `x << 8` inside a `|` chain) stay grouped;
3313 // mustBreakBinaryOperation() handles the forced breaks instead.
3314 if (Style.BreakBinaryOperations.PerOperator.empty() &&
3315 Style.BreakBinaryOperations.Default ==
3316 FormatStyle::BBO_OnePerLine) {
3317 CurrentPrecedence = prec::Additive;
3318 }
3319 }
3320
3321 if (Precedence == CurrentPrecedence && Current &&
3322 Current->is(TT: TT_SelectorName)) {
3323 if (LatestOperator)
3324 addFakeParenthesis(Start, Precedence: prec::Level(Precedence));
3325 Start = Current;
3326 }
3327
3328 if ((Style.isCSharp() || Style.isJavaScript() || Style.isJava()) &&
3329 Precedence == prec::Additive && Current) {
3330 // A string can be broken without parentheses around it when it is
3331 // already in a sequence of strings joined by `+` signs.
3332 FormatToken *Prev = Current->getPreviousNonComment();
3333 if (Prev && Prev->is(Kind: tok::string_literal) &&
3334 (Prev == Start || Prev->endsSequence(K1: tok::string_literal, Tokens: tok::plus,
3335 Tokens: TT_StringInConcatenation))) {
3336 Prev->setType(TT_StringInConcatenation);
3337 }
3338 }
3339
3340 // At the end of the line or when an operator with lower precedence is
3341 // found, insert fake parenthesis and return.
3342 if (!Current ||
3343 (Current->closesScope() &&
3344 (Current->MatchingParen || Current->is(TT: TT_TemplateString))) ||
3345 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
3346 (CurrentPrecedence == prec::Conditional &&
3347 Precedence == prec::Assignment && Current->is(Kind: tok::colon))) {
3348 break;
3349 }
3350
3351 // Consume scopes: (), [], <> and {}
3352 // In addition to that we handle require clauses as scope, so that the
3353 // constraints in that are correctly indented.
3354 if (Current->opensScope() ||
3355 Current->isOneOf(K1: TT_RequiresClause,
3356 K2: TT_RequiresClauseInARequiresExpression)) {
3357 // In fragment of a JavaScript template string can look like '}..${' and
3358 // thus close a scope and open a new one at the same time.
3359 while (Current && (!Current->closesScope() || Current->opensScope())) {
3360 next();
3361 parse();
3362 }
3363 next();
3364 } else {
3365 // Operator found.
3366 if (CurrentPrecedence == Precedence) {
3367 if (LatestOperator)
3368 LatestOperator->NextOperator = Current;
3369 LatestOperator = Current;
3370 Current->OperatorIndex = OperatorIndex;
3371 ++OperatorIndex;
3372 }
3373 next(/*SkipPastLeadingComments=*/Precedence > 0);
3374 }
3375 }
3376
3377 // Group variables of the same type.
3378 if (Style.isVerilog() && Precedence == prec::Comma && VerilogFirstOfType)
3379 addFakeParenthesis(Start: VerilogFirstOfType, Precedence: prec::Comma);
3380
3381 if (LatestOperator && (Current || Precedence > 0)) {
3382 // The requires clauses do not neccessarily end in a semicolon or a brace,
3383 // but just go over to struct/class or a function declaration, we need to
3384 // intervene so that the fake right paren is inserted correctly.
3385 auto End =
3386 (Start->Previous &&
3387 Start->Previous->isOneOf(K1: TT_RequiresClause,
3388 K2: TT_RequiresClauseInARequiresExpression))
3389 ? [this]() {
3390 auto Ret = Current ? Current : Line.Last;
3391 while (!Ret->ClosesRequiresClause && Ret->Previous)
3392 Ret = Ret->Previous;
3393 return Ret;
3394 }()
3395 : nullptr;
3396
3397 if (Precedence == PrecedenceArrowAndPeriod) {
3398 // Call expressions don't have a binary operator precedence.
3399 addFakeParenthesis(Start, Precedence: prec::Unknown, End);
3400 } else {
3401 addFakeParenthesis(Start, Precedence: prec::Level(Precedence), End);
3402 }
3403 }
3404 }
3405
3406private:
3407 /// Gets the precedence (+1) of the given token for binary operators
3408 /// and other tokens that we treat like binary operators.
3409 int getCurrentPrecedence() {
3410 if (Current) {
3411 const FormatToken *NextNonComment = Current->getNextNonComment();
3412 if (Current->is(TT: TT_ConditionalExpr))
3413 return prec::Conditional;
3414 if (NextNonComment && Current->is(TT: TT_SelectorName) &&
3415 (NextNonComment->isOneOf(K1: TT_DictLiteral, K2: TT_JsTypeColon) ||
3416 (Style.isProto() && NextNonComment->is(Kind: tok::less)))) {
3417 return prec::Assignment;
3418 }
3419 if (Current->is(TT: TT_JsComputedPropertyName))
3420 return prec::Assignment;
3421 if (Current->is(TT: TT_LambdaArrow))
3422 return prec::Comma;
3423 if (Current->is(TT: TT_FatArrow))
3424 return prec::Assignment;
3425 if (Current->isOneOf(K1: tok::semi, K2: TT_InlineASMColon, Ks: TT_SelectorName) ||
3426 (Current->is(Kind: tok::comment) && NextNonComment &&
3427 NextNonComment->is(TT: TT_SelectorName))) {
3428 return 0;
3429 }
3430 if (Current->is(TT: TT_RangeBasedForLoopColon))
3431 return prec::Comma;
3432 if ((Style.isJava() || Style.isJavaScript()) &&
3433 Current->is(II: Keywords.kw_instanceof)) {
3434 return prec::Relational;
3435 }
3436 if (Style.isJavaScript() &&
3437 Current->isOneOf(K1: Keywords.kw_in, K2: Keywords.kw_as)) {
3438 return prec::Relational;
3439 }
3440 if (Current->isOneOf(K1: TT_BinaryOperator, K2: tok::comma))
3441 return Current->getPrecedence();
3442 if (Current->isOneOf(K1: tok::period, K2: tok::arrow) &&
3443 Current->isNot(Kind: TT_TrailingReturnArrow)) {
3444 return PrecedenceArrowAndPeriod;
3445 }
3446 if ((Style.isJava() || Style.isJavaScript()) &&
3447 Current->isOneOf(K1: Keywords.kw_extends, K2: Keywords.kw_implements,
3448 Ks: Keywords.kw_throws)) {
3449 return 0;
3450 }
3451 // In Verilog case labels are not on separate lines straight out of
3452 // UnwrappedLineParser. The colon is not part of an expression.
3453 if (Style.isVerilog() && Current->is(Kind: tok::colon))
3454 return 0;
3455 }
3456 return -1;
3457 }
3458
3459 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence,
3460 FormatToken *End = nullptr) {
3461 // Do not assign fake parenthesis to tokens that are part of an
3462 // unexpanded macro call. The line within the macro call contains
3463 // the parenthesis and commas, and we will not find operators within
3464 // that structure.
3465 if (Start->MacroParent)
3466 return;
3467
3468 Start->FakeLParens.push_back(Elt: Precedence);
3469 if (Precedence > prec::Unknown)
3470 Start->StartsBinaryExpression = true;
3471 if (!End && Current)
3472 End = Current->getPreviousNonComment();
3473 if (End) {
3474 ++End->FakeRParens;
3475 if (Precedence > prec::Unknown)
3476 End->EndsBinaryExpression = true;
3477 }
3478 }
3479
3480 /// Parse unary operator expressions and surround them with fake
3481 /// parentheses if appropriate.
3482 void parseUnaryOperator() {
3483 SmallVector<FormatToken *, 2> Tokens;
3484 while (Current && Current->is(TT: TT_UnaryOperator)) {
3485 Tokens.push_back(Elt: Current);
3486 next();
3487 }
3488 parse(Precedence: PrecedenceArrowAndPeriod);
3489 for (FormatToken *Token : reverse(C&: Tokens)) {
3490 // The actual precedence doesn't matter.
3491 addFakeParenthesis(Start: Token, Precedence: prec::Unknown);
3492 }
3493 }
3494
3495 void parseConditionalExpr() {
3496 while (Current && Current->isTrailingComment())
3497 next();
3498 FormatToken *Start = Current;
3499 parse(Precedence: prec::LogicalOr);
3500 if (!Current || Current->isNot(Kind: tok::question))
3501 return;
3502 next();
3503 parse(Precedence: prec::Assignment);
3504 if (!Current || Current->isNot(Kind: TT_ConditionalExpr))
3505 return;
3506 next();
3507 parse(Precedence: prec::Assignment);
3508 addFakeParenthesis(Start, Precedence: prec::Conditional);
3509 }
3510
3511 void next(bool SkipPastLeadingComments = true) {
3512 if (Current)
3513 Current = Current->Next;
3514 while (Current &&
3515 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
3516 Current->isTrailingComment()) {
3517 Current = Current->Next;
3518 }
3519 }
3520
3521 // Add fake parenthesis around declarations of the same type for example in a
3522 // module prototype. Return the first port / variable of the current type.
3523 FormatToken *verilogGroupDecl(FormatToken *FirstOfType,
3524 FormatToken *PreviousComma) {
3525 if (!Current)
3526 return nullptr;
3527
3528 FormatToken *Start = Current;
3529
3530 // Skip attributes.
3531 while (Start->startsSequence(K1: tok::l_paren, Tokens: tok::star)) {
3532 if (!(Start = Start->MatchingParen) ||
3533 !(Start = Start->getNextNonComment())) {
3534 return nullptr;
3535 }
3536 }
3537
3538 FormatToken *Tok = Start;
3539
3540 if (Tok->is(II: Keywords.kw_assign))
3541 Tok = Tok->getNextNonComment();
3542
3543 // Skip any type qualifiers to find the first identifier. It may be either a
3544 // new type name or a variable name. There can be several type qualifiers
3545 // preceding a variable name, and we can not tell them apart by looking at
3546 // the word alone since a macro can be defined as either a type qualifier or
3547 // a variable name. Thus we use the last word before the dimensions instead
3548 // of the first word as the candidate for the variable or type name.
3549 FormatToken *First = nullptr;
3550 while (Tok) {
3551 FormatToken *Next = Tok->getNextNonComment();
3552
3553 if (Tok->is(Kind: tok::hash)) {
3554 // Start of a macro expansion.
3555 First = Tok;
3556 Tok = Next;
3557 if (Tok)
3558 Tok = Tok->getNextNonComment();
3559 } else if (Tok->is(Kind: tok::hashhash)) {
3560 // Concatenation. Skip.
3561 Tok = Next;
3562 if (Tok)
3563 Tok = Tok->getNextNonComment();
3564 } else if (Keywords.isVerilogQualifier(Tok: *Tok) ||
3565 Keywords.isVerilogIdentifier(Tok: *Tok)) {
3566 First = Tok;
3567 Tok = Next;
3568 // The name may have dots like `interface_foo.modport_foo`.
3569 while (Tok && Tok->isOneOf(K1: tok::period, K2: tok::coloncolon) &&
3570 (Tok = Tok->getNextNonComment())) {
3571 if (Keywords.isVerilogIdentifier(Tok: *Tok))
3572 Tok = Tok->getNextNonComment();
3573 }
3574 } else if (!Next) {
3575 Tok = nullptr;
3576 } else if (Tok->is(Kind: tok::l_paren)) {
3577 // Make sure the parenthesized list is a drive strength. Otherwise the
3578 // statement may be a module instantiation in which case we have already
3579 // found the instance name.
3580 if (Next->isOneOf(
3581 K1: Keywords.kw_highz0, K2: Keywords.kw_highz1, Ks: Keywords.kw_large,
3582 Ks: Keywords.kw_medium, Ks: Keywords.kw_pull0, Ks: Keywords.kw_pull1,
3583 Ks: Keywords.kw_small, Ks: Keywords.kw_strong0, Ks: Keywords.kw_strong1,
3584 Ks: Keywords.kw_supply0, Ks: Keywords.kw_supply1, Ks: Keywords.kw_weak0,
3585 Ks: Keywords.kw_weak1)) {
3586 Tok->setType(TT_VerilogStrength);
3587 Tok = Tok->MatchingParen;
3588 if (Tok) {
3589 Tok->setType(TT_VerilogStrength);
3590 Tok = Tok->getNextNonComment();
3591 }
3592 } else {
3593 break;
3594 }
3595 } else if (Tok->is(II: Keywords.kw_verilogHash)) {
3596 // Delay control.
3597 if (Next->is(Kind: tok::l_paren))
3598 Next = Next->MatchingParen;
3599 if (Next)
3600 Tok = Next->getNextNonComment();
3601 } else {
3602 break;
3603 }
3604 }
3605
3606 // Find the second identifier. If it exists it will be the name.
3607 FormatToken *Second = nullptr;
3608 // Dimensions.
3609 while (Tok && Tok->is(Kind: tok::l_square) && (Tok = Tok->MatchingParen))
3610 Tok = Tok->getNextNonComment();
3611 if (Tok && (Tok->is(Kind: tok::hash) || Keywords.isVerilogIdentifier(Tok: *Tok)))
3612 Second = Tok;
3613
3614 // If the second identifier doesn't exist and there are qualifiers, the type
3615 // is implied.
3616 FormatToken *TypedName = nullptr;
3617 if (Second) {
3618 TypedName = Second;
3619 if (First && First->is(TT: TT_Unknown))
3620 First->setType(TT_VerilogDimensionedTypeName);
3621 } else if (First != Start) {
3622 // If 'First' is null, then this isn't a declaration, 'TypedName' gets set
3623 // to null as intended.
3624 TypedName = First;
3625 }
3626
3627 if (TypedName) {
3628 // This is a declaration with a new type.
3629 if (TypedName->is(TT: TT_Unknown))
3630 TypedName->setType(TT_StartOfName);
3631 // Group variables of the previous type.
3632 if (FirstOfType && PreviousComma) {
3633 PreviousComma->setType(TT_VerilogTypeComma);
3634 addFakeParenthesis(Start: FirstOfType, Precedence: prec::Comma, End: PreviousComma->Previous);
3635 }
3636
3637 FirstOfType = TypedName;
3638
3639 // Don't let higher precedence handle the qualifiers. For example if we
3640 // have:
3641 // parameter x = 0
3642 // We skip `parameter` here. This way the fake parentheses for the
3643 // assignment will be around `x = 0`.
3644 while (Current && Current != FirstOfType) {
3645 if (Current->opensScope()) {
3646 next();
3647 parse();
3648 }
3649 next();
3650 }
3651 }
3652
3653 return FirstOfType;
3654 }
3655
3656 const FormatStyle &Style;
3657 const AdditionalKeywords &Keywords;
3658 const AnnotatedLine &Line;
3659 FormatToken *Current;
3660};
3661
3662} // end anonymous namespace
3663
3664void TokenAnnotator::setCommentLineLevels(
3665 SmallVectorImpl<AnnotatedLine *> &Lines) const {
3666 const AnnotatedLine *NextNonCommentLine = nullptr;
3667 for (AnnotatedLine *Line : reverse(C&: Lines)) {
3668 assert(Line->First);
3669
3670 // If the comment is currently aligned with the line immediately following
3671 // it, that's probably intentional and we should keep it.
3672 if (const auto Column = Line->First->OriginalColumn;
3673 NextNonCommentLine && NextNonCommentLine->First->NewlinesBefore < 2 &&
3674 Line->isComment() && !isClangFormatOff(Comment: Line->First->TokenText) &&
3675 NextNonCommentLine->First->OriginalColumn == Column) {
3676 const bool PPDirectiveOrImportStmt =
3677 NextNonCommentLine->Type == LT_PreprocessorDirective ||
3678 NextNonCommentLine->Type == LT_ImportStatement;
3679 if (PPDirectiveOrImportStmt)
3680 Line->Type = LT_CommentAbovePPDirective;
3681 if (const auto IndentWidth = Style.IndentWidth;
3682 NextNonCommentLine->First->Finalized && IndentWidth > 0 &&
3683 Column % IndentWidth == 0) {
3684 Line->Level = Column / IndentWidth;
3685 } else {
3686 // Align comments for preprocessor lines with the # in column 0 if
3687 // preprocessor lines are not indented. Otherwise, align with the next
3688 // line.
3689 Line->Level =
3690 Style.IndentPPDirectives < FormatStyle::PPDIS_BeforeHash &&
3691 PPDirectiveOrImportStmt
3692 ? 0
3693 : NextNonCommentLine->Level;
3694 }
3695 } else {
3696 NextNonCommentLine = Line->First->isNot(Kind: tok::r_brace) ? Line : nullptr;
3697 }
3698
3699 setCommentLineLevels(Line->Children);
3700 }
3701}
3702
3703static unsigned maxNestingDepth(const AnnotatedLine &Line) {
3704 unsigned Result = 0;
3705 for (const auto *Tok = Line.First; Tok; Tok = Tok->Next)
3706 Result = std::max(a: Result, b: Tok->NestingLevel);
3707 return Result;
3708}
3709
3710// Returns the token after the first qualifier of the name, or nullptr if there
3711// is no qualifier.
3712static FormatToken *skipNameQualifier(const FormatToken *Tok) {
3713 assert(Tok);
3714
3715 // Qualified names must start with an identifier.
3716 if (Tok->isNot(Kind: tok::identifier))
3717 return nullptr;
3718
3719 Tok = Tok->getNextNonComment();
3720 if (!Tok)
3721 return nullptr;
3722
3723 // Consider: A::B::B()
3724 // Tok --^
3725 if (Tok->is(Kind: tok::coloncolon))
3726 return Tok->getNextNonComment();
3727
3728 // Consider: A<float>::B<int>::B()
3729 // Tok --^
3730 if (Tok->is(TT: TT_TemplateOpener)) {
3731 Tok = Tok->MatchingParen;
3732 if (!Tok)
3733 return nullptr;
3734
3735 Tok = Tok->getNextNonComment();
3736 if (!Tok)
3737 return nullptr;
3738 }
3739
3740 return Tok->is(Kind: tok::coloncolon) ? Tok->getNextNonComment() : nullptr;
3741}
3742
3743// Returns the name of a function with no return type, e.g. a constructor or
3744// destructor.
3745static FormatToken *getFunctionName(const AnnotatedLine &Line,
3746 FormatToken *&OpeningParen) {
3747 for (FormatToken *Tok = Line.getFirstNonComment(), *Name = nullptr; Tok;
3748 Tok = Tok->getNextNonComment()) {
3749 // Skip C++11 attributes both before and after the function name.
3750 if (Tok->is(TT: TT_AttributeLSquare)) {
3751 Tok = Tok->MatchingParen;
3752 if (!Tok)
3753 return nullptr;
3754 continue;
3755 }
3756
3757 // Make sure the name is followed by a pair of parentheses.
3758 if (Name) {
3759 if (Tok->is(Kind: tok::l_paren) && Tok->is(TT: TT_Unknown) && Tok->MatchingParen) {
3760 OpeningParen = Tok;
3761 return Name;
3762 }
3763 return nullptr;
3764 }
3765
3766 // Skip keywords that may precede the constructor/destructor name.
3767 if (Tok->isOneOf(K1: tok::kw_friend, K2: tok::kw_inline, Ks: tok::kw_virtual,
3768 Ks: tok::kw_constexpr, Ks: tok::kw_consteval, Ks: tok::kw_explicit)) {
3769 continue;
3770 }
3771
3772 // Skip past template typename declarations that may precede the
3773 // constructor/destructor name.
3774 if (Tok->is(Kind: tok::kw_template)) {
3775 Tok = Tok->getNextNonComment();
3776 if (!Tok)
3777 return nullptr;
3778
3779 // If the next token after the template keyword is not an opening bracket,
3780 // it is a template instantiation, and not a function.
3781 if (Tok->isNot(Kind: TT_TemplateOpener))
3782 return nullptr;
3783
3784 Tok = Tok->MatchingParen;
3785 if (!Tok)
3786 return nullptr;
3787
3788 continue;
3789 }
3790
3791 // A qualified name may start from the global namespace.
3792 if (Tok->is(Kind: tok::coloncolon)) {
3793 Tok = Tok->Next;
3794 if (!Tok)
3795 return nullptr;
3796 }
3797
3798 // Skip to the unqualified part of the name.
3799 while (auto *Next = skipNameQualifier(Tok))
3800 Tok = Next;
3801
3802 // Skip the `~` if a destructor name.
3803 if (Tok->is(Kind: tok::tilde)) {
3804 Tok = Tok->Next;
3805 if (!Tok)
3806 return nullptr;
3807 }
3808
3809 // Make sure the name is not already annotated, e.g. as NamespaceMacro.
3810 if (Tok->isNot(Kind: tok::identifier) || Tok->isNot(Kind: TT_Unknown))
3811 return nullptr;
3812
3813 Name = Tok;
3814 }
3815
3816 return nullptr;
3817}
3818
3819// Checks if Tok is a constructor/destructor name qualified by its class name.
3820static bool isCtorOrDtorName(const FormatToken *Tok) {
3821 assert(Tok && Tok->is(tok::identifier));
3822 const auto *Prev = Tok->Previous;
3823
3824 if (Prev && Prev->is(Kind: tok::tilde))
3825 Prev = Prev->Previous;
3826
3827 // Consider: A::A() and A<int>::A()
3828 if (!Prev || (!Prev->endsSequence(K1: tok::coloncolon, Tokens: tok::identifier) &&
3829 !Prev->endsSequence(K1: tok::coloncolon, Tokens: TT_TemplateCloser))) {
3830 return false;
3831 }
3832
3833 assert(Prev->Previous);
3834 if (Prev->Previous->is(TT: TT_TemplateCloser) && Prev->Previous->MatchingParen) {
3835 Prev = Prev->Previous->MatchingParen;
3836 assert(Prev->Previous);
3837 }
3838
3839 return Prev->Previous->TokenText == Tok->TokenText;
3840}
3841
3842void TokenAnnotator::annotate(AnnotatedLine &Line) {
3843 if (!Line.InMacroBody)
3844 MacroBodyScopes.clear();
3845
3846 auto &ScopeStack = Line.InMacroBody ? MacroBodyScopes : Scopes;
3847 AnnotatingParser Parser(Style, Line, Keywords, ScopeStack);
3848 Line.Type = Parser.parseLine();
3849
3850 if (!Line.Children.empty()) {
3851 ScopeStack.push_back(Elt: ST_Other);
3852 const bool InRequiresExpression = Line.Type == LT_RequiresExpression;
3853 for (auto &Child : Line.Children) {
3854 if (InRequiresExpression &&
3855 Child->First->isNoneOf(Ks: tok::kw_typename, Ks: tok::kw_requires,
3856 Ks: TT_CompoundRequirementLBrace)) {
3857 Child->Type = LT_SimpleRequirement;
3858 }
3859 annotate(Line&: *Child);
3860 }
3861 // ScopeStack can become empty if Child has an unmatched `}`.
3862 if (!ScopeStack.empty())
3863 ScopeStack.pop_back();
3864 }
3865
3866 // With very deep nesting, ExpressionParser uses lots of stack and the
3867 // formatting algorithm is very slow. We're not going to do a good job here
3868 // anyway - it's probably generated code being formatted by mistake.
3869 // Just skip the whole line.
3870 if (maxNestingDepth(Line) > 50)
3871 Line.Type = LT_Invalid;
3872
3873 if (Line.Type == LT_Invalid)
3874 return;
3875
3876 ExpressionParser ExprParser(Style, Keywords, Line);
3877 ExprParser.parse();
3878
3879 if (IsCpp) {
3880 FormatToken *OpeningParen = nullptr;
3881 auto *Tok = getFunctionName(Line, OpeningParen);
3882 if (Tok && ((!ScopeStack.empty() && ScopeStack.back() == ST_Class) ||
3883 Line.endsWith(Tokens: TT_FunctionLBrace) || isCtorOrDtorName(Tok))) {
3884 Tok->setFinalizedType(TT_CtorDtorDeclName);
3885 assert(OpeningParen);
3886 OpeningParen->setFinalizedType(TT_FunctionDeclarationLParen);
3887 }
3888 }
3889
3890 if (Line.startsWith(Tokens: TT_ObjCMethodSpecifier))
3891 Line.Type = LT_ObjCMethodDecl;
3892 else if (Line.startsWith(Tokens: TT_ObjCDecl))
3893 Line.Type = LT_ObjCDecl;
3894 else if (Line.startsWith(Tokens: TT_ObjCProperty))
3895 Line.Type = LT_ObjCProperty;
3896
3897 auto *First = Line.First;
3898 First->SpacesRequiredBefore = 1;
3899 First->CanBreakBefore = First->MustBreakBefore;
3900}
3901
3902// This function heuristically determines whether 'Current' starts the name of a
3903// function declaration.
3904static bool isFunctionDeclarationName(const LangOptions &LangOpts,
3905 const FormatToken &Current,
3906 const AnnotatedLine &Line,
3907 FormatToken *&ClosingParen) {
3908 if (Current.is(TT: TT_FunctionDeclarationName))
3909 return true;
3910
3911 if (Current.isNoneOf(Ks: tok::identifier, Ks: tok::kw_operator))
3912 return false;
3913
3914 const auto *Prev = Current.getPreviousNonComment();
3915 assert(Prev);
3916
3917 const auto &Previous = *Prev;
3918
3919 if (const auto *PrevPrev = Previous.getPreviousNonComment();
3920 PrevPrev && PrevPrev->is(TT: TT_ObjCDecl)) {
3921 return false;
3922 }
3923
3924 auto skipOperatorName =
3925 [&LangOpts](const FormatToken *Next) -> const FormatToken * {
3926 for (; Next; Next = Next->Next) {
3927 if (Next->is(TT: TT_OverloadedOperatorLParen))
3928 return Next;
3929 if (Next->is(TT: TT_OverloadedOperator))
3930 continue;
3931 if (Next->isPlacementOperator() || Next->is(Kind: tok::kw_co_await)) {
3932 // For 'new[]' and 'delete[]'.
3933 if (Next->Next &&
3934 Next->Next->startsSequence(K1: tok::l_square, Tokens: tok::r_square)) {
3935 Next = Next->Next->Next;
3936 }
3937 continue;
3938 }
3939 if (Next->startsSequence(K1: tok::l_square, Tokens: tok::r_square)) {
3940 // For operator[]().
3941 Next = Next->Next;
3942 continue;
3943 }
3944 if ((Next->isTypeName(LangOpts) || Next->is(Kind: tok::identifier)) &&
3945 Next->Next && Next->Next->isPointerOrReference()) {
3946 // For operator void*(), operator char*(), operator Foo*().
3947 Next = Next->Next;
3948 continue;
3949 }
3950 if (Next->is(TT: TT_TemplateOpener) && Next->MatchingParen) {
3951 Next = Next->MatchingParen;
3952 continue;
3953 }
3954
3955 break;
3956 }
3957 return nullptr;
3958 };
3959
3960 const auto *Next = Current.Next;
3961 const bool IsCpp = LangOpts.CXXOperatorNames || LangOpts.C11;
3962
3963 // Find parentheses of parameter list.
3964 if (Current.is(Kind: tok::kw_operator)) {
3965 if (Line.startsWith(Tokens: tok::kw_friend))
3966 return true;
3967 if (Previous.Tok.getIdentifierInfo() &&
3968 Previous.isNoneOf(Ks: tok::kw_return, Ks: tok::kw_co_return)) {
3969 return true;
3970 }
3971 if (Previous.is(Kind: tok::r_paren) && Previous.is(TT: TT_TypeDeclarationParen)) {
3972 assert(Previous.MatchingParen);
3973 assert(Previous.MatchingParen->is(tok::l_paren));
3974 assert(Previous.MatchingParen->is(TT_TypeDeclarationParen));
3975 return true;
3976 }
3977 if (!Previous.isPointerOrReference() && Previous.isNot(Kind: TT_TemplateCloser))
3978 return false;
3979 Next = skipOperatorName(Next);
3980 } else {
3981 if (Current.isNot(Kind: TT_StartOfName) || Current.NestingLevel != 0)
3982 return false;
3983 while (Next && Next->startsSequence(K1: tok::hashhash, Tokens: tok::identifier))
3984 Next = Next->Next->Next;
3985 for (; Next; Next = Next->Next) {
3986 if (Next->is(TT: TT_TemplateOpener) && Next->MatchingParen) {
3987 Next = Next->MatchingParen;
3988 } else if (Next->is(Kind: tok::coloncolon)) {
3989 Next = Next->Next;
3990 if (!Next)
3991 return false;
3992 if (Next->is(Kind: tok::kw_operator)) {
3993 Next = skipOperatorName(Next->Next);
3994 break;
3995 }
3996 if (Next->isNot(Kind: tok::identifier))
3997 return false;
3998 } else if (isCppAttribute(IsCpp, Tok: *Next)) {
3999 Next = Next->MatchingParen;
4000 if (!Next)
4001 return false;
4002 } else if (Next->is(Kind: tok::l_paren)) {
4003 break;
4004 } else {
4005 return false;
4006 }
4007 }
4008 }
4009
4010 // Check whether parameter list can belong to a function declaration.
4011 if (!Next || Next->isNot(Kind: tok::l_paren) || !Next->MatchingParen)
4012 return false;
4013 ClosingParen = Next->MatchingParen;
4014 assert(ClosingParen->is(tok::r_paren));
4015 // If the lines ends with "{", this is likely a function definition.
4016 if (Line.Last->is(Kind: tok::l_brace))
4017 return true;
4018 if (Next->Next == ClosingParen)
4019 return true; // Empty parentheses.
4020 // If there is an &/&& after the r_paren, this is likely a function.
4021 if (ClosingParen->Next && ClosingParen->Next->is(TT: TT_PointerOrReference))
4022 return true;
4023
4024 // Check for K&R C function definitions (and C++ function definitions with
4025 // unnamed parameters), e.g.:
4026 // int f(i)
4027 // {
4028 // return i + 1;
4029 // }
4030 // bool g(size_t = 0, bool b = false)
4031 // {
4032 // return !b;
4033 // }
4034 if (IsCpp && Next->Next && Next->Next->is(Kind: tok::identifier) &&
4035 !Line.endsWith(Tokens: tok::semi)) {
4036 return true;
4037 }
4038
4039 for (const FormatToken *Tok = Next->Next; Tok && Tok != ClosingParen;
4040 Tok = Tok->Next) {
4041 if (Tok->is(TT: TT_TypeDeclarationParen))
4042 return true;
4043 if (Tok->isOneOf(K1: tok::l_paren, K2: TT_TemplateOpener) && Tok->MatchingParen) {
4044 Tok = Tok->MatchingParen;
4045 continue;
4046 }
4047 if (Tok->is(Kind: tok::kw_const) || Tok->isTypeName(LangOpts) ||
4048 Tok->isOneOf(K1: TT_PointerOrReference, K2: TT_StartOfName, Ks: tok::ellipsis)) {
4049 return true;
4050 }
4051 if (Tok->isOneOf(K1: tok::l_brace, K2: TT_ObjCMethodExpr) || Tok->Tok.isLiteral())
4052 return false;
4053 }
4054 return false;
4055}
4056
4057bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
4058 assert(Line.MightBeFunctionDecl);
4059
4060 if ((Style.BreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
4061 Style.BreakAfterReturnType == FormatStyle::RTBS_TopLevelDefinitions) &&
4062 Line.Level > 0) {
4063 return false;
4064 }
4065
4066 switch (Style.BreakAfterReturnType) {
4067 case FormatStyle::RTBS_None:
4068 case FormatStyle::RTBS_Automatic:
4069 case FormatStyle::RTBS_ExceptShortType:
4070 return false;
4071 case FormatStyle::RTBS_All:
4072 case FormatStyle::RTBS_TopLevel:
4073 return true;
4074 case FormatStyle::RTBS_AllDefinitions:
4075 case FormatStyle::RTBS_TopLevelDefinitions:
4076 return Line.mightBeFunctionDefinition();
4077 }
4078
4079 return false;
4080}
4081
4082bool TokenAnnotator::mustBreakBeforeReturnType(
4083 const AnnotatedLine &Line) const {
4084 assert(Line.MightBeFunctionDecl);
4085
4086 switch (Style.BreakBeforeReturnType) {
4087 case FormatStyle::BBRTS_None:
4088 return false;
4089 case FormatStyle::BBRTS_All:
4090 return true;
4091 case FormatStyle::BBRTS_TopLevel:
4092 return Line.Level == 0;
4093 case FormatStyle::BBRTS_AllDefinitions:
4094 return Line.mightBeFunctionDefinition();
4095 case FormatStyle::BBRTS_TopLevelDefinitions:
4096 return Line.Level == 0 && Line.mightBeFunctionDefinition();
4097 }
4098
4099 return false;
4100}
4101
4102static FormatToken *findReturnTypeStart(const AnnotatedLine &Line) {
4103 auto *Tok = Line.getFirstNonComment();
4104 if (!Tok)
4105 return nullptr;
4106
4107 if (Tok->is(Kind: tok::kw_template)) {
4108 auto *Opener = Tok->Next;
4109 while (Opener && Opener->isNot(Kind: TT_TemplateOpener))
4110 Opener = Opener->Next;
4111 if (!Opener || !Opener->MatchingParen)
4112 return nullptr;
4113 Tok = Opener->MatchingParen->Next;
4114 }
4115
4116 if (Tok && Tok->is(TT: TT_RequiresClause)) {
4117 while (Tok && !Tok->ClosesRequiresClause)
4118 Tok = Tok->Next;
4119 if (Tok)
4120 Tok = Tok->Next;
4121 }
4122
4123 while (Tok) {
4124 if (isReturnTypePrefixSpecifier(Tok: *Tok) ||
4125 Tok->isOneOf(K1: tok::kw___attribute, K2: tok::kw___declspec,
4126 Ks: TT_AttributeMacro)) {
4127 auto *Next = Tok->Next;
4128 if (Next && Next->is(Kind: tok::l_paren) && Next->MatchingParen)
4129 Tok = Next->MatchingParen->Next;
4130 else
4131 Tok = Next;
4132 continue;
4133 }
4134 if (Tok->is(TT: TT_AttributeLSquare) && Tok->MatchingParen) {
4135 Tok = Tok->MatchingParen->Next;
4136 continue;
4137 }
4138 break;
4139 }
4140 return Tok;
4141}
4142
4143void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
4144 if (Line.Computed)
4145 return;
4146
4147 Line.Computed = true;
4148
4149 for (AnnotatedLine *ChildLine : Line.Children)
4150 calculateFormattingInformation(Line&: *ChildLine);
4151
4152 auto *First = Line.First;
4153 First->TotalLength = First->IsMultiline
4154 ? Style.ColumnLimit
4155 : Line.FirstStartColumn + First->ColumnWidth;
4156 bool AlignArrayOfStructures =
4157 (Style.AlignArrayOfStructures != FormatStyle::AIAS_None &&
4158 Line.Type == LT_ArrayOfStructInitializer);
4159 if (AlignArrayOfStructures)
4160 calculateArrayInitializerColumnList(Line);
4161
4162 const auto *FirstNonComment = Line.getFirstNonComment();
4163 bool SeenName = false;
4164 bool LineIsFunctionDeclaration = false;
4165 FormatToken *AfterLastAttribute = nullptr;
4166 FormatToken *ClosingParen = nullptr;
4167
4168 for (auto *Tok = FirstNonComment && FirstNonComment->isNot(Kind: tok::kw_using)
4169 ? FirstNonComment->Next
4170 : nullptr;
4171 Tok && Tok->isNot(Kind: BK_BracedInit); Tok = Tok->Next) {
4172 if (Tok->is(TT: TT_StartOfName))
4173 SeenName = true;
4174 if (Tok->Previous->EndsCppAttributeGroup)
4175 AfterLastAttribute = Tok;
4176 if (const bool IsCtorOrDtor = Tok->is(TT: TT_CtorDtorDeclName);
4177 IsCtorOrDtor ||
4178 isFunctionDeclarationName(LangOpts, Current: *Tok, Line, ClosingParen)) {
4179 if (!IsCtorOrDtor)
4180 Tok->setFinalizedType(TT_FunctionDeclarationName);
4181 LineIsFunctionDeclaration = true;
4182 SeenName = true;
4183 if (ClosingParen) {
4184 auto *OpeningParen = ClosingParen->MatchingParen;
4185 assert(OpeningParen);
4186 if (OpeningParen->is(TT: TT_Unknown))
4187 OpeningParen->setType(TT_FunctionDeclarationLParen);
4188 }
4189 break;
4190 }
4191 }
4192
4193 if (IsCpp) {
4194 if ((LineIsFunctionDeclaration ||
4195 (FirstNonComment && FirstNonComment->is(TT: TT_CtorDtorDeclName))) &&
4196 Line.endsWith(Tokens: tok::semi, Tokens: tok::r_brace)) {
4197 auto *Tok = Line.Last->Previous;
4198 while (Tok->isNot(Kind: tok::r_brace))
4199 Tok = Tok->Previous;
4200 if (auto *LBrace = Tok->MatchingParen; LBrace && LBrace->is(TT: TT_Unknown)) {
4201 assert(LBrace->is(tok::l_brace));
4202 Tok->setBlockKind(BK_Block);
4203 LBrace->setBlockKind(BK_Block);
4204 LBrace->setFinalizedType(TT_FunctionLBrace);
4205 }
4206 }
4207
4208 if (SeenName && AfterLastAttribute &&
4209 mustBreakAfterAttributes(Tok: *AfterLastAttribute, Style)) {
4210 AfterLastAttribute->MustBreakBefore = true;
4211 if (LineIsFunctionDeclaration)
4212 Line.ReturnTypeWrapped = true;
4213 }
4214
4215 if (!LineIsFunctionDeclaration) {
4216 Line.ReturnTypeWrapped = false;
4217 // Annotate */&/&& in `operator` function calls as binary operators.
4218 for (const auto *Tok = FirstNonComment; Tok; Tok = Tok->Next) {
4219 if (Tok->isNot(Kind: tok::kw_operator))
4220 continue;
4221 do {
4222 Tok = Tok->Next;
4223 } while (Tok && Tok->isNot(Kind: TT_OverloadedOperatorLParen));
4224 if (!Tok || !Tok->MatchingParen)
4225 break;
4226 const auto *LeftParen = Tok;
4227 for (Tok = Tok->Next; Tok && Tok != LeftParen->MatchingParen;
4228 Tok = Tok->Next) {
4229 if (Tok->isNot(Kind: tok::identifier))
4230 continue;
4231 auto *Next = Tok->Next;
4232 const bool NextIsBinaryOperator =
4233 Next && Next->isPointerOrReference() && Next->Next &&
4234 Next->Next->is(Kind: tok::identifier);
4235 if (!NextIsBinaryOperator)
4236 continue;
4237 Next->setType(TT_BinaryOperator);
4238 Tok = Next;
4239 }
4240 }
4241 } else if (ClosingParen) {
4242 for (auto *Tok = ClosingParen->Next; Tok; Tok = Tok->Next) {
4243 if (Tok->is(TT: TT_CtorInitializerColon))
4244 break;
4245 if (Tok->is(Kind: tok::arrow)) {
4246 Tok->overwriteFixedType(T: TT_TrailingReturnArrow);
4247 break;
4248 }
4249 if (Tok->isNot(Kind: TT_TrailingAnnotation))
4250 continue;
4251 const auto *Next = Tok->Next;
4252 if (!Next || Next->isNot(Kind: tok::l_paren))
4253 continue;
4254 Tok = Next->MatchingParen;
4255 if (!Tok)
4256 break;
4257 }
4258 }
4259 }
4260
4261 if (Line.MightBeFunctionDecl && LineIsFunctionDeclaration &&
4262 mustBreakBeforeReturnType(Line)) {
4263 if (auto *ReturnTypeStart = findReturnTypeStart(Line);
4264 ReturnTypeStart && ReturnTypeStart != FirstNonComment &&
4265 ReturnTypeStart->isNoneOf(Ks: TT_FunctionDeclarationName,
4266 Ks: TT_CtorDtorDeclName, Ks: tok::tilde)) {
4267 ReturnTypeStart->MustBreakBefore = true;
4268 Line.ReturnTypeWrapped = true;
4269 }
4270 }
4271
4272 if (First->is(TT: TT_ElseLBrace)) {
4273 First->CanBreakBefore = true;
4274 First->MustBreakBefore = true;
4275 }
4276
4277 bool InFunctionDecl = Line.MightBeFunctionDecl;
4278 bool InParameterList = false;
4279 for (auto *Current = First->Next; Current; Current = Current->Next) {
4280 const FormatToken *Prev = Current->Previous;
4281 if (Current->is(TT: TT_LineComment)) {
4282 if (Prev->is(BBK: BK_BracedInit) && Prev->opensScope()) {
4283 Current->SpacesRequiredBefore =
4284 (Style.Cpp11BracedListStyle == FormatStyle::BLS_AlignFirstComment &&
4285 !Style.SpacesInParensOptions.Other)
4286 ? 0
4287 : 1;
4288 } else if (Prev->is(TT: TT_VerilogMultiLineListLParen)) {
4289 Current->SpacesRequiredBefore = 0;
4290 } else {
4291 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
4292 }
4293
4294 // If we find a trailing comment, iterate backwards to determine whether
4295 // it seems to relate to a specific parameter. If so, break before that
4296 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
4297 // to the previous line in:
4298 // SomeFunction(a,
4299 // b, // comment
4300 // c);
4301 if (!Current->HasUnescapedNewline) {
4302 for (FormatToken *Parameter = Current->Previous; Parameter;
4303 Parameter = Parameter->Previous) {
4304 if (Parameter->isOneOf(K1: tok::comment, K2: tok::r_brace))
4305 break;
4306 if (Parameter->Previous && Parameter->Previous->is(Kind: tok::comma)) {
4307 if (Parameter->Previous->isNot(Kind: TT_CtorInitializerComma) &&
4308 Parameter->HasUnescapedNewline) {
4309 Parameter->MustBreakBefore = true;
4310 }
4311 break;
4312 }
4313 }
4314 }
4315 } else if (!Current->Finalized && Current->SpacesRequiredBefore == 0 &&
4316 spaceRequiredBefore(Line, Right: *Current)) {
4317 Current->SpacesRequiredBefore = 1;
4318 }
4319
4320 const auto &Children = Prev->Children;
4321 if (!Children.empty() && Children.back()->Last->is(TT: TT_LineComment)) {
4322 Current->MustBreakBefore = true;
4323 } else {
4324 Current->MustBreakBefore =
4325 Current->MustBreakBefore || mustBreakBefore(Line, Right: *Current);
4326 if (!Current->MustBreakBefore && InFunctionDecl &&
4327 Current->is(TT: TT_FunctionDeclarationName)) {
4328 Current->MustBreakBefore = mustBreakForReturnType(Line);
4329 }
4330 }
4331
4332 Current->CanBreakBefore =
4333 !Line.IsModuleOrImportDecl &&
4334 (Current->MustBreakBefore || canBreakBefore(Line, Right: *Current));
4335
4336 if (Current->is(TT: TT_FunctionDeclarationLParen)) {
4337 InParameterList = true;
4338 } else if (Current->is(Kind: tok::r_paren)) {
4339 const auto *LParen = Current->MatchingParen;
4340 if (LParen && LParen->is(TT: TT_FunctionDeclarationLParen))
4341 InParameterList = false;
4342 } else if (InParameterList &&
4343 Current->endsSequence(K1: TT_AttributeMacro,
4344 Tokens: TT_PointerOrReference)) {
4345 Current->CanBreakBefore = false;
4346 }
4347
4348 unsigned ChildSize = 0;
4349 if (Prev->Children.size() == 1) {
4350 FormatToken &LastOfChild = *Prev->Children[0]->Last;
4351 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
4352 : LastOfChild.TotalLength + 1;
4353 }
4354 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
4355 (Prev->Children.size() == 1 &&
4356 Prev->Children[0]->First->MustBreakBefore) ||
4357 Current->IsMultiline) {
4358 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
4359 } else {
4360 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
4361 ChildSize + Current->SpacesRequiredBefore;
4362 }
4363
4364 if ((Style.PackParameters.BinPack == FormatStyle::BPPS_UseBreakAfter &&
4365 Prev->MightBeFunctionDeclParen &&
4366 Prev->ParameterCount > Style.PackParameters.BreakAfter) ||
4367 (Style.PackArguments.BinPack == FormatStyle::BPAS_UseBreakAfter &&
4368 !Prev->MightBeFunctionDeclParen &&
4369 Prev->isOneOf(K1: tok::l_paren, K2: tok::l_brace,
4370 Ks: TT_ArrayInitializerLSquare) &&
4371 Prev->ParameterCount > Style.PackArguments.BreakAfter)) {
4372 const auto *RParen = Prev->MatchingParen;
4373 for (auto *ParamTok = Current; ParamTok && ParamTok != RParen;
4374 ParamTok = ParamTok->Next) {
4375 if (ParamTok->opensScope()) {
4376 ParamTok = ParamTok->MatchingParen;
4377 continue;
4378 }
4379
4380 if (startsNextParameter(Current: *ParamTok, Style)) {
4381 ParamTok->MustBreakBefore = true;
4382 ParamTok->CanBreakBefore = true;
4383 }
4384 }
4385 }
4386
4387 if (Current->is(TT: TT_ControlStatementLBrace)) {
4388 if (Style.ColumnLimit > 0 &&
4389 Style.BraceWrapping.AfterControlStatement ==
4390 FormatStyle::BWACS_MultiLine &&
4391 Line.Level * Style.IndentWidth + Line.Last->TotalLength >
4392 Style.ColumnLimit) {
4393 Current->CanBreakBefore = true;
4394 Current->MustBreakBefore = true;
4395 }
4396 } else if (Current->is(TT: TT_CtorInitializerColon)) {
4397 InFunctionDecl = false;
4398 }
4399
4400 // FIXME: Only calculate this if CanBreakBefore is true once static
4401 // initializers etc. are sorted out.
4402 // FIXME: Move magic numbers to a better place.
4403
4404 // Reduce penalty for aligning ObjC method arguments using the colon
4405 // alignment as this is the canonical way (still prefer fitting everything
4406 // into one line if possible). Trying to fit a whole expression into one
4407 // line should not force other line breaks (e.g. when ObjC method
4408 // expression is a part of other expression).
4409 Current->SplitPenalty = splitPenalty(Line, Tok: *Current, InFunctionDecl);
4410 if (Style.Language == FormatStyle::LK_ObjC &&
4411 Current->is(TT: TT_SelectorName) && Current->ParameterIndex > 0) {
4412 if (Current->ParameterIndex == 1)
4413 Current->SplitPenalty += 5 * Current->BindingStrength;
4414 } else {
4415 Current->SplitPenalty += 20 * Current->BindingStrength;
4416 }
4417 }
4418
4419 calculateUnbreakableTailLengths(Line);
4420 unsigned IndentLevel = Line.Level;
4421 for (auto *Current = First; Current; Current = Current->Next) {
4422 if (Current->Role)
4423 Current->Role->precomputeFormattingInfos(Token: Current);
4424 if (Current->MatchingParen &&
4425 Current->MatchingParen->opensBlockOrBlockTypeList(Style) &&
4426 IndentLevel > 0) {
4427 --IndentLevel;
4428 }
4429 Current->IndentLevel = IndentLevel;
4430 if (Current->opensBlockOrBlockTypeList(Style))
4431 ++IndentLevel;
4432 }
4433
4434 LLVM_DEBUG({ printDebugInfo(Line); });
4435}
4436
4437void TokenAnnotator::calculateUnbreakableTailLengths(
4438 AnnotatedLine &Line) const {
4439 unsigned UnbreakableTailLength = 0;
4440 FormatToken *Current = Line.Last;
4441 while (Current) {
4442 Current->UnbreakableTailLength = UnbreakableTailLength;
4443 if (Current->CanBreakBefore ||
4444 Current->isOneOf(K1: tok::comment, K2: tok::string_literal)) {
4445 UnbreakableTailLength = 0;
4446 } else {
4447 UnbreakableTailLength +=
4448 Current->ColumnWidth + Current->SpacesRequiredBefore;
4449 }
4450 Current = Current->Previous;
4451 }
4452}
4453
4454void TokenAnnotator::calculateArrayInitializerColumnList(
4455 AnnotatedLine &Line) const {
4456 if (Line.First == Line.Last)
4457 return;
4458 auto *CurrentToken = Line.First;
4459 CurrentToken->ArrayInitializerLineStart = true;
4460 unsigned Depth = 0;
4461 while (CurrentToken && CurrentToken != Line.Last) {
4462 if (CurrentToken->is(Kind: tok::l_brace)) {
4463 CurrentToken->IsArrayInitializer = true;
4464 if (CurrentToken->Next)
4465 CurrentToken->Next->MustBreakBefore = true;
4466 CurrentToken =
4467 calculateInitializerColumnList(Line, CurrentToken: CurrentToken->Next, Depth: Depth + 1);
4468 } else {
4469 CurrentToken = CurrentToken->Next;
4470 }
4471 }
4472}
4473
4474FormatToken *TokenAnnotator::calculateInitializerColumnList(
4475 AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) const {
4476 while (CurrentToken && CurrentToken != Line.Last) {
4477 if (CurrentToken->is(Kind: tok::l_brace))
4478 ++Depth;
4479 else if (CurrentToken->is(Kind: tok::r_brace))
4480 --Depth;
4481 if (Depth == 2 && CurrentToken->isOneOf(K1: tok::l_brace, K2: tok::comma)) {
4482 CurrentToken = CurrentToken->Next;
4483 if (!CurrentToken)
4484 break;
4485 CurrentToken->StartsColumn = true;
4486 CurrentToken = CurrentToken->Previous;
4487 }
4488 CurrentToken = CurrentToken->Next;
4489 }
4490 return CurrentToken;
4491}
4492
4493unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
4494 const FormatToken &Tok,
4495 bool InFunctionDecl) const {
4496 const FormatToken &Left = *Tok.Previous;
4497 const FormatToken &Right = Tok;
4498
4499 if (Left.is(Kind: tok::semi))
4500 return 0;
4501
4502 // Language specific handling.
4503 if (Style.isJava()) {
4504 if (Right.isOneOf(K1: Keywords.kw_extends, K2: Keywords.kw_throws))
4505 return 1;
4506 if (Right.is(II: Keywords.kw_implements))
4507 return 2;
4508 if (Left.is(Kind: tok::comma) && Left.NestingLevel == 0)
4509 return 3;
4510 } else if (Style.isJavaScript()) {
4511 if (Right.is(II: Keywords.kw_function) && Left.isNot(Kind: tok::comma))
4512 return 100;
4513 if (Left.is(TT: TT_JsTypeColon))
4514 return 35;
4515 if ((Left.is(TT: TT_TemplateString) && Left.TokenText.ends_with(Suffix: "${")) ||
4516 (Right.is(TT: TT_TemplateString) && Right.TokenText.starts_with(Prefix: "}"))) {
4517 return 100;
4518 }
4519 // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
4520 if (Left.opensScope() && Right.closesScope())
4521 return 200;
4522 } else if (Style.Language == FormatStyle::LK_Proto) {
4523 if (Right.is(Kind: tok::l_square))
4524 return 1;
4525 if (Right.is(Kind: tok::period))
4526 return 500;
4527 }
4528
4529 if (Right.is(Kind: tok::identifier) && Right.Next && Right.Next->is(TT: TT_DictLiteral))
4530 return 1;
4531 if (Right.is(Kind: tok::l_square)) {
4532 if (Left.is(Kind: tok::r_square))
4533 return 200;
4534 // Slightly prefer formatting local lambda definitions like functions.
4535 if (Right.is(TT: TT_LambdaLSquare) && Left.is(Kind: tok::equal))
4536 return 35;
4537 if (Right.isNoneOf(Ks: TT_ObjCMethodExpr, Ks: TT_LambdaLSquare,
4538 Ks: TT_ArrayInitializerLSquare,
4539 Ks: TT_DesignatedInitializerLSquare, Ks: TT_AttributeLSquare)) {
4540 return 500;
4541 }
4542 }
4543
4544 if (Left.is(Kind: tok::coloncolon))
4545 return Style.PenaltyBreakScopeResolution;
4546 if (Right.isOneOf(K1: TT_StartOfName, K2: TT_FunctionDeclarationName,
4547 Ks: tok::kw_operator)) {
4548 if (Line.startsWith(Tokens: tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
4549 return 3;
4550 if (Left.is(TT: TT_StartOfName))
4551 return 110;
4552 if (InFunctionDecl && Right.NestingLevel == 0)
4553 return Style.PenaltyReturnTypeOnItsOwnLine;
4554 return 200;
4555 }
4556 if (Right.is(TT: TT_PointerOrReference))
4557 return 190;
4558 if (Right.is(TT: TT_LambdaArrow))
4559 return 110;
4560 if (Left.is(Kind: tok::equal) && Right.is(Kind: tok::l_brace))
4561 return 160;
4562 if (Left.is(TT: TT_CastRParen))
4563 return 100;
4564 if (Left.isOneOf(K1: tok::kw_class, K2: tok::kw_struct, Ks: tok::kw_union))
4565 return 5000;
4566 if (Left.is(Kind: tok::comment))
4567 return 1000;
4568
4569 if (Left.isOneOf(K1: TT_RangeBasedForLoopColon, K2: TT_InheritanceColon,
4570 Ks: TT_CtorInitializerColon)) {
4571 return 2;
4572 }
4573
4574 if (Right.isMemberAccess()) {
4575 // Breaking before the "./->" of a chained call/member access is reasonably
4576 // cheap, as formatting those with one call per line is generally
4577 // desirable. In particular, it should be cheaper to break before the call
4578 // than it is to break inside a call's parameters, which could lead to weird
4579 // "hanging" indents. The exception is the very last "./->" to support this
4580 // frequent pattern:
4581 //
4582 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
4583 // dddddddd);
4584 //
4585 // which might otherwise be blown up onto many lines. Here, clang-format
4586 // won't produce "hanging" indents anyway as there is no other trailing
4587 // call.
4588 //
4589 // Also apply higher penalty is not a call as that might lead to a wrapping
4590 // like:
4591 //
4592 // aaaaaaa
4593 // .aaaaaaaaa.bbbbbbbb(cccccccc);
4594 const auto *NextOperator = Right.NextOperator;
4595 const auto Penalty = Style.PenaltyBreakBeforeMemberAccess;
4596 return NextOperator && NextOperator->Previous->closesScope()
4597 ? std::min(a: Penalty, b: 35u)
4598 : Penalty;
4599 }
4600
4601 if (Right.is(TT: TT_TrailingAnnotation) &&
4602 (!Right.Next || Right.Next->isNot(Kind: tok::l_paren))) {
4603 // Moving trailing annotations to the next line is fine for ObjC method
4604 // declarations.
4605 if (Line.startsWith(Tokens: TT_ObjCMethodSpecifier))
4606 return 10;
4607 // Generally, breaking before a trailing annotation is bad unless it is
4608 // function-like. It seems to be especially preferable to keep standard
4609 // annotations (i.e. "const", "final" and "override") on the same line.
4610 // Use a slightly higher penalty after ")" so that annotations like
4611 // "const override" are kept together.
4612 bool is_short_annotation = Right.TokenText.size() < 10;
4613 return (Left.is(Kind: tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
4614 }
4615
4616 // In for-loops, prefer breaking at ',' and ';'.
4617 if (Line.startsWith(Tokens: tok::kw_for) && Left.is(Kind: tok::equal))
4618 return 4;
4619
4620 // In Objective-C method expressions, prefer breaking before "param:" over
4621 // breaking after it.
4622 if (Right.is(TT: TT_SelectorName))
4623 return 0;
4624 if (Left.is(Kind: tok::colon)) {
4625 if (Left.is(TT: TT_ObjCMethodExpr))
4626 return Line.MightBeFunctionDecl ? 50 : 500;
4627 if (Left.is(TT: TT_ObjCSelector))
4628 return 500;
4629 }
4630
4631 // In Objective-C type declarations, avoid breaking after the category's
4632 // open paren (we'll prefer breaking after the protocol list's opening
4633 // angle bracket, if present).
4634 if (Line.Type == LT_ObjCDecl && Left.is(Kind: tok::l_paren) && Left.Previous &&
4635 Left.Previous->isOneOf(K1: tok::identifier, K2: tok::greater)) {
4636 return 500;
4637 }
4638
4639 if (Left.is(Kind: tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
4640 return Style.PenaltyBreakOpenParenthesis;
4641 if (Left.is(Kind: tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
4642 return 100;
4643 if (Left.is(Kind: tok::l_paren) && Left.Previous &&
4644 (Left.Previous->isOneOf(K1: tok::kw_for, K2: tok::kw__Generic) ||
4645 Left.Previous->isIf())) {
4646 return 1000;
4647 }
4648 if (Left.is(Kind: tok::equal) && InFunctionDecl)
4649 return 110;
4650 if (Right.is(Kind: tok::r_brace))
4651 return 1;
4652 if (Left.is(TT: TT_TemplateOpener))
4653 return 100;
4654 if (Left.opensScope()) {
4655 // If we aren't aligning after opening parens/braces we can always break
4656 // here unless the style does not want us to place all arguments on the
4657 // next line.
4658 if (!Style.AlignAfterOpenBracket &&
4659 (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) {
4660 return 0;
4661 }
4662 if (Left.is(Kind: tok::l_brace) &&
4663 Style.Cpp11BracedListStyle == FormatStyle::BLS_Block) {
4664 return 19;
4665 }
4666 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
4667 : 19;
4668 }
4669 if (Left.is(TT: TT_JavaAnnotation))
4670 return 50;
4671
4672 if (Left.is(TT: TT_UnaryOperator))
4673 return 60;
4674 if (Left.isOneOf(K1: tok::plus, K2: tok::comma) && Left.Previous &&
4675 Left.Previous->isLabelString() &&
4676 (Left.NextOperator || Left.OperatorIndex != 0)) {
4677 return 50;
4678 }
4679 if (Right.is(Kind: tok::plus) && Left.isLabelString() &&
4680 (Right.NextOperator || Right.OperatorIndex != 0)) {
4681 return 25;
4682 }
4683 if (Left.is(Kind: tok::comma))
4684 return 1;
4685 if (Right.is(Kind: tok::lessless) && Left.isLabelString() &&
4686 (Right.NextOperator || Right.OperatorIndex != 1)) {
4687 return 25;
4688 }
4689 if (Right.is(Kind: tok::lessless)) {
4690 // Breaking at a << is really cheap.
4691 if (Left.isNot(Kind: tok::r_paren) || Right.OperatorIndex > 0) {
4692 // Slightly prefer to break before the first one in log-like statements.
4693 return 2;
4694 }
4695 return 1;
4696 }
4697 if (Left.ClosesTemplateDeclaration)
4698 return Style.PenaltyBreakTemplateDeclaration;
4699 if (Left.ClosesRequiresClause)
4700 return 0;
4701 if (Left.is(TT: TT_ConditionalExpr))
4702 return prec::Conditional;
4703 prec::Level Level = Left.getPrecedence();
4704 if (Level == prec::Unknown)
4705 Level = Right.getPrecedence();
4706 if (Level == prec::Assignment)
4707 return Style.PenaltyBreakAssignment;
4708 if (Level != prec::Unknown)
4709 return Level;
4710
4711 return 3;
4712}
4713
4714bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
4715 if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always)
4716 return true;
4717 if (Right.is(TT: TT_OverloadedOperatorLParen) &&
4718 Style.SpaceBeforeParensOptions.AfterOverloadedOperator) {
4719 return true;
4720 }
4721 if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses &&
4722 Right.ParameterCount > 0) {
4723 return true;
4724 }
4725 return false;
4726}
4727
4728bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
4729 const FormatToken &Left,
4730 const FormatToken &Right) const {
4731 if (Left.is(Kind: tok::kw_return) &&
4732 Right.isNoneOf(Ks: tok::semi, Ks: tok::r_paren, Ks: tok::hashhash)) {
4733 return true;
4734 }
4735 if (Left.is(Kind: tok::kw_throw) && Right.is(Kind: tok::l_paren) && Right.MatchingParen &&
4736 Right.MatchingParen->is(TT: TT_CastRParen)) {
4737 return true;
4738 }
4739 if (Left.is(II: Keywords.kw_assert) && Style.isJava())
4740 return true;
4741 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
4742 Left.is(Kind: tok::objc_property)) {
4743 return true;
4744 }
4745 if (Right.is(Kind: tok::hashhash))
4746 return Left.is(Kind: tok::hash);
4747 if (Left.isOneOf(K1: tok::hashhash, K2: tok::hash))
4748 return Right.is(Kind: tok::hash);
4749 if (Style.SpacesInParens == FormatStyle::SIPO_Custom) {
4750 if (Left.is(Kind: tok::l_paren) && Right.is(Kind: tok::r_paren))
4751 return Style.SpacesInParensOptions.InEmptyParentheses;
4752 if (Style.SpacesInParensOptions.ExceptDoubleParentheses &&
4753 Left.is(Kind: tok::r_paren) && Right.is(Kind: tok::r_paren)) {
4754 auto *InnerLParen = Left.MatchingParen;
4755 if (InnerLParen && InnerLParen->Previous == Right.MatchingParen) {
4756 InnerLParen->SpacesRequiredBefore = 0;
4757 return false;
4758 }
4759 }
4760 const FormatToken *LeftParen = nullptr;
4761 if (Left.is(Kind: tok::l_paren))
4762 LeftParen = &Left;
4763 else if (Right.is(Kind: tok::r_paren) && Right.MatchingParen)
4764 LeftParen = Right.MatchingParen;
4765 if (LeftParen && (LeftParen->is(TT: TT_ConditionLParen) ||
4766 (LeftParen->Previous &&
4767 isKeywordWithCondition(Tok: *LeftParen->Previous)))) {
4768 return Style.SpacesInParensOptions.InConditionalStatements;
4769 }
4770 }
4771
4772 // trailing return type 'auto': []() -> auto {}, auto foo() -> auto {}
4773 if (Left.is(Kind: tok::kw_auto) && Right.isOneOf(K1: TT_LambdaLBrace, K2: TT_FunctionLBrace,
4774 // function return type 'auto'
4775 Ks: TT_FunctionTypeLParen)) {
4776 return true;
4777 }
4778
4779 // auto{x} auto(x)
4780 if (Left.is(Kind: tok::kw_auto) && Right.isOneOf(K1: tok::l_paren, K2: tok::l_brace))
4781 return false;
4782
4783 const auto *BeforeLeft = Left.Previous;
4784
4785 // operator co_await(x)
4786 if (Right.is(Kind: tok::l_paren) && Left.is(Kind: tok::kw_co_await) && BeforeLeft &&
4787 BeforeLeft->is(Kind: tok::kw_operator)) {
4788 return false;
4789 }
4790 // co_await (x), co_yield (x), co_return (x)
4791 if (Left.isOneOf(K1: tok::kw_co_await, K2: tok::kw_co_yield, Ks: tok::kw_co_return) &&
4792 Right.isNoneOf(Ks: tok::semi, Ks: tok::r_paren)) {
4793 return true;
4794 }
4795
4796 if (Left.is(Kind: tok::l_paren) || Right.is(Kind: tok::r_paren)) {
4797 return (Right.is(TT: TT_CastRParen) ||
4798 (Left.MatchingParen && Left.MatchingParen->is(TT: TT_CastRParen)))
4799 ? Style.SpacesInParensOptions.InCStyleCasts
4800 : Style.SpacesInParensOptions.Other;
4801 }
4802 if (Right.isOneOf(K1: tok::semi, K2: tok::comma))
4803 return false;
4804 if (Right.is(Kind: tok::less) && Line.Type == LT_ObjCDecl) {
4805 bool IsLightweightGeneric = Right.MatchingParen &&
4806 Right.MatchingParen->Next &&
4807 Right.MatchingParen->Next->is(Kind: tok::colon);
4808 return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
4809 }
4810 if (Right.is(Kind: tok::less) && Left.is(Kind: tok::kw_template))
4811 return Style.SpaceAfterTemplateKeyword;
4812 if (Left.isOneOf(K1: tok::exclaim, K2: tok::tilde))
4813 return false;
4814 if (Left.is(Kind: tok::at) &&
4815 Right.isOneOf(K1: tok::identifier, K2: tok::string_literal, Ks: tok::char_constant,
4816 Ks: tok::numeric_constant, Ks: tok::l_paren, Ks: tok::l_brace,
4817 Ks: tok::kw_true, Ks: tok::kw_false)) {
4818 return false;
4819 }
4820 if (Left.is(Kind: tok::colon))
4821 return Left.isNoneOf(Ks: TT_ObjCSelector, Ks: TT_ObjCMethodExpr);
4822 if (Left.is(Kind: tok::coloncolon))
4823 return false;
4824 if (Left.is(Kind: tok::less) || Right.isOneOf(K1: tok::greater, K2: tok::less)) {
4825 if (Style.isTextProto() ||
4826 (Style.Language == FormatStyle::LK_Proto &&
4827 (Left.is(TT: TT_DictLiteral) || Right.is(TT: TT_DictLiteral)))) {
4828 // Format empty list as `<>`.
4829 if (Left.is(Kind: tok::less) && Right.is(Kind: tok::greater))
4830 return false;
4831 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
4832 }
4833 // Don't attempt to format operator<(), as it is handled later.
4834 if (Right.isNot(Kind: TT_OverloadedOperatorLParen))
4835 return false;
4836 }
4837 if (Right.is(Kind: tok::ellipsis)) {
4838 return Left.Tok.isLiteral() || (Left.is(Kind: tok::identifier) && BeforeLeft &&
4839 BeforeLeft->is(Kind: tok::kw_case));
4840 }
4841 if (Left.is(Kind: tok::l_square) && Right.is(Kind: tok::amp))
4842 return Style.SpacesInSquareBrackets;
4843 if (Right.is(TT: TT_PointerOrReference)) {
4844 if (Left.is(Kind: tok::r_paren) && Line.MightBeFunctionDecl) {
4845 if (!Left.MatchingParen)
4846 return true;
4847 FormatToken *TokenBeforeMatchingParen =
4848 Left.MatchingParen->getPreviousNonComment();
4849 if (!TokenBeforeMatchingParen || Left.isNot(Kind: TT_TypeDeclarationParen))
4850 return true;
4851 }
4852 // Add a space if the previous token is a pointer qualifier or the closing
4853 // parenthesis of __attribute__(()) expression and the style requires spaces
4854 // after pointer qualifiers.
4855 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After ||
4856 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
4857 (Left.is(TT: TT_AttributeRParen) ||
4858 Left.canBePointerOrReferenceQualifier())) {
4859 return true;
4860 }
4861 if (Left.Tok.isLiteral())
4862 return true;
4863 // for (auto a = 0, b = 0; const auto & c : {1, 2, 3})
4864 if (Left.isTypeOrIdentifier(LangOpts) && Right.Next && Right.Next->Next &&
4865 Right.Next->Next->is(TT: TT_RangeBasedForLoopColon)) {
4866 return getTokenPointerOrReferenceAlignment(PointerOrReference: Right) !=
4867 FormatStyle::PAS_Left;
4868 }
4869 return Left.isNoneOf(Ks: TT_PointerOrReference, Ks: tok::l_paren) &&
4870 (getTokenPointerOrReferenceAlignment(PointerOrReference: Right) !=
4871 FormatStyle::PAS_Left ||
4872 (Line.IsMultiVariableDeclStmt &&
4873 (Left.NestingLevel == 0 ||
4874 (Left.NestingLevel == 1 && startsWithInitStatement(Line)))));
4875 }
4876 if (Right.is(TT: TT_FunctionTypeLParen) && Left.isNot(Kind: tok::l_paren) &&
4877 (Left.isNot(Kind: TT_PointerOrReference) ||
4878 (getTokenPointerOrReferenceAlignment(PointerOrReference: Left) != FormatStyle::PAS_Right &&
4879 !Line.IsMultiVariableDeclStmt))) {
4880 return true;
4881 }
4882 if (Left.is(TT: TT_PointerOrReference)) {
4883 // Add a space if the next token is a pointer qualifier and the style
4884 // requires spaces before pointer qualifiers.
4885 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before ||
4886 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
4887 Right.canBePointerOrReferenceQualifier()) {
4888 return true;
4889 }
4890 // & 1
4891 if (Right.Tok.isLiteral())
4892 return true;
4893 // & /* comment
4894 if (Right.is(TT: TT_BlockComment))
4895 return true;
4896 // foo() -> const Bar * override/final
4897 // S::foo() & noexcept/requires
4898 if (Right.isOneOf(K1: Keywords.kw_override, K2: Keywords.kw_final, Ks: tok::kw_noexcept,
4899 Ks: TT_RequiresClause) &&
4900 Right.isNot(Kind: TT_StartOfName)) {
4901 return true;
4902 }
4903 // & {
4904 if (Right.is(Kind: tok::l_brace) && Right.is(BBK: BK_Block))
4905 return true;
4906 // for (auto a = 0, b = 0; const auto& c : {1, 2, 3})
4907 if (BeforeLeft && BeforeLeft->isTypeOrIdentifier(LangOpts) && Right.Next &&
4908 Right.Next->is(TT: TT_RangeBasedForLoopColon)) {
4909 return getTokenPointerOrReferenceAlignment(PointerOrReference: Left) !=
4910 FormatStyle::PAS_Right;
4911 }
4912 if (Right.isOneOf(K1: TT_PointerOrReference, K2: TT_ArraySubscriptLSquare,
4913 Ks: tok::l_paren)) {
4914 return false;
4915 }
4916 if (getTokenPointerOrReferenceAlignment(PointerOrReference: Left) == FormatStyle::PAS_Right)
4917 return false;
4918 // FIXME: Setting IsMultiVariableDeclStmt for the whole line is error-prone,
4919 // because it does not take into account nested scopes like lambdas.
4920 // In multi-variable declaration statements, attach */& to the variable
4921 // independently of the style. However, avoid doing it if we are in a nested
4922 // scope, e.g. lambda. We still need to special-case statements with
4923 // initializers.
4924 if (Line.IsMultiVariableDeclStmt &&
4925 (Left.NestingLevel == Line.First->NestingLevel ||
4926 ((Left.NestingLevel == Line.First->NestingLevel + 1) &&
4927 startsWithInitStatement(Line)))) {
4928 return false;
4929 }
4930 if (!BeforeLeft)
4931 return false;
4932 if (BeforeLeft->is(Kind: tok::coloncolon)) {
4933 if (Left.isNot(Kind: tok::star))
4934 return false;
4935 assert(Style.PointerAlignment != FormatStyle::PAS_Right);
4936 if (!Right.startsSequence(K1: tok::identifier, Tokens: tok::r_paren))
4937 return true;
4938 assert(Right.Next);
4939 const auto *LParen = Right.Next->MatchingParen;
4940 return !LParen || LParen->isNot(Kind: TT_FunctionTypeLParen);
4941 }
4942 return BeforeLeft->isNoneOf(Ks: tok::l_paren, Ks: tok::l_square);
4943 }
4944 // Ensure right pointer alignment with ellipsis e.g. int *...P
4945 if (Left.is(Kind: tok::ellipsis) && BeforeLeft &&
4946 BeforeLeft->isPointerOrReference()) {
4947 return Style.PointerAlignment != FormatStyle::PAS_Right;
4948 }
4949
4950 if (Right.is(Kind: tok::star) && Left.is(Kind: tok::l_paren))
4951 return false;
4952 if (Left.is(Kind: tok::star) && Right.isPointerOrReference())
4953 return false;
4954 if (Right.isPointerOrReference()) {
4955 const FormatToken *Previous = &Left;
4956 while (Previous && Previous->isNot(Kind: tok::kw_operator)) {
4957 if (Previous->is(Kind: tok::identifier) || Previous->isTypeName(LangOpts)) {
4958 Previous = Previous->getPreviousNonComment();
4959 continue;
4960 }
4961 if (Previous->is(TT: TT_TemplateCloser) && Previous->MatchingParen) {
4962 Previous = Previous->MatchingParen->getPreviousNonComment();
4963 continue;
4964 }
4965 if (Previous->is(Kind: tok::coloncolon)) {
4966 Previous = Previous->getPreviousNonComment();
4967 continue;
4968 }
4969 break;
4970 }
4971 // Space between the type and the * in:
4972 // operator void*()
4973 // operator char*()
4974 // operator void const*()
4975 // operator void volatile*()
4976 // operator /*comment*/ const char*()
4977 // operator volatile /*comment*/ char*()
4978 // operator Foo*()
4979 // operator C<T>*()
4980 // operator std::Foo*()
4981 // operator C<T>::D<U>*()
4982 // dependent on PointerAlignment style.
4983 if (Previous) {
4984 if (Previous->endsSequence(K1: tok::kw_operator))
4985 return Style.PointerAlignment != FormatStyle::PAS_Left;
4986 if (Previous->isOneOf(K1: tok::kw_const, K2: tok::kw_volatile)) {
4987 return (Style.PointerAlignment != FormatStyle::PAS_Left) ||
4988 (Style.SpaceAroundPointerQualifiers ==
4989 FormatStyle::SAPQ_After) ||
4990 (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both);
4991 }
4992 }
4993 }
4994 if (Style.isCSharp() && Left.is(II: Keywords.kw_is) && Right.is(Kind: tok::l_square))
4995 return true;
4996 const auto SpaceRequiredForArrayInitializerLSquare =
4997 [](const FormatToken &LSquareTok, const FormatStyle &Style) {
4998 return Style.SpacesInContainerLiterals ||
4999 (Style.isProto() &&
5000 Style.Cpp11BracedListStyle == FormatStyle::BLS_Block &&
5001 LSquareTok.endsSequence(K1: tok::l_square, Tokens: tok::colon,
5002 Tokens: TT_SelectorName));
5003 };
5004 if (Left.is(Kind: tok::l_square)) {
5005 return (Left.is(TT: TT_ArrayInitializerLSquare) && Right.isNot(Kind: tok::r_square) &&
5006 SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
5007 (Left.isOneOf(K1: TT_ArraySubscriptLSquare, K2: TT_StructuredBindingLSquare,
5008 Ks: TT_LambdaLSquare) &&
5009 Style.SpacesInSquareBrackets && Right.isNot(Kind: tok::r_square));
5010 }
5011 if (Right.is(Kind: tok::r_square)) {
5012 return Right.MatchingParen &&
5013 ((Right.MatchingParen->is(TT: TT_ArrayInitializerLSquare) &&
5014 SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
5015 Style)) ||
5016 (Style.SpacesInSquareBrackets &&
5017 Right.MatchingParen->isOneOf(K1: TT_ArraySubscriptLSquare,
5018 K2: TT_StructuredBindingLSquare,
5019 Ks: TT_LambdaLSquare)));
5020 }
5021 if (Right.is(Kind: tok::l_square) &&
5022 Right.isNoneOf(Ks: TT_ObjCMethodExpr, Ks: TT_LambdaLSquare,
5023 Ks: TT_DesignatedInitializerLSquare,
5024 Ks: TT_StructuredBindingLSquare, Ks: TT_AttributeLSquare) &&
5025 Left.isNoneOf(Ks: tok::numeric_constant, Ks: TT_DictLiteral) &&
5026 !(Left.isNot(Kind: tok::r_square) && Style.SpaceBeforeSquareBrackets &&
5027 Right.is(TT: TT_ArraySubscriptLSquare))) {
5028 return false;
5029 }
5030 if ((Left.is(Kind: tok::l_brace) && Left.isNot(Kind: BK_Block)) ||
5031 (Right.is(Kind: tok::r_brace) && Right.MatchingParen &&
5032 Right.MatchingParen->isNot(Kind: BK_Block))) {
5033 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block ||
5034 Style.SpacesInParensOptions.Other;
5035 }
5036 if (Left.is(TT: TT_BlockComment)) {
5037 // No whitespace in x(/*foo=*/1), except for JavaScript.
5038 return Style.isJavaScript() || !Left.TokenText.ends_with(Suffix: "=*/");
5039 }
5040
5041 // Space between template and attribute.
5042 // e.g. template <typename T> [[nodiscard]] ...
5043 if (Left.is(TT: TT_TemplateCloser) && Right.is(TT: TT_AttributeLSquare))
5044 return true;
5045 // Space before parentheses common for all languages
5046 if (Right.is(Kind: tok::l_paren)) {
5047 // Function declaration or definition
5048 if (Line.MightBeFunctionDecl && Right.is(TT: TT_FunctionDeclarationLParen)) {
5049 if (spaceRequiredBeforeParens(Right))
5050 return true;
5051 const auto &Options = Style.SpaceBeforeParensOptions;
5052 return Line.mightBeFunctionDefinition()
5053 ? Options.AfterFunctionDefinitionName
5054 : Options.AfterFunctionDeclarationName;
5055 }
5056 if (Left.is(TT: TT_TemplateCloser) && Right.isNot(Kind: TT_FunctionTypeLParen))
5057 return spaceRequiredBeforeParens(Right);
5058 if (Left.isOneOf(K1: TT_RequiresClause,
5059 K2: TT_RequiresClauseInARequiresExpression)) {
5060 return Style.SpaceBeforeParensOptions.AfterRequiresInClause ||
5061 spaceRequiredBeforeParens(Right);
5062 }
5063 if (Left.is(TT: TT_RequiresExpression)) {
5064 return Style.SpaceBeforeParensOptions.AfterRequiresInExpression ||
5065 spaceRequiredBeforeParens(Right);
5066 }
5067 if (Left.isOneOf(K1: TT_AttributeRParen, K2: TT_AttributeRSquare))
5068 return true;
5069 if (Left.is(TT: TT_ForEachMacro)) {
5070 return Style.SpaceBeforeParensOptions.AfterForeachMacros ||
5071 spaceRequiredBeforeParens(Right);
5072 }
5073 if (Left.is(TT: TT_IfMacro)) {
5074 return Style.SpaceBeforeParensOptions.AfterIfMacros ||
5075 spaceRequiredBeforeParens(Right);
5076 }
5077 if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
5078 Left.isPlacementOperator() &&
5079 Right.isNot(Kind: TT_OverloadedOperatorLParen) &&
5080 !(Line.MightBeFunctionDecl && Left.is(TT: TT_FunctionDeclarationName))) {
5081 const auto *RParen = Right.MatchingParen;
5082 return Style.SpaceBeforeParensOptions.AfterPlacementOperator ||
5083 (RParen && RParen->is(TT: TT_CastRParen));
5084 }
5085 if (Line.Type == LT_ObjCDecl)
5086 return true;
5087 if (Left.is(Kind: tok::semi))
5088 return true;
5089 if (Left.isOneOf(K1: tok::pp_elif, K2: tok::kw_for, Ks: tok::kw_while, Ks: tok::kw_switch,
5090 Ks: tok::kw_case, Ks: TT_ForEachMacro, Ks: TT_ObjCForIn) ||
5091 Left.isIf(AllowConstexprMacro: Line.Type != LT_PreprocessorDirective) ||
5092 Right.is(TT: TT_ConditionLParen)) {
5093 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5094 spaceRequiredBeforeParens(Right);
5095 }
5096
5097 // TODO add Operator overloading specific Options to
5098 // SpaceBeforeParensOptions
5099 if (Right.is(TT: TT_OverloadedOperatorLParen))
5100 return spaceRequiredBeforeParens(Right);
5101
5102 // Lambda
5103 if (Line.Type != LT_PreprocessorDirective && Left.is(Kind: tok::r_square) &&
5104 Left.MatchingParen && Left.MatchingParen->is(TT: TT_LambdaLSquare)) {
5105 return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
5106 spaceRequiredBeforeParens(Right);
5107 }
5108 if (!BeforeLeft || BeforeLeft->isNoneOf(Ks: tok::period, Ks: tok::arrow)) {
5109 if (Left.isOneOf(K1: tok::kw_try, K2: Keywords.kw___except, Ks: tok::kw_catch)) {
5110 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5111 spaceRequiredBeforeParens(Right);
5112 }
5113 if (Left.isPlacementOperator() ||
5114 (Left.is(Kind: tok::r_square) && Left.MatchingParen &&
5115 Left.MatchingParen->Previous &&
5116 Left.MatchingParen->Previous->is(Kind: tok::kw_delete))) {
5117 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
5118 spaceRequiredBeforeParens(Right);
5119 }
5120 }
5121 auto CompoundLiteral = [](const FormatToken &Tok) {
5122 if (Tok.isNot(Kind: tok::l_paren))
5123 return false;
5124 const auto *RParen = Tok.MatchingParen;
5125 if (!RParen)
5126 return false;
5127 const auto *Next = RParen->Next;
5128 return Next && Next->is(Kind: tok::l_brace) && Next->is(BBK: BK_BracedInit);
5129 };
5130 if (Left.is(Kind: tok::kw_sizeof) && CompoundLiteral(Right))
5131 return true;
5132 // Handle builtins like identifiers.
5133 if (Line.Type != LT_PreprocessorDirective &&
5134 (Left.Tok.getIdentifierInfo() || Left.is(Kind: tok::r_paren))) {
5135 return spaceRequiredBeforeParens(Right);
5136 }
5137 return false;
5138 }
5139 if (Left.is(Kind: tok::at) && Right.isNot(Kind: tok::objc_not_keyword))
5140 return false;
5141 if (Right.is(TT: TT_UnaryOperator)) {
5142 return Left.isNoneOf(Ks: tok::l_paren, Ks: tok::l_square, Ks: tok::at) &&
5143 (Left.isNot(Kind: tok::colon) || Left.isNot(Kind: TT_ObjCMethodExpr));
5144 }
5145 // No space between the variable name and the initializer list.
5146 // A a1{1};
5147 // Verilog doesn't have such syntax, but it has word operators that are C++
5148 // identifiers like `a inside {b, c}`. So the rule is not applicable.
5149 if (!Style.isVerilog() &&
5150 (Left.isOneOf(K1: tok::identifier, K2: tok::greater, Ks: tok::r_square,
5151 Ks: tok::r_paren) ||
5152 Left.isTypeName(LangOpts)) &&
5153 Right.is(Kind: tok::l_brace) && Right.getNextNonComment() &&
5154 Right.isNot(Kind: BK_Block)) {
5155 return false;
5156 }
5157 if (Left.is(Kind: tok::period) || Right.is(Kind: tok::period))
5158 return false;
5159 // u#str, U#str, L#str, u8#str
5160 // uR#str, UR#str, LR#str, u8R#str
5161 if (Right.is(Kind: tok::hash) && Left.is(Kind: tok::identifier) &&
5162 (Left.TokenText == "L" || Left.TokenText == "u" ||
5163 Left.TokenText == "U" || Left.TokenText == "u8" ||
5164 Left.TokenText == "LR" || Left.TokenText == "uR" ||
5165 Left.TokenText == "UR" || Left.TokenText == "u8R")) {
5166 return false;
5167 }
5168 if (Left.is(TT: TT_TemplateCloser) && Left.MatchingParen &&
5169 Left.MatchingParen->Previous &&
5170 Left.MatchingParen->Previous->isOneOf(K1: tok::period, K2: tok::coloncolon)) {
5171 // Java call to generic function with explicit type:
5172 // A.<B<C<...>>>DoSomething();
5173 // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference.
5174 return false;
5175 }
5176 if (Left.is(TT: TT_TemplateCloser) && Right.is(Kind: tok::l_square))
5177 return false;
5178 if (Left.is(Kind: tok::l_brace) && Left.endsSequence(K1: TT_DictLiteral, Tokens: tok::at)) {
5179 // Objective-C dictionary literal -> no space after opening brace.
5180 return false;
5181 }
5182 if (Right.is(Kind: tok::r_brace) && Right.MatchingParen &&
5183 Right.MatchingParen->endsSequence(K1: TT_DictLiteral, Tokens: tok::at)) {
5184 // Objective-C dictionary literal -> no space before closing brace.
5185 return false;
5186 }
5187 if (Right.is(TT: TT_TrailingAnnotation) && Right.isOneOf(K1: tok::amp, K2: tok::ampamp) &&
5188 Left.isOneOf(K1: tok::kw_const, K2: tok::kw_volatile) &&
5189 (!Right.Next || Right.Next->is(Kind: tok::semi))) {
5190 // Match const and volatile ref-qualifiers without any additional
5191 // qualifiers such as
5192 // void Fn() const &;
5193 return getTokenReferenceAlignment(PointerOrReference: Right) != FormatStyle::PAS_Left;
5194 }
5195
5196 return true;
5197}
5198
5199bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
5200 const FormatToken &Right) const {
5201 const FormatToken &Left = *Right.Previous;
5202
5203 // If the token is finalized don't touch it (as it could be in a
5204 // clang-format-off section).
5205 if (Left.Finalized)
5206 return Right.hasWhitespaceBefore();
5207
5208 const bool IsVerilog = Style.isVerilog();
5209 assert(!IsVerilog || !IsCpp);
5210
5211 // Never ever merge two words.
5212 if (Keywords.isWordLike(Tok: Right, IsVerilog) &&
5213 Keywords.isWordLike(Tok: Left, IsVerilog)) {
5214 return true;
5215 }
5216
5217 // Leave a space between * and /* to avoid C4138 `comment end` found outside
5218 // of comment.
5219 if (Left.is(Kind: tok::star) && Right.is(Kind: tok::comment))
5220 return true;
5221
5222 if (Left.is(Kind: tok::l_brace) && Right.is(Kind: tok::r_brace) &&
5223 Left.Children.empty()) {
5224 if (Left.is(BBK: BK_Block))
5225 return Style.SpaceInEmptyBraces != FormatStyle::SIEB_Never;
5226 if (Style.Cpp11BracedListStyle != FormatStyle::BLS_Block) {
5227 return Style.SpacesInParens == FormatStyle::SIPO_Custom &&
5228 Style.SpacesInParensOptions.InEmptyParentheses;
5229 }
5230 return Style.SpaceInEmptyBraces == FormatStyle::SIEB_Always;
5231 }
5232
5233 const auto *BeforeLeft = Left.Previous;
5234
5235 if (IsCpp) {
5236 if (Left.is(TT: TT_OverloadedOperator) &&
5237 Right.isOneOf(K1: TT_TemplateOpener, K2: TT_TemplateCloser)) {
5238 return true;
5239 }
5240 // Space between UDL and dot: auto b = 4s .count();
5241 if (Right.is(Kind: tok::period) && Left.is(Kind: tok::numeric_constant))
5242 return true;
5243 // Space between import <iostream>.
5244 // or import .....;
5245 if (Left.is(II: Keywords.kw_import) &&
5246 Right.isOneOf(K1: tok::less, K2: tok::ellipsis) &&
5247 (!BeforeLeft || BeforeLeft->is(Kind: tok::kw_export))) {
5248 return true;
5249 }
5250 // Space between `import :`.
5251 if (Left.is(II: Keywords.kw_import) && Right.is(TT: TT_ModulePartitionColon))
5252 return true;
5253
5254 if (Right.is(TT: TT_AfterPPDirective))
5255 return true;
5256
5257 // No space between `module foo:bar`.
5258 if (Left.is(Kind: tok::identifier) && Right.is(TT: TT_ModulePartitionColon))
5259 return false;
5260 // No space between :bar;
5261 if (Left.is(TT: TT_ModulePartitionColon) && Right.is(Kind: tok::identifier))
5262 return false;
5263 if (Left.is(Kind: tok::ellipsis) && Right.is(Kind: tok::identifier) &&
5264 Line.First->is(II: Keywords.kw_import)) {
5265 return false;
5266 }
5267 // Space in __attribute__((attr)) ::type.
5268 if (Left.isOneOf(K1: TT_AttributeRParen, K2: TT_AttributeMacro) &&
5269 Right.is(Kind: tok::coloncolon)) {
5270 return true;
5271 }
5272
5273 if (Left.is(Kind: tok::kw_operator))
5274 return Right.is(Kind: tok::coloncolon) || Style.SpaceAfterOperatorKeyword;
5275 if (Right.is(Kind: tok::l_brace) && Right.is(BBK: BK_BracedInit) &&
5276 !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) {
5277 return true;
5278 }
5279 if (Left.is(Kind: tok::less) && Left.is(TT: TT_OverloadedOperator) &&
5280 Right.is(TT: TT_TemplateOpener)) {
5281 return true;
5282 }
5283 // C++ Core Guidelines suppression tag, e.g. `[[suppress(type.5)]]`.
5284 if (Left.is(Kind: tok::identifier) && Right.is(Kind: tok::numeric_constant))
5285 return Right.TokenText[0] != '.';
5286 // `Left` is a keyword (including C++ alternative operator) or identifier.
5287 if (Left.Tok.getIdentifierInfo() && Right.Tok.isLiteral())
5288 return true;
5289 } else if (Style.isProto()) {
5290 if (Right.is(Kind: tok::period) && !(BeforeLeft && BeforeLeft->is(Kind: tok::period)) &&
5291 Left.isOneOf(K1: Keywords.kw_optional, K2: Keywords.kw_required,
5292 Ks: Keywords.kw_repeated, Ks: Keywords.kw_extend)) {
5293 return true;
5294 }
5295 if (Right.is(Kind: tok::l_paren) &&
5296 Left.isOneOf(K1: Keywords.kw_returns, K2: Keywords.kw_option)) {
5297 return true;
5298 }
5299 if (Right.isOneOf(K1: tok::l_brace, K2: tok::less) && Left.is(TT: TT_SelectorName))
5300 return true;
5301 // Slashes occur in text protocol extension syntax: [type/type] { ... }.
5302 if (Left.is(Kind: tok::slash) || Right.is(Kind: tok::slash))
5303 return false;
5304 if (Left.MatchingParen &&
5305 Left.MatchingParen->is(TT: TT_ProtoExtensionLSquare) &&
5306 Right.isOneOf(K1: tok::l_brace, K2: tok::less)) {
5307 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
5308 }
5309 // A percent is probably part of a formatting specification, such as %lld.
5310 if (Left.is(Kind: tok::percent))
5311 return false;
5312 // Preserve the existence of a space before a percent for cases like 0x%04x
5313 // and "%d %d"
5314 if (Left.is(Kind: tok::numeric_constant) && Right.is(Kind: tok::percent))
5315 return Right.hasWhitespaceBefore();
5316 } else if (Style.isJson()) {
5317 if (Right.is(Kind: tok::colon) && Left.is(Kind: tok::string_literal))
5318 return Style.SpaceBeforeJsonColon;
5319 } else if (Style.isCSharp()) {
5320 // Require spaces around '{' and before '}' unless they appear in
5321 // interpolated strings. Interpolated strings are merged into a single token
5322 // so cannot have spaces inserted by this function.
5323
5324 // No space between 'this' and '['
5325 if (Left.is(Kind: tok::kw_this) && Right.is(Kind: tok::l_square))
5326 return false;
5327
5328 // No space between 'new' and '('
5329 if (Left.is(Kind: tok::kw_new) && Right.is(Kind: tok::l_paren))
5330 return false;
5331
5332 // Space before { (including space within '{ {').
5333 if (Right.is(Kind: tok::l_brace))
5334 return true;
5335
5336 // Spaces inside braces.
5337 if (Left.is(Kind: tok::l_brace) && Right.isNot(Kind: tok::r_brace))
5338 return true;
5339
5340 if (Left.isNot(Kind: tok::l_brace) && Right.is(Kind: tok::r_brace))
5341 return true;
5342
5343 // Spaces around '=>'.
5344 if (Left.is(TT: TT_FatArrow) || Right.is(TT: TT_FatArrow))
5345 return true;
5346
5347 // No spaces around attribute target colons
5348 if (Left.is(TT: TT_AttributeColon) || Right.is(TT: TT_AttributeColon))
5349 return false;
5350
5351 // space between type and variable e.g. Dictionary<string,string> foo;
5352 if (Left.is(TT: TT_TemplateCloser) && Right.is(TT: TT_StartOfName))
5353 return true;
5354
5355 // spaces inside square brackets.
5356 if (Left.is(Kind: tok::l_square) || Right.is(Kind: tok::r_square))
5357 return Style.SpacesInSquareBrackets;
5358
5359 // No space before ? in nullable types.
5360 if (Right.is(TT: TT_CSharpNullable))
5361 return false;
5362
5363 // No space before null forgiving '!'.
5364 if (Right.is(TT: TT_NonNullAssertion))
5365 return false;
5366
5367 // No space between consecutive commas '[,,]'.
5368 if (Left.is(Kind: tok::comma) && Right.is(Kind: tok::comma))
5369 return false;
5370
5371 // space after var in `var (key, value)`
5372 if (Left.is(II: Keywords.kw_var) && Right.is(Kind: tok::l_paren))
5373 return true;
5374
5375 // space between keywords and paren e.g. "using ("
5376 if (Right.is(Kind: tok::l_paren)) {
5377 if (Left.isOneOf(K1: tok::kw_using, K2: Keywords.kw_async, Ks: Keywords.kw_when,
5378 Ks: Keywords.kw_lock)) {
5379 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5380 spaceRequiredBeforeParens(Right);
5381 }
5382 }
5383
5384 // space between method modifier and opening parenthesis of a tuple return
5385 // type
5386 if ((Left.isAccessSpecifierKeyword() ||
5387 Left.isOneOf(K1: tok::kw_virtual, K2: tok::kw_extern, Ks: tok::kw_static,
5388 Ks: Keywords.kw_internal, Ks: Keywords.kw_abstract,
5389 Ks: Keywords.kw_sealed, Ks: Keywords.kw_override,
5390 Ks: Keywords.kw_async, Ks: Keywords.kw_unsafe)) &&
5391 Right.is(Kind: tok::l_paren)) {
5392 return true;
5393 }
5394 } else if (Style.isJavaScript()) {
5395 if (Left.is(TT: TT_FatArrow))
5396 return true;
5397 // for await ( ...
5398 if (Right.is(Kind: tok::l_paren) && Left.is(II: Keywords.kw_await) && BeforeLeft &&
5399 BeforeLeft->is(Kind: tok::kw_for)) {
5400 return true;
5401 }
5402 if (Left.is(II: Keywords.kw_async) && Right.is(Kind: tok::l_paren) &&
5403 Right.MatchingParen) {
5404 const FormatToken *Next = Right.MatchingParen->getNextNonComment();
5405 // An async arrow function, for example: `x = async () => foo();`,
5406 // as opposed to calling a function called async: `x = async();`
5407 if (Next && Next->is(TT: TT_FatArrow))
5408 return true;
5409 }
5410 if ((Left.is(TT: TT_TemplateString) && Left.TokenText.ends_with(Suffix: "${")) ||
5411 (Right.is(TT: TT_TemplateString) && Right.TokenText.starts_with(Prefix: "}"))) {
5412 return false;
5413 }
5414 // In tagged template literals ("html`bar baz`"), there is no space between
5415 // the tag identifier and the template string.
5416 if (Keywords.isJavaScriptIdentifier(Tok: Left,
5417 /* AcceptIdentifierName= */ false) &&
5418 Right.is(TT: TT_TemplateString)) {
5419 return false;
5420 }
5421 if (Right.is(Kind: tok::star) &&
5422 Left.isOneOf(K1: Keywords.kw_function, K2: Keywords.kw_yield)) {
5423 return false;
5424 }
5425 if (Right.isOneOf(K1: tok::l_brace, K2: tok::l_square) &&
5426 Left.isOneOf(K1: Keywords.kw_function, K2: Keywords.kw_yield,
5427 Ks: Keywords.kw_extends, Ks: Keywords.kw_implements)) {
5428 return true;
5429 }
5430 if (Right.is(Kind: tok::l_paren)) {
5431 // JS methods can use some keywords as names (e.g. `delete()`).
5432 if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
5433 return false;
5434 // Valid JS method names can include keywords, e.g. `foo.delete()` or
5435 // `bar.instanceof()`. Recognize call positions by preceding period.
5436 if (BeforeLeft && BeforeLeft->is(Kind: tok::period) &&
5437 Left.Tok.getIdentifierInfo()) {
5438 return false;
5439 }
5440 // Additional unary JavaScript operators that need a space after.
5441 if (Left.isOneOf(K1: tok::kw_throw, K2: Keywords.kw_await, Ks: Keywords.kw_typeof,
5442 Ks: tok::kw_void)) {
5443 return true;
5444 }
5445 }
5446 // `foo as const;` casts into a const type.
5447 if (Left.endsSequence(K1: tok::kw_const, Tokens: Keywords.kw_as))
5448 return false;
5449 if ((Left.isOneOf(K1: Keywords.kw_let, K2: Keywords.kw_var, Ks: Keywords.kw_in,
5450 Ks: tok::kw_const) ||
5451 // "of" is only a keyword if it appears after another identifier
5452 // (e.g. as "const x of y" in a for loop), or after a destructuring
5453 // operation (const [x, y] of z, const {a, b} of c).
5454 (Left.is(II: Keywords.kw_of) && BeforeLeft &&
5455 BeforeLeft->isOneOf(K1: tok::identifier, K2: tok::r_square, Ks: tok::r_brace))) &&
5456 (!BeforeLeft || BeforeLeft->isNot(Kind: tok::period))) {
5457 return true;
5458 }
5459 if (Left.isOneOf(K1: tok::kw_for, K2: Keywords.kw_as) && BeforeLeft &&
5460 BeforeLeft->is(Kind: tok::period) && Right.is(Kind: tok::l_paren)) {
5461 return false;
5462 }
5463 if (Left.is(II: Keywords.kw_as) &&
5464 Right.isOneOf(K1: tok::l_square, K2: tok::l_brace, Ks: tok::l_paren)) {
5465 return true;
5466 }
5467 if (Left.is(Kind: tok::kw_default) && BeforeLeft &&
5468 BeforeLeft->is(Kind: tok::kw_export)) {
5469 return true;
5470 }
5471 if (Left.is(II: Keywords.kw_is) && Right.is(Kind: tok::l_brace))
5472 return true;
5473 if (Right.isOneOf(K1: TT_JsTypeColon, K2: TT_JsTypeOptionalQuestion))
5474 return false;
5475 if (Left.is(TT: TT_JsTypeOperator) || Right.is(TT: TT_JsTypeOperator))
5476 return false;
5477 if ((Left.is(Kind: tok::l_brace) || Right.is(Kind: tok::r_brace)) &&
5478 Line.First->isOneOf(K1: Keywords.kw_import, K2: tok::kw_export)) {
5479 return false;
5480 }
5481 if (Left.is(Kind: tok::ellipsis))
5482 return false;
5483 if (Left.is(TT: TT_TemplateCloser) &&
5484 Right.isNoneOf(Ks: tok::equal, Ks: tok::l_brace, Ks: tok::comma, Ks: tok::l_square,
5485 Ks: Keywords.kw_implements, Ks: Keywords.kw_extends)) {
5486 // Type assertions ('<type>expr') are not followed by whitespace. Other
5487 // locations that should have whitespace following are identified by the
5488 // above set of follower tokens.
5489 return false;
5490 }
5491 if (Right.is(TT: TT_NonNullAssertion))
5492 return false;
5493 if (Left.is(TT: TT_NonNullAssertion) &&
5494 Right.isOneOf(K1: Keywords.kw_as, K2: Keywords.kw_in)) {
5495 return true; // "x! as string", "x! in y"
5496 }
5497 } else if (Style.isJava()) {
5498 if (Left.is(TT: TT_CaseLabelArrow) || Right.is(TT: TT_CaseLabelArrow))
5499 return true;
5500 if (Left.is(Kind: tok::r_square) && Right.is(Kind: tok::l_brace))
5501 return true;
5502 // spaces inside square brackets.
5503 if (Left.is(Kind: tok::l_square) || Right.is(Kind: tok::r_square))
5504 return Style.SpacesInSquareBrackets;
5505
5506 if (Left.is(II: Keywords.kw_synchronized) && Right.is(Kind: tok::l_paren)) {
5507 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5508 spaceRequiredBeforeParens(Right);
5509 }
5510 if ((Left.isAccessSpecifierKeyword() ||
5511 Left.isOneOf(K1: tok::kw_static, K2: Keywords.kw_final, Ks: Keywords.kw_abstract,
5512 Ks: Keywords.kw_native)) &&
5513 Right.is(TT: TT_TemplateOpener)) {
5514 return true;
5515 }
5516 } else if (IsVerilog) {
5517 // An escaped identifier ends with whitespace.
5518 if (Left.is(Kind: tok::identifier) && Left.TokenText[0] == '\\')
5519 return true;
5520 // Add space between things in a primitive's state table unless in a
5521 // transition like `(0?)`.
5522 if ((Left.is(TT: TT_VerilogTableItem) &&
5523 Right.isNoneOf(Ks: tok::r_paren, Ks: tok::semi)) ||
5524 (Right.is(TT: TT_VerilogTableItem) && Left.isNot(Kind: tok::l_paren))) {
5525 const FormatToken *Next = Right.getNextNonComment();
5526 return !(Next && Next->is(Kind: tok::r_paren));
5527 }
5528 // Don't add space within a delay like `#0`.
5529 if (Left.isNot(Kind: TT_BinaryOperator) &&
5530 Left.isOneOf(K1: Keywords.kw_verilogHash, K2: Keywords.kw_verilogHashHash)) {
5531 return false;
5532 }
5533 // Add space after a delay.
5534 if (Right.isNot(Kind: tok::semi) &&
5535 (Left.endsSequence(K1: tok::numeric_constant, Tokens: Keywords.kw_verilogHash) ||
5536 Left.endsSequence(K1: tok::numeric_constant,
5537 Tokens: Keywords.kw_verilogHashHash) ||
5538 (Left.is(Kind: tok::r_paren) && Left.MatchingParen &&
5539 Left.MatchingParen->endsSequence(K1: tok::l_paren, Tokens: tok::at)))) {
5540 return true;
5541 }
5542 // Don't add embedded spaces in a number literal like `16'h1?ax` or an array
5543 // literal like `'{}`.
5544 if (Left.is(II: Keywords.kw_apostrophe) ||
5545 (Left.is(TT: TT_VerilogNumberBase) && Right.is(Kind: tok::numeric_constant))) {
5546 return false;
5547 }
5548 // Add spaces around the implication operator `->`.
5549 if (Left.is(Kind: tok::arrow) || Right.is(Kind: tok::arrow))
5550 return true;
5551 // Don't add spaces between two at signs. Like in a coverage event.
5552 // Don't add spaces between at and a sensitivity list like
5553 // `@(posedge clk)`.
5554 if (Left.is(Kind: tok::at) && Right.isOneOf(K1: tok::l_paren, K2: tok::star, Ks: tok::at))
5555 return false;
5556 // Add space between the type name and dimension like `logic [1:0]`.
5557 if (Right.is(Kind: tok::l_square) &&
5558 Left.isOneOf(K1: TT_VerilogDimensionedTypeName, K2: Keywords.kw_function)) {
5559 return true;
5560 }
5561 // In a tagged union expression, there should be a space after the tag.
5562 if (Right.isOneOf(K1: tok::period, K2: Keywords.kw_apostrophe) &&
5563 Keywords.isVerilogIdentifier(Tok: Left) && Left.getPreviousNonComment() &&
5564 Left.getPreviousNonComment()->is(II: Keywords.kw_tagged)) {
5565 return true;
5566 }
5567 // Don't add spaces between a casting type and the quote or repetition count
5568 // and the brace. The case of tagged union expressions is handled by the
5569 // previous rule.
5570 if ((Right.is(II: Keywords.kw_apostrophe) ||
5571 (Right.is(BBK: BK_BracedInit) && Right.is(Kind: tok::l_brace))) &&
5572 Left.isNoneOf(Ks: Keywords.kw_assign, Ks: Keywords.kw_unique) &&
5573 !Keywords.isVerilogWordOperator(Tok: Left) &&
5574 (Left.isOneOf(K1: tok::r_square, K2: tok::r_paren, Ks: tok::r_brace,
5575 Ks: tok::numeric_constant) ||
5576 Keywords.isWordLike(Tok: Left))) {
5577 return false;
5578 }
5579 // Don't add spaces in imports like `import foo::*;`.
5580 if ((Right.is(Kind: tok::star) && Left.is(Kind: tok::coloncolon)) ||
5581 (Left.is(Kind: tok::star) && Right.is(Kind: tok::semi))) {
5582 return false;
5583 }
5584 // Add space in attribute like `(* ASYNC_REG = "TRUE" *)`.
5585 if (Left.endsSequence(K1: tok::star, Tokens: tok::l_paren) && Right.is(Kind: tok::identifier))
5586 return true;
5587 // Add space before drive strength like in `wire (strong1, pull0)`.
5588 if (Right.is(Kind: tok::l_paren) && Right.is(TT: TT_VerilogStrength))
5589 return true;
5590 // Don't add space in a streaming concatenation like `{>>{j}}`.
5591 if ((Left.is(Kind: tok::l_brace) &&
5592 Right.isOneOf(K1: tok::lessless, K2: tok::greatergreater)) ||
5593 (Left.endsSequence(K1: tok::lessless, Tokens: tok::l_brace) ||
5594 Left.endsSequence(K1: tok::greatergreater, Tokens: tok::l_brace))) {
5595 return false;
5596 }
5597 } else if (Style.isTableGen()) {
5598 // Avoid to connect [ and {. [{ is start token of multiline string.
5599 if (Left.is(Kind: tok::l_square) && Right.is(Kind: tok::l_brace))
5600 return true;
5601 if (Left.is(Kind: tok::r_brace) && Right.is(Kind: tok::r_square))
5602 return true;
5603 // Do not insert around colon in DAGArg and cond operator.
5604 if (Right.isOneOf(K1: TT_TableGenDAGArgListColon,
5605 K2: TT_TableGenDAGArgListColonToAlign) ||
5606 Left.isOneOf(K1: TT_TableGenDAGArgListColon,
5607 K2: TT_TableGenDAGArgListColonToAlign)) {
5608 return false;
5609 }
5610 if (Right.is(TT: TT_TableGenCondOperatorColon))
5611 return false;
5612 if (Left.isOneOf(K1: TT_TableGenDAGArgOperatorID,
5613 K2: TT_TableGenDAGArgOperatorToBreak) &&
5614 Right.isNot(Kind: TT_TableGenDAGArgCloser)) {
5615 return true;
5616 }
5617 // Do not insert bang operators and consequent openers.
5618 if (Right.isOneOf(K1: tok::l_paren, K2: tok::less) &&
5619 Left.isOneOf(K1: TT_TableGenBangOperator, K2: TT_TableGenCondOperator)) {
5620 return false;
5621 }
5622 // Trailing paste requires space before '{' or ':', the case in name values.
5623 // Not before ';', the case in normal values.
5624 if (Left.is(TT: TT_TableGenTrailingPasteOperator) &&
5625 Right.isOneOf(K1: tok::l_brace, K2: tok::colon)) {
5626 return true;
5627 }
5628 // Otherwise paste operator does not prefer space around.
5629 if (Left.is(Kind: tok::hash) || Right.is(Kind: tok::hash))
5630 return false;
5631 // Sure not to connect after defining keywords.
5632 if (Keywords.isTableGenDefinition(Tok: Left))
5633 return true;
5634 }
5635
5636 if (Left.is(TT: TT_ImplicitStringLiteral))
5637 return Right.hasWhitespaceBefore();
5638 if (Line.Type == LT_ObjCMethodDecl) {
5639 if (Left.is(TT: TT_ObjCMethodSpecifier))
5640 return Style.ObjCSpaceAfterMethodDeclarationPrefix;
5641 if (Left.is(Kind: tok::r_paren) && Left.isNot(Kind: TT_AttributeRParen) &&
5642 canBeObjCSelectorComponent(Tok: Right)) {
5643 // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
5644 // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
5645 // method declaration.
5646 return false;
5647 }
5648 }
5649 if (Line.Type == LT_ObjCProperty &&
5650 (Right.is(Kind: tok::equal) || Left.is(Kind: tok::equal))) {
5651 return false;
5652 }
5653
5654 if (Right.isOneOf(K1: TT_TrailingReturnArrow, K2: TT_LambdaArrow) ||
5655 Left.isOneOf(K1: TT_TrailingReturnArrow, K2: TT_LambdaArrow)) {
5656 return true;
5657 }
5658 if (Left.is(Kind: tok::comma) && Right.isNot(Kind: TT_OverloadedOperatorLParen) &&
5659 // In an unexpanded macro call we only find the parentheses and commas
5660 // in a line; the commas and closing parenthesis do not require a space.
5661 (Left.Children.empty() || !Left.MacroParent)) {
5662 return true;
5663 }
5664 if (Right.is(Kind: tok::comma))
5665 return false;
5666 if (Right.is(TT: TT_ObjCBlockLParen))
5667 return true;
5668 if (Right.is(TT: TT_CtorInitializerColon))
5669 return Style.SpaceBeforeCtorInitializerColon;
5670 if (Right.is(TT: TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
5671 return false;
5672 if (Right.is(TT: TT_EnumUnderlyingTypeColon) &&
5673 !Style.SpaceBeforeEnumUnderlyingTypeColon) {
5674 return false;
5675 }
5676 if (Right.is(TT: TT_RangeBasedForLoopColon) &&
5677 !Style.SpaceBeforeRangeBasedForLoopColon) {
5678 return false;
5679 }
5680 if (Left.is(TT: TT_BitFieldColon)) {
5681 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
5682 Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
5683 }
5684 if (Right.is(Kind: tok::colon)) {
5685 if (Right.is(TT: TT_CaseLabelColon))
5686 return Style.SpaceBeforeCaseColon;
5687 if (Right.is(TT: TT_GotoLabelColon))
5688 return false;
5689 // `private:` and `public:`.
5690 if (!Right.getNextNonComment())
5691 return false;
5692 if (Right.isOneOf(K1: TT_ObjCSelector, K2: TT_ObjCMethodExpr))
5693 return false;
5694 if (Left.is(Kind: tok::question))
5695 return false;
5696 if (Right.is(TT: TT_InlineASMColon) && Left.is(Kind: tok::coloncolon))
5697 return false;
5698 if (Right.is(TT: TT_DictLiteral))
5699 return Style.SpacesInContainerLiterals;
5700 if (Right.is(TT: TT_AttributeColon))
5701 return false;
5702 if (Right.is(TT: TT_CSharpNamedArgumentColon))
5703 return false;
5704 if (Right.is(TT: TT_GenericSelectionColon))
5705 return false;
5706 if (Right.is(TT: TT_BitFieldColon)) {
5707 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
5708 Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
5709 }
5710 return true;
5711 }
5712 // Do not merge "- -" into "--".
5713 if ((Left.isOneOf(K1: tok::minus, K2: tok::minusminus) &&
5714 Right.isOneOf(K1: tok::minus, K2: tok::minusminus)) ||
5715 (Left.isOneOf(K1: tok::plus, K2: tok::plusplus) &&
5716 Right.isOneOf(K1: tok::plus, K2: tok::plusplus))) {
5717 return true;
5718 }
5719 if (Left.is(TT: TT_UnaryOperator)) {
5720 // Lambda captures allow for a lone &, so "&]" needs to be properly
5721 // handled.
5722 if (Left.is(Kind: tok::amp) && Right.is(Kind: tok::r_square))
5723 return Style.SpacesInSquareBrackets;
5724 if (Left.isNot(Kind: tok::exclaim))
5725 return false;
5726 if (Left.TokenText == "!")
5727 return Style.SpaceAfterLogicalNot;
5728 assert(Left.TokenText == "not");
5729 return Right.isOneOf(K1: tok::coloncolon, K2: TT_UnaryOperator) ||
5730 (Right.is(Kind: tok::l_paren) && Style.SpaceBeforeParensOptions.AfterNot);
5731 }
5732
5733 // If the next token is a binary operator or a selector name, we have
5734 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
5735 if (Left.is(TT: TT_CastRParen)) {
5736 return Style.SpaceAfterCStyleCast ||
5737 Right.isOneOf(K1: TT_BinaryOperator, K2: TT_SelectorName);
5738 }
5739
5740 auto ShouldAddSpacesInAngles = [this, &Right]() {
5741 if (this->Style.SpacesInAngles == FormatStyle::SIAS_Always)
5742 return true;
5743 if (this->Style.SpacesInAngles == FormatStyle::SIAS_Leave)
5744 return Right.hasWhitespaceBefore();
5745 return false;
5746 };
5747
5748 if (Left.is(Kind: tok::greater) && Right.is(Kind: tok::greater)) {
5749 if (Style.isTextProto() ||
5750 (Style.Language == FormatStyle::LK_Proto && Left.is(TT: TT_DictLiteral))) {
5751 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
5752 }
5753 return Right.is(TT: TT_TemplateCloser) && Left.is(TT: TT_TemplateCloser) &&
5754 ((Style.Standard < FormatStyle::LS_Cpp11) ||
5755 ShouldAddSpacesInAngles());
5756 }
5757 if (Right.isOneOf(K1: tok::arrow, K2: tok::arrowstar, Ks: tok::periodstar) ||
5758 Left.isOneOf(K1: tok::arrow, K2: tok::period, Ks: tok::arrowstar, Ks: tok::periodstar) ||
5759 (Right.is(Kind: tok::period) && Right.isNot(Kind: TT_DesignatedInitializerPeriod))) {
5760 return false;
5761 }
5762 if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(Kind: TT_TemplateCloser) &&
5763 Right.getPrecedence() == prec::Assignment) {
5764 return false;
5765 }
5766 if (Style.isJava() && Right.is(Kind: tok::coloncolon) &&
5767 Left.isOneOf(K1: tok::identifier, K2: tok::kw_this)) {
5768 return false;
5769 }
5770 if (Right.is(Kind: tok::coloncolon) && Left.is(Kind: tok::identifier)) {
5771 // Preserve the space in constructs such as ALWAYS_INLINE ::std::string.
5772 return Left.isPossibleMacro(/*AllowFollowingColonColon=*/true) &&
5773 Right.hasWhitespaceBefore();
5774 }
5775 if (Right.is(Kind: tok::coloncolon) &&
5776 Left.isNoneOf(Ks: tok::l_brace, Ks: tok::comment, Ks: tok::l_paren)) {
5777 // Put a space between < and :: in vector< ::std::string >
5778 return (Left.is(TT: TT_TemplateOpener) &&
5779 ((Style.Standard < FormatStyle::LS_Cpp11) ||
5780 ShouldAddSpacesInAngles())) ||
5781 Left.isNoneOf(Ks: tok::l_paren, Ks: tok::r_paren, Ks: tok::l_square,
5782 Ks: tok::kw___super, Ks: TT_TemplateOpener,
5783 Ks: TT_TemplateCloser) ||
5784 (Left.is(Kind: tok::l_paren) && Style.SpacesInParensOptions.Other);
5785 }
5786 if ((Left.is(TT: TT_TemplateOpener)) != (Right.is(TT: TT_TemplateCloser)))
5787 return ShouldAddSpacesInAngles();
5788 if (Left.is(Kind: tok::r_paren) && Left.isNot(Kind: TT_TypeDeclarationParen) &&
5789 Right.is(TT: TT_PointerOrReference) && Right.isOneOf(K1: tok::amp, K2: tok::ampamp)) {
5790 return true;
5791 }
5792 // Space before TT_StructuredBindingLSquare.
5793 if (Right.is(TT: TT_StructuredBindingLSquare)) {
5794 return Left.isNoneOf(Ks: tok::amp, Ks: tok::ampamp) ||
5795 getTokenReferenceAlignment(PointerOrReference: Left) != FormatStyle::PAS_Right;
5796 }
5797 // Space before & or && following a TT_StructuredBindingLSquare.
5798 if (Right.Next && Right.Next->is(TT: TT_StructuredBindingLSquare) &&
5799 Right.isOneOf(K1: tok::amp, K2: tok::ampamp)) {
5800 return getTokenReferenceAlignment(PointerOrReference: Right) != FormatStyle::PAS_Left;
5801 }
5802 if ((Right.is(TT: TT_BinaryOperator) && Left.isNot(Kind: tok::l_paren)) ||
5803 (Left.isOneOf(K1: TT_BinaryOperator, K2: TT_EnumEqual, Ks: TT_ConditionalExpr) &&
5804 Right.isNot(Kind: tok::r_paren))) {
5805 return true;
5806 }
5807 if (Right.is(TT: TT_TemplateOpener) && Left.is(Kind: tok::r_paren) &&
5808 Left.MatchingParen &&
5809 Left.MatchingParen->is(TT: TT_OverloadedOperatorLParen)) {
5810 return false;
5811 }
5812 if (Right.is(Kind: tok::less) && Left.isNot(Kind: tok::l_paren) &&
5813 Line.Type == LT_ImportStatement) {
5814 return true;
5815 }
5816 if (Right.is(TT: TT_TrailingUnaryOperator))
5817 return false;
5818 if (Left.is(TT: TT_RegexLiteral))
5819 return false;
5820 return spaceRequiredBetween(Line, Left, Right);
5821}
5822
5823// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
5824static bool isAllmanBrace(const FormatToken &Tok) {
5825 return Tok.is(Kind: tok::l_brace) && Tok.is(BBK: BK_Block) &&
5826 Tok.isNoneOf(Ks: TT_ObjCBlockLBrace, Ks: TT_LambdaLBrace, Ks: TT_DictLiteral);
5827}
5828
5829// Returns 'true' if 'Tok' is a function argument.
5830static bool IsFunctionArgument(const FormatToken &Tok) {
5831 return Tok.MatchingParen && Tok.MatchingParen->Next &&
5832 Tok.MatchingParen->Next->isOneOf(K1: tok::comma, K2: tok::r_paren,
5833 Ks: tok::r_brace);
5834}
5835
5836static bool
5837isEmptyLambdaAllowed(const FormatToken &Tok,
5838 FormatStyle::ShortLambdaStyle ShortLambdaOption) {
5839 return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None;
5840}
5841
5842static bool isAllmanLambdaBrace(const FormatToken &Tok) {
5843 return Tok.is(Kind: tok::l_brace) && Tok.is(BBK: BK_Block) &&
5844 Tok.isNoneOf(Ks: TT_ObjCBlockLBrace, Ks: TT_DictLiteral);
5845}
5846
5847bool TokenAnnotator::mustBreakBefore(AnnotatedLine &Line,
5848 const FormatToken &Right) const {
5849 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0 &&
5850 (!Style.RemoveEmptyLinesInUnwrappedLines || &Right == Line.First)) {
5851 return true;
5852 }
5853
5854 const FormatToken &Left = *Right.Previous;
5855
5856 if (Style.BreakFunctionDeclarationParameters && Line.MightBeFunctionDecl &&
5857 !Line.mightBeFunctionDefinition() && Left.MightBeFunctionDeclParen &&
5858 Left.ParameterCount > 0) {
5859 return true;
5860 }
5861
5862 if (Style.BreakFunctionDefinitionParameters && Line.MightBeFunctionDecl &&
5863 Line.mightBeFunctionDefinition() && Left.MightBeFunctionDeclParen &&
5864 Left.ParameterCount > 0) {
5865 return true;
5866 }
5867
5868 // Ignores the first parameter as this will be handled separately by
5869 // BreakFunctionDefinitionParameters or AlignAfterOpenBracket.
5870 if (Style.PackParameters.BinPack == FormatStyle::BPPS_AlwaysOnePerLine &&
5871 Line.MightBeFunctionDecl && !Left.opensScope() &&
5872 startsNextParameter(Current: Right, Style)) {
5873 return true;
5874 }
5875
5876 const auto *BeforeLeft = Left.Previous;
5877 const auto *AfterRight = Right.Next;
5878
5879 if (Style.isCSharp()) {
5880 if (Left.is(TT: TT_FatArrow) && Right.is(Kind: tok::l_brace) &&
5881 Style.BraceWrapping.AfterFunction) {
5882 return true;
5883 }
5884 if (Right.is(TT: TT_CSharpNamedArgumentColon) ||
5885 Left.is(TT: TT_CSharpNamedArgumentColon)) {
5886 return false;
5887 }
5888 if (Right.is(TT: TT_CSharpGenericTypeConstraint))
5889 return true;
5890 if (AfterRight && AfterRight->is(TT: TT_FatArrow) &&
5891 (Right.is(Kind: tok::numeric_constant) ||
5892 (Right.is(Kind: tok::identifier) && Right.TokenText == "_"))) {
5893 return true;
5894 }
5895
5896 // Break after C# [...] and before public/protected/private/internal.
5897 if (Left.is(TT: TT_AttributeRSquare) &&
5898 (Right.isAccessSpecifier(/*ColonRequired=*/false) ||
5899 Right.is(II: Keywords.kw_internal))) {
5900 return true;
5901 }
5902 // Break between ] and [ but only when there are really 2 attributes.
5903 if (Left.is(TT: TT_AttributeRSquare) && Right.is(TT: TT_AttributeLSquare))
5904 return true;
5905 } else if (Style.isJavaScript()) {
5906 // FIXME: This might apply to other languages and token kinds.
5907 if (Right.is(Kind: tok::string_literal) && Left.is(Kind: tok::plus) && BeforeLeft &&
5908 BeforeLeft->is(Kind: tok::string_literal)) {
5909 return true;
5910 }
5911 if (Left.is(TT: TT_DictLiteral) && Left.is(Kind: tok::l_brace) && Line.Level == 0 &&
5912 BeforeLeft && BeforeLeft->is(Kind: tok::equal) &&
5913 Line.First->isOneOf(K1: tok::identifier, K2: Keywords.kw_import, Ks: tok::kw_export,
5914 Ks: tok::kw_const) &&
5915 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
5916 // above.
5917 Line.First->isNoneOf(Ks: Keywords.kw_var, Ks: Keywords.kw_let)) {
5918 // Object literals on the top level of a file are treated as "enum-style".
5919 // Each key/value pair is put on a separate line, instead of bin-packing.
5920 return true;
5921 }
5922 if (Left.is(Kind: tok::l_brace) && Line.Level == 0 &&
5923 (Line.startsWith(Tokens: tok::kw_enum) ||
5924 Line.startsWith(Tokens: tok::kw_const, Tokens: tok::kw_enum) ||
5925 Line.startsWith(Tokens: tok::kw_export, Tokens: tok::kw_enum) ||
5926 Line.startsWith(Tokens: tok::kw_export, Tokens: tok::kw_const, Tokens: tok::kw_enum))) {
5927 // JavaScript top-level enum key/value pairs are put on separate lines
5928 // instead of bin-packing.
5929 return true;
5930 }
5931 if (Right.is(Kind: tok::r_brace) && Left.is(Kind: tok::l_brace) && BeforeLeft &&
5932 BeforeLeft->is(TT: TT_FatArrow)) {
5933 // JS arrow function (=> {...}).
5934 switch (Style.AllowShortLambdasOnASingleLine) {
5935 case FormatStyle::SLS_All:
5936 return false;
5937 case FormatStyle::SLS_None:
5938 return true;
5939 case FormatStyle::SLS_Empty:
5940 return !Left.Children.empty();
5941 case FormatStyle::SLS_Inline:
5942 // allow one-lining inline (e.g. in function call args) and empty arrow
5943 // functions.
5944 return (Left.NestingLevel == 0 && Line.Level == 0) &&
5945 !Left.Children.empty();
5946 }
5947 llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum");
5948 }
5949
5950 if (Right.is(Kind: tok::r_brace) && Left.is(Kind: tok::l_brace) &&
5951 !Left.Children.empty()) {
5952 // Support AllowShortFunctionsOnASingleLine for JavaScript.
5953 if (Left.NestingLevel == 0 && Line.Level == 0)
5954 return !Style.AllowShortFunctionsOnASingleLine.Other;
5955
5956 return !Style.AllowShortFunctionsOnASingleLine.Inline;
5957 }
5958 } else if (Style.isJava()) {
5959 if (Right.is(Kind: tok::plus) && Left.is(Kind: tok::string_literal) && AfterRight &&
5960 AfterRight->is(Kind: tok::string_literal)) {
5961 return true;
5962 }
5963 } else if (Style.isVerilog()) {
5964 // Break between assignments.
5965 if (Left.is(TT: TT_VerilogAssignComma))
5966 return true;
5967 // Break between ports of different types.
5968 if (Left.is(TT: TT_VerilogTypeComma))
5969 return true;
5970 // Break between ports in a module instantiation and after the parameter
5971 // list.
5972 if (Style.VerilogBreakBetweenInstancePorts &&
5973 (Left.is(TT: TT_VerilogInstancePortComma) ||
5974 (Left.is(Kind: tok::r_paren) && Keywords.isVerilogIdentifier(Tok: Right) &&
5975 Left.MatchingParen &&
5976 Left.MatchingParen->is(TT: TT_VerilogInstancePortLParen)))) {
5977 return true;
5978 }
5979 // Break after labels. In Verilog labels don't have the 'case' keyword, so
5980 // it is hard to identify them in UnwrappedLineParser.
5981 if (!Keywords.isVerilogBegin(Tok: Right) && Keywords.isVerilogEndOfLabel(Tok: Left))
5982 return true;
5983 } else if (Style.BreakAdjacentStringLiterals &&
5984 (IsCpp || Style.isProto() || Style.isTableGen())) {
5985 if (Left.isStringLiteral() && Right.isStringLiteral())
5986 return true;
5987 }
5988
5989 // Basic JSON newline processing.
5990 if (Style.isJson()) {
5991 // Always break after a JSON record opener.
5992 // {
5993 // }
5994 if (Left.is(TT: TT_DictLiteral) && Left.is(Kind: tok::l_brace))
5995 return true;
5996 // Always break after a JSON array opener based on BreakArrays.
5997 if ((Left.is(TT: TT_ArrayInitializerLSquare) && Left.is(Kind: tok::l_square) &&
5998 Right.isNot(Kind: tok::r_square)) ||
5999 Left.is(Kind: tok::comma)) {
6000 if (Right.is(Kind: tok::l_brace))
6001 return true;
6002 // scan to the right if an we see an object or an array inside
6003 // then break.
6004 for (const auto *Tok = &Right; Tok; Tok = Tok->Next) {
6005 if (Tok->isOneOf(K1: tok::l_brace, K2: tok::l_square))
6006 return true;
6007 if (Tok->isOneOf(K1: tok::r_brace, K2: tok::r_square))
6008 break;
6009 }
6010 return Style.BreakArrays;
6011 }
6012 } else if (Style.isTableGen()) {
6013 // Break the comma in side cond operators.
6014 // !cond(case1:1,
6015 // case2:0);
6016 if (Left.is(TT: TT_TableGenCondOperatorComma))
6017 return true;
6018 if (Left.is(TT: TT_TableGenDAGArgOperatorToBreak) &&
6019 Right.isNot(Kind: TT_TableGenDAGArgCloser)) {
6020 return true;
6021 }
6022 if (Left.is(TT: TT_TableGenDAGArgListCommaToBreak))
6023 return true;
6024 if (Right.is(TT: TT_TableGenDAGArgCloser) && Right.MatchingParen &&
6025 Right.MatchingParen->is(TT: TT_TableGenDAGArgOpenerToBreak) &&
6026 &Left != Right.MatchingParen->Next) {
6027 // Check to avoid empty DAGArg such as (ins).
6028 return Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakAll;
6029 }
6030 }
6031
6032 if (Line.startsWith(Tokens: tok::kw_asm) && Right.is(TT: TT_InlineASMColon) &&
6033 Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always) {
6034 return true;
6035 }
6036
6037 // If the last token before a '}', ']', or ')' is a comma or a trailing
6038 // comment, the intention is to insert a line break after it in order to make
6039 // shuffling around entries easier. Import statements, especially in
6040 // JavaScript, can be an exception to this rule.
6041 if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
6042 const FormatToken *BeforeClosingBrace = nullptr;
6043 if ((Left.isOneOf(K1: tok::l_brace, K2: TT_ArrayInitializerLSquare) ||
6044 (Style.isJavaScript() && Left.is(Kind: tok::l_paren))) &&
6045 Left.isNot(Kind: BK_Block) && Left.MatchingParen) {
6046 BeforeClosingBrace = Left.MatchingParen->Previous;
6047 } else if (Right.MatchingParen &&
6048 (Right.MatchingParen->isOneOf(K1: tok::l_brace,
6049 K2: TT_ArrayInitializerLSquare) ||
6050 (Style.isJavaScript() &&
6051 Right.MatchingParen->is(Kind: tok::l_paren)))) {
6052 BeforeClosingBrace = &Left;
6053 }
6054 if (BeforeClosingBrace && (BeforeClosingBrace->is(Kind: tok::comma) ||
6055 BeforeClosingBrace->isTrailingComment())) {
6056 return true;
6057 }
6058 }
6059
6060 if (Right.is(Kind: tok::comment)) {
6061 return Left.isNoneOf(Ks: BK_BracedInit, Ks: TT_CtorInitializerColon) &&
6062 Right.NewlinesBefore > 0 && Right.HasUnescapedNewline;
6063 }
6064 if (Left.isTrailingComment())
6065 return true;
6066 if (Left.IsUnterminatedLiteral)
6067 return true;
6068
6069 if (BeforeLeft && BeforeLeft->is(Kind: tok::lessless) &&
6070 Left.is(Kind: tok::string_literal) && Right.is(Kind: tok::lessless) && AfterRight &&
6071 AfterRight->is(Kind: tok::string_literal)) {
6072 return Right.NewlinesBefore > 0;
6073 }
6074
6075 if (Right.is(TT: TT_RequiresClause)) {
6076 switch (Style.RequiresClausePosition) {
6077 case FormatStyle::RCPS_OwnLine:
6078 case FormatStyle::RCPS_OwnLineWithBrace:
6079 case FormatStyle::RCPS_WithFollowing:
6080 return true;
6081 default:
6082 break;
6083 }
6084 }
6085 // Can break after template<> declaration
6086 if (Left.ClosesTemplateDeclaration && Left.MatchingParen &&
6087 Left.MatchingParen->NestingLevel == 0) {
6088 // Put concepts on the next line e.g.
6089 // template<typename T>
6090 // concept ...
6091 if (Right.is(Kind: tok::kw_concept))
6092 return Style.BreakBeforeConceptDeclarations == FormatStyle::BBCDS_Always;
6093 return Style.BreakTemplateDeclarations == FormatStyle::BTDS_Yes ||
6094 (Style.BreakTemplateDeclarations == FormatStyle::BTDS_Leave &&
6095 Right.NewlinesBefore > 0);
6096 }
6097 if (Left.ClosesRequiresClause) {
6098 switch (Style.RequiresClausePosition) {
6099 case FormatStyle::RCPS_OwnLine:
6100 case FormatStyle::RCPS_WithPreceding:
6101 return Right.isNot(Kind: tok::semi);
6102 case FormatStyle::RCPS_OwnLineWithBrace:
6103 return Right.isNoneOf(Ks: tok::semi, Ks: tok::l_brace);
6104 default:
6105 break;
6106 }
6107 }
6108 if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) {
6109 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon &&
6110 (Left.is(TT: TT_CtorInitializerComma) ||
6111 Right.is(TT: TT_CtorInitializerColon))) {
6112 return true;
6113 }
6114
6115 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
6116 Left.isOneOf(K1: TT_CtorInitializerColon, K2: TT_CtorInitializerComma)) {
6117 return true;
6118 }
6119
6120 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterComma &&
6121 Left.is(TT: TT_CtorInitializerComma)) {
6122 return true;
6123 }
6124 }
6125 if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine &&
6126 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
6127 Right.isOneOf(K1: TT_CtorInitializerComma, K2: TT_CtorInitializerColon)) {
6128 return true;
6129 }
6130 if (Style.PackConstructorInitializers == FormatStyle::PCIS_NextLineOnly) {
6131 if ((Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon ||
6132 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) &&
6133 Right.is(TT: TT_CtorInitializerColon)) {
6134 return true;
6135 }
6136
6137 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
6138 Left.is(TT: TT_CtorInitializerColon)) {
6139 return true;
6140 }
6141 }
6142 // Break only if we have multiple inheritance.
6143 if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
6144 Right.is(TT: TT_InheritanceComma)) {
6145 return true;
6146 }
6147 if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma &&
6148 Left.is(TT: TT_InheritanceComma)) {
6149 return true;
6150 }
6151 if (Right.is(Kind: tok::string_literal) && Right.TokenText.starts_with(Prefix: "R\"")) {
6152 // Multiline raw string literals are special wrt. line breaks. The author
6153 // has made a deliberate choice and might have aligned the contents of the
6154 // string literal accordingly. Thus, we try keep existing line breaks.
6155 return Right.IsMultiline && Right.NewlinesBefore > 0;
6156 }
6157 if ((Left.is(Kind: tok::l_brace) ||
6158 (Left.is(Kind: tok::less) && BeforeLeft && BeforeLeft->is(Kind: tok::equal))) &&
6159 Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
6160 // Don't put enums or option definitions onto single lines in protocol
6161 // buffers.
6162 return true;
6163 }
6164 if (Right.is(TT: TT_InlineASMBrace))
6165 return Right.HasUnescapedNewline;
6166
6167 if (isAllmanBrace(Tok: Left) || isAllmanBrace(Tok: Right)) {
6168 auto *FirstNonComment = Line.getFirstNonComment();
6169 bool AccessSpecifier =
6170 FirstNonComment && (FirstNonComment->is(II: Keywords.kw_internal) ||
6171 FirstNonComment->isAccessSpecifierKeyword());
6172
6173 if (Style.BraceWrapping.AfterEnum) {
6174 if (Line.startsWith(Tokens: tok::kw_enum) ||
6175 Line.startsWith(Tokens: tok::kw_typedef, Tokens: tok::kw_enum) ||
6176 Line.startsWith(Tokens: tok::kw_export, Tokens: tok::kw_enum)) {
6177 return true;
6178 }
6179 // Ensure BraceWrapping for `public enum A {`.
6180 if (AccessSpecifier && FirstNonComment->Next &&
6181 FirstNonComment->Next->is(Kind: tok::kw_enum)) {
6182 return true;
6183 }
6184 }
6185
6186 // Ensure BraceWrapping for `public interface A {`.
6187 if (Style.BraceWrapping.AfterClass &&
6188 ((AccessSpecifier && FirstNonComment->Next &&
6189 FirstNonComment->Next->is(II: Keywords.kw_interface)) ||
6190 Line.startsWith(Tokens: Keywords.kw_interface))) {
6191 return true;
6192 }
6193
6194 // Don't attempt to interpret record return types as records.
6195 if (Right.isNot(Kind: TT_FunctionLBrace)) {
6196 return Style.AllowShortRecordOnASingleLine == FormatStyle::SRS_Never &&
6197 ((Line.startsWith(Tokens: tok::kw_class) &&
6198 Style.BraceWrapping.AfterClass) ||
6199 (Line.startsWith(Tokens: tok::kw_struct) &&
6200 Style.BraceWrapping.AfterStruct) ||
6201 (Line.startsWith(Tokens: tok::kw_union) &&
6202 Style.BraceWrapping.AfterUnion));
6203 }
6204 }
6205
6206 if (Left.is(TT: TT_ObjCBlockLBrace) &&
6207 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
6208 return true;
6209 }
6210
6211 // Ensure wrapping after __attribute__((XX)) and @interface etc.
6212 if (Left.isOneOf(K1: TT_AttributeRParen, K2: TT_AttributeMacro) &&
6213 Right.is(TT: TT_ObjCDecl)) {
6214 return true;
6215 }
6216
6217 if (Left.is(TT: TT_LambdaLBrace)) {
6218 if (IsFunctionArgument(Tok: Left) &&
6219 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline) {
6220 return false;
6221 }
6222
6223 if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
6224 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
6225 (!Left.Children.empty() &&
6226 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty)) {
6227 return true;
6228 }
6229 }
6230
6231 if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT: TT_LambdaLBrace) &&
6232 (Left.isPointerOrReference() || Left.is(TT: TT_TemplateCloser))) {
6233 return true;
6234 }
6235
6236 // Put multiple Java annotation on a new line.
6237 if ((Style.isJava() || Style.isJavaScript()) &&
6238 Left.is(TT: TT_LeadingJavaAnnotation) &&
6239 Right.isNoneOf(Ks: TT_LeadingJavaAnnotation, Ks: tok::l_paren) &&
6240 (Line.Last->is(Kind: tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) {
6241 return true;
6242 }
6243
6244 if (Right.is(TT: TT_ProtoExtensionLSquare))
6245 return true;
6246
6247 // In text proto instances if a submessage contains at least 2 entries and at
6248 // least one of them is a submessage, like A { ... B { ... } ... },
6249 // put all of the entries of A on separate lines by forcing the selector of
6250 // the submessage B to be put on a newline.
6251 //
6252 // Example: these can stay on one line:
6253 // a { scalar_1: 1 scalar_2: 2 }
6254 // a { b { key: value } }
6255 //
6256 // and these entries need to be on a new line even if putting them all in one
6257 // line is under the column limit:
6258 // a {
6259 // scalar: 1
6260 // b { key: value }
6261 // }
6262 //
6263 // We enforce this by breaking before a submessage field that has previous
6264 // siblings, *and* breaking before a field that follows a submessage field.
6265 //
6266 // Be careful to exclude the case [proto.ext] { ... } since the `]` is
6267 // the TT_SelectorName there, but we don't want to break inside the brackets.
6268 //
6269 // Another edge case is @submessage { key: value }, which is a common
6270 // substitution placeholder. In this case we want to keep `@` and `submessage`
6271 // together.
6272 //
6273 // We ensure elsewhere that extensions are always on their own line.
6274 if (Style.isProto() && Right.is(TT: TT_SelectorName) &&
6275 Right.isNot(Kind: tok::r_square) && AfterRight) {
6276 // Keep `@submessage` together in:
6277 // @submessage { key: value }
6278 if (Left.is(Kind: tok::at))
6279 return false;
6280 // Look for the scope opener after selector in cases like:
6281 // selector { ...
6282 // selector: { ...
6283 // selector: @base { ...
6284 const auto *LBrace = AfterRight;
6285 if (LBrace && LBrace->is(Kind: tok::colon)) {
6286 LBrace = LBrace->Next;
6287 if (LBrace && LBrace->is(Kind: tok::at)) {
6288 LBrace = LBrace->Next;
6289 if (LBrace)
6290 LBrace = LBrace->Next;
6291 }
6292 }
6293 if (LBrace &&
6294 // The scope opener is one of {, [, <:
6295 // selector { ... }
6296 // selector [ ... ]
6297 // selector < ... >
6298 //
6299 // In case of selector { ... }, the l_brace is TT_DictLiteral.
6300 // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
6301 // so we check for immediately following r_brace.
6302 ((LBrace->is(Kind: tok::l_brace) &&
6303 (LBrace->is(TT: TT_DictLiteral) ||
6304 (LBrace->Next && LBrace->Next->is(Kind: tok::r_brace)))) ||
6305 LBrace->isOneOf(K1: TT_ArrayInitializerLSquare, K2: tok::less))) {
6306 // If Left.ParameterCount is 0, then this submessage entry is not the
6307 // first in its parent submessage, and we want to break before this entry.
6308 // If Left.ParameterCount is greater than 0, then its parent submessage
6309 // might contain 1 or more entries and we want to break before this entry
6310 // if it contains at least 2 entries. We deal with this case later by
6311 // detecting and breaking before the next entry in the parent submessage.
6312 if (Left.ParameterCount == 0)
6313 return true;
6314 // However, if this submessage is the first entry in its parent
6315 // submessage, Left.ParameterCount might be 1 in some cases.
6316 // We deal with this case later by detecting an entry
6317 // following a closing paren of this submessage.
6318 }
6319
6320 // If this is an entry immediately following a submessage, it will be
6321 // preceded by a closing paren of that submessage, like in:
6322 // left---. .---right
6323 // v v
6324 // sub: { ... } key: value
6325 // If there was a comment between `}` an `key` above, then `key` would be
6326 // put on a new line anyways.
6327 if (Left.isOneOf(K1: tok::r_brace, K2: tok::greater, Ks: tok::r_square))
6328 return true;
6329 }
6330
6331 if (Style.BreakAfterAttributes == FormatStyle::ABS_LeaveAll &&
6332 Left.is(TT: TT_AttributeRSquare) && Right.NewlinesBefore > 0) {
6333 Line.ReturnTypeWrapped = true;
6334 return true;
6335 }
6336
6337 return false;
6338}
6339
6340bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
6341 const FormatToken &Right) const {
6342 const FormatToken &Left = *Right.Previous;
6343 // Language-specific stuff.
6344 if (Style.isCSharp()) {
6345 if (Left.isOneOf(K1: TT_CSharpNamedArgumentColon, K2: TT_AttributeColon) ||
6346 Right.isOneOf(K1: TT_CSharpNamedArgumentColon, K2: TT_AttributeColon)) {
6347 return false;
6348 }
6349 // Only break after commas for generic type constraints.
6350 if (Line.First->is(TT: TT_CSharpGenericTypeConstraint))
6351 return Left.is(TT: TT_CSharpGenericTypeConstraintComma);
6352 // Keep nullable operators attached to their identifiers.
6353 if (Right.is(TT: TT_CSharpNullable))
6354 return false;
6355 } else if (Style.isJava()) {
6356 if (Left.isOneOf(K1: Keywords.kw_throws, K2: Keywords.kw_extends,
6357 Ks: Keywords.kw_implements)) {
6358 return false;
6359 }
6360 if (Right.isOneOf(K1: Keywords.kw_throws, K2: Keywords.kw_extends,
6361 Ks: Keywords.kw_implements)) {
6362 return true;
6363 }
6364 } else if (Style.isJavaScript()) {
6365 const FormatToken *NonComment = Right.getPreviousNonComment();
6366 if (NonComment &&
6367 (NonComment->isAccessSpecifierKeyword() ||
6368 NonComment->isOneOf(
6369 K1: tok::kw_return, K2: Keywords.kw_yield, Ks: tok::kw_continue, Ks: tok::kw_break,
6370 Ks: tok::kw_throw, Ks: Keywords.kw_interface, Ks: Keywords.kw_type,
6371 Ks: tok::kw_static, Ks: Keywords.kw_readonly, Ks: Keywords.kw_override,
6372 Ks: Keywords.kw_abstract, Ks: Keywords.kw_get, Ks: Keywords.kw_set,
6373 Ks: Keywords.kw_async, Ks: Keywords.kw_await))) {
6374 return false; // Otherwise automatic semicolon insertion would trigger.
6375 }
6376 if (Right.NestingLevel == 0 &&
6377 (Left.Tok.getIdentifierInfo() ||
6378 Left.isOneOf(K1: tok::r_square, K2: tok::r_paren)) &&
6379 Right.isOneOf(K1: tok::l_square, K2: tok::l_paren)) {
6380 return false; // Otherwise automatic semicolon insertion would trigger.
6381 }
6382 if (NonComment && NonComment->is(Kind: tok::identifier) &&
6383 NonComment->TokenText == "asserts") {
6384 return false;
6385 }
6386 if (Left.is(TT: TT_FatArrow) && Right.is(Kind: tok::l_brace))
6387 return false;
6388 if (Left.is(TT: TT_JsTypeColon))
6389 return true;
6390 // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
6391 if (Left.is(Kind: tok::exclaim) && Right.is(Kind: tok::colon))
6392 return false;
6393 // Look for is type annotations like:
6394 // function f(): a is B { ... }
6395 // Do not break before is in these cases.
6396 if (Right.is(II: Keywords.kw_is)) {
6397 const FormatToken *Next = Right.getNextNonComment();
6398 // If `is` is followed by a colon, it's likely that it's a dict key, so
6399 // ignore it for this check.
6400 // For example this is common in Polymer:
6401 // Polymer({
6402 // is: 'name',
6403 // ...
6404 // });
6405 if (!Next || Next->isNot(Kind: tok::colon))
6406 return false;
6407 }
6408 if (Left.is(II: Keywords.kw_in))
6409 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
6410 if (Right.is(II: Keywords.kw_in))
6411 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
6412 if (Right.is(II: Keywords.kw_as))
6413 return false; // must not break before as in 'x as type' casts
6414 if (Right.isOneOf(K1: Keywords.kw_extends, K2: Keywords.kw_infer)) {
6415 // extends and infer can appear as keywords in conditional types:
6416 // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
6417 // do not break before them, as the expressions are subject to ASI.
6418 return false;
6419 }
6420 if (Left.is(II: Keywords.kw_as))
6421 return true;
6422 if (Left.is(TT: TT_NonNullAssertion))
6423 return true;
6424 if (Left.is(II: Keywords.kw_declare) &&
6425 Right.isOneOf(K1: Keywords.kw_module, K2: tok::kw_namespace,
6426 Ks: Keywords.kw_function, Ks: tok::kw_class, Ks: tok::kw_enum,
6427 Ks: Keywords.kw_interface, Ks: Keywords.kw_type, Ks: Keywords.kw_var,
6428 Ks: Keywords.kw_let, Ks: tok::kw_const)) {
6429 // See grammar for 'declare' statements at:
6430 // https://github.com/Microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md#A.10
6431 return false;
6432 }
6433 if (Left.isOneOf(K1: Keywords.kw_module, K2: tok::kw_namespace) &&
6434 Right.isOneOf(K1: tok::identifier, K2: tok::string_literal)) {
6435 return false; // must not break in "module foo { ...}"
6436 }
6437 if (Right.is(TT: TT_TemplateString) && Right.closesScope())
6438 return false;
6439 // Don't split tagged template literal so there is a break between the tag
6440 // identifier and template string.
6441 if (Left.is(Kind: tok::identifier) && Right.is(TT: TT_TemplateString))
6442 return false;
6443 if (Left.is(TT: TT_TemplateString) && Left.opensScope())
6444 return true;
6445 } else if (Style.isTableGen()) {
6446 // Avoid to break after "def", "class", "let" and so on.
6447 if (Keywords.isTableGenDefinition(Tok: Left))
6448 return false;
6449 // Avoid to break after '(' in the cases that is in bang operators.
6450 if (Right.is(Kind: tok::l_paren)) {
6451 return Left.isNoneOf(Ks: TT_TableGenBangOperator, Ks: TT_TableGenCondOperator,
6452 Ks: TT_TemplateCloser);
6453 }
6454 // Avoid to break between the value and its suffix part.
6455 if (Left.is(TT: TT_TableGenValueSuffix))
6456 return false;
6457 // Avoid to break around paste operator.
6458 if (Left.is(Kind: tok::hash) || Right.is(Kind: tok::hash))
6459 return false;
6460 if (Left.isOneOf(K1: TT_TableGenBangOperator, K2: TT_TableGenCondOperator))
6461 return false;
6462 }
6463
6464 // We can break before an r_brace if there was a break after the matching
6465 // l_brace, which is tracked by BreakBeforeClosingBrace, or if we are in a
6466 // block-indented initialization list.
6467 if (Right.is(Kind: tok::r_brace)) {
6468 return Right.MatchingParen && (Right.MatchingParen->is(BBK: BK_Block) ||
6469 (Right.isBlockIndentedInitRBrace(Style)));
6470 }
6471
6472 // We can break before r_paren if we're in a block indented context or
6473 // a control statement with an explicit style option.
6474 if (Right.is(Kind: tok::r_paren)) {
6475 if (!Right.MatchingParen)
6476 return false;
6477 auto Next = Right.Next;
6478 if (Next && Next->is(Kind: tok::r_paren))
6479 Next = Next->Next;
6480 if (Next && Next->is(Kind: tok::l_paren))
6481 return false;
6482 const FormatToken *Previous = Right.MatchingParen->Previous;
6483 if (!Previous)
6484 return false;
6485 if (Previous->isIf())
6486 return Style.BreakBeforeCloseBracketIf;
6487 if (Previous->isLoop(Style))
6488 return Style.BreakBeforeCloseBracketLoop;
6489 if (Previous->is(Kind: tok::kw_switch))
6490 return Style.BreakBeforeCloseBracketSwitch;
6491 return Style.BreakBeforeCloseBracketFunction;
6492 }
6493
6494 if (Left.isOneOf(K1: tok::r_paren, K2: TT_TrailingAnnotation) &&
6495 Right.is(TT: TT_TrailingAnnotation) &&
6496 Style.BreakBeforeCloseBracketFunction) {
6497 return false;
6498 }
6499
6500 if (Right.is(TT: TT_TemplateCloser))
6501 return Style.BreakBeforeTemplateCloser;
6502
6503 if (Left.isOneOf(K1: tok::at, K2: tok::objc_interface))
6504 return false;
6505 if (Left.isOneOf(K1: TT_JavaAnnotation, K2: TT_LeadingJavaAnnotation))
6506 return Right.isNot(Kind: tok::l_paren);
6507 if (Right.is(TT: TT_PointerOrReference)) {
6508 return Line.IsMultiVariableDeclStmt ||
6509 (getTokenPointerOrReferenceAlignment(PointerOrReference: Right) ==
6510 FormatStyle::PAS_Right &&
6511 !(Right.Next &&
6512 Right.Next->isOneOf(K1: TT_FunctionDeclarationName, K2: tok::kw_const)));
6513 }
6514 if (Left.is(Kind: tok::hashhash) || Right.is(Kind: tok::hashhash))
6515 return false;
6516 if (Right.isOneOf(K1: TT_StartOfName, K2: TT_FunctionDeclarationName,
6517 Ks: TT_ClassHeadName, Ks: TT_QtProperty, Ks: tok::kw_operator)) {
6518 return true;
6519 }
6520 if (Left.is(TT: TT_PointerOrReference))
6521 return false;
6522 if (Right.isTrailingComment()) {
6523 // We rely on MustBreakBefore being set correctly here as we should not
6524 // change the "binding" behavior of a comment.
6525 // The first comment in a braced lists is always interpreted as belonging to
6526 // the first list element. Otherwise, it should be placed outside of the
6527 // list.
6528 return Left.is(BBK: BK_BracedInit) ||
6529 (Left.is(TT: TT_CtorInitializerColon) && Right.NewlinesBefore > 0 &&
6530 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
6531 }
6532 if (Left.is(Kind: tok::question) && Right.is(Kind: tok::colon))
6533 return false;
6534 if (Right.isOneOf(K1: TT_ConditionalExpr, K2: tok::question))
6535 return Style.BreakBeforeTernaryOperators;
6536 if (Left.isOneOf(K1: TT_ConditionalExpr, K2: tok::question))
6537 return !Style.BreakBeforeTernaryOperators;
6538 if (Left.is(TT: TT_InheritanceColon))
6539 return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
6540 if (Right.is(TT: TT_InheritanceColon))
6541 return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
6542 // When the method parameter has no name, allow breaking before the colon.
6543 if (Right.is(TT: TT_ObjCMethodExpr) && Right.isNot(Kind: tok::r_square) &&
6544 Left.isNot(Kind: TT_SelectorName)) {
6545 return true;
6546 }
6547
6548 if (Right.is(Kind: tok::colon) &&
6549 Right.isNoneOf(Ks: TT_CtorInitializerColon, Ks: TT_InlineASMColon,
6550 Ks: TT_BitFieldColon)) {
6551 return false;
6552 }
6553 if (Left.is(Kind: tok::colon) && Left.isOneOf(K1: TT_ObjCSelector, K2: TT_ObjCMethodExpr))
6554 return true;
6555 if (Left.is(Kind: tok::colon) && Left.is(TT: TT_DictLiteral)) {
6556 if (Style.isProto()) {
6557 if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
6558 return false;
6559 // Prevent cases like:
6560 //
6561 // submessage:
6562 // { key: valueeeeeeeeeeee }
6563 //
6564 // when the snippet does not fit into one line.
6565 // Prefer:
6566 //
6567 // submessage: {
6568 // key: valueeeeeeeeeeee
6569 // }
6570 //
6571 // instead, even if it is longer by one line.
6572 //
6573 // Note that this allows the "{" to go over the column limit
6574 // when the column limit is just between ":" and "{", but that does
6575 // not happen too often and alternative formattings in this case are
6576 // not much better.
6577 //
6578 // The code covers the cases:
6579 //
6580 // submessage: { ... }
6581 // submessage: < ... >
6582 // repeated: [ ... ]
6583 if ((Right.isOneOf(K1: tok::l_brace, K2: tok::less) &&
6584 Right.is(TT: TT_DictLiteral)) ||
6585 Right.is(TT: TT_ArrayInitializerLSquare)) {
6586 return false;
6587 }
6588 }
6589 return true;
6590 }
6591 if (Right.is(Kind: tok::r_square) && Right.MatchingParen &&
6592 Right.MatchingParen->is(TT: TT_ProtoExtensionLSquare)) {
6593 return false;
6594 }
6595 if (Right.is(TT: TT_SelectorName) || (Right.is(Kind: tok::identifier) && Right.Next &&
6596 Right.Next->is(TT: TT_ObjCMethodExpr))) {
6597 return Left.isNot(Kind: tok::period); // FIXME: Properly parse ObjC calls.
6598 }
6599 if (Left.is(Kind: tok::r_paren) && Line.Type == LT_ObjCProperty)
6600 return true;
6601 if (Right.is(Kind: tok::kw_concept))
6602 return Style.BreakBeforeConceptDeclarations != FormatStyle::BBCDS_Never;
6603 if (Right.is(TT: TT_RequiresClause))
6604 return true;
6605 if (Left.ClosesTemplateDeclaration) {
6606 return Style.BreakTemplateDeclarations != FormatStyle::BTDS_Leave ||
6607 Right.NewlinesBefore > 0;
6608 }
6609 if (Left.is(TT: TT_FunctionAnnotationRParen))
6610 return true;
6611 if (Left.ClosesRequiresClause)
6612 return true;
6613 if (Right.isOneOf(K1: TT_RangeBasedForLoopColon, K2: TT_OverloadedOperatorLParen,
6614 Ks: TT_OverloadedOperator)) {
6615 return false;
6616 }
6617 if (Left.is(TT: TT_RangeBasedForLoopColon))
6618 return true;
6619 if (Right.is(TT: TT_RangeBasedForLoopColon))
6620 return false;
6621 if (Left.is(TT: TT_TemplateCloser) && Right.is(TT: TT_TemplateOpener))
6622 return true;
6623 if ((Left.is(Kind: tok::greater) && Right.is(Kind: tok::greater)) ||
6624 (Left.is(Kind: tok::less) && Right.is(Kind: tok::less))) {
6625 return false;
6626 }
6627 if (Right.is(TT: TT_BinaryOperator) &&
6628 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
6629 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
6630 Right.getPrecedence() != prec::Assignment)) {
6631 return true;
6632 }
6633 if (Left.isOneOf(K1: TT_TemplateCloser, K2: TT_UnaryOperator, Ks: tok::kw_operator))
6634 return false;
6635 if (Left.is(Kind: tok::equal) && Right.isNoneOf(Ks: tok::kw_default, Ks: tok::kw_delete) &&
6636 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) {
6637 return false;
6638 }
6639 if (Left.is(Kind: tok::equal) && Right.is(Kind: tok::l_brace) &&
6640 Style.Cpp11BracedListStyle == FormatStyle::BLS_Block) {
6641 return false;
6642 }
6643 if (Left.is(TT: TT_AttributeLParen) ||
6644 (Left.is(Kind: tok::l_paren) && Left.is(TT: TT_TypeDeclarationParen))) {
6645 return false;
6646 }
6647 if (Left.is(Kind: tok::l_paren) && Left.Previous &&
6648 (Left.Previous->isOneOf(K1: TT_BinaryOperator, K2: TT_CastRParen))) {
6649 return false;
6650 }
6651 if (Right.is(TT: TT_ImplicitStringLiteral))
6652 return false;
6653
6654 if (Right.is(Kind: tok::r_square) && Right.MatchingParen &&
6655 Right.MatchingParen->is(TT: TT_LambdaLSquare)) {
6656 return false;
6657 }
6658
6659 // Allow breaking after a trailing annotation, e.g. after a method
6660 // declaration.
6661 if (Left.is(TT: TT_TrailingAnnotation)) {
6662 return Right.isNoneOf(Ks: tok::l_brace, Ks: tok::semi, Ks: tok::equal, Ks: tok::l_paren,
6663 Ks: tok::less, Ks: tok::coloncolon);
6664 }
6665
6666 if (Right.isAttribute())
6667 return true;
6668
6669 if (Right.is(TT: TT_AttributeLSquare)) {
6670 assert(Left.isNot(tok::l_square));
6671 return true;
6672 }
6673
6674 if (Left.is(Kind: tok::identifier) && Right.is(Kind: tok::string_literal))
6675 return true;
6676
6677 if (Right.is(Kind: tok::identifier) && Right.Next && Right.Next->is(TT: TT_DictLiteral))
6678 return true;
6679
6680 if (Left.is(TT: TT_CtorInitializerColon)) {
6681 return (Style.BreakConstructorInitializers ==
6682 FormatStyle::BCIS_AfterColon ||
6683 Style.BreakConstructorInitializers ==
6684 FormatStyle::BCIS_AfterComma) &&
6685 (!Right.isTrailingComment() || Right.NewlinesBefore > 0);
6686 }
6687 if (Right.is(TT: TT_CtorInitializerColon)) {
6688 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon &&
6689 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterComma;
6690 }
6691 if (Left.is(TT: TT_CtorInitializerComma) &&
6692 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
6693 return false;
6694 }
6695 if (Right.is(TT: TT_CtorInitializerComma) &&
6696 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
6697 return true;
6698 }
6699 if (Left.is(TT: TT_InheritanceComma) &&
6700 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
6701 return false;
6702 }
6703 if (Right.is(TT: TT_InheritanceComma) &&
6704 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
6705 return true;
6706 }
6707 if (Left.is(TT: TT_ArrayInitializerLSquare))
6708 return true;
6709 if (Right.is(Kind: tok::kw_typename) && Left.isNot(Kind: tok::kw_const))
6710 return true;
6711 if ((Left.isBinaryOperator() || Left.is(TT: TT_BinaryOperator)) &&
6712 Left.isNoneOf(Ks: tok::arrowstar, Ks: tok::lessless) &&
6713 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
6714 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
6715 Left.getPrecedence() == prec::Assignment)) {
6716 return true;
6717 }
6718 if (Left.is(TT: TT_AttributeLSquare) && Right.is(Kind: tok::l_square)) {
6719 assert(Right.isNot(TT_AttributeLSquare));
6720 return false;
6721 }
6722 if (Left.is(Kind: tok::r_square) && Right.is(TT: TT_AttributeRSquare)) {
6723 assert(Left.isNot(TT_AttributeRSquare));
6724 return false;
6725 }
6726
6727 if (Style.BraceWrapping.AfterRequiresExpression &&
6728 Right.is(TT: TT_RequiresExpressionLBrace)) {
6729 return true;
6730 }
6731
6732 auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
6733 if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT: TT_LambdaLBrace)) {
6734 if (isAllmanLambdaBrace(Tok: Left))
6735 return !isEmptyLambdaAllowed(Tok: Left, ShortLambdaOption);
6736 if (isAllmanLambdaBrace(Tok: Right))
6737 return !isEmptyLambdaAllowed(Tok: Right, ShortLambdaOption);
6738 }
6739
6740 if (Right.is(Kind: tok::kw_noexcept) && Right.is(TT: TT_TrailingAnnotation)) {
6741 switch (Style.AllowBreakBeforeNoexceptSpecifier) {
6742 case FormatStyle::BBNSS_Never:
6743 return false;
6744 case FormatStyle::BBNSS_Always:
6745 return true;
6746 case FormatStyle::BBNSS_OnlyWithParen:
6747 return Right.Next && Right.Next->is(Kind: tok::l_paren);
6748 }
6749 }
6750
6751 return Left.isOneOf(K1: tok::comma, K2: tok::coloncolon, Ks: tok::semi, Ks: tok::l_brace,
6752 Ks: tok::kw_class, Ks: tok::kw_struct, Ks: tok::comment) ||
6753 Right.isMemberAccess() ||
6754 Right.isOneOf(K1: TT_TrailingReturnArrow, K2: TT_LambdaArrow, Ks: tok::lessless,
6755 Ks: tok::colon, Ks: tok::l_square, Ks: tok::at) ||
6756 (Left.is(Kind: tok::r_paren) &&
6757 Right.isOneOf(K1: tok::identifier, K2: tok::kw_const)) ||
6758 (Left.is(Kind: tok::l_paren) && Right.isNot(Kind: tok::r_paren)) ||
6759 (Left.is(TT: TT_TemplateOpener) && Right.isNot(Kind: TT_TemplateCloser));
6760}
6761
6762void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) const {
6763 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << ", P=" << Line.PPLevel
6764 << ", T=" << Line.Type << ", C=" << Line.IsContinuation
6765 << "):\n";
6766 const FormatToken *Tok = Line.First;
6767 while (Tok) {
6768 llvm::errs() << " I=" << Tok->IndentLevel << " M=" << Tok->MustBreakBefore
6769 << " C=" << Tok->CanBreakBefore
6770 << " T=" << getTokenTypeName(Type: Tok->getType())
6771 << " S=" << Tok->SpacesRequiredBefore
6772 << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount
6773 << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty
6774 << " Name=" << Tok->Tok.getName() << " N=" << Tok->NestingLevel
6775 << " L=" << Tok->TotalLength
6776 << " PPK=" << Tok->getPackingKind() << " FakeLParens=";
6777 for (prec::Level LParen : Tok->FakeLParens)
6778 llvm::errs() << LParen << "/";
6779 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
6780 llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
6781 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
6782 if (!Tok->Next)
6783 assert(Tok == Line.Last);
6784 Tok = Tok->Next;
6785 }
6786 llvm::errs() << "----\n";
6787}
6788
6789FormatStyle::PointerAlignmentStyle
6790TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) const {
6791 assert(Reference.isOneOf(tok::amp, tok::ampamp));
6792 switch (Style.ReferenceAlignment) {
6793 case FormatStyle::RAS_Pointer:
6794 return Style.PointerAlignment;
6795 case FormatStyle::RAS_Left:
6796 return FormatStyle::PAS_Left;
6797 case FormatStyle::RAS_Right:
6798 return FormatStyle::PAS_Right;
6799 case FormatStyle::RAS_Middle:
6800 return FormatStyle::PAS_Middle;
6801 }
6802 assert(0); //"Unhandled value of ReferenceAlignment"
6803 return Style.PointerAlignment;
6804}
6805
6806FormatStyle::PointerAlignmentStyle
6807TokenAnnotator::getTokenPointerOrReferenceAlignment(
6808 const FormatToken &PointerOrReference) const {
6809 if (PointerOrReference.isOneOf(K1: tok::amp, K2: tok::ampamp))
6810 return getTokenReferenceAlignment(Reference: PointerOrReference);
6811 assert(PointerOrReference.is(tok::star));
6812 return Style.PointerAlignment;
6813}
6814
6815} // namespace format
6816} // namespace clang
6817