clang 24.0.0git
TokenAnnotator.cpp
Go to the documentation of this file.
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"
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
27 const FormatStyle &Style) {
28 switch (Style.BreakAfterAttributes) {
30 return true;
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(tok::kw_for) || Line.startsWith(tok::kw_if) ||
44 Line.startsWith(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(tok::greater) &&
68 Left->Previous->MatchingParen &&
69 Left->Previous->MatchingParen->is(TT_TemplateOpener)) {
70 Left = Left->Previous->MatchingParen;
71 }
72
73 // Check for `[...]`.
74 return Left->Previous && Left->Previous->is(tok::r_square) &&
75 Left->Previous->MatchingParen &&
76 Left->Previous->MatchingParen->is(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(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
83 tok::kw_constexpr, 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(tok::l_square, 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(tok::at, 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(tok::kw_using, tok::identifier, tok::colon))
100 return true;
101 if (AttrTok->isNot(tok::identifier))
102 return false;
103 while (AttrTok && !AttrTok->startsSequence(tok::r_square, 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(tok::colon) ||
108 AttrTok->startsSequence(tok::identifier, tok::identifier) ||
109 AttrTok->startsSequence(tok::r_paren, tok::identifier)) {
110 return false;
111 }
112 if (AttrTok->is(tok::ellipsis))
113 return true;
114 AttrTok = AttrTok->Next;
115 }
116 return AttrTok && AttrTok->startsSequence(tok::r_square, 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(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:
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(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(tok::r_brace))
169 return false;
170 if (BeforeLess->is(tok::r_paren) && Contexts.size() > 1 &&
171 !(BeforeLess->MatchingParen &&
172 BeforeLess->MatchingParen->is(TT_OverloadedOperatorLParen))) {
173 return false;
174 }
175 if (BeforeLess->is(tok::kw_operator) && CurrentToken->is(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(tok::kw_template))
186 Contexts.back().ContextType = Context::TemplateArgument;
187
188 if (Style.isJava() && CurrentToken->is(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(tok::greater)) {
195 const auto *Next = CurrentToken->Next;
196 if (CurrentToken->isNot(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(tok::greater) &&
204 Left->ParentBracket != tok::less &&
205 CurrentToken->getStartOfNonWhitespace() ==
206 Next->getStartOfNonWhitespace().getLocWithOffset(-1)) {
207 return false;
208 }
209 if (InExpr && SeenTernaryOperator &&
210 (!Next || Next->isNoneOf(tok::l_paren, tok::l_brace))) {
211 return false;
212 }
213 if (!MaybeAngles)
214 return false;
215 if (ParentContext.InStaticAssertFirstArgument && Next &&
216 Next->isOneOf(tok::minus, 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(TT_SelectorName, 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_TemplateName)) {
241 next();
242 continue;
243 }
244 if (CurrentToken->is(tok::question) && Style.isJava()) {
245 next();
246 continue;
247 }
248 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, 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(tok::kw_template) &&
258 Prev.is(TT_BinaryOperator) &&
259 Prev.isOneOf(tok::pipepipe, tok::ampamp)) {
260 MaybeAngles = false;
261 }
262 if (Prev.isOneOf(tok::question, tok::colon) && !Style.isProto())
263 SeenTernaryOperator = true;
264 updateParameterCount(Left, CurrentToken);
265 if (Style.Language == FormatStyle::LK_Proto) {
266 if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
267 if (CurrentToken->is(tok::colon) ||
268 (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
269 Previous->isNot(tok::colon))) {
270 Previous->setType(TT_SelectorName);
271 }
272 }
273 } else if (Style.isTableGen()) {
274 if (CurrentToken->isOneOf(tok::comma, 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_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(tok::objc_selector) && MaybeSel->Previous &&
337 MaybeSel->Previous->is(tok::at)) {
338 StartsObjCSelector = true;
339 }
340 }
341 }
342
343 if (OpeningParen.is(TT_OverloadedOperatorLParen)) {
344 // Find the previous kw_operator token.
345 FormatToken *Prev = &OpeningParen;
346 while (Prev->isNot(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(tok::period, tok::arrow);
356 Contexts.back().IsExpression = OperatorCalledAsMemberFunction;
357 } else if (OpeningParen.is(TT_VerilogInstancePortLParen)) {
358 Contexts.back().IsExpression = true;
359 Contexts.back().ContextType = Context::VerilogInstancePortList;
360 } else if (Style.isJavaScript() &&
361 (Line.startsWith(Keywords.kw_type, tok::identifier) ||
362 Line.startsWith(tok::kw_export, Keywords.kw_type,
363 tok::identifier))) {
364 // type X = (...);
365 // export type X = (...);
366 Contexts.back().IsExpression = false;
367 } else if (OpeningParen.Previous &&
368 (OpeningParen.Previous->isOneOf(
369 tok::kw_noexcept, tok::kw_explicit, tok::kw_while,
370 tok::l_paren, tok::comma, TT_CastRParen,
371 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(Keywords.kw_function) ||
377 (OpeningParen.Previous->endsSequence(tok::identifier,
378 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_JsTypeColon)) {
383 // let x: (SomeType);
384 Contexts.back().IsExpression = false;
385 } else if (isLambdaParameterList(&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_RequiresExpressionLParen)) {
390 Contexts.back().IsExpression = false;
391 } else if (OpeningParen.Previous &&
392 OpeningParen.Previous->is(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(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_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 TT_ObjCBlockLParen, 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(tok::kw_for, 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_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(&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_Unknown)) {
448 if (PrevNonComment->isAttribute()) {
449 OpeningParen.setType(TT_AttributeLParen);
450 } else if (PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
451 tok::kw_typeof,
452#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) tok::kw___##Trait,
453#include "clang/Basic/BuiltinTraits.inc"
454 tok::kw__Atomic)) {
455 OpeningParen.setType(TT_TypeDeclarationParen);
456 // decltype() and typeof() usually contain expressions.
457 if (PrevNonComment->isOneOf(tok::kw_decltype, 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(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(tok::caret);
481 bool HasMultipleLines = false;
482 bool HasMultipleParametersOnALine = false;
483 bool MightBeObjCForRangeLoop =
484 OpeningParen.Previous && OpeningParen.Previous->is(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_PointerOrReference) &&
490 PrevPrev->isOneOf(tok::l_paren, tok::coloncolon)) {
491 ProbablyFunctionType = true;
492 }
493 if (CurrentToken->is(tok::comma))
494 MightBeFunctionType = false;
495 if (Prev.is(TT_BinaryOperator))
496 Contexts.back().IsExpression = true;
497 if (CurrentToken->is(tok::r_paren)) {
498 if (Prev.is(TT_PointerOrReference) &&
499 (PrevPrev == &OpeningParen || PrevPrev->is(tok::coloncolon))) {
500 MightBeFunctionType = true;
501 }
502 if (OpeningParen.isNot(TT_CppCastLParen) && MightBeFunctionType &&
503 ProbablyFunctionType && CurrentToken->Next &&
504 (CurrentToken->Next->is(tok::l_paren) ||
505 (CurrentToken->Next->is(tok::l_square) &&
506 (Line.MustBeDeclaration ||
507 (PrevNonComment && PrevNonComment->isTypeName(LangOpts)))))) {
508 OpeningParen.setType(OpeningParen.Next->is(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(tok::l_brace) &&
516 OpeningParen.Previous && OpeningParen.Previous->is(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_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_AttributeLParen))
536 CurrentToken->setType(TT_AttributeRParen);
537 if (OpeningParen.is(TT_TypeDeclarationParen))
538 CurrentToken->setType(TT_TypeDeclarationParen);
539 if (OpeningParen.Previous &&
540 OpeningParen.Previous->is(TT_JavaAnnotation)) {
541 CurrentToken->setType(TT_JavaAnnotation);
542 }
543 if (OpeningParen.Previous &&
544 OpeningParen.Previous->is(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(tok::r_square, tok::r_brace))
559 return false;
560
561 if (CurrentToken->is(tok::l_brace) && OpeningParen.is(TT_ObjCBlockLParen))
562 OpeningParen.setType(TT_Unknown);
563 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
564 !CurrentToken->Next->HasUnescapedNewline &&
565 !CurrentToken->Next->isTrailingComment()) {
566 HasMultipleParametersOnALine = true;
567 }
568 bool ProbablyFunctionTypeLParen =
569 (CurrentToken->is(tok::l_paren) && CurrentToken->Next &&
570 CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret));
571 if ((Prev.isOneOf(tok::kw_const, tok::kw_auto) ||
572 Prev.isTypeName(LangOpts)) &&
573 !(CurrentToken->is(tok::l_brace) ||
574 (CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen))) {
575 Contexts.back().IsExpression = false;
576 }
577 if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
578 MightBeObjCForRangeLoop = false;
579 if (PossibleObjCForInToken) {
580 PossibleObjCForInToken->setType(TT_Unknown);
581 PossibleObjCForInToken = nullptr;
582 }
583 }
584 if (IsIf && CurrentToken->is(tok::semi)) {
585 for (auto *Tok = OpeningParen.Next;
586 Tok != CurrentToken &&
587 Tok->isNoneOf(tok::equal, tok::l_paren, tok::l_brace);
588 Tok = Tok->Next) {
589 if (Tok->isPointerOrReference())
590 Tok->setFinalizedType(TT_PointerOrReference);
591 }
592 }
593 if (MightBeObjCForRangeLoop && CurrentToken->is(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(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(tok::comma)) {
608 if (Contexts.back().IsTableGenCondOpe)
609 CurrentToken->setType(TT_TableGenCondOperatorComma);
610 next();
611 } else if (CurrentToken->is(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(&OpeningParen, 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(tok::identifier))
638 return false;
639
640 // Chains of [] in `identifier[i][j][k]` are not attributes.
641 if (Tok.Previous && Tok.Previous->is(tok::r_square)) {
642 auto *MatchingParen = Tok.Previous->MatchingParen;
643 if (!MatchingParen || MatchingParen->is(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(tok::r_square))
653 return false;
654
655 // Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
656 while (AttrTok && AttrTok->isNot(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(tok::comment, tok::kw_class, tok::kw_static,
670 tok::l_square, Keywords.kw_internal)) {
671 return true;
672 }
673
674 // incase its a [XXX] retval func(....
675 if (AttrTok->Next &&
676 AttrTok->Next->startsSequence(tok::identifier, 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_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, *Left) || IsInnerSquare;
706
707 // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
708 bool IsCSharpAttributeSpecifier =
709 isCSharpAttributeSpecifier(*Left) ||
710 Contexts.back().InCSharpAttributeSpecifier;
711
712 bool InsideInlineASM = Line.startsWith(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(TT_LambdaLSquare) &&
718 CurrentToken->isNoneOf(tok::l_brace, 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(tok::comma) ||
723 Contexts.back().ContextKind != tok::l_brace) &&
724 (!Parent ||
725 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
726 tok::kw_return, tok::kw_throw) ||
727 Parent->isUnaryOperator() ||
728 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
729 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
730 (getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
732 bool ColonFound = false;
733
734 unsigned BindingIncrease = 1;
735 if (IsCppStructuredBinding) {
736 Left->setType(TT_StructuredBindingLSquare);
737 } else if (Left->is(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(tok::l_brace, tok::comma)) {
751 Left->setType(TT_JsComputedPropertyName);
752 } else if (IsCpp && Contexts.back().ContextKind == tok::l_brace &&
753 Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
754 Left->setType(TT_DesignatedInitializerLSquare);
755 } else if (IsCSharpAttributeSpecifier) {
756 Left->setType(TT_AttributeLSquare);
757 } else if (CurrentToken->is(tok::r_square) && Parent &&
758 Parent->is(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(tok::l_square, tok::numeric_constant,
789 tok::equal) &&
790 !Left->endsSequence(tok::l_square, tok::numeric_constant,
791 tok::identifier) &&
792 !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
793 Left->setType(TT_ProtoExtensionLSquare);
794 BindingIncrease = 10;
795 }
796 } else if (!CppArrayTemplates && Parent &&
797 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
798 tok::comma, tok::l_paren, tok::l_square,
799 tok::question, tok::colon, tok::kw_return,
800 // Should only be relevant to JavaScript:
801 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_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(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(tok::l_paren)) ||
828 (CurrentToken->Previous &&
829 CurrentToken->Previous->Previous == Left)) &&
830 Left->is(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_Unknown) &&
844 canBeObjCSelectorComponent(*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_PointerOrReference))
851 Parent->overwriteFixedType(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_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_TableGenListOpener))
876 CurrentToken->setType(TT_TableGenListCloser);
877 next();
878 return true;
879 }
880 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
881 return false;
882 if (CurrentToken->is(tok::colon)) {
883 if (IsCpp11AttributeSpecifier &&
884 CurrentToken->endsSequence(tok::colon, tok::identifier,
885 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(TT_ArraySubscriptLSquare,
891 TT_DesignatedInitializerLSquare)) {
892 Left->setType(TT_ObjCMethodExpr);
893 StartsObjCMethodExpr = true;
894 Contexts.back().ColonIsObjCMethodExpr = true;
895 if (Parent && Parent->is(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(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
903 !ColonFound) {
904 Left->setType(TT_ArrayInitializerLSquare);
905 }
906 FormatToken *Tok = CurrentToken;
907 if (Style.isTableGen()) {
908 if (CurrentToken->isOneOf(tok::comma, tok::minus, 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, Tok);
918 continue;
919 }
920 if (!consumeToken())
921 return false;
922 updateParameterCount(Left, Tok);
923 }
924 return false;
925 }
926
927 void skipToNextNonComment() {
928 next();
929 while (CurrentToken && CurrentToken->is(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(tok::comment))
942 next();
943 if (!parseTableGenSimpleValue())
944 return false;
945 if (!CurrentToken)
946 return true;
947 // Value "#" [Value]
948 if (CurrentToken->is(tok::hash)) {
949 if (CurrentToken->Next &&
950 CurrentToken->Next->isOneOf(tok::colon, tok::semi, 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(tok::l_brace))
968 return true;
969 // These tokens indicates this is a value with suffixes.
970 if (CurrentToken->isOneOf(tok::l_brace, tok::l_square, tok::period)) {
971 CurrentToken->setType(TT_TableGenValueSuffix);
972 FormatToken *Suffix = CurrentToken;
973 skipToNextNonComment();
974 if (Suffix->is(tok::l_square))
975 return parseSquare();
976 if (Suffix->is(tok::l_brace)) {
977 Scopes.push_back(getScopeType(*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(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(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(tok::identifier) ||
1027 Tok.isOneOf(TT_TableGenBangOperator, 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(tok::colon))
1032 return false;
1033 return llvm::is_contained(Opes, 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(*FirstTok)) {
1047 // Special case for identifier DAGArg operator.
1048 BreakInside = true;
1049 Opener->setType(TT_TableGenDAGArgOpenerToBreak);
1050 if (FirstTok->isOneOf(TT_TableGenBangOperator,
1051 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(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(tok::comma)) {
1075 CurrentToken->setType(BreakInside ? TT_TableGenDAGArgListCommaToBreak
1076 : TT_TableGenDAGArgListComma);
1077 skipToNextNonComment();
1078 }
1079 if (CurrentToken && CurrentToken->is(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 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(tok::numeric_constant, tok::string_literal,
1104 TT_TableGenMultiLineString, tok::kw_true, tok::kw_false,
1105 tok::question, tok::kw_int)) {
1106 return true;
1107 }
1108 // SimpleValue 4: ValueList, Type
1109 if (Tok->is(tok::l_brace)) {
1110 Scopes.push_back(getScopeType(*Tok));
1111 return parseBrace();
1112 }
1113 // SimpleValue 5: List initializer
1114 if (Tok->is(tok::l_square)) {
1115 Tok->setType(TT_TableGenListOpener);
1116 if (!parseSquare())
1117 return false;
1118 if (Tok->is(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(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(Tok);
1132 }
1133 // SimpleValue 9: Bang operator
1134 if (Tok->is(TT_TableGenBangOperator)) {
1135 if (CurrentToken && CurrentToken->is(tok::less)) {
1136 CurrentToken->setType(TT_TemplateOpener);
1137 skipToNextNonComment();
1138 if (!parseAngle())
1139 return false;
1140 }
1141 if (!CurrentToken || CurrentToken->isNot(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_TableGenCondOperator)) {
1152 if (!CurrentToken || CurrentToken->isNot(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(tok::identifier)) {
1161 // SimpleValue 8: Anonymous record
1162 if (CurrentToken && CurrentToken->is(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(Contexts.rbegin(), 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(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(BK_BracedInit))
1203 Contexts.back().IsExpression = true;
1204 if (Style.isJavaScript() && OpeningBrace.Previous &&
1205 OpeningBrace.Previous->is(TT_JsTypeColon)) {
1206 Contexts.back().IsExpression = false;
1207 }
1208 if (Style.isVerilog() &&
1209 (!OpeningBrace.getPreviousNonComment() ||
1210 OpeningBrace.getPreviousNonComment()->isNot(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(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(tok::r_paren, tok::r_square))
1235 return false;
1236 updateParameterCount(&OpeningBrace, CurrentToken);
1237 if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
1238 FormatToken *Previous = CurrentToken->getPreviousNonComment();
1239 if (Previous->is(TT_JsTypeOptionalQuestion))
1240 Previous = Previous->getPreviousNonComment();
1241 if ((CurrentToken->is(tok::colon) && !Style.isTableGen() &&
1242 (!Contexts.back().ColonIsDictLiteral || !IsCpp)) ||
1243 Style.isProto()) {
1244 OpeningBrace.setType(TT_DictLiteral);
1245 Scopes.back() = getScopeType(OpeningBrace);
1246 if (Previous->Tok.getIdentifierInfo() ||
1247 Previous->is(tok::string_literal)) {
1248 Previous->setType(TT_SelectorName);
1249 }
1250 }
1251 if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown) &&
1252 !Style.isTableGen()) {
1253 OpeningBrace.setType(TT_DictLiteral);
1254 Scopes.back() = getScopeType(OpeningBrace);
1255 } else if (Style.isJavaScript()) {
1256 OpeningBrace.overwriteFixedType(TT_DictLiteral);
1257 Scopes.back() = getScopeType(OpeningBrace);
1258 }
1259 }
1260 bool IsBracedListComma = false;
1261 if (CurrentToken->is(tok::comma)) {
1262 if (Style.isJavaScript()) {
1263 OpeningBrace.overwriteFixedType(TT_DictLiteral);
1264 Scopes.back() = getScopeType(OpeningBrace);
1265 } else {
1266 IsBracedListComma = OpeningBrace.is(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(tok::l_brace) && Current->is(BK_Block))
1283 ++Left->BlockParameterCount;
1284 if (Current->is(tok::comma)) {
1285 ++Left->ParameterCount;
1286 if (!Left->Role)
1287 Left->Role.reset(new CommaSeparatedList(Style));
1288 Left->Role->CommaFound(Current);
1289 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
1290 Left->ParameterCount = 1;
1291 }
1292 }
1293
1294 bool parseConditional() {
1295 while (CurrentToken) {
1296 if (CurrentToken->is(tok::colon) && CurrentToken->is(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(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(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_AttributeRSquare) &&
1335 CurrentToken->isOneOf(tok::kw_if, tok::kw_switch, tok::kw_case,
1336 tok::kw_default, tok::kw_for, tok::kw_while) &&
1337 mustBreakAfterAttributes(*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_VerilogTableItem))
1346 return true;
1347 // Multi-line string itself is a single annotated token.
1348 if (Tok->is(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(tok::kw_enum, 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(TT_BinaryOperator)) {
1390 // The distribution weight operators are labeled
1391 // TT_BinaryOperator by the lexer.
1392 if (Keywords.isVerilogEnd(*Prev) || Keywords.isVerilogBegin(*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(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(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(TT_ObjCMethodSpecifier) &&
1422 Prev->is(tok::identifier) && Prev->is(TT_Unknown);
1423 if (!PrevPrev ||
1424 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
1425 !(PrevPrev->is(TT_CastRParen) ||
1426 (PrevPrev->is(TT_ObjCMethodExpr) && PrevPrev->is(tok::colon))) ||
1427 PrevPrev->is(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(tok::semi, 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(tok::numeric_constant)) ||
1452 (Prev->is(TT_StartOfName) && !Scopes.empty() &&
1453 Scopes.back() == ST_Class)) {
1454 Tok->setType(TT_BitFieldColon);
1455 } else if (Contexts.size() == 1 &&
1456 Line.getFirstNonComment()->isNoneOf(tok::kw_enum, tok::kw_case,
1457 tok::kw_default) &&
1458 !Line.startsWith(tok::kw_typedef, tok::kw_enum)) {
1459 if (Prev->isOneOf(tok::r_paren, tok::kw_noexcept) ||
1460 Prev->ClosesRequiresClause) {
1461 Tok->setType(TT_CtorInitializerColon);
1462 } else if (Prev->is(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(tok::r_paren, 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(*Prev) && Next &&
1475 (Next->isOneOf(tok::r_paren, tok::comma) ||
1476 (canBeObjCSelectorComponent(*Next) && Next->Next &&
1477 Next->Next->is(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(Keywords.kw_then))
1496 next(); // skip then
1497 break;
1498 }
1499 if (CurrentToken &&
1500 CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier)) {
1501 next();
1502 }
1503 IsIf = true;
1504 [[fallthrough]];
1505 case tok::kw_while:
1506 if (CurrentToken && CurrentToken->is(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(tok::period)) || (Next && Next->is(tok::colon)))
1516 break;
1517 // JS' for await ( ...
1518 if (CurrentToken && CurrentToken->is(Keywords.kw_await))
1519 next();
1520 }
1521 if (IsCpp && CurrentToken && CurrentToken->is(tok::kw_co_await))
1522 next();
1523 Contexts.back().ColonIsForRangeExpr = true;
1524 if (!CurrentToken || CurrentToken->isNot(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(tok::r_paren) && Prev->MatchingParen &&
1536 Prev->MatchingParen->is(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(*Prev) &&
1561 Keywords.isVerilogIdentifier(*PrevPrev)) {
1562 return true;
1563 }
1564 // Case B.
1565 if (Prev->is(Keywords.kw_verilogHash) &&
1566 Keywords.isVerilogIdentifier(*PrevPrev)) {
1567 return true;
1568 }
1569 // Case C.
1570 if (Keywords.isVerilogIdentifier(*Prev) && PrevPrev->is(tok::r_paren))
1571 return true;
1572 // Case D.
1573 if (Keywords.isVerilogIdentifier(*Prev) && PrevPrev->is(tok::comma)) {
1574 const FormatToken *PrevParen = PrevPrev->getPreviousNonComment();
1575 if (PrevParen && PrevParen->is(tok::r_paren) &&
1576 PrevParen->MatchingParen &&
1577 PrevParen->MatchingParen->is(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(TT_ObjCProperty) &&
1592 !Line.startsWith(tok::l_paren) &&
1593 Tok->isNoneOf(TT_TypeDeclarationParen, TT_RequiresExpressionLParen)) {
1594 if (!Prev ||
1595 (!Prev->isAttribute() &&
1596 Prev->isNoneOf(TT_RequiresClause, TT_LeadingJavaAnnotation,
1597 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_RequiresExpressionLBrace))
1612 Line.Type = LT_RequiresExpression;
1613 } else if (Style.isTextProto()) {
1614 if (Prev && Prev->isNot(TT_DictLiteral))
1615 Prev->setType(TT_SelectorName);
1616 }
1617 Scopes.push_back(getScopeType(*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(TT_SelectorName, TT_DictLiteral))) {
1632 Tok->setType(TT_DictLiteral);
1633 if (Prev && Prev->isNot(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(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_Unknown))
1658 Tok->setType(TT_BinaryOperator);
1659 if (Prev && Prev->is(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(tok::kw_co_await) ||
1671 Info->isCPlusPlusOperatorKeyword())) {
1672 FormatToken *LParen;
1673 if (CurrentToken->startsSequence(tok::kw_decltype, tok::l_paren,
1674 tok::kw_auto, 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(tok::l_paren); LParen = LParen->Next) {
1681 if (LParen->isPointerOrReference())
1682 LParen->setFinalizedType(TT_PointerOrReference);
1683 }
1684 }
1685 if (LParen && LParen->is(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(tok::l_paren, tok::semi, tok::r_paren,
1696 tok::r_brace)) {
1697 if (CurrentToken->isOneOf(tok::star, tok::amp))
1698 CurrentToken->setType(TT_PointerOrReference);
1699 auto Next = CurrentToken->getNextNonComment();
1700 if (!Next)
1701 break;
1702 if (Next->is(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(tok::comma) && Previous->isNot(tok::kw_operator))
1711 break;
1712 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator, tok::comma,
1713 tok::arrow) ||
1714 (!Previous->isTypeFinalized() &&
1715 Previous->isPointerOrReference()) ||
1716 // User defined literal.
1717 Previous->TokenText.starts_with("\"\"")) {
1718 Previous->setType(TT_OverloadedOperator);
1719 if (CurrentToken->isOneOf(tok::less, tok::greater))
1720 break;
1721 }
1722 }
1723 if (CurrentToken && CurrentToken->is(tok::l_paren))
1724 CurrentToken->setType(TT_OverloadedOperatorLParen);
1725 if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
1726 CurrentToken->Previous->setType(TT_OverloadedOperator);
1727 break;
1728 case tok::question:
1729 if (Style.isJavaScript() && Next &&
1730 Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
1731 tok::r_brace, 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(tok::r_paren, tok::greater) ||
1749 Next->startsSequence(tok::identifier, tok::semi) ||
1750 Next->startsSequence(tok::identifier, 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(tok::identifier, tok::string_literal) ||
1762 !Next->Next || Next->Next->isNoneOf(tok::colon, 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(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) &&
1800 (Line.Level > 1 || (!Line.InPPDirective && Line.Level > 0))) {
1801 --Line.Level;
1802 }
1803 break;
1804 case tok::identifier:
1805 if (Tok->isOneOf(Keywords.kw___has_include,
1806 Keywords.kw___has_include_next)) {
1807 parseHasInclude();
1808 }
1809 if (IsCpp) {
1810 if (Next && Next->is(tok::l_paren) && Prev &&
1811 Prev->isOneOf(tok::kw___cdecl, tok::kw___stdcall,
1812 tok::kw___fastcall, tok::kw___thiscall,
1813 tok::kw___regcall, tok::kw___vectorcall)) {
1814 Tok->setFinalizedType(TT_FunctionDeclarationName);
1815 Next->setFinalizedType(TT_FunctionDeclarationLParen);
1816 }
1817 } else if (Style.isCSharp()) {
1818 if (Tok->is(Keywords.kw_where) && Next && Next->isNot(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(Keywords.kw_assert)) {
1826 if (!parseTableGenValue())
1827 return false;
1828 } else if (Tok->isOneOf(Keywords.kw_def, Keywords.kw_defm) &&
1829 (!Next || Next->isNoneOf(tok::colon, tok::l_brace))) {
1830 // The case NameValue appears.
1831 if (!parseTableGenValue(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(TT_LambdaArrow) && Prev && Prev->is(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(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(tok::greater)) {
1867 CurrentToken->setType(TT_TemplateCloser);
1868 --OpenAngleBracketsCount;
1869 next();
1870 } else if (CurrentToken->is(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(Keywords.kw_where)) {
1876 CurrentToken->setType(TT_CSharpGenericTypeConstraint);
1877 next();
1878 } else if (CurrentToken->is(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(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(tok::comment) &&
1894 !CurrentToken->TokenText.starts_with("//")) {
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(Keywords.kw_mark, Keywords.kw_option,
1917 Keywords.kw_region)) {
1918 bool IsMarkOrRegion =
1919 CurrentToken->isOneOf(Keywords.kw_mark, 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_BinaryOperator))
1924 CurrentToken->setType(TT_ImplicitStringLiteral);
1925 next();
1926 }
1927 }
1928 }
1929
1930 void parseHasInclude() {
1931 if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
1932 return;
1933 next(); // '('
1934 parseIncludeDirective();
1935 next(); // ')'
1936 }
1937
1938 LineType parsePreprocessorDirective() {
1939 bool IsFirstToken = CurrentToken->IsFirst;
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(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(*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();
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(tok::l_paren)) {
1999 parseParens();
2000 } else if (Tok->isOneOf(Keywords.kw___has_include,
2001 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(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(Keywords.kw_package)) ||
2027 (!Style.isVerilog() && Info &&
2028 Info->getPPKeywordID() == tok::pp_import && CurrentToken->Next &&
2029 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
2030 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(tok::less) && Line.Last->is(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(Keywords.kw_option, Keywords.kw_package)) {
2047 next();
2048 if (CurrentToken && CurrentToken->is(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(Keywords.kw_import))
2060 ImportStatement = true;
2061
2062 while (CurrentToken) {
2063 if (CurrentToken->is(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(tok::kw_export) &&
2073 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
2074 CurrentToken->Next->isStringLiteral()) {
2075 ImportStatement = true;
2076 }
2077 if (isClosureImportStatement(*CurrentToken))
2078 ImportStatement = true;
2079 }
2080 if (!consumeToken())
2081 return LT_Invalid;
2082 }
2083 if (const auto Type = Line.Type; Type == LT_AccessModifier ||
2086 return Type;
2087 }
2088 if (KeywordVirtualFound)
2090 if (ImportStatement)
2091 return LT_ImportStatement;
2092
2093 if (Line.startsWith(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)
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(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(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 TT_LambdaLSquare, TT_LambdaLBrace, TT_AttributeMacro, TT_IfMacro,
2131 TT_ForEachMacro, TT_TypenameMacro, TT_FunctionLBrace,
2132 TT_ImplicitStringLiteral, TT_InlineASMBrace, TT_FatArrow,
2133 TT_LambdaArrow, TT_NamespaceMacro, TT_OverloadedOperator,
2134 TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral,
2135 TT_UntouchableMacroFunc, TT_StatementAttributeLikeMacro,
2136 TT_FunctionLikeOrFreestandingMacro, TT_ClassLBrace, TT_EnumLBrace,
2137 TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, TT_RequiresClause,
2138 TT_RequiresClauseInARequiresExpression, TT_RequiresExpression,
2139 TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace,
2140 TT_CompoundRequirementLBrace, TT_BracedListLBrace,
2141 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(*CurrentToken);
2157 determineTokenType(*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(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(tok::kw_using, tok::kw_return))
2246 return false;
2247 if (Line.First->is(tok::kw_template)) {
2248 assert(Current.Previous);
2249 if (Current.Previous->is(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(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(tok::kw_typename,
2267 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(tok::kw_class, tok::kw_enum, tok::kw_struct,
2278 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(Keywords.kw_type, tok::identifier) ||
2289 Line.startsWith(tok::kw_export, Keywords.kw_type,
2290 tok::identifier))) {
2291 return false;
2292 }
2293
2294 return !Current.Previous || Current.Previous->isNot(tok::kw_operator);
2295 };
2296
2297 if (AssignmentStartsExpression()) {
2298 Contexts.back().IsExpression = true;
2299 if (!Line.startsWith(TT_UnaryOperator)) {
2300 for (FormatToken *Previous = Current.Previous;
2301 Previous && Previous->Previous &&
2302 Previous->Previous->isNoneOf(tok::comma, tok::semi);
2303 Previous = Previous->Previous) {
2304 if (Previous->isOneOf(tok::r_square, tok::r_paren, 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(TT_BinaryOperator, TT_UnaryOperator) &&
2313 Previous->isPointerOrReference() && Previous->Previous &&
2314 Previous->Previous->isNot(tok::equal)) {
2315 Previous->setType(TT_PointerOrReference);
2316 }
2317 }
2318 }
2319 } else if (Current.is(tok::lessless) &&
2320 (!Current.Previous ||
2321 Current.Previous->isNot(tok::kw_operator))) {
2322 Contexts.back().IsExpression = true;
2323 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
2324 Contexts.back().IsExpression = true;
2325 } else if (Current.is(TT_TrailingReturnArrow)) {
2326 Contexts.back().IsExpression = false;
2327 } else if (Current.isOneOf(TT_LambdaArrow, Keywords.kw_assert)) {
2328 Contexts.back().IsExpression = Style.isJava();
2329 } else if (Current.Previous &&
2330 Current.Previous->is(TT_CtorInitializerColon)) {
2331 Contexts.back().IsExpression = true;
2332 Contexts.back().ContextType = Context::CtorInitializer;
2333 } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
2334 Contexts.back().ContextType = Context::InheritanceList;
2335 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
2336 for (FormatToken *Previous = Current.Previous;
2337 Previous && Previous->isOneOf(tok::star, 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(tok::kw_new)) {
2346 Contexts.back().CanBeExpression = false;
2347 } else if (Current.is(tok::semi) ||
2348 (Current.is(tok::exclaim) && Current.Previous &&
2349 Current.Previous->isNot(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(tok::l_paren))
2362 ++ParenLevel;
2363 if (Current->is(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(tok::r_paren) &&
2375 Current.startsSequence(tok::arrow, tok::identifier, 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(tok::l_paren)) {
2382 // No Matching Paren yet so skip to matching paren
2383 TemplateCloser = untilMatchingParen(TemplateCloser);
2384 if (!TemplateCloser)
2385 break;
2386 }
2387 if (TemplateCloser->is(tok::less))
2388 ++NestingLevel;
2389 if (TemplateCloser->is(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(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(TT_Unknown)) {
2414 // The token type is already known.
2415 return;
2416 }
2417
2418 if ((Style.isJavaScript() || Style.isCSharp()) &&
2419 Current.is(tok::exclaim)) {
2420 if (Current.Previous) {
2421 bool IsIdentifier =
2422 Style.isJavaScript()
2423 ? Keywords.isJavaScriptIdentifier(
2424 *Current.Previous, /* AcceptIdentifierName= */ true)
2425 : Current.Previous->is(tok::identifier);
2426 if (IsIdentifier ||
2427 Current.Previous->isOneOf(
2428 tok::kw_default, tok::kw_namespace, tok::r_paren, tok::r_square,
2429 tok::r_brace, tok::kw_false, tok::kw_true, Keywords.kw_type,
2430 Keywords.kw_get, Keywords.kw_init, 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(TT_BinaryOperator, 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(Keywords.kw_instanceof)) {
2448 Current.setType(TT_BinaryOperator);
2449 } else if (isStartOfName(Current) &&
2450 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
2451 Contexts.back().FirstStartOfName = &Current;
2452 Current.setType(TT_StartOfName);
2453 } else if (Current.is(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(tok::kw_auto, tok::kw___auto_type)) {
2459 AutoFound = true;
2460 } else if (Current.is(tok::arrow) && Style.isJava()) {
2461 Current.setType(TT_LambdaArrow);
2462 } else if (Current.is(tok::arrow) && Style.isVerilog()) {
2463 // The implication operator.
2464 Current.setType(TT_BinaryOperator);
2465 } else if (Current.is(tok::arrow) && AutoFound &&
2466 Line.MightBeFunctionDecl && Current.NestingLevel == 0 &&
2467 Current.Previous->isNoneOf(tok::kw_operator, tok::identifier)) {
2468 // not auto operator->() -> xxx;
2469 Current.setType(TT_TrailingReturnArrow);
2470 } else if (Current.is(tok::arrow) && Current.Previous &&
2471 Current.Previous->is(tok::r_brace) &&
2472 Current.Previous->is(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 Current,
2482 (Contexts.back().CanBeExpression && Contexts.back().IsExpression) ||
2483 Contexts.back().InStaticAssertFirstArgument,
2484 Contexts.back().ContextType == Context::TemplateArgument));
2485 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret) ||
2486 (Style.isVerilog() && Current.is(tok::pipe))) {
2487 Current.setType(determinePlusMinusCaretUsage(Current));
2488 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
2489 Contexts.back().CaretFound = true;
2490 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
2491 Current.setType(determineIncrementUsage(Current));
2492 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
2493 Current.setType(TT_UnaryOperator);
2494 } else if (Current.is(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(tok::l_square)) &&
2510 (Current.isNot(tok::greater) && !Style.isTextProto())) {
2511 if (Style.isVerilog()) {
2512 if (Current.is(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(tok::comment)) {
2524 if (Current.TokenText.starts_with("/*")) {
2525 if (Current.TokenText.ends_with("*/")) {
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(tok::string_literal)) {
2536 if (Style.isVerilog() && Contexts.back().VerilogMayBeConcatenation &&
2537 Current.getPreviousNonComment() &&
2538 Current.getPreviousNonComment()->isOneOf(tok::comma, tok::l_brace) &&
2539 Current.getNextNonComment() &&
2540 Current.getNextNonComment()->isOneOf(tok::comma, tok::r_brace)) {
2541 Current.setType(TT_StringInConcatenation);
2542 }
2543 } else if (Current.is(tok::l_paren)) {
2544 if (lParenStartsCppCast(Current))
2545 Current.setType(TT_CppCastLParen);
2546 } else if (Current.is(tok::r_paren)) {
2547 if (rParenEndsCast(Current))
2548 Current.setType(TT_CastRParen);
2549 if (Current.MatchingParen && Current.MatchingParen->is(TT_InlineASMParen))
2550 Current.setType(TT_InlineASMParen);
2551 if (Current.MatchingParen && Current.Next &&
2552 !Current.Next->isBinaryOperator() &&
2553 Current.Next->isNoneOf(
2554 tok::semi, tok::colon, tok::l_brace, tok::l_paren, tok::comma,
2555 tok::period, tok::arrow, tok::coloncolon, tok::kw_noexcept)) {
2556 if (FormatToken *AfterParen = Current.MatchingParen->Next;
2557 AfterParen && AfterParen->isNot(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(tok::identifier) &&
2561 BeforeParen->isNot(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(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(tok::period)) {
2587 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
2588 if (PreviousNoComment &&
2589 PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) {
2590 Current.setType(TT_DesignatedInitializerPeriod);
2591 } else if (Style.isJava() && Current.Previous &&
2592 Current.Previous->isOneOf(TT_JavaAnnotation,
2593 TT_LeadingJavaAnnotation)) {
2594 Current.setType(Current.Previous->getType());
2595 }
2596 } else if (canBeObjCSelectorComponent(Current) &&
2597 // FIXME(bug 36976): ObjC return types shouldn't use
2598 // TT_CastRParen.
2599 Current.Previous && Current.Previous->is(TT_CastRParen) &&
2600 Current.Previous->MatchingParen &&
2601 Current.Previous->MatchingParen->Previous &&
2602 Current.Previous->MatchingParen->Previous->is(
2603 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(tok::identifier, tok::kw_const, tok::kw_noexcept,
2609 tok::kw_requires) &&
2610 Current.Previous &&
2611 Current.Previous->isNoneOf(tok::equal, tok::at,
2612 TT_CtorInitializerComma,
2613 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(tok::at) &&
2620 Current.isNot(Keywords.kw_interface)) {
2621 const FormatToken &AtToken = *Current.Previous;
2622 const FormatToken *Previous = AtToken.getPreviousNonComment();
2623 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
2624 Current.setType(TT_LeadingJavaAnnotation);
2625 else
2626 Current.setType(TT_JavaAnnotation);
2627 } else if (Current.Previous->is(tok::period) &&
2628 Current.Previous->isOneOf(TT_JavaAnnotation,
2629 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(tok::identifier) || Tok.is(TT_ClassHeadName))
2646 return false;
2647
2648 if (Tok.endsSequence(Keywords.kw_final, TT_ClassHeadName))
2649 return false;
2650
2651 if ((Style.isJavaScript() || Style.isJava()) && Tok.is(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(TT_ClassHeadName, tok::string_literal) ||
2659 (Line.InPragmaDirective && NextNonComment->is(tok::identifier))))) {
2660 return false;
2661 }
2662
2663 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
2664 Keywords.kw_as)) {
2665 return false;
2666 }
2667 if (Style.isJavaScript() && Tok.Previous->is(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(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(*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(tok::identifier) &&
2694 PreviousNotConst->Previous &&
2695 PreviousNotConst->Previous->is(tok::hash);
2696
2697 if (PreviousNotConst->is(TT_TemplateCloser)) {
2698 return PreviousNotConst && PreviousNotConst->MatchingParen &&
2699 PreviousNotConst->MatchingParen->Previous &&
2700 PreviousNotConst->MatchingParen->Previous->isNoneOf(
2701 tok::period, tok::kw_template);
2702 }
2703
2704 if ((PreviousNotConst->is(tok::r_paren) &&
2705 PreviousNotConst->is(TT_TypeDeclarationParen)) ||
2706 PreviousNotConst->is(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(tok::identifier, tok::kw_auto) &&
2716 !PreviousNotConst->endsSequence(Keywords.kw_import, tok::kw_export) &&
2717 PreviousNotConst->isNot(TT_StatementAttributeLikeMacro)) {
2718 return true;
2719 }
2720
2721 // *a or &a or &&a.
2722 if (PreviousNotConst->is(TT_PointerOrReference) ||
2723 PreviousNotConst->endsSequence(tok::coloncolon,
2724 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(tok::r_square))
2734 return true;
2735
2736 // const a = in JavaScript.
2737 return Style.isJavaScript() && PreviousNotConst->is(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_TemplateCloser) &&
2748 LeftOfParens->MatchingParen) {
2749 auto *Prev = LeftOfParens->MatchingParen->getPreviousNonComment();
2750 if (Prev &&
2751 Prev->isOneOf(tok::kw_const_cast, tok::kw_dynamic_cast,
2752 tok::kw_reinterpret_cast, 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(TT_OverloadedOperatorLParen, 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(tok::r_paren) &&
2788 LeftOfParens->isNot(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(tok::r_square)) {
2797 // delete[] (void *)ptr;
2798 auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
2799 if (Tok->isNot(tok::r_square))
2800 return nullptr;
2801
2802 Tok = Tok->getPreviousNonComment();
2803 if (!Tok || Tok->isNot(tok::l_square))
2804 return nullptr;
2805
2806 Tok = Tok->getPreviousNonComment();
2807 if (!Tok || Tok->isNot(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(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(TT_ObjCForIn, tok::kw_return, tok::kw_case,
2827 tok::kw_delete, 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(tok::at, tok::r_square, TT_OverloadedOperator,
2834 TT_TemplateCloser, tok::ellipsis)) {
2835 return false;
2836 }
2837 }
2838
2839 if (AfterRParen->is(tok::question) ||
2840 (AfterRParen->is(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(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(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
2851 tok::kw_requires, tok::kw_throw, tok::arrow,
2852 Keywords.kw_override, Keywords.kw_final) ||
2853 isCppAttribute(IsCpp, *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(tok::l_paren))
2860 return true;
2861
2862 // If a (non-string) literal follows, this is likely a cast.
2863 if (AfterRParen->isOneOf(tok::kw_sizeof, tok::kw_alignof) ||
2864 (AfterRParen->Tok.isLiteral() &&
2865 AfterRParen->isNot(tok::string_literal))) {
2866 return true;
2867 }
2868
2869 auto IsNonVariableTemplate = [](const FormatToken &Tok) {
2870 if (Tok.isNot(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(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_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_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_PointerOrReference);
2911 };
2912
2913 bool ParensAreType = IsNonVariableTemplate(*BeforeRParen) ||
2914 BeforeRParen->is(TT_TypeDeclarationParen) ||
2915 BeforeRParen->isTypeName(LangOpts) ||
2916 IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
2917 bool ParensCouldEndDecl =
2918 AfterRParen->isOneOf(tok::equal, tok::semi, tok::l_brace, 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_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(tok::identifier, tok::kw_this))
2937 return true;
2938
2939 // Look for a cast `( x ) (`, where x may be a qualified identifier.
2940 if (AfterRParen->is(tok::l_paren)) {
2941 for (const auto *Prev = BeforeRParen; Prev->is(tok::identifier);) {
2942 Prev = Prev->Previous;
2943 if (Prev->is(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(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(tok::amp, tok::star);
2964 if (!(AfterRParen->isUnaryOperator() || NextIsAmpOrStar) ||
2965 AfterRParen->is(tok::plus) ||
2966 AfterRParen->Next->isNoneOf(tok::identifier, tok::numeric_constant)) {
2967 return false;
2968 }
2969
2970 if (NextIsAmpOrStar &&
2971 (AfterRParen->Next->is(tok::numeric_constant) || Line.InPPDirective)) {
2972 return false;
2973 }
2974
2975 if (Line.InPPDirective && AfterRParen->is(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(tok::r_paren)) {
2982 if (Prev->is(TT_CastRParen))
2983 return false;
2984 Prev = Prev->MatchingParen;
2985 if (!Prev)
2986 return false;
2987 Prev = Prev->Previous;
2988 if (!Prev || Prev->isNot(tok::r_paren))
2989 return false;
2990 Prev = Prev->MatchingParen;
2991 return Prev && Prev->is(TT_FunctionTypeLParen);
2992 }
2993
2994 // Search for unexpected tokens.
2995 for (Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous)
2996 if (Prev->isNoneOf(tok::kw_const, tok::identifier, 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 TT_ConditionalExpr, tok::l_paren, tok::comma, tok::colon, tok::semi,
3016 tok::equal, tok::question, tok::l_square, tok::l_brace,
3017 tok::kw_case, tok::kw_co_await, tok::kw_co_return, tok::kw_co_yield,
3018 tok::kw_delete, tok::kw_return, 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(tok::kw_sizeof))
3026 return true;
3027
3028 // A sequence of leading unary operators.
3029 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
3030 return true;
3031
3032 // There can't be two consecutive binary operators.
3033 if (PrevToken->is(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(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(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(tok::ampamp))
3066 return TT_BinaryOperator;
3067
3068 auto *NextToken = Tok.getNextNonComment();
3069 if (!NextToken)
3070 return TT_PointerOrReference;
3071 if (NextToken->is(tok::greater))
3072 return TT_PointerOrReference;
3073
3074 if (InTemplateArgument && NextToken->is(tok::kw_noexcept))
3075 return TT_BinaryOperator;
3076
3077 if (NextToken->isOneOf(tok::arrow, tok::equal, tok::comma, tok::r_paren,
3078 tok::semi, TT_RequiresClause) ||
3079 (NextToken->is(tok::kw_noexcept) && !IsExpression) ||
3080 NextToken->canBePointerOrReferenceQualifier() ||
3081 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) {
3082 return TT_PointerOrReference;
3083 }
3084
3085 if (PrevToken->is(tok::coloncolon))
3086 return TT_PointerOrReference;
3087
3088 if (PrevToken->is(tok::r_paren) && PrevToken->is(TT_TypeDeclarationParen))
3089 return TT_PointerOrReference;
3090
3091 if (determineUnaryOperatorByUsage(Tok))
3092 return TT_UnaryOperator;
3093
3094 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
3095 return TT_PointerOrReference;
3096 if (NextToken->is(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(tok::r_brace) && Tok.is(tok::star) &&
3110 !PrevToken->MatchingParen) {
3111 return TT_PointerOrReference;
3112 }
3113
3114 if (PrevToken->endsSequence(tok::r_square, tok::l_square, tok::kw_delete))
3115 return TT_UnaryOperator;
3116
3117 if (PrevToken->Tok.isLiteral() ||
3118 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
3119 tok::kw_false, tok::r_brace)) {
3120 return TT_BinaryOperator;
3121 }
3122
3123 const FormatToken *NextNonParen = NextToken;
3124 while (NextNonParen && NextNonParen->is(tok::l_paren))
3125 NextNonParen = NextNonParen->getNextNonComment();
3126 if (NextNonParen && (NextNonParen->Tok.isLiteral() ||
3127 NextNonParen->isOneOf(tok::kw_true, 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(tok::ampamp) &&
3141 NextToken->isOneOf(tok::l_paren, tok::star, 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(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 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(tok::amp, tok::period, tok::arrow,
3177 tok::arrowstar, tok::periodstar);
3178 };
3179
3180 // It's more likely that & represents operator& than an uninitialized
3181 // reference.
3182 if (Tok.is(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(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(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_CastRParen))
3219 return TT_UnaryOperator;
3220 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, 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(tok::kw_return) ||
3263 (Current->is(tok::colon) &&
3264 Current->isOneOf(TT_ObjCMethodExpr, 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(VerilogFirstOfType, LatestOperator);
3300 }
3301
3302 // Consume operators with higher precedence.
3303 parse(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 ==
3317 CurrentPrecedence = prec::Additive;
3318 }
3319 }
3320
3321 if (Precedence == CurrentPrecedence && Current &&
3322 Current->is(TT_SelectorName)) {
3323 if (LatestOperator)
3324 addFakeParenthesis(Start, 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(tok::string_literal) &&
3334 (Prev == Start || Prev->endsSequence(tok::string_literal, tok::plus,
3335 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_TemplateString))) ||
3345 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
3346 (CurrentPrecedence == prec::Conditional &&
3347 Precedence == prec::Assignment && Current->is(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(TT_RequiresClause,
3356 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(VerilogFirstOfType, 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(TT_RequiresClause,
3388 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, prec::Unknown, End);
3400 } else {
3401 addFakeParenthesis(Start, 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_ConditionalExpr))
3413 return prec::Conditional;
3414 if (NextNonComment && Current->is(TT_SelectorName) &&
3415 (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
3416 (Style.isProto() && NextNonComment->is(tok::less)))) {
3417 return prec::Assignment;
3418 }
3419 if (Current->is(TT_JsComputedPropertyName))
3420 return prec::Assignment;
3421 if (Current->is(TT_LambdaArrow))
3422 return prec::Comma;
3423 if (Current->is(TT_FatArrow))
3424 return prec::Assignment;
3425 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
3426 (Current->is(tok::comment) && NextNonComment &&
3427 NextNonComment->is(TT_SelectorName))) {
3428 return 0;
3429 }
3430 if (Current->is(TT_RangeBasedForLoopColon))
3431 return prec::Comma;
3432 if ((Style.isJava() || Style.isJavaScript()) &&
3433 Current->is(Keywords.kw_instanceof)) {
3434 return prec::Relational;
3435 }
3436 if (Style.isJavaScript() &&
3437 Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) {
3438 return prec::Relational;
3439 }
3440 if (Current->isOneOf(TT_BinaryOperator, tok::comma))
3441 return Current->getPrecedence();
3442 if (Current->isOneOf(tok::period, tok::arrow) &&
3443 Current->isNot(TT_TrailingReturnArrow)) {
3444 return PrecedenceArrowAndPeriod;
3445 }
3446 if ((Style.isJava() || Style.isJavaScript()) &&
3447 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
3448 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(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(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_UnaryOperator)) {
3485 Tokens.push_back(Current);
3486 next();
3487 }
3488 parse(PrecedenceArrowAndPeriod);
3489 for (FormatToken *Token : reverse(Tokens)) {
3490 // The actual precedence doesn't matter.
3491 addFakeParenthesis(Token, prec::Unknown);
3492 }
3493 }
3494
3495 void parseConditionalExpr() {
3496 while (Current && Current->isTrailingComment())
3497 next();
3498 FormatToken *Start = Current;
3499 parse(prec::LogicalOr);
3500 if (!Current || Current->isNot(tok::question))
3501 return;
3502 next();
3503 parse(prec::Assignment);
3504 if (!Current || Current->isNot(TT_ConditionalExpr))
3505 return;
3506 next();
3507 parse(prec::Assignment);
3508 addFakeParenthesis(Start, 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(tok::l_paren, 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(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(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(tok::hashhash)) {
3560 // Concatenation. Skip.
3561 Tok = Next;
3562 if (Tok)
3563 Tok = Tok->getNextNonComment();
3564 } else if (Keywords.isVerilogQualifier(*Tok) ||
3565 Keywords.isVerilogIdentifier(*Tok)) {
3566 First = Tok;
3567 Tok = Next;
3568 // The name may have dots like `interface_foo.modport_foo`.
3569 while (Tok && Tok->isOneOf(tok::period, tok::coloncolon) &&
3570 (Tok = Tok->getNextNonComment())) {
3571 if (Keywords.isVerilogIdentifier(*Tok))
3572 Tok = Tok->getNextNonComment();
3573 }
3574 } else if (!Next) {
3575 Tok = nullptr;
3576 } else if (Tok->is(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 Keywords.kw_highz0, Keywords.kw_highz1, Keywords.kw_large,
3582 Keywords.kw_medium, Keywords.kw_pull0, Keywords.kw_pull1,
3583 Keywords.kw_small, Keywords.kw_strong0, Keywords.kw_strong1,
3584 Keywords.kw_supply0, Keywords.kw_supply1, Keywords.kw_weak0,
3585 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(Keywords.kw_verilogHash)) {
3596 // Delay control.
3597 if (Next->is(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(tok::l_square) && (Tok = Tok->MatchingParen))
3610 Tok = Tok->getNextNonComment();
3611 if (Tok && (Tok->is(tok::hash) || Keywords.isVerilogIdentifier(*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_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_Unknown))
3630 TypedName->setType(TT_StartOfName);
3631 // Group variables of the previous type.
3632 if (FirstOfType && PreviousComma) {
3633 PreviousComma->setType(TT_VerilogTypeComma);
3634 addFakeParenthesis(FirstOfType, prec::Comma, 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
3665 SmallVectorImpl<AnnotatedLine *> &Lines) const {
3666 const AnnotatedLine *NextNonCommentLine = nullptr;
3667 for (AnnotatedLine *Line : reverse(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(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)
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(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(Result, 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.
3713 assert(Tok);
3714
3715 // Qualified names must start with an identifier.
3716 if (Tok->isNot(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(tok::coloncolon))
3726 return Tok->getNextNonComment();
3727
3728 // Consider: A<float>::B<int>::B()
3729 // Tok --^
3730 if (Tok->is(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(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.
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_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(tok::l_paren) && Tok->is(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(tok::kw_friend, tok::kw_inline, tok::kw_virtual,
3768 tok::kw_constexpr, tok::kw_consteval, 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(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(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(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(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(tok::identifier) || Tok->isNot(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(tok::tilde))
3825 Prev = Prev->Previous;
3826
3827 // Consider: A::A() and A<int>::A()
3828 if (!Prev || (!Prev->endsSequence(tok::coloncolon, tok::identifier) &&
3829 !Prev->endsSequence(tok::coloncolon, TT_TemplateCloser))) {
3830 return false;
3831 }
3832
3833 assert(Prev->Previous);
3834 if (Prev->Previous->is(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
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(ST_Other);
3852 const bool InRequiresExpression = Line.Type == LT_RequiresExpression;
3853 for (auto &Child : Line.Children) {
3854 if (InRequiresExpression &&
3855 Child->First->isNoneOf(tok::kw_typename, tok::kw_requires,
3856 TT_CompoundRequirementLBrace)) {
3857 Child->Type = LT_SimpleRequirement;
3858 }
3859 annotate(*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(TT_FunctionLBrace) || isCtorOrDtorName(Tok))) {
3884 Tok->setFinalizedType(TT_CtorDtorDeclName);
3885 assert(OpeningParen);
3886 OpeningParen->setFinalizedType(TT_FunctionDeclarationLParen);
3887 }
3888 }
3889
3890 if (Line.startsWith(TT_ObjCMethodSpecifier))
3891 Line.Type = LT_ObjCMethodDecl;
3892 else if (Line.startsWith(TT_ObjCDecl))
3893 Line.Type = LT_ObjCDecl;
3894 else if (Line.startsWith(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_FunctionDeclarationName))
3909 return true;
3910
3911 if (Current.isNoneOf(tok::identifier, 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_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_OverloadedOperatorLParen))
3928 return Next;
3929 if (Next->is(TT_OverloadedOperator))
3930 continue;
3931 if (Next->isPlacementOperator() || Next->is(tok::kw_co_await)) {
3932 // For 'new[]' and 'delete[]'.
3933 if (Next->Next &&
3934 Next->Next->startsSequence(tok::l_square, tok::r_square)) {
3935 Next = Next->Next->Next;
3936 }
3937 continue;
3938 }
3939 if (Next->startsSequence(tok::l_square, tok::r_square)) {
3940 // For operator[]().
3941 Next = Next->Next;
3942 continue;
3943 }
3944 if ((Next->isTypeName(LangOpts) || Next->is(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_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(tok::kw_operator)) {
3965 if (Line.startsWith(tok::kw_friend))
3966 return true;
3967 if (Previous.Tok.getIdentifierInfo() &&
3968 Previous.isNoneOf(tok::kw_return, tok::kw_co_return)) {
3969 return true;
3970 }
3971 if (Previous.is(tok::r_paren) && Previous.is(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(TT_TemplateCloser))
3978 return false;
3979 Next = skipOperatorName(Next);
3980 } else {
3981 if (Current.isNot(TT_StartOfName) || Current.NestingLevel != 0)
3982 return false;
3983 while (Next && Next->startsSequence(tok::hashhash, tok::identifier))
3984 Next = Next->Next->Next;
3985 for (; Next; Next = Next->Next) {
3986 if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
3987 Next = Next->MatchingParen;
3988 } else if (Next->is(tok::coloncolon)) {
3989 Next = Next->Next;
3990 if (!Next)
3991 return false;
3992 if (Next->is(tok::kw_operator)) {
3993 Next = skipOperatorName(Next->Next);
3994 break;
3995 }
3996 if (Next->isNot(tok::identifier))
3997 return false;
3998 } else if (isCppAttribute(IsCpp, *Next)) {
3999 Next = Next->MatchingParen;
4000 if (!Next)
4001 return false;
4002 } else if (Next->is(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(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(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_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(tok::identifier) &&
4035 !Line.endsWith(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_TypeDeclarationParen))
4042 return true;
4043 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
4044 Tok = Tok->MatchingParen;
4045 continue;
4046 }
4047 if (Tok->is(tok::kw_const) || Tok->isTypeName(LangOpts) ||
4048 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) {
4049 return true;
4050 }
4051 if (Tok->isOneOf(tok::l_brace, 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) {
4070 return false;
4073 return true;
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) {
4088 return false;
4090 return true;
4092 return Line.Level == 0;
4094 return Line.mightBeFunctionDefinition();
4096 return Line.Level == 0 && Line.mightBeFunctionDefinition();
4097 }
4098
4099 return false;
4100}
4101
4103 auto *Tok = Line.getFirstNonComment();
4104 if (!Tok)
4105 return nullptr;
4106
4107 if (Tok->is(tok::kw_template)) {
4108 auto *Opener = Tok->Next;
4109 while (Opener && Opener->isNot(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_RequiresClause)) {
4117 while (Tok && !Tok->ClosesRequiresClause)
4118 Tok = Tok->Next;
4119 if (Tok)
4120 Tok = Tok->Next;
4121 }
4122
4123 while (Tok) {
4125 Tok->isOneOf(tok::kw___attribute, tok::kw___declspec,
4126 TT_AttributeMacro)) {
4127 auto *Next = Tok->Next;
4128 if (Next && Next->is(tok::l_paren) && Next->MatchingParen)
4129 Tok = Next->MatchingParen->Next;
4130 else
4131 Tok = Next;
4132 continue;
4133 }
4134 if (Tok->is(TT_AttributeLSquare) && Tok->MatchingParen) {
4135 Tok = Tok->MatchingParen->Next;
4136 continue;
4137 }
4138 break;
4139 }
4140 return Tok;
4141}
4142
4144 if (Line.Computed)
4145 return;
4146
4147 Line.Computed = true;
4148
4149 for (AnnotatedLine *ChildLine : Line.Children)
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 &&
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(tok::kw_using)
4169 ? FirstNonComment->Next
4170 : nullptr;
4171 Tok && Tok->isNot(BK_BracedInit); Tok = Tok->Next) {
4172 if (Tok->is(TT_StartOfName))
4173 SeenName = true;
4174 if (Tok->Previous->EndsCppAttributeGroup)
4175 AfterLastAttribute = Tok;
4176 if (const bool IsCtorOrDtor = Tok->is(TT_CtorDtorDeclName);
4177 IsCtorOrDtor ||
4178 isFunctionDeclarationName(LangOpts, *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_Unknown))
4187 OpeningParen->setType(TT_FunctionDeclarationLParen);
4188 }
4189 break;
4190 }
4191 }
4192
4193 if (IsCpp) {
4194 if ((LineIsFunctionDeclaration ||
4195 (FirstNonComment && FirstNonComment->is(TT_CtorDtorDeclName))) &&
4196 Line.endsWith(tok::semi, tok::r_brace)) {
4197 auto *Tok = Line.Last->Previous;
4198 while (Tok->isNot(tok::r_brace))
4199 Tok = Tok->Previous;
4200 if (auto *LBrace = Tok->MatchingParen; LBrace && LBrace->is(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(*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(tok::kw_operator))
4220 continue;
4221 do {
4222 Tok = Tok->Next;
4223 } while (Tok && Tok->isNot(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(tok::identifier))
4230 continue;
4231 auto *Next = Tok->Next;
4232 const bool NextIsBinaryOperator =
4233 Next && Next->isPointerOrReference() && Next->Next &&
4234 Next->Next->is(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_CtorInitializerColon))
4244 break;
4245 if (Tok->is(tok::arrow)) {
4246 Tok->overwriteFixedType(TT_TrailingReturnArrow);
4247 break;
4248 }
4249 if (Tok->isNot(TT_TrailingAnnotation))
4250 continue;
4251 const auto *Next = Tok->Next;
4252 if (!Next || Next->isNot(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(TT_FunctionDeclarationName,
4266 TT_CtorDtorDeclName, tok::tilde)) {
4267 ReturnTypeStart->MustBreakBefore = true;
4268 Line.ReturnTypeWrapped = true;
4269 }
4270 }
4271
4272 if (First->is(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_LineComment)) {
4282 if (Prev->is(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_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(tok::comment, tok::r_brace))
4305 break;
4306 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
4307 if (Parameter->Previous->isNot(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, *Current)) {
4317 Current->SpacesRequiredBefore = 1;
4318 }
4319
4320 const auto &Children = Prev->Children;
4321 if (!Children.empty() && Children.back()->Last->is(TT_LineComment)) {
4322 Current->MustBreakBefore = true;
4323 } else {
4324 Current->MustBreakBefore =
4325 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
4326 if (!Current->MustBreakBefore && InFunctionDecl &&
4327 Current->is(TT_FunctionDeclarationName)) {
4328 Current->MustBreakBefore = mustBreakForReturnType(Line);
4329 }
4330 }
4331
4332 Current->CanBreakBefore =
4333 !Line.IsModuleOrImportDecl &&
4334 (Current->MustBreakBefore || canBreakBefore(Line, *Current));
4335
4336 if (Current->is(TT_FunctionDeclarationLParen)) {
4337 InParameterList = true;
4338 } else if (Current->is(tok::r_paren)) {
4339 const auto *LParen = Current->MatchingParen;
4340 if (LParen && LParen->is(TT_FunctionDeclarationLParen))
4341 InParameterList = false;
4342 } else if (InParameterList &&
4343 Current->endsSequence(TT_AttributeMacro,
4344 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 &&
4366 Prev->ParameterCount > Style.PackParameters.BreakAfter) ||
4367 (Style.PackArguments.BinPack == FormatStyle::BPAS_UseBreakAfter &&
4368 !Prev->MightBeFunctionDeclParen &&
4369 Prev->isOneOf(tok::l_paren, tok::l_brace,
4370 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(*ParamTok, Style)) {
4381 ParamTok->MustBreakBefore = true;
4382 ParamTok->CanBreakBefore = true;
4383 }
4384 }
4385 }
4386
4387 if (Current->is(TT_ControlStatementLBrace)) {
4388 if (Style.ColumnLimit > 0 &&
4389 Style.BraceWrapping.AfterControlStatement ==
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_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, *Current, InFunctionDecl);
4410 if (Style.Language == FormatStyle::LK_ObjC &&
4411 Current->is(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(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) {
4443 if (Current->CanBreakBefore ||
4444 Current->isOneOf(tok::comment, tok::string_literal)) {
4446 } else {
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(tok::l_brace)) {
4463 CurrentToken->IsArrayInitializer = true;
4464 if (CurrentToken->Next)
4465 CurrentToken->Next->MustBreakBefore = true;
4466 CurrentToken =
4467 calculateInitializerColumnList(Line, CurrentToken->Next, 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(tok::l_brace))
4478 ++Depth;
4479 else if (CurrentToken->is(tok::r_brace))
4480 --Depth;
4481 if (Depth == 2 && CurrentToken->isOneOf(tok::l_brace, 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(tok::semi))
4500 return 0;
4501
4502 // Language specific handling.
4503 if (Style.isJava()) {
4504 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
4505 return 1;
4506 if (Right.is(Keywords.kw_implements))
4507 return 2;
4508 if (Left.is(tok::comma) && Left.NestingLevel == 0)
4509 return 3;
4510 } else if (Style.isJavaScript()) {
4511 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
4512 return 100;
4513 if (Left.is(TT_JsTypeColon))
4514 return 35;
4515 if ((Left.is(TT_TemplateString) && Left.TokenText.ends_with("${")) ||
4516 (Right.is(TT_TemplateString) && Right.TokenText.starts_with("}"))) {
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(tok::l_square))
4524 return 1;
4525 if (Right.is(tok::period))
4526 return 500;
4527 }
4528
4529 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
4530 return 1;
4531 if (Right.is(tok::l_square)) {
4532 if (Left.is(tok::r_square))
4533 return 200;
4534 // Slightly prefer formatting local lambda definitions like functions.
4535 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
4536 return 35;
4537 if (Right.isNoneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
4538 TT_ArrayInitializerLSquare,
4539 TT_DesignatedInitializerLSquare, TT_AttributeLSquare)) {
4540 return 500;
4541 }
4542 }
4543
4544 if (Left.is(tok::coloncolon))
4545 return Style.PenaltyBreakScopeResolution;
4546 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
4547 tok::kw_operator)) {
4548 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
4549 return 3;
4550 if (Left.is(TT_StartOfName))
4551 return 110;
4552 if (InFunctionDecl && Right.NestingLevel == 0)
4553 return Style.PenaltyReturnTypeOnItsOwnLine;
4554 return 200;
4555 }
4556 if (Right.is(TT_PointerOrReference))
4557 return 190;
4558 if (Right.is(TT_LambdaArrow))
4559 return 110;
4560 if (Left.is(tok::equal) && Right.is(tok::l_brace))
4561 return 160;
4562 if (Left.is(TT_CastRParen))
4563 return 100;
4564 if (Left.isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union))
4565 return 5000;
4566 if (Left.is(tok::comment))
4567 return 1000;
4568
4569 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
4570 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(Penalty, 35u)
4598 : Penalty;
4599 }
4600
4601 if (Right.is(TT_TrailingAnnotation) &&
4602 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
4603 // Moving trailing annotations to the next line is fine for ObjC method
4604 // declarations.
4605 if (Line.startsWith(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(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
4614 }
4615
4616 // In for-loops, prefer breaking at ',' and ';'.
4617 if (Line.startsWith(tok::kw_for) && Left.is(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_SelectorName))
4623 return 0;
4624 if (Left.is(tok::colon)) {
4625 if (Left.is(TT_ObjCMethodExpr))
4626 return Line.MightBeFunctionDecl ? 50 : 500;
4627 if (Left.is(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(tok::l_paren) && Left.Previous &&
4635 Left.Previous->isOneOf(tok::identifier, tok::greater)) {
4636 return 500;
4637 }
4638
4639 if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
4640 return Style.PenaltyBreakOpenParenthesis;
4641 if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
4642 return 100;
4643 if (Left.is(tok::l_paren) && Left.Previous &&
4644 (Left.Previous->isOneOf(tok::kw_for, tok::kw__Generic) ||
4645 Left.Previous->isIf())) {
4646 return 1000;
4647 }
4648 if (Left.is(tok::equal) && InFunctionDecl)
4649 return 110;
4650 if (Right.is(tok::r_brace))
4651 return 1;
4652 if (Left.is(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(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_JavaAnnotation))
4670 return 50;
4671
4672 if (Left.is(TT_UnaryOperator))
4673 return 60;
4674 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
4675 Left.Previous->isLabelString() &&
4676 (Left.NextOperator || Left.OperatorIndex != 0)) {
4677 return 50;
4678 }
4679 if (Right.is(tok::plus) && Left.isLabelString() &&
4680 (Right.NextOperator || Right.OperatorIndex != 0)) {
4681 return 25;
4682 }
4683 if (Left.is(tok::comma))
4684 return 1;
4685 if (Right.is(tok::lessless) && Left.isLabelString() &&
4686 (Right.NextOperator || Right.OperatorIndex != 1)) {
4687 return 25;
4688 }
4689 if (Right.is(tok::lessless)) {
4690 // Breaking at a << is really cheap.
4691 if (Left.isNot(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_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_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(tok::kw_return) &&
4732 Right.isNoneOf(tok::semi, tok::r_paren, tok::hashhash)) {
4733 return true;
4734 }
4735 if (Left.is(tok::kw_throw) && Right.is(tok::l_paren) && Right.MatchingParen &&
4736 Right.MatchingParen->is(TT_CastRParen)) {
4737 return true;
4738 }
4739 if (Left.is(Keywords.kw_assert) && Style.isJava())
4740 return true;
4741 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
4742 Left.is(tok::objc_property)) {
4743 return true;
4744 }
4745 if (Right.is(tok::hashhash))
4746 return Left.is(tok::hash);
4747 if (Left.isOneOf(tok::hashhash, tok::hash))
4748 return Right.is(tok::hash);
4749 if (Style.SpacesInParens == FormatStyle::SIPO_Custom) {
4750 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
4751 return Style.SpacesInParensOptions.InEmptyParentheses;
4752 if (Style.SpacesInParensOptions.ExceptDoubleParentheses &&
4753 Left.is(tok::r_paren) && Right.is(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(tok::l_paren))
4762 LeftParen = &Left;
4763 else if (Right.is(tok::r_paren) && Right.MatchingParen)
4764 LeftParen = Right.MatchingParen;
4765 if (LeftParen && (LeftParen->is(TT_ConditionLParen) ||
4766 (LeftParen->Previous &&
4767 isKeywordWithCondition(*LeftParen->Previous)))) {
4768 return Style.SpacesInParensOptions.InConditionalStatements;
4769 }
4770 }
4771
4772 // trailing return type 'auto': []() -> auto {}, auto foo() -> auto {}
4773 if (Left.is(tok::kw_auto) && Right.isOneOf(TT_LambdaLBrace, TT_FunctionLBrace,
4774 // function return type 'auto'
4775 TT_FunctionTypeLParen)) {
4776 return true;
4777 }
4778
4779 // auto{x} auto(x)
4780 if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace))
4781 return false;
4782
4783 const auto *BeforeLeft = Left.Previous;
4784
4785 // operator co_await(x)
4786 if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && BeforeLeft &&
4787 BeforeLeft->is(tok::kw_operator)) {
4788 return false;
4789 }
4790 // co_await (x), co_yield (x), co_return (x)
4791 if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) &&
4792 Right.isNoneOf(tok::semi, tok::r_paren)) {
4793 return true;
4794 }
4795
4796 if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) {
4797 return (Right.is(TT_CastRParen) ||
4798 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
4799 ? Style.SpacesInParensOptions.InCStyleCasts
4800 : Style.SpacesInParensOptions.Other;
4801 }
4802 if (Right.isOneOf(tok::semi, tok::comma))
4803 return false;
4804 if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
4805 bool IsLightweightGeneric = Right.MatchingParen &&
4806 Right.MatchingParen->Next &&
4807 Right.MatchingParen->Next->is(tok::colon);
4808 return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
4809 }
4810 if (Right.is(tok::less) && Left.is(tok::kw_template))
4811 return Style.SpaceAfterTemplateKeyword;
4812 if (Left.isOneOf(tok::exclaim, tok::tilde))
4813 return false;
4814 if (Left.is(tok::at) &&
4815 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
4816 tok::numeric_constant, tok::l_paren, tok::l_brace,
4817 tok::kw_true, tok::kw_false)) {
4818 return false;
4819 }
4820 if (Left.is(tok::colon))
4821 return Left.isNoneOf(TT_ObjCSelector, TT_ObjCMethodExpr);
4822 if (Left.is(tok::coloncolon))
4823 return false;
4824 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
4825 if (Style.isTextProto() ||
4826 (Style.Language == FormatStyle::LK_Proto &&
4827 (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
4828 // Format empty list as `<>`.
4829 if (Left.is(tok::less) && Right.is(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(TT_OverloadedOperatorLParen))
4835 return false;
4836 }
4837 if (Right.is(tok::ellipsis)) {
4838 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && BeforeLeft &&
4839 BeforeLeft->is(tok::kw_case));
4840 }
4841 if (Left.is(tok::l_square) && Right.is(tok::amp))
4842 return Style.SpacesInSquareBrackets;
4843 if (Right.is(TT_PointerOrReference)) {
4844 if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
4845 if (!Left.MatchingParen)
4846 return true;
4847 FormatToken *TokenBeforeMatchingParen =
4848 Left.MatchingParen->getPreviousNonComment();
4849 if (!TokenBeforeMatchingParen || Left.isNot(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_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_RangeBasedForLoopColon)) {
4866 return getTokenPointerOrReferenceAlignment(Right) !=
4868 }
4869 return Left.isNoneOf(TT_PointerOrReference, tok::l_paren) &&
4870 (getTokenPointerOrReferenceAlignment(Right) !=
4872 (Line.IsMultiVariableDeclStmt &&
4873 (Left.NestingLevel == 0 ||
4874 (Left.NestingLevel == 1 && startsWithInitStatement(Line)))));
4875 }
4876 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
4877 (Left.isNot(TT_PointerOrReference) ||
4878 (getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right &&
4879 !Line.IsMultiVariableDeclStmt))) {
4880 return true;
4881 }
4882 if (Left.is(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_BlockComment))
4895 return true;
4896 // foo() -> const Bar * override/final
4897 // S::foo() & noexcept/requires
4898 if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final, tok::kw_noexcept,
4899 TT_RequiresClause) &&
4900 Right.isNot(TT_StartOfName)) {
4901 return true;
4902 }
4903 // & {
4904 if (Right.is(tok::l_brace) && Right.is(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_RangeBasedForLoopColon)) {
4909 return getTokenPointerOrReferenceAlignment(Left) !=
4911 }
4912 if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
4913 tok::l_paren)) {
4914 return false;
4915 }
4916 if (getTokenPointerOrReferenceAlignment(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(tok::coloncolon)) {
4933 if (Left.isNot(tok::star))
4934 return false;
4935 assert(Style.PointerAlignment != FormatStyle::PAS_Right);
4936 if (!Right.startsSequence(tok::identifier, tok::r_paren))
4937 return true;
4938 assert(Right.Next);
4939 const auto *LParen = Right.Next->MatchingParen;
4940 return !LParen || LParen->isNot(TT_FunctionTypeLParen);
4941 }
4942 return BeforeLeft->isNoneOf(tok::l_paren, tok::l_square);
4943 }
4944 // Ensure right pointer alignment with ellipsis e.g. int *...P
4945 if (Left.is(tok::ellipsis) && BeforeLeft &&
4946 BeforeLeft->isPointerOrReference()) {
4947 return Style.PointerAlignment != FormatStyle::PAS_Right;
4948 }
4949
4950 if (Right.is(tok::star) && Left.is(tok::l_paren))
4951 return false;
4952 if (Left.is(tok::star) && Right.isPointerOrReference())
4953 return false;
4954 if (Right.isPointerOrReference()) {
4955 const FormatToken *Previous = &Left;
4956 while (Previous && Previous->isNot(tok::kw_operator)) {
4957 if (Previous->is(tok::identifier) || Previous->isTypeName(LangOpts)) {
4958 Previous = Previous->getPreviousNonComment();
4959 continue;
4960 }
4961 if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) {
4962 Previous = Previous->MatchingParen->getPreviousNonComment();
4963 continue;
4964 }
4965 if (Previous->is(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(tok::kw_operator))
4985 return Style.PointerAlignment != FormatStyle::PAS_Left;
4986 if (Previous->isOneOf(tok::kw_const, tok::kw_volatile)) {
4987 return (Style.PointerAlignment != FormatStyle::PAS_Left) ||
4988 (Style.SpaceAroundPointerQualifiers ==
4990 (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both);
4991 }
4992 }
4993 }
4994 if (Style.isCSharp() && Left.is(Keywords.kw_is) && Right.is(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(tok::l_square, tok::colon,
5002 TT_SelectorName));
5003 };
5004 if (Left.is(tok::l_square)) {
5005 return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
5006 SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
5007 (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare,
5008 TT_LambdaLSquare) &&
5009 Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
5010 }
5011 if (Right.is(tok::r_square)) {
5012 return Right.MatchingParen &&
5013 ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
5014 SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
5015 Style)) ||
5016 (Style.SpacesInSquareBrackets &&
5017 Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
5018 TT_StructuredBindingLSquare,
5019 TT_LambdaLSquare)));
5020 }
5021 if (Right.is(tok::l_square) &&
5022 Right.isNoneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
5023 TT_DesignatedInitializerLSquare,
5024 TT_StructuredBindingLSquare, TT_AttributeLSquare) &&
5025 Left.isNoneOf(tok::numeric_constant, TT_DictLiteral) &&
5026 !(Left.isNot(tok::r_square) && Style.SpaceBeforeSquareBrackets &&
5027 Right.is(TT_ArraySubscriptLSquare))) {
5028 return false;
5029 }
5030 if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) ||
5031 (Right.is(tok::r_brace) && Right.MatchingParen &&
5032 Right.MatchingParen->isNot(BK_Block))) {
5033 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block ||
5034 Style.SpacesInParensOptions.Other;
5035 }
5036 if (Left.is(TT_BlockComment)) {
5037 // No whitespace in x(/*foo=*/1), except for JavaScript.
5038 return Style.isJavaScript() || !Left.TokenText.ends_with("=*/");
5039 }
5040
5041 // Space between template and attribute.
5042 // e.g. template <typename T> [[nodiscard]] ...
5043 if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeLSquare))
5044 return true;
5045 // Space before parentheses common for all languages
5046 if (Right.is(tok::l_paren)) {
5047 // Function declaration or definition
5048 if (Line.MightBeFunctionDecl && Right.is(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_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen))
5057 return spaceRequiredBeforeParens(Right);
5058 if (Left.isOneOf(TT_RequiresClause,
5059 TT_RequiresClauseInARequiresExpression)) {
5060 return Style.SpaceBeforeParensOptions.AfterRequiresInClause ||
5061 spaceRequiredBeforeParens(Right);
5062 }
5063 if (Left.is(TT_RequiresExpression)) {
5064 return Style.SpaceBeforeParensOptions.AfterRequiresInExpression ||
5065 spaceRequiredBeforeParens(Right);
5066 }
5067 if (Left.isOneOf(TT_AttributeRParen, TT_AttributeRSquare))
5068 return true;
5069 if (Left.is(TT_ForEachMacro)) {
5070 return Style.SpaceBeforeParensOptions.AfterForeachMacros ||
5071 spaceRequiredBeforeParens(Right);
5072 }
5073 if (Left.is(TT_IfMacro)) {
5074 return Style.SpaceBeforeParensOptions.AfterIfMacros ||
5075 spaceRequiredBeforeParens(Right);
5076 }
5077 if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
5078 Left.isPlacementOperator() &&
5079 Right.isNot(TT_OverloadedOperatorLParen) &&
5080 !(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
5081 const auto *RParen = Right.MatchingParen;
5082 return Style.SpaceBeforeParensOptions.AfterPlacementOperator ||
5083 (RParen && RParen->is(TT_CastRParen));
5084 }
5085 if (Line.Type == LT_ObjCDecl)
5086 return true;
5087 if (Left.is(tok::semi))
5088 return true;
5089 if (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, tok::kw_switch,
5090 tok::kw_case, TT_ForEachMacro, TT_ObjCForIn) ||
5091 Left.isIf(Line.Type != LT_PreprocessorDirective) ||
5092 Right.is(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_OverloadedOperatorLParen))
5100 return spaceRequiredBeforeParens(Right);
5101
5102 // Lambda
5103 if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) &&
5104 Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare)) {
5105 return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
5106 spaceRequiredBeforeParens(Right);
5107 }
5108 if (!BeforeLeft || BeforeLeft->isNoneOf(tok::period, tok::arrow)) {
5109 if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) {
5110 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5111 spaceRequiredBeforeParens(Right);
5112 }
5113 if (Left.isPlacementOperator() ||
5114 (Left.is(tok::r_square) && Left.MatchingParen &&
5115 Left.MatchingParen->Previous &&
5116 Left.MatchingParen->Previous->is(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(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(tok::l_brace) && Next->is(BK_BracedInit);
5129 };
5130 if (Left.is(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(tok::r_paren))) {
5135 return spaceRequiredBeforeParens(Right);
5136 }
5137 return false;
5138 }
5139 if (Left.is(tok::at) && Right.isNot(tok::objc_not_keyword))
5140 return false;
5141 if (Right.is(TT_UnaryOperator)) {
5142 return Left.isNoneOf(tok::l_paren, tok::l_square, tok::at) &&
5143 (Left.isNot(tok::colon) || Left.isNot(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(tok::identifier, tok::greater, tok::r_square,
5151 tok::r_paren) ||
5152 Left.isTypeName(LangOpts)) &&
5153 Right.is(tok::l_brace) && Right.getNextNonComment() &&
5154 Right.isNot(BK_Block)) {
5155 return false;
5156 }
5157 if (Left.is(tok::period) || Right.is(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(tok::hash) && Left.is(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_TemplateCloser) && Left.MatchingParen &&
5169 Left.MatchingParen->Previous &&
5170 Left.MatchingParen->Previous->isOneOf(tok::period, 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_TemplateCloser) && Right.is(tok::l_square))
5177 return false;
5178 if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at)) {
5179 // Objective-C dictionary literal -> no space after opening brace.
5180 return false;
5181 }
5182 if (Right.is(tok::r_brace) && Right.MatchingParen &&
5183 Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) {
5184 // Objective-C dictionary literal -> no space before closing brace.
5185 return false;
5186 }
5187 if (Right.is(TT_TrailingAnnotation) && Right.isOneOf(tok::amp, tok::ampamp) &&
5188 Left.isOneOf(tok::kw_const, tok::kw_volatile) &&
5189 (!Right.Next || Right.Next->is(tok::semi))) {
5190 // Match const and volatile ref-qualifiers without any additional
5191 // qualifiers such as
5192 // void Fn() const &;
5193 return getTokenReferenceAlignment(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(Right, IsVerilog) &&
5213 Keywords.isWordLike(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(tok::star) && Right.is(tok::comment))
5220 return true;
5221
5222 if (Left.is(tok::l_brace) && Right.is(tok::r_brace) &&
5223 Left.Children.empty()) {
5224 if (Left.is(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_OverloadedOperator) &&
5237 Right.isOneOf(TT_TemplateOpener, TT_TemplateCloser)) {
5238 return true;
5239 }
5240 // Space between UDL and dot: auto b = 4s .count();
5241 if (Right.is(tok::period) && Left.is(tok::numeric_constant))
5242 return true;
5243 // Space between import <iostream>.
5244 // or import .....;
5245 if (Left.is(Keywords.kw_import) &&
5246 Right.isOneOf(tok::less, tok::ellipsis) &&
5247 (!BeforeLeft || BeforeLeft->is(tok::kw_export))) {
5248 return true;
5249 }
5250 // Space between `import :`.
5251 if (Left.is(Keywords.kw_import) && Right.is(TT_ModulePartitionColon))
5252 return true;
5253
5254 if (Right.is(TT_AfterPPDirective))
5255 return true;
5256
5257 // No space between `module foo:bar`.
5258 if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon))
5259 return false;
5260 // No space between :bar;
5261 if (Left.is(TT_ModulePartitionColon) && Right.is(tok::identifier))
5262 return false;
5263 if (Left.is(tok::ellipsis) && Right.is(tok::identifier) &&
5264 Line.First->is(Keywords.kw_import)) {
5265 return false;
5266 }
5267 // Space in __attribute__((attr)) ::type.
5268 if (Left.isOneOf(TT_AttributeRParen, TT_AttributeMacro) &&
5269 Right.is(tok::coloncolon)) {
5270 return true;
5271 }
5272
5273 if (Left.is(tok::kw_operator))
5274 return Right.is(tok::coloncolon) || Style.SpaceAfterOperatorKeyword;
5275 if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) &&
5276 !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) {
5277 return true;
5278 }
5279 if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) &&
5280 Right.is(TT_TemplateOpener)) {
5281 return true;
5282 }
5283 // C++ Core Guidelines suppression tag, e.g. `[[suppress(type.5)]]`.
5284 if (Left.is(tok::identifier) && Right.is(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(tok::period) && !(BeforeLeft && BeforeLeft->is(tok::period)) &&
5291 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
5292 Keywords.kw_repeated, Keywords.kw_extend)) {
5293 return true;
5294 }
5295 if (Right.is(tok::l_paren) &&
5296 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) {
5297 return true;
5298 }
5299 if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
5300 return true;
5301 // Slashes occur in text protocol extension syntax: [type/type] { ... }.
5302 if (Left.is(tok::slash) || Right.is(tok::slash))
5303 return false;
5304 if (Left.MatchingParen &&
5305 Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
5306 Right.isOneOf(tok::l_brace, 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(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(tok::numeric_constant) && Right.is(tok::percent))
5315 return Right.hasWhitespaceBefore();
5316 } else if (Style.isJson()) {
5317 if (Right.is(tok::colon) && Left.is(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(tok::kw_this) && Right.is(tok::l_square))
5326 return false;
5327
5328 // No space between 'new' and '('
5329 if (Left.is(tok::kw_new) && Right.is(tok::l_paren))
5330 return false;
5331
5332 // Space before { (including space within '{ {').
5333 if (Right.is(tok::l_brace))
5334 return true;
5335
5336 // Spaces inside braces.
5337 if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace))
5338 return true;
5339
5340 if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace))
5341 return true;
5342
5343 // Spaces around '=>'.
5344 if (Left.is(TT_FatArrow) || Right.is(TT_FatArrow))
5345 return true;
5346
5347 // No spaces around attribute target colons
5348 if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon))
5349 return false;
5350
5351 // space between type and variable e.g. Dictionary<string,string> foo;
5352 if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
5353 return true;
5354
5355 // spaces inside square brackets.
5356 if (Left.is(tok::l_square) || Right.is(tok::r_square))
5357 return Style.SpacesInSquareBrackets;
5358
5359 // No space before ? in nullable types.
5360 if (Right.is(TT_CSharpNullable))
5361 return false;
5362
5363 // No space before null forgiving '!'.
5364 if (Right.is(TT_NonNullAssertion))
5365 return false;
5366
5367 // No space between consecutive commas '[,,]'.
5368 if (Left.is(tok::comma) && Right.is(tok::comma))
5369 return false;
5370
5371 // space after var in `var (key, value)`
5372 if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren))
5373 return true;
5374
5375 // space between keywords and paren e.g. "using ("
5376 if (Right.is(tok::l_paren)) {
5377 if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when,
5378 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(tok::kw_virtual, tok::kw_extern, tok::kw_static,
5388 Keywords.kw_internal, Keywords.kw_abstract,
5389 Keywords.kw_sealed, Keywords.kw_override,
5390 Keywords.kw_async, Keywords.kw_unsafe)) &&
5391 Right.is(tok::l_paren)) {
5392 return true;
5393 }
5394 } else if (Style.isJavaScript()) {
5395 if (Left.is(TT_FatArrow))
5396 return true;
5397 // for await ( ...
5398 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && BeforeLeft &&
5399 BeforeLeft->is(tok::kw_for)) {
5400 return true;
5401 }
5402 if (Left.is(Keywords.kw_async) && Right.is(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_FatArrow))
5408 return true;
5409 }
5410 if ((Left.is(TT_TemplateString) && Left.TokenText.ends_with("${")) ||
5411 (Right.is(TT_TemplateString) && Right.TokenText.starts_with("}"))) {
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(Left,
5417 /* AcceptIdentifierName= */ false) &&
5418 Right.is(TT_TemplateString)) {
5419 return false;
5420 }
5421 if (Right.is(tok::star) &&
5422 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield)) {
5423 return false;
5424 }
5425 if (Right.isOneOf(tok::l_brace, tok::l_square) &&
5426 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
5427 Keywords.kw_extends, Keywords.kw_implements)) {
5428 return true;
5429 }
5430 if (Right.is(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(tok::period) &&
5437 Left.Tok.getIdentifierInfo()) {
5438 return false;
5439 }
5440 // Additional unary JavaScript operators that need a space after.
5441 if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
5442 tok::kw_void)) {
5443 return true;
5444 }
5445 }
5446 // `foo as const;` casts into a const type.
5447 if (Left.endsSequence(tok::kw_const, Keywords.kw_as))
5448 return false;
5449 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
5450 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(Keywords.kw_of) && BeforeLeft &&
5455 BeforeLeft->isOneOf(tok::identifier, tok::r_square, tok::r_brace))) &&
5456 (!BeforeLeft || BeforeLeft->isNot(tok::period))) {
5457 return true;
5458 }
5459 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && BeforeLeft &&
5460 BeforeLeft->is(tok::period) && Right.is(tok::l_paren)) {
5461 return false;
5462 }
5463 if (Left.is(Keywords.kw_as) &&
5464 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren)) {
5465 return true;
5466 }
5467 if (Left.is(tok::kw_default) && BeforeLeft &&
5468 BeforeLeft->is(tok::kw_export)) {
5469 return true;
5470 }
5471 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
5472 return true;
5473 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
5474 return false;
5475 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
5476 return false;
5477 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
5478 Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) {
5479 return false;
5480 }
5481 if (Left.is(tok::ellipsis))
5482 return false;
5483 if (Left.is(TT_TemplateCloser) &&
5484 Right.isNoneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
5485 Keywords.kw_implements, 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_NonNullAssertion))
5492 return false;
5493 if (Left.is(TT_NonNullAssertion) &&
5494 Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) {
5495 return true; // "x! as string", "x! in y"
5496 }
5497 } else if (Style.isJava()) {
5498 if (Left.is(TT_CaseLabelArrow) || Right.is(TT_CaseLabelArrow))
5499 return true;
5500 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
5501 return true;
5502 // spaces inside square brackets.
5503 if (Left.is(tok::l_square) || Right.is(tok::r_square))
5504 return Style.SpacesInSquareBrackets;
5505
5506 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) {
5507 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5508 spaceRequiredBeforeParens(Right);
5509 }
5510 if ((Left.isAccessSpecifierKeyword() ||
5511 Left.isOneOf(tok::kw_static, Keywords.kw_final, Keywords.kw_abstract,
5512 Keywords.kw_native)) &&
5513 Right.is(TT_TemplateOpener)) {
5514 return true;
5515 }
5516 } else if (IsVerilog) {
5517 // An escaped identifier ends with whitespace.
5518 if (Left.is(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_VerilogTableItem) &&
5523 Right.isNoneOf(tok::r_paren, tok::semi)) ||
5524 (Right.is(TT_VerilogTableItem) && Left.isNot(tok::l_paren))) {
5525 const FormatToken *Next = Right.getNextNonComment();
5526 return !(Next && Next->is(tok::r_paren));
5527 }
5528 // Don't add space within a delay like `#0`.
5529 if (Left.isNot(TT_BinaryOperator) &&
5530 Left.isOneOf(Keywords.kw_verilogHash, Keywords.kw_verilogHashHash)) {
5531 return false;
5532 }
5533 // Add space after a delay.
5534 if (Right.isNot(tok::semi) &&
5535 (Left.endsSequence(tok::numeric_constant, Keywords.kw_verilogHash) ||
5536 Left.endsSequence(tok::numeric_constant,
5537 Keywords.kw_verilogHashHash) ||
5538 (Left.is(tok::r_paren) && Left.MatchingParen &&
5539 Left.MatchingParen->endsSequence(tok::l_paren, 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(Keywords.kw_apostrophe) ||
5545 (Left.is(TT_VerilogNumberBase) && Right.is(tok::numeric_constant))) {
5546 return false;
5547 }
5548 // Add spaces around the implication operator `->`.
5549 if (Left.is(tok::arrow) || Right.is(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(tok::at) && Right.isOneOf(tok::l_paren, tok::star, tok::at))
5555 return false;
5556 // Add space between the type name and dimension like `logic [1:0]`.
5557 if (Right.is(tok::l_square) &&
5558 Left.isOneOf(TT_VerilogDimensionedTypeName, 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(tok::period, Keywords.kw_apostrophe) &&
5563 Keywords.isVerilogIdentifier(Left) && Left.getPreviousNonComment() &&
5564 Left.getPreviousNonComment()->is(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(Keywords.kw_apostrophe) ||
5571 (Right.is(BK_BracedInit) && Right.is(tok::l_brace))) &&
5572 Left.isNoneOf(Keywords.kw_assign, Keywords.kw_unique) &&
5573 !Keywords.isVerilogWordOperator(Left) &&
5574 (Left.isOneOf(tok::r_square, tok::r_paren, tok::r_brace,
5575 tok::numeric_constant) ||
5576 Keywords.isWordLike(Left))) {
5577 return false;
5578 }
5579 // Don't add spaces in imports like `import foo::*;`.
5580 if ((Right.is(tok::star) && Left.is(tok::coloncolon)) ||
5581 (Left.is(tok::star) && Right.is(tok::semi))) {
5582 return false;
5583 }
5584 // Add space in attribute like `(* ASYNC_REG = "TRUE" *)`.
5585 if (Left.endsSequence(tok::star, tok::l_paren) && Right.is(tok::identifier))
5586 return true;
5587 // Add space before drive strength like in `wire (strong1, pull0)`.
5588 if (Right.is(tok::l_paren) && Right.is(TT_VerilogStrength))
5589 return true;
5590 // Don't add space in a streaming concatenation like `{>>{j}}`.
5591 if ((Left.is(tok::l_brace) &&
5592 Right.isOneOf(tok::lessless, tok::greatergreater)) ||
5593 (Left.endsSequence(tok::lessless, tok::l_brace) ||
5594 Left.endsSequence(tok::greatergreater, 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(tok::l_square) && Right.is(tok::l_brace))
5600 return true;
5601 if (Left.is(tok::r_brace) && Right.is(tok::r_square))
5602 return true;
5603 // Do not insert around colon in DAGArg and cond operator.
5604 if (Right.isOneOf(TT_TableGenDAGArgListColon,
5605 TT_TableGenDAGArgListColonToAlign) ||
5606 Left.isOneOf(TT_TableGenDAGArgListColon,
5607 TT_TableGenDAGArgListColonToAlign)) {
5608 return false;
5609 }
5610 if (Right.is(TT_TableGenCondOperatorColon))
5611 return false;
5612 if (Left.isOneOf(TT_TableGenDAGArgOperatorID,
5613 TT_TableGenDAGArgOperatorToBreak) &&
5614 Right.isNot(TT_TableGenDAGArgCloser)) {
5615 return true;
5616 }
5617 // Do not insert bang operators and consequent openers.
5618 if (Right.isOneOf(tok::l_paren, tok::less) &&
5619 Left.isOneOf(TT_TableGenBangOperator, 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_TableGenTrailingPasteOperator) &&
5625 Right.isOneOf(tok::l_brace, tok::colon)) {
5626 return true;
5627 }
5628 // Otherwise paste operator does not prefer space around.
5629 if (Left.is(tok::hash) || Right.is(tok::hash))
5630 return false;
5631 // Sure not to connect after defining keywords.
5632 if (Keywords.isTableGenDefinition(Left))
5633 return true;
5634 }
5635
5636 if (Left.is(TT_ImplicitStringLiteral))
5637 return Right.hasWhitespaceBefore();
5638 if (Line.Type == LT_ObjCMethodDecl) {
5639 if (Left.is(TT_ObjCMethodSpecifier))
5640 return Style.ObjCSpaceAfterMethodDeclarationPrefix;
5641 if (Left.is(tok::r_paren) && Left.isNot(TT_AttributeRParen) &&
5642 canBeObjCSelectorComponent(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(tok::equal) || Left.is(tok::equal))) {
5651 return false;
5652 }
5653
5654 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
5655 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) {
5656 return true;
5657 }
5658 if (Left.is(tok::comma) && Right.isNot(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(tok::comma))
5665 return false;
5666 if (Right.is(TT_ObjCBlockLParen))
5667 return true;
5668 if (Right.is(TT_CtorInitializerColon))
5669 return Style.SpaceBeforeCtorInitializerColon;
5670 if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
5671 return false;
5672 if (Right.is(TT_EnumUnderlyingTypeColon) &&
5673 !Style.SpaceBeforeEnumUnderlyingTypeColon) {
5674 return false;
5675 }
5676 if (Right.is(TT_RangeBasedForLoopColon) &&
5677 !Style.SpaceBeforeRangeBasedForLoopColon) {
5678 return false;
5679 }
5680 if (Left.is(TT_BitFieldColon)) {
5681 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
5682 Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
5683 }
5684 if (Right.is(tok::colon)) {
5685 if (Right.is(TT_CaseLabelColon))
5686 return Style.SpaceBeforeCaseColon;
5687 if (Right.is(TT_GotoLabelColon))
5688 return false;
5689 // `private:` and `public:`.
5690 if (!Right.getNextNonComment())
5691 return false;
5692 if (Right.isOneOf(TT_ObjCSelector, TT_ObjCMethodExpr))
5693 return false;
5694 if (Left.is(tok::question))
5695 return false;
5696 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
5697 return false;
5698 if (Right.is(TT_DictLiteral))
5699 return Style.SpacesInContainerLiterals;
5700 if (Right.is(TT_AttributeColon))
5701 return false;
5702 if (Right.is(TT_CSharpNamedArgumentColon))
5703 return false;
5704 if (Right.is(TT_GenericSelectionColon))
5705 return false;
5706 if (Right.is(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(tok::minus, tok::minusminus) &&
5714 Right.isOneOf(tok::minus, tok::minusminus)) ||
5715 (Left.isOneOf(tok::plus, tok::plusplus) &&
5716 Right.isOneOf(tok::plus, tok::plusplus))) {
5717 return true;
5718 }
5719 if (Left.is(TT_UnaryOperator)) {
5720 // Lambda captures allow for a lone &, so "&]" needs to be properly
5721 // handled.
5722 if (Left.is(tok::amp) && Right.is(tok::r_square))
5723 return Style.SpacesInSquareBrackets;
5724 if (Left.isNot(tok::exclaim))
5725 return false;
5726 if (Left.TokenText == "!")
5727 return Style.SpaceAfterLogicalNot;
5728 assert(Left.TokenText == "not");
5729 return Right.isOneOf(tok::coloncolon, TT_UnaryOperator) ||
5730 (Right.is(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_CastRParen)) {
5736 return Style.SpaceAfterCStyleCast ||
5737 Right.isOneOf(TT_BinaryOperator, 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(tok::greater) && Right.is(tok::greater)) {
5749 if (Style.isTextProto() ||
5750 (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral))) {
5751 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
5752 }
5753 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
5754 ((Style.Standard < FormatStyle::LS_Cpp11) ||
5755 ShouldAddSpacesInAngles());
5756 }
5757 if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
5758 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
5759 (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod))) {
5760 return false;
5761 }
5762 if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) &&
5763 Right.getPrecedence() == prec::Assignment) {
5764 return false;
5765 }
5766 if (Style.isJava() && Right.is(tok::coloncolon) &&
5767 Left.isOneOf(tok::identifier, tok::kw_this)) {
5768 return false;
5769 }
5770 if (Right.is(tok::coloncolon) && Left.is(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(tok::coloncolon) &&
5776 Left.isNoneOf(tok::l_brace, tok::comment, tok::l_paren)) {
5777 // Put a space between < and :: in vector< ::std::string >
5778 return (Left.is(TT_TemplateOpener) &&
5779 ((Style.Standard < FormatStyle::LS_Cpp11) ||
5780 ShouldAddSpacesInAngles())) ||
5781 Left.isNoneOf(tok::l_paren, tok::r_paren, tok::l_square,
5782 tok::kw___super, TT_TemplateOpener,
5783 TT_TemplateCloser) ||
5784 (Left.is(tok::l_paren) && Style.SpacesInParensOptions.Other);
5785 }
5786 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
5787 return ShouldAddSpacesInAngles();
5788 if (Left.is(tok::r_paren) && Left.isNot(TT_TypeDeclarationParen) &&
5789 Right.is(TT_PointerOrReference) && Right.isOneOf(tok::amp, tok::ampamp)) {
5790 return true;
5791 }
5792 // Space before TT_StructuredBindingLSquare.
5793 if (Right.is(TT_StructuredBindingLSquare)) {
5794 return Left.isNoneOf(tok::amp, tok::ampamp) ||
5795 getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right;
5796 }
5797 // Space before & or && following a TT_StructuredBindingLSquare.
5798 if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
5799 Right.isOneOf(tok::amp, tok::ampamp)) {
5800 return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
5801 }
5802 if ((Right.is(TT_BinaryOperator) && Left.isNot(tok::l_paren)) ||
5803 (Left.isOneOf(TT_BinaryOperator, TT_EnumEqual, TT_ConditionalExpr) &&
5804 Right.isNot(tok::r_paren))) {
5805 return true;
5806 }
5807 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
5808 Left.MatchingParen &&
5809 Left.MatchingParen->is(TT_OverloadedOperatorLParen)) {
5810 return false;
5811 }
5812 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
5813 Line.Type == LT_ImportStatement) {
5814 return true;
5815 }
5816 if (Right.is(TT_TrailingUnaryOperator))
5817 return false;
5818 if (Left.is(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(tok::l_brace) && Tok.is(BK_Block) &&
5826 Tok.isNoneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
5827}
5828
5829// Returns 'true' if 'Tok' is a function argument.
5831 return Tok.MatchingParen && Tok.MatchingParen->Next &&
5832 Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren,
5833 tok::r_brace);
5834}
5835
5836static bool
5838 FormatStyle::ShortLambdaStyle ShortLambdaOption) {
5839 return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None;
5840}
5841
5843 return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
5844 Tok.isNoneOf(TT_ObjCBlockLBrace, 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(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_FatArrow) && Right.is(tok::l_brace) &&
5881 Style.BraceWrapping.AfterFunction) {
5882 return true;
5883 }
5884 if (Right.is(TT_CSharpNamedArgumentColon) ||
5885 Left.is(TT_CSharpNamedArgumentColon)) {
5886 return false;
5887 }
5888 if (Right.is(TT_CSharpGenericTypeConstraint))
5889 return true;
5890 if (AfterRight && AfterRight->is(TT_FatArrow) &&
5891 (Right.is(tok::numeric_constant) ||
5892 (Right.is(tok::identifier) && Right.TokenText == "_"))) {
5893 return true;
5894 }
5895
5896 // Break after C# [...] and before public/protected/private/internal.
5897 if (Left.is(TT_AttributeRSquare) &&
5898 (Right.isAccessSpecifier(/*ColonRequired=*/false) ||
5899 Right.is(Keywords.kw_internal))) {
5900 return true;
5901 }
5902 // Break between ] and [ but only when there are really 2 attributes.
5903 if (Left.is(TT_AttributeRSquare) && Right.is(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(tok::string_literal) && Left.is(tok::plus) && BeforeLeft &&
5908 BeforeLeft->is(tok::string_literal)) {
5909 return true;
5910 }
5911 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
5912 BeforeLeft && BeforeLeft->is(tok::equal) &&
5913 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
5914 tok::kw_const) &&
5915 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
5916 // above.
5917 Line.First->isNoneOf(Keywords.kw_var, 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(tok::l_brace) && Line.Level == 0 &&
5923 (Line.startsWith(tok::kw_enum) ||
5924 Line.startsWith(tok::kw_const, tok::kw_enum) ||
5925 Line.startsWith(tok::kw_export, tok::kw_enum) ||
5926 Line.startsWith(tok::kw_export, tok::kw_const, 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(tok::r_brace) && Left.is(tok::l_brace) && BeforeLeft &&
5932 BeforeLeft->is(TT_FatArrow)) {
5933 // JS arrow function (=> {...}).
5934 switch (Style.AllowShortLambdasOnASingleLine) {
5936 return false;
5938 return true;
5940 return !Left.Children.empty();
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(tok::r_brace) && Left.is(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(tok::plus) && Left.is(tok::string_literal) && AfterRight &&
5960 AfterRight->is(tok::string_literal)) {
5961 return true;
5962 }
5963 } else if (Style.isVerilog()) {
5964 // Break between assignments.
5965 if (Left.is(TT_VerilogAssignComma))
5966 return true;
5967 // Break between ports of different types.
5968 if (Left.is(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_VerilogInstancePortComma) ||
5974 (Left.is(tok::r_paren) && Keywords.isVerilogIdentifier(Right) &&
5975 Left.MatchingParen &&
5976 Left.MatchingParen->is(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(Right) && Keywords.isVerilogEndOfLabel(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_DictLiteral) && Left.is(tok::l_brace))
5995 return true;
5996 // Always break after a JSON array opener based on BreakArrays.
5997 if ((Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) &&
5998 Right.isNot(tok::r_square)) ||
5999 Left.is(tok::comma)) {
6000 if (Right.is(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(tok::l_brace, tok::l_square))
6006 return true;
6007 if (Tok->isOneOf(tok::r_brace, 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_TableGenCondOperatorComma))
6017 return true;
6018 if (Left.is(TT_TableGenDAGArgOperatorToBreak) &&
6019 Right.isNot(TT_TableGenDAGArgCloser)) {
6020 return true;
6021 }
6022 if (Left.is(TT_TableGenDAGArgListCommaToBreak))
6023 return true;
6024 if (Right.is(TT_TableGenDAGArgCloser) && Right.MatchingParen &&
6025 Right.MatchingParen->is(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(tok::kw_asm) && Right.is(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(tok::l_brace, TT_ArrayInitializerLSquare) ||
6044 (Style.isJavaScript() && Left.is(tok::l_paren))) &&
6045 Left.isNot(BK_Block) && Left.MatchingParen) {
6046 BeforeClosingBrace = Left.MatchingParen->Previous;
6047 } else if (Right.MatchingParen &&
6048 (Right.MatchingParen->isOneOf(tok::l_brace,
6049 TT_ArrayInitializerLSquare) ||
6050 (Style.isJavaScript() &&
6051 Right.MatchingParen->is(tok::l_paren)))) {
6052 BeforeClosingBrace = &Left;
6053 }
6054 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
6055 BeforeClosingBrace->isTrailingComment())) {
6056 return true;
6057 }
6058 }
6059
6060 if (Right.is(tok::comment)) {
6061 return Left.isNoneOf(BK_BracedInit, 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(tok::lessless) &&
6070 Left.is(tok::string_literal) && Right.is(tok::lessless) && AfterRight &&
6071 AfterRight->is(tok::string_literal)) {
6072 return Right.NewlinesBefore > 0;
6073 }
6074
6075 if (Right.is(TT_RequiresClause)) {
6076 switch (Style.RequiresClausePosition) {
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(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) {
6101 return Right.isNot(tok::semi);
6103 return Right.isNoneOf(tok::semi, 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_CtorInitializerComma) ||
6111 Right.is(TT_CtorInitializerColon))) {
6112 return true;
6113 }
6114
6115 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
6116 Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma)) {
6117 return true;
6118 }
6119
6120 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterComma &&
6121 Left.is(TT_CtorInitializerComma)) {
6122 return true;
6123 }
6124 }
6125 if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine &&
6126 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
6127 Right.isOneOf(TT_CtorInitializerComma, 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_CtorInitializerColon)) {
6134 return true;
6135 }
6136
6137 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
6138 Left.is(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_InheritanceComma)) {
6145 return true;
6146 }
6147 if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma &&
6148 Left.is(TT_InheritanceComma)) {
6149 return true;
6150 }
6151 if (Right.is(tok::string_literal) && Right.TokenText.starts_with("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(tok::l_brace) ||
6158 (Left.is(tok::less) && BeforeLeft && BeforeLeft->is(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_InlineASMBrace))
6165 return Right.HasUnescapedNewline;
6166
6167 if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
6168 auto *FirstNonComment = Line.getFirstNonComment();
6169 bool AccessSpecifier =
6170 FirstNonComment && (FirstNonComment->is(Keywords.kw_internal) ||
6171 FirstNonComment->isAccessSpecifierKeyword());
6172
6173 if (Style.BraceWrapping.AfterEnum) {
6174 if (Line.startsWith(tok::kw_enum) ||
6175 Line.startsWith(tok::kw_typedef, tok::kw_enum) ||
6176 Line.startsWith(tok::kw_export, tok::kw_enum)) {
6177 return true;
6178 }
6179 // Ensure BraceWrapping for `public enum A {`.
6180 if (AccessSpecifier && FirstNonComment->Next &&
6181 FirstNonComment->Next->is(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(Keywords.kw_interface)) ||
6190 Line.startsWith(Keywords.kw_interface))) {
6191 return true;
6192 }
6193
6194 // Don't attempt to interpret record return types as records.
6195 if (Right.isNot(TT_FunctionLBrace)) {
6196 return Style.AllowShortRecordOnASingleLine == FormatStyle::SRS_Never &&
6197 ((Line.startsWith(tok::kw_class) &&
6198 Style.BraceWrapping.AfterClass) ||
6199 (Line.startsWith(tok::kw_struct) &&
6200 Style.BraceWrapping.AfterStruct) ||
6201 (Line.startsWith(tok::kw_union) &&
6202 Style.BraceWrapping.AfterUnion));
6203 }
6204 }
6205
6206 if (Left.is(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(TT_AttributeRParen, TT_AttributeMacro) &&
6213 Right.is(TT_ObjCDecl)) {
6214 return true;
6215 }
6216
6217 if (Left.is(TT_LambdaLBrace)) {
6218 if (IsFunctionArgument(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_LambdaLBrace) &&
6232 (Left.isPointerOrReference() || Left.is(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_LeadingJavaAnnotation) &&
6239 Right.isNoneOf(TT_LeadingJavaAnnotation, tok::l_paren) &&
6240 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) {
6241 return true;
6242 }
6243
6244 if (Right.is(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_SelectorName) &&
6275 Right.isNot(tok::r_square) && AfterRight) {
6276 // Keep `@submessage` together in:
6277 // @submessage { key: value }
6278 if (Left.is(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(tok::colon)) {
6286 LBrace = LBrace->Next;
6287 if (LBrace && LBrace->is(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(tok::l_brace) &&
6303 (LBrace->is(TT_DictLiteral) ||
6304 (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
6305 LBrace->isOneOf(TT_ArrayInitializerLSquare, 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(tok::r_brace, tok::greater, tok::r_square))
6328 return true;
6329 }
6330
6331 if (Style.BreakAfterAttributes == FormatStyle::ABS_LeaveAll &&
6332 Left.is(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(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
6346 Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) {
6347 return false;
6348 }
6349 // Only break after commas for generic type constraints.
6350 if (Line.First->is(TT_CSharpGenericTypeConstraint))
6351 return Left.is(TT_CSharpGenericTypeConstraintComma);
6352 // Keep nullable operators attached to their identifiers.
6353 if (Right.is(TT_CSharpNullable))
6354 return false;
6355 } else if (Style.isJava()) {
6356 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
6357 Keywords.kw_implements)) {
6358 return false;
6359 }
6360 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
6361 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 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
6370 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
6371 tok::kw_static, Keywords.kw_readonly, Keywords.kw_override,
6372 Keywords.kw_abstract, Keywords.kw_get, Keywords.kw_set,
6373 Keywords.kw_async, 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(tok::r_square, tok::r_paren)) &&
6379 Right.isOneOf(tok::l_square, tok::l_paren)) {
6380 return false; // Otherwise automatic semicolon insertion would trigger.
6381 }
6382 if (NonComment && NonComment->is(tok::identifier) &&
6383 NonComment->TokenText == "asserts") {
6384 return false;
6385 }
6386 if (Left.is(TT_FatArrow) && Right.is(tok::l_brace))
6387 return false;
6388 if (Left.is(TT_JsTypeColon))
6389 return true;
6390 // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
6391 if (Left.is(tok::exclaim) && Right.is(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(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(tok::colon))
6406 return false;
6407 }
6408 if (Left.is(Keywords.kw_in))
6409 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
6410 if (Right.is(Keywords.kw_in))
6411 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
6412 if (Right.is(Keywords.kw_as))
6413 return false; // must not break before as in 'x as type' casts
6414 if (Right.isOneOf(Keywords.kw_extends, 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(Keywords.kw_as))
6421 return true;
6422 if (Left.is(TT_NonNullAssertion))
6423 return true;
6424 if (Left.is(Keywords.kw_declare) &&
6425 Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
6426 Keywords.kw_function, tok::kw_class, tok::kw_enum,
6427 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
6428 Keywords.kw_let, 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(Keywords.kw_module, tok::kw_namespace) &&
6434 Right.isOneOf(tok::identifier, tok::string_literal)) {
6435 return false; // must not break in "module foo { ...}"
6436 }
6437 if (Right.is(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(tok::identifier) && Right.is(TT_TemplateString))
6442 return false;
6443 if (Left.is(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(Left))
6448 return false;
6449 // Avoid to break after '(' in the cases that is in bang operators.
6450 if (Right.is(tok::l_paren)) {
6451 return Left.isNoneOf(TT_TableGenBangOperator, TT_TableGenCondOperator,
6452 TT_TemplateCloser);
6453 }
6454 // Avoid to break between the value and its suffix part.
6455 if (Left.is(TT_TableGenValueSuffix))
6456 return false;
6457 // Avoid to break around paste operator.
6458 if (Left.is(tok::hash) || Right.is(tok::hash))
6459 return false;
6460 if (Left.isOneOf(TT_TableGenBangOperator, 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(tok::r_brace)) {
6468 return Right.MatchingParen && (Right.MatchingParen->is(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(tok::r_paren)) {
6475 if (!Right.MatchingParen)
6476 return false;
6477 auto Next = Right.Next;
6478 if (Next && Next->is(tok::r_paren))
6479 Next = Next->Next;
6480 if (Next && Next->is(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(tok::kw_switch))
6490 return Style.BreakBeforeCloseBracketSwitch;
6491 return Style.BreakBeforeCloseBracketFunction;
6492 }
6493
6494 if (Left.isOneOf(tok::r_paren, TT_TrailingAnnotation) &&
6495 Right.is(TT_TrailingAnnotation) &&
6496 Style.BreakBeforeCloseBracketFunction) {
6497 return false;
6498 }
6499
6500 if (Right.is(TT_TemplateCloser))
6501 return Style.BreakBeforeTemplateCloser;
6502
6503 if (Left.isOneOf(tok::at, tok::objc_interface))
6504 return false;
6505 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
6506 return Right.isNot(tok::l_paren);
6507 if (Right.is(TT_PointerOrReference)) {
6508 return Line.IsMultiVariableDeclStmt ||
6509 (getTokenPointerOrReferenceAlignment(Right) ==
6511 !(Right.Next &&
6512 Right.Next->isOneOf(TT_FunctionDeclarationName, tok::kw_const)));
6513 }
6514 if (Left.is(tok::hashhash) || Right.is(tok::hashhash))
6515 return false;
6516 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
6517 TT_ClassHeadName, TT_QtProperty, tok::kw_operator)) {
6518 return true;
6519 }
6520 if (Left.is(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(BK_BracedInit) ||
6529 (Left.is(TT_CtorInitializerColon) && Right.NewlinesBefore > 0 &&
6530 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
6531 }
6532 if (Left.is(tok::question) && Right.is(tok::colon))
6533 return false;
6534 if (Right.isOneOf(TT_ConditionalExpr, tok::question))
6535 return Style.BreakBeforeTernaryOperators;
6536 if (Left.isOneOf(TT_ConditionalExpr, tok::question))
6537 return !Style.BreakBeforeTernaryOperators;
6538 if (Left.is(TT_InheritanceColon))
6539 return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
6540 if (Right.is(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_ObjCMethodExpr) && Right.isNot(tok::r_square) &&
6544 Left.isNot(TT_SelectorName)) {
6545 return true;
6546 }
6547
6548 if (Right.is(tok::colon) &&
6549 Right.isNoneOf(TT_CtorInitializerColon, TT_InlineASMColon,
6550 TT_BitFieldColon)) {
6551 return false;
6552 }
6553 if (Left.is(tok::colon) && Left.isOneOf(TT_ObjCSelector, TT_ObjCMethodExpr))
6554 return true;
6555 if (Left.is(tok::colon) && Left.is(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(tok::l_brace, tok::less) &&
6584 Right.is(TT_DictLiteral)) ||
6585 Right.is(TT_ArrayInitializerLSquare)) {
6586 return false;
6587 }
6588 }
6589 return true;
6590 }
6591 if (Right.is(tok::r_square) && Right.MatchingParen &&
6592 Right.MatchingParen->is(TT_ProtoExtensionLSquare)) {
6593 return false;
6594 }
6595 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
6596 Right.Next->is(TT_ObjCMethodExpr))) {
6597 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
6598 }
6599 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
6600 return true;
6601 if (Right.is(tok::kw_concept))
6602 return Style.BreakBeforeConceptDeclarations != FormatStyle::BBCDS_Never;
6603 if (Right.is(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_FunctionAnnotationRParen))
6610 return true;
6611 if (Left.ClosesRequiresClause)
6612 return true;
6613 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
6614 TT_OverloadedOperator)) {
6615 return false;
6616 }
6617 if (Left.is(TT_RangeBasedForLoopColon))
6618 return true;
6619 if (Right.is(TT_RangeBasedForLoopColon))
6620 return false;
6621 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
6622 return true;
6623 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
6624 (Left.is(tok::less) && Right.is(tok::less))) {
6625 return false;
6626 }
6627 if (Right.is(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(TT_TemplateCloser, TT_UnaryOperator, tok::kw_operator))
6634 return false;
6635 if (Left.is(tok::equal) && Right.isNoneOf(tok::kw_default, tok::kw_delete) &&
6636 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) {
6637 return false;
6638 }
6639 if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
6640 Style.Cpp11BracedListStyle == FormatStyle::BLS_Block) {
6641 return false;
6642 }
6643 if (Left.is(TT_AttributeLParen) ||
6644 (Left.is(tok::l_paren) && Left.is(TT_TypeDeclarationParen))) {
6645 return false;
6646 }
6647 if (Left.is(tok::l_paren) && Left.Previous &&
6648 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) {
6649 return false;
6650 }
6651 if (Right.is(TT_ImplicitStringLiteral))
6652 return false;
6653
6654 if (Right.is(tok::r_square) && Right.MatchingParen &&
6655 Right.MatchingParen->is(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_TrailingAnnotation)) {
6662 return Right.isNoneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
6663 tok::less, tok::coloncolon);
6664 }
6665
6666 if (Right.isAttribute())
6667 return true;
6668
6669 if (Right.is(TT_AttributeLSquare)) {
6670 assert(Left.isNot(tok::l_square));
6671 return true;
6672 }
6673
6674 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
6675 return true;
6676
6677 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
6678 return true;
6679
6680 if (Left.is(TT_CtorInitializerColon)) {
6681 return (Style.BreakConstructorInitializers ==
6683 Style.BreakConstructorInitializers ==
6685 (!Right.isTrailingComment() || Right.NewlinesBefore > 0);
6686 }
6687 if (Right.is(TT_CtorInitializerColon)) {
6688 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon &&
6689 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterComma;
6690 }
6691 if (Left.is(TT_CtorInitializerComma) &&
6692 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
6693 return false;
6694 }
6695 if (Right.is(TT_CtorInitializerComma) &&
6696 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
6697 return true;
6698 }
6699 if (Left.is(TT_InheritanceComma) &&
6700 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
6701 return false;
6702 }
6703 if (Right.is(TT_InheritanceComma) &&
6704 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
6705 return true;
6706 }
6707 if (Left.is(TT_ArrayInitializerLSquare))
6708 return true;
6709 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
6710 return true;
6711 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
6712 Left.isNoneOf(tok::arrowstar, 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_AttributeLSquare) && Right.is(tok::l_square)) {
6719 assert(Right.isNot(TT_AttributeLSquare));
6720 return false;
6721 }
6722 if (Left.is(tok::r_square) && Right.is(TT_AttributeRSquare)) {
6723 assert(Left.isNot(TT_AttributeRSquare));
6724 return false;
6725 }
6726
6727 auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
6728 if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) {
6729 if (isAllmanLambdaBrace(Left))
6730 return !isEmptyLambdaAllowed(Left, ShortLambdaOption);
6731 if (isAllmanLambdaBrace(Right))
6732 return !isEmptyLambdaAllowed(Right, ShortLambdaOption);
6733 }
6734
6735 if (Right.is(tok::kw_noexcept) && Right.is(TT_TrailingAnnotation)) {
6736 switch (Style.AllowBreakBeforeNoexceptSpecifier) {
6738 return false;
6740 return true;
6742 return Right.Next && Right.Next->is(tok::l_paren);
6743 }
6744 }
6745
6746 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
6747 tok::kw_class, tok::kw_struct, tok::comment) ||
6748 Right.isMemberAccess() ||
6749 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
6750 tok::colon, tok::l_square, tok::at) ||
6751 (Left.is(tok::r_paren) &&
6752 Right.isOneOf(tok::identifier, tok::kw_const)) ||
6753 (Left.is(tok::l_paren) && Right.isNot(tok::r_paren)) ||
6754 (Left.is(TT_TemplateOpener) && Right.isNot(TT_TemplateCloser));
6755}
6756
6757void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) const {
6758 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << ", P=" << Line.PPLevel
6759 << ", T=" << Line.Type << ", C=" << Line.IsContinuation
6760 << "):\n";
6761 const FormatToken *Tok = Line.First;
6762 while (Tok) {
6763 llvm::errs() << " I=" << Tok->IndentLevel << " M=" << Tok->MustBreakBefore
6764 << " C=" << Tok->CanBreakBefore
6765 << " T=" << getTokenTypeName(Tok->getType())
6766 << " S=" << Tok->SpacesRequiredBefore
6767 << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount
6768 << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty
6769 << " Name=" << Tok->Tok.getName() << " N=" << Tok->NestingLevel
6770 << " L=" << Tok->TotalLength
6771 << " PPK=" << Tok->getPackingKind() << " FakeLParens=";
6772 for (prec::Level LParen : Tok->FakeLParens)
6773 llvm::errs() << LParen << "/";
6774 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
6775 llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
6776 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
6777 if (!Tok->Next)
6778 assert(Tok == Line.Last);
6779 Tok = Tok->Next;
6780 }
6781 llvm::errs() << "----\n";
6782}
6783
6785TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) const {
6786 assert(Reference.isOneOf(tok::amp, tok::ampamp));
6787 switch (Style.ReferenceAlignment) {
6789 return Style.PointerAlignment;
6791 return FormatStyle::PAS_Left;
6796 }
6797 assert(0); //"Unhandled value of ReferenceAlignment"
6798 return Style.PointerAlignment;
6799}
6800
6802TokenAnnotator::getTokenPointerOrReferenceAlignment(
6803 const FormatToken &PointerOrReference) const {
6804 if (PointerOrReference.isOneOf(tok::amp, tok::ampamp))
6805 return getTokenReferenceAlignment(PointerOrReference);
6806 assert(PointerOrReference.is(tok::star));
6807 return Style.PointerAlignment;
6808}
6809
6810} // namespace format
6811} // namespace clang
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
unsigned OperatorIndex
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
unsigned NestingLevel
The nesting level of this token, i.e.
unsigned UnbreakableTailLength
The length of following tokens until the next natural split point, or the next token that can be brok...
FormatToken * NextOperator
If this is an operator (or "."/"->") in a sequence of operators with the same precedence,...
FormatToken()
Token Tok
The Token.
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
unsigned IndentLevel
The indent level of this token. Copied from the surrounding line.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
This file implements a token annotator, i.e.
Defines the clang::TokenKind enum and support functions.
#define TRANSFORM_TYPE_TRAIT_DEF(Enum, _)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Parser - This implements a parser for the C family of languages.
Definition Parser.h:256
void calculateFormattingInformation(AnnotatedLine &Line) const
void annotate(AnnotatedLine &Line)
void setCommentLineLevels(SmallVectorImpl< AnnotatedLine * > &Lines) const
Adapts the indent levels of comment lines to the indent of the subsequent line.
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
static bool isAllmanLambdaBrace(const FormatToken &Tok)
static bool isFunctionDeclarationName(const LangOptions &LangOpts, const FormatToken &Current, const AnnotatedLine &Line, FormatToken *&ClosingParen)
static bool IsFunctionArgument(const FormatToken &Tok)
static unsigned maxNestingDepth(const AnnotatedLine &Line)
static FormatToken * findReturnTypeStart(const AnnotatedLine &Line)
static bool mustBreakAfterAttributes(const FormatToken &Tok, const FormatStyle &Style)
static FormatToken * skipNameQualifier(const FormatToken *Tok)
bool isClangFormatOff(StringRef Comment)
Definition Format.cpp:4916
LangOptions getFormattingLangOpts(const FormatStyle &Style=getLLVMStyle())
Returns the LangOpts that the formatter expects you to set.
Definition Format.cpp:4510
static bool isEmptyLambdaAllowed(const FormatToken &Tok, FormatStyle::ShortLambdaStyle ShortLambdaOption)
static bool isCtorOrDtorName(const FormatToken *Tok)
static bool isAllmanBrace(const FormatToken &Tok)
static FormatToken * getFunctionName(const AnnotatedLine &Line, FormatToken *&OpeningParen)
TokenType
Determines the semantic type of a syntactic token, e.g.
bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style)
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:289
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:909
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
bool isReturnTypePrefixSpecifier(const FormatToken &Tok)
@ Type
The name was classified as a type.
Definition Sema.h:559
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
#define false
Definition stdbool.h:26
@ RTBS_TopLevelDefinitions
Always break after the return type of top-level definitions.
Definition Format.h:1205
@ RTBS_ExceptShortType
Same as Automatic above, except that there is no break after short return types.
Definition Format.h:1141
@ RTBS_All
Always break after the return type.
Definition Format.h:1159
@ RTBS_TopLevel
Always break after the return types of top-level functions.
Definition Format.h:1174
@ RTBS_None
This is deprecated. See Automatic below.
Definition Format.h:1118
@ RTBS_Automatic
Break after return type based on PenaltyReturnTypeOnItsOwnLine.
Definition Format.h:1129
@ RTBS_AllDefinitions
Always break after the return type of function definitions.
Definition Format.h:1191
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:56
@ LK_C
Should be used for C.
Definition Format.h:3817
@ LK_ObjC
Should be used for Objective-C, Objective-C++.
Definition Format.h:3829
@ LK_Proto
Should be used for Protocol Buffers
Definition Format.h:3831
ShortLambdaStyle
Different styles for merging short lambdas containing at most one statement.
Definition Format.h:1031
@ SLS_All
Merge all lambdas fitting on a single line.
Definition Format.h:1055
@ SLS_Inline
Merge lambda into a single line if the lambda is argument of a function.
Definition Format.h:1049
@ SLS_None
Never merge lambdas into a single line.
Definition Format.h:1033
@ SLS_Empty
Only merge empty lambdas.
Definition Format.h:1041
@ BPPS_UseBreakAfter
Use the BreakAfter option to handle parameter packing instead.
Definition Format.h:4377
@ BPPS_AlwaysOnePerLine
Always put each parameter on its own line.
Definition Format.h:4374
@ BCIS_AfterColon
Break constructor initializers after the colon and commas.
Definition Format.h:2665
@ BCIS_AfterComma
Break constructor initializers only after the commas.
Definition Format.h:2671
@ BCIS_BeforeColon
Break constructor initializers before the colon and after the commas.
Definition Format.h:2650
@ BCIS_BeforeComma
Break constructor initializers before the colon and commas, and align the commas with the colon.
Definition Format.h:2658
@ BOS_All
Break before operators.
Definition Format.h:1907
@ BOS_None
Break after operators.
Definition Format.h:1883
@ SIPO_Custom
Configure each individual space in parentheses in SpacesInParensOptions.
Definition Format.h:5715
@ SRS_Never
Never merge records into a single line.
Definition Format.h:1076
@ BBIAS_Always
Always break before inline ASM colon.
Definition Format.h:2458
@ PPDIS_BeforeHash
Indents directives before the hash.
Definition Format.h:3372
@ SBS_Never
Never merge blocks into a single line.
Definition Format.h:751
@ BTDS_Yes
Always break after template declaration.
Definition Format.h:1276
@ BTDS_Leave
Do not change the line breaking before the declaration.
Definition Format.h:1244
@ SBPO_Never
This is deprecated and replaced by Custom below, with all SpaceBeforeParensOptions but AfterPlacement...
Definition Format.h:5314
@ SBPO_Custom
Configure each individual space before parentheses in SpaceBeforeParensOptions.
Definition Format.h:5363
@ SBPO_Always
Always put a space before opening parentheses, except when it's prohibited by the syntax rules (in fu...
Definition Format.h:5360
@ PCIS_NextLineOnly
Put all constructor initializers on the next line if they fit.
Definition Format.h:4343
@ PCIS_Never
Always put each constructor initializer on its own line.
Definition Format.h:4296
@ PCIS_CurrentLine
Put all constructor initializers on the current line if they fit.
Definition Format.h:4314
@ BBRTS_None
Do not force a break before the return type.
Definition Format.h:2468
@ BBRTS_TopLevelDefinitions
Break before the return type of top-level definitions only.
Definition Format.h:2480
@ BBRTS_TopLevel
Break before the return type of top-level functions only.
Definition Format.h:2476
@ BBRTS_All
Always break before the return type.
Definition Format.h:2474
@ BBRTS_AllDefinitions
Break before the return type of function definitions only.
Definition Format.h:2478
@ BILS_AfterColon
Break inheritance list after the colon and commas.
Definition Format.h:2803
@ BILS_AfterComma
Break inheritance list only after the commas.
Definition Format.h:2810
@ BILS_BeforeComma
Break inheritance list before the colon and commas, and align the commas with the colon.
Definition Format.h:2795
@ DAS_DontBreak
Never break inside DAGArg.
Definition Format.h:5933
@ DAS_BreakAll
Break inside DAGArg after the operator and the all elements.
Definition Format.h:5948
@ BBNSS_Never
No line break allowed.
Definition Format.h:704
@ BBNSS_Always
Line breaks are allowed.
Definition Format.h:727
@ BBNSS_OnlyWithParen
For a simple noexcept there is no line break allowed, but when we have a condition it is.
Definition Format.h:715
@ RCPS_OwnLineWithBrace
As with OwnLine, except, unless otherwise prohibited, place a following open brace (of a function def...
Definition Format.h:4889
@ RCPS_OwnLine
Always put the requires clause on its own line (possibly followed by a semicolon).
Definition Format.h:4871
@ RCPS_WithPreceding
Try to put the clause together with the preceding part of a declaration.
Definition Format.h:4906
@ RCPS_WithFollowing
Try to put the requires clause together with the class or function declaration.
Definition Format.h:4920
@ LS_Cpp11
Parse and format as C++11.
Definition Format.h:5848
@ BWACS_MultiLine
Only wrap braces after a multi-line control statement.
Definition Format.h:1410
@ ABS_Never
Never break after the last attribute of the group.
Definition Format.h:1775
@ ABS_Always
Always break after the last attribute of the group.
Definition Format.h:1714
@ ABS_LeaveAll
Same as Leave except that it applies to all attributes of the group.
Definition Format.h:1753
@ BFCS_Both
Add one space on each side of the :
Definition Format.h:1333
@ BFCS_Before
Add space before the : only.
Definition Format.h:1344
@ BFCS_After
Add space after the : only (space may be added before if needed for AlignConsecutiveBitFields).
Definition Format.h:1350
@ BBCDS_Never
Keep the template declaration line together with concept.
Definition Format.h:2418
@ BBCDS_Always
Always break before concept, putting it in the line after the template declaration.
Definition Format.h:2429
@ BLS_AlignFirstComment
Same as FunctionCall, except for the handling of a comment at the begin, it then aligns everything fo...
Definition Format.h:2921
@ BLS_Block
Best suited for pre C++11 braced lists.
Definition Format.h:2883
@ SAPQ_After
Ensure that there is a space after pointer qualifiers.
Definition Format.h:5229
@ SAPQ_Both
Ensure that there is a space both before and after pointer qualifiers.
Definition Format.h:5235
@ SAPQ_Before
Ensure that there is a space before pointer qualifiers.
Definition Format.h:5223
@ AIAS_None
Don't align array initializer columns.
Definition Format.h:112
@ BBO_OnePerLine
Binary operations will either be all on the same line, or each operation will have one line each.
Definition Format.h:2550
@ SIAS_Always
Add spaces after < and before >.
Definition Format.h:5603
@ SIAS_Leave
Keep a single space after < and before > if any spaces were present.
Definition Format.h:5606
@ BPAS_UseBreakAfter
Use the BreakAfter option to handle argument packing instead.
Definition Format.h:4244
@ SIEB_Always
Always insert a space in empty braces.
Definition Format.h:5536
@ SIEB_Never
Never insert a space in empty braces.
Definition Format.h:5552
PointerAlignmentStyle
The &, && and * alignment style.
Definition Format.h:4471
@ PAS_Left
Align pointer to the left.
Definition Format.h:4476
@ PAS_Middle
Align pointer in the middle.
Definition Format.h:4486
@ PAS_Right
Align pointer to the right.
Definition Format.h:4481
@ RAS_Right
Align reference to the right.
Definition Format.h:4667
@ RAS_Left
Align reference to the left.
Definition Format.h:4662
@ RAS_Pointer
Align reference like PointerAlignment.
Definition Format.h:4657
@ RAS_Middle
Align reference in the middle.
Definition Format.h:4672
A wrapper around a Token storing information about the whitespace characters preceding it.
unsigned NestingLevel
The nesting level of this token, i.e.
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
bool MightBeFunctionDeclParen
Might be function declaration open/closing paren.
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
unsigned CanBreakBefore
true if it is allowed to break before this token.
bool isNot(T Kind) const
unsigned Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside),...
bool isNoneOf(Ts... Ks) const
FormatToken * Next
The next token in the unwrapped line.
unsigned NewlinesBefore
The number of newlines immediately before the Token.
unsigned SpacesRequiredBefore
The number of spaces that should be inserted before this token.
unsigned MustBreakBefore
Whether there must be a line break before this token.
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
unsigned UnbreakableTailLength
The length of following tokens until the next natural split point, or the next token that can be brok...
bool is(tok::TokenKind Kind) const
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
bool isOneOf(A K1, B K2) const
unsigned ParameterCount
Number of parameters, if this is "(", "[" or "<".
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
FormatToken * Previous
The previous token in the unwrapped line.
void setFinalizedType(TokenType T)
Sets the type and also the finalized flag.