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) {
29 case FormatStyle::ABS_Always:
30 return true;
31 case FormatStyle::ABS_Never:
32 return false;
33 default: // ABS_Leave and ABS_LeaveAll
34 return Tok.NewlinesBefore > 0;
35 }
36}
37
38namespace {
39
40/// Returns \c true if the line starts with a token that can start a statement
41/// with an initializer.
42static bool startsWithInitStatement(const AnnotatedLine &Line) {
43 return Line.startsWith(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/Traits.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->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
2312 Previous->isPointerOrReference() && Previous->Previous &&
2313 Previous->Previous->isNot(tok::equal)) {
2314 Previous->setType(TT_PointerOrReference);
2315 }
2316 }
2317 }
2318 } else if (Current.is(tok::lessless) &&
2319 (!Current.Previous ||
2320 Current.Previous->isNot(tok::kw_operator))) {
2321 Contexts.back().IsExpression = true;
2322 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
2323 Contexts.back().IsExpression = true;
2324 } else if (Current.is(TT_TrailingReturnArrow)) {
2325 Contexts.back().IsExpression = false;
2326 } else if (Current.isOneOf(TT_LambdaArrow, Keywords.kw_assert)) {
2327 Contexts.back().IsExpression = Style.isJava();
2328 } else if (Current.Previous &&
2329 Current.Previous->is(TT_CtorInitializerColon)) {
2330 Contexts.back().IsExpression = true;
2331 Contexts.back().ContextType = Context::CtorInitializer;
2332 } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
2333 Contexts.back().ContextType = Context::InheritanceList;
2334 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
2335 for (FormatToken *Previous = Current.Previous;
2336 Previous && Previous->isOneOf(tok::star, tok::amp);
2337 Previous = Previous->Previous) {
2338 Previous->setType(TT_PointerOrReference);
2339 }
2340 if (Line.MustBeDeclaration &&
2341 Contexts.front().ContextType != Context::CtorInitializer) {
2342 Contexts.back().IsExpression = false;
2343 }
2344 } else if (Current.is(tok::kw_new)) {
2345 Contexts.back().CanBeExpression = false;
2346 } else if (Current.is(tok::semi) ||
2347 (Current.is(tok::exclaim) && Current.Previous &&
2348 Current.Previous->isNot(tok::kw_operator))) {
2349 // This should be the condition or increment in a for-loop.
2350 // But not operator !() (can't use TT_OverloadedOperator here as its not
2351 // been annotated yet).
2352 Contexts.back().IsExpression = true;
2353 }
2354 }
2355
2356 static FormatToken *untilMatchingParen(FormatToken *Current) {
2357 // Used when `MatchingParen` is not yet established.
2358 int ParenLevel = 0;
2359 while (Current) {
2360 if (Current->is(tok::l_paren))
2361 ++ParenLevel;
2362 if (Current->is(tok::r_paren))
2363 --ParenLevel;
2364 if (ParenLevel < 1)
2365 break;
2366 Current = Current->Next;
2367 }
2368 return Current;
2369 }
2370
2371 static bool isDeductionGuide(FormatToken &Current) {
2372 // Look for a deduction guide template<T> A(...) -> A<...>;
2373 if (Current.Previous && Current.Previous->is(tok::r_paren) &&
2374 Current.startsSequence(tok::arrow, tok::identifier, tok::less)) {
2375 // Find the TemplateCloser.
2376 FormatToken *TemplateCloser = Current.Next->Next;
2377 int NestingLevel = 0;
2378 while (TemplateCloser) {
2379 // Skip over an expressions in parens A<(3 < 2)>;
2380 if (TemplateCloser->is(tok::l_paren)) {
2381 // No Matching Paren yet so skip to matching paren
2382 TemplateCloser = untilMatchingParen(TemplateCloser);
2383 if (!TemplateCloser)
2384 break;
2385 }
2386 if (TemplateCloser->is(tok::less))
2387 ++NestingLevel;
2388 if (TemplateCloser->is(tok::greater))
2389 --NestingLevel;
2390 if (NestingLevel < 1)
2391 break;
2392 TemplateCloser = TemplateCloser->Next;
2393 }
2394 // Assuming we have found the end of the template ensure its followed
2395 // with a semi-colon.
2396 if (TemplateCloser && TemplateCloser->Next &&
2397 TemplateCloser->Next->is(tok::semi) &&
2398 Current.Previous->MatchingParen) {
2399 // Determine if the identifier `A` prior to the A<..>; is the same as
2400 // prior to the A(..)
2401 FormatToken *LeadingIdentifier =
2402 Current.Previous->MatchingParen->Previous;
2403
2404 return LeadingIdentifier &&
2405 LeadingIdentifier->TokenText == Current.Next->TokenText;
2406 }
2407 }
2408 return false;
2409 }
2410
2411 void determineTokenType(FormatToken &Current) {
2412 if (Current.isNot(TT_Unknown)) {
2413 // The token type is already known.
2414 return;
2415 }
2416
2417 if ((Style.isJavaScript() || Style.isCSharp()) &&
2418 Current.is(tok::exclaim)) {
2419 if (Current.Previous) {
2420 bool IsIdentifier =
2421 Style.isJavaScript()
2422 ? Keywords.isJavaScriptIdentifier(
2423 *Current.Previous, /* AcceptIdentifierName= */ true)
2424 : Current.Previous->is(tok::identifier);
2425 if (IsIdentifier ||
2426 Current.Previous->isOneOf(
2427 tok::kw_default, tok::kw_namespace, tok::r_paren, tok::r_square,
2428 tok::r_brace, tok::kw_false, tok::kw_true, Keywords.kw_type,
2429 Keywords.kw_get, Keywords.kw_init, Keywords.kw_set) ||
2430 Current.Previous->Tok.isLiteral()) {
2431 Current.setType(TT_NonNullAssertion);
2432 return;
2433 }
2434 }
2435 if (Current.Next &&
2436 Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
2437 Current.setType(TT_NonNullAssertion);
2438 return;
2439 }
2440 }
2441
2442 // Line.MightBeFunctionDecl can only be true after the parentheses of a
2443 // function declaration have been found. In this case, 'Current' is a
2444 // trailing token of this declaration and thus cannot be a name.
2445 if ((Style.isJavaScript() || Style.isJava()) &&
2446 Current.is(Keywords.kw_instanceof)) {
2447 Current.setType(TT_BinaryOperator);
2448 } else if (isStartOfName(Current) &&
2449 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
2450 Contexts.back().FirstStartOfName = &Current;
2451 Current.setType(TT_StartOfName);
2452 } else if (Current.is(tok::semi)) {
2453 // Reset FirstStartOfName after finding a semicolon so that a for loop
2454 // with multiple increment statements is not confused with a for loop
2455 // having multiple variable declarations.
2456 Contexts.back().FirstStartOfName = nullptr;
2457 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
2458 AutoFound = true;
2459 } else if (Current.is(tok::arrow) && Style.isJava()) {
2460 Current.setType(TT_LambdaArrow);
2461 } else if (Current.is(tok::arrow) && Style.isVerilog()) {
2462 // The implication operator.
2463 Current.setType(TT_BinaryOperator);
2464 } else if (Current.is(tok::arrow) && AutoFound &&
2465 Line.MightBeFunctionDecl && Current.NestingLevel == 0 &&
2466 Current.Previous->isNoneOf(tok::kw_operator, tok::identifier)) {
2467 // not auto operator->() -> xxx;
2468 Current.setType(TT_TrailingReturnArrow);
2469 } else if (Current.is(tok::arrow) && Current.Previous &&
2470 Current.Previous->is(tok::r_brace) &&
2471 Current.Previous->is(BK_Block)) {
2472 // Concept implicit conversion constraint needs to be treated like
2473 // a trailing return type ... } -> <type>.
2474 Current.setType(TT_TrailingReturnArrow);
2475 } else if (isDeductionGuide(Current)) {
2476 // Deduction guides trailing arrow " A(...) -> A<T>;".
2477 Current.setType(TT_TrailingReturnArrow);
2478 } else if (Current.isPointerOrReference()) {
2479 Current.setType(determineStarAmpUsage(
2480 Current,
2481 (Contexts.back().CanBeExpression && Contexts.back().IsExpression) ||
2482 Contexts.back().InStaticAssertFirstArgument,
2483 Contexts.back().ContextType == Context::TemplateArgument));
2484 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret) ||
2485 (Style.isVerilog() && Current.is(tok::pipe))) {
2486 Current.setType(determinePlusMinusCaretUsage(Current));
2487 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
2488 Contexts.back().CaretFound = true;
2489 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
2490 Current.setType(determineIncrementUsage(Current));
2491 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
2492 Current.setType(TT_UnaryOperator);
2493 } else if (Current.is(tok::question)) {
2494 if (Style.isJavaScript() && Line.MustBeDeclaration &&
2495 !Contexts.back().IsExpression) {
2496 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
2497 // on the interface, not a ternary expression.
2498 Current.setType(TT_JsTypeOptionalQuestion);
2499 } else if (Style.isTableGen()) {
2500 // In TableGen, '?' is just an identifier like token.
2501 Current.setType(TT_Unknown);
2502 } else {
2503 Current.setType(TT_ConditionalExpr);
2504 if (IsCpp)
2505 Contexts.back().IsExpression = true;
2506 }
2507 } else if (Current.isBinaryOperator() &&
2508 (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
2509 (Current.isNot(tok::greater) && !Style.isTextProto())) {
2510 if (Style.isVerilog()) {
2511 if (Current.is(tok::lessequal) && Contexts.size() == 1 &&
2512 !Contexts.back().VerilogAssignmentFound) {
2513 // In Verilog `<=` is assignment if in its own statement. It is a
2514 // statement instead of an expression, that is it can not be chained.
2515 Current.ForcedPrecedence = prec::Assignment;
2516 Current.setFinalizedType(TT_BinaryOperator);
2517 }
2518 if (Current.getPrecedence() == prec::Assignment)
2519 Contexts.back().VerilogAssignmentFound = true;
2520 }
2521 Current.setType(TT_BinaryOperator);
2522 } else if (Current.is(tok::comment)) {
2523 if (Current.TokenText.starts_with("/*")) {
2524 if (Current.TokenText.ends_with("*/")) {
2525 Current.setType(TT_BlockComment);
2526 } else {
2527 // The lexer has for some reason determined a comment here. But we
2528 // cannot really handle it, if it isn't properly terminated.
2529 Current.Tok.setKind(tok::unknown);
2530 }
2531 } else {
2532 Current.setType(TT_LineComment);
2533 }
2534 } else if (Current.is(tok::string_literal)) {
2535 if (Style.isVerilog() && Contexts.back().VerilogMayBeConcatenation &&
2536 Current.getPreviousNonComment() &&
2537 Current.getPreviousNonComment()->isOneOf(tok::comma, tok::l_brace) &&
2538 Current.getNextNonComment() &&
2539 Current.getNextNonComment()->isOneOf(tok::comma, tok::r_brace)) {
2540 Current.setType(TT_StringInConcatenation);
2541 }
2542 } else if (Current.is(tok::l_paren)) {
2543 if (lParenStartsCppCast(Current))
2544 Current.setType(TT_CppCastLParen);
2545 } else if (Current.is(tok::r_paren)) {
2546 if (rParenEndsCast(Current))
2547 Current.setType(TT_CastRParen);
2548 if (Current.MatchingParen && Current.MatchingParen->is(TT_InlineASMParen))
2549 Current.setType(TT_InlineASMParen);
2550 if (Current.MatchingParen && Current.Next &&
2551 !Current.Next->isBinaryOperator() &&
2552 Current.Next->isNoneOf(
2553 tok::semi, tok::colon, tok::l_brace, tok::l_paren, tok::comma,
2554 tok::period, tok::arrow, tok::coloncolon, tok::kw_noexcept)) {
2555 if (FormatToken *AfterParen = Current.MatchingParen->Next;
2556 AfterParen && AfterParen->isNot(tok::caret)) {
2557 // Make sure this isn't the return type of an Obj-C block declaration.
2558 if (FormatToken *BeforeParen = Current.MatchingParen->Previous;
2559 BeforeParen && BeforeParen->is(tok::identifier) &&
2560 BeforeParen->isNot(TT_TypenameMacro) &&
2561 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
2562 (!BeforeParen->Previous ||
2563 BeforeParen->Previous->ClosesTemplateDeclaration ||
2564 BeforeParen->Previous->ClosesRequiresClause)) {
2565 Current.setType(TT_FunctionAnnotationRParen);
2566 }
2567 }
2568 }
2569 } else if (Current.is(tok::at) && Current.Next && !Style.isJavaScript() &&
2570 !Style.isJava()) {
2571 // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
2572 // marks declarations and properties that need special formatting.
2573 switch (Current.Next->Tok.getObjCKeywordID()) {
2574 case tok::objc_interface:
2575 case tok::objc_implementation:
2576 case tok::objc_protocol:
2577 Current.setType(TT_ObjCDecl);
2578 break;
2579 case tok::objc_property:
2580 Current.setType(TT_ObjCProperty);
2581 break;
2582 default:
2583 break;
2584 }
2585 } else if (Current.is(tok::period)) {
2586 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
2587 if (PreviousNoComment &&
2588 PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) {
2589 Current.setType(TT_DesignatedInitializerPeriod);
2590 } else if (Style.isJava() && Current.Previous &&
2591 Current.Previous->isOneOf(TT_JavaAnnotation,
2592 TT_LeadingJavaAnnotation)) {
2593 Current.setType(Current.Previous->getType());
2594 }
2595 } else if (canBeObjCSelectorComponent(Current) &&
2596 // FIXME(bug 36976): ObjC return types shouldn't use
2597 // TT_CastRParen.
2598 Current.Previous && Current.Previous->is(TT_CastRParen) &&
2599 Current.Previous->MatchingParen &&
2600 Current.Previous->MatchingParen->Previous &&
2601 Current.Previous->MatchingParen->Previous->is(
2602 TT_ObjCMethodSpecifier)) {
2603 // This is the first part of an Objective-C selector name. (If there's no
2604 // colon after this, this is the only place which annotates the identifier
2605 // as a selector.)
2606 Current.setType(TT_SelectorName);
2607 } else if (Current.isOneOf(tok::identifier, tok::kw_const, tok::kw_noexcept,
2608 tok::kw_requires) &&
2609 Current.Previous &&
2610 Current.Previous->isNoneOf(tok::equal, tok::at,
2611 TT_CtorInitializerComma,
2612 TT_CtorInitializerColon) &&
2613 Line.MightBeFunctionDecl && Contexts.size() == 1) {
2614 // Line.MightBeFunctionDecl can only be true after the parentheses of a
2615 // function declaration have been found.
2616 Current.setType(TT_TrailingAnnotation);
2617 } else if ((Style.isJava() || Style.isJavaScript()) && Current.Previous) {
2618 if (Current.Previous->is(tok::at) &&
2619 Current.isNot(Keywords.kw_interface)) {
2620 const FormatToken &AtToken = *Current.Previous;
2621 const FormatToken *Previous = AtToken.getPreviousNonComment();
2622 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
2623 Current.setType(TT_LeadingJavaAnnotation);
2624 else
2625 Current.setType(TT_JavaAnnotation);
2626 } else if (Current.Previous->is(tok::period) &&
2627 Current.Previous->isOneOf(TT_JavaAnnotation,
2628 TT_LeadingJavaAnnotation)) {
2629 Current.setType(Current.Previous->getType());
2630 }
2631 }
2632 }
2633
2634 /// Take a guess at whether \p Tok starts a name of a function or
2635 /// variable declaration.
2636 ///
2637 /// This is a heuristic based on whether \p Tok is an identifier following
2638 /// something that is likely a type.
2639 bool isStartOfName(const FormatToken &Tok) {
2640 // Handled in ExpressionParser for Verilog.
2641 if (Style.isVerilog())
2642 return false;
2643
2644 if (!Tok.Previous || Tok.isNot(tok::identifier) || Tok.is(TT_ClassHeadName))
2645 return false;
2646
2647 if (Tok.endsSequence(Keywords.kw_final, TT_ClassHeadName))
2648 return false;
2649
2650 if ((Style.isJavaScript() || Style.isJava()) && Tok.is(Keywords.kw_extends))
2651 return false;
2652
2653 if (const auto *NextNonComment = Tok.getNextNonComment();
2654 (!NextNonComment && !Line.InMacroBody) ||
2655 (NextNonComment &&
2656 (NextNonComment->isPointerOrReference() ||
2657 NextNonComment->isOneOf(TT_ClassHeadName, tok::string_literal) ||
2658 (Line.InPragmaDirective && NextNonComment->is(tok::identifier))))) {
2659 return false;
2660 }
2661
2662 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
2663 Keywords.kw_as)) {
2664 return false;
2665 }
2666 if (Style.isJavaScript() && Tok.Previous->is(Keywords.kw_in))
2667 return false;
2668
2669 // Skip "const" as it does not have an influence on whether this is a name.
2670 FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
2671
2672 // For javascript const can be like "let" or "var"
2673 if (!Style.isJavaScript())
2674 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
2675 PreviousNotConst = PreviousNotConst->getPreviousNonComment();
2676
2677 if (!PreviousNotConst)
2678 return false;
2679
2680 if (PreviousNotConst->ClosesRequiresClause)
2681 return false;
2682
2683 if (Style.isTableGen()) {
2684 // keywords such as let and def* defines names.
2685 if (Keywords.isTableGenDefinition(*PreviousNotConst))
2686 return true;
2687 // Otherwise C++ style declarations is available only inside the brace.
2688 if (Contexts.back().ContextKind != tok::l_brace)
2689 return false;
2690 }
2691
2692 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
2693 PreviousNotConst->Previous &&
2694 PreviousNotConst->Previous->is(tok::hash);
2695
2696 if (PreviousNotConst->is(TT_TemplateCloser)) {
2697 return PreviousNotConst && PreviousNotConst->MatchingParen &&
2698 PreviousNotConst->MatchingParen->Previous &&
2699 PreviousNotConst->MatchingParen->Previous->isNoneOf(
2700 tok::period, tok::kw_template);
2701 }
2702
2703 if ((PreviousNotConst->is(tok::r_paren) &&
2704 PreviousNotConst->is(TT_TypeDeclarationParen)) ||
2705 PreviousNotConst->is(TT_AttributeRParen)) {
2706 return true;
2707 }
2708
2709 // If is a preprocess keyword like #define.
2710 if (IsPPKeyword)
2711 return false;
2712
2713 // int a or auto a.
2714 if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto) &&
2715 !PreviousNotConst->endsSequence(Keywords.kw_import, tok::kw_export) &&
2716 PreviousNotConst->isNot(TT_StatementAttributeLikeMacro)) {
2717 return true;
2718 }
2719
2720 // *a or &a or &&a.
2721 if (PreviousNotConst->is(TT_PointerOrReference) ||
2722 PreviousNotConst->endsSequence(tok::coloncolon,
2723 TT_PointerOrReference)) {
2724 return true;
2725 }
2726
2727 // MyClass a;
2728 if (PreviousNotConst->isTypeName(LangOpts))
2729 return true;
2730
2731 // type[] a in Java
2732 if (Style.isJava() && PreviousNotConst->is(tok::r_square))
2733 return true;
2734
2735 // const a = in JavaScript.
2736 return Style.isJavaScript() && PreviousNotConst->is(tok::kw_const);
2737 }
2738
2739 /// Determine whether '(' is starting a C++ cast.
2740 bool lParenStartsCppCast(const FormatToken &Tok) {
2741 // C-style casts are only used in C++.
2742 if (!IsCpp)
2743 return false;
2744
2745 FormatToken *LeftOfParens = Tok.getPreviousNonComment();
2746 if (LeftOfParens && LeftOfParens->is(TT_TemplateCloser) &&
2747 LeftOfParens->MatchingParen) {
2748 auto *Prev = LeftOfParens->MatchingParen->getPreviousNonComment();
2749 if (Prev &&
2750 Prev->isOneOf(tok::kw_const_cast, tok::kw_dynamic_cast,
2751 tok::kw_reinterpret_cast, tok::kw_static_cast)) {
2752 // FIXME: Maybe we should handle identifiers ending with "_cast",
2753 // e.g. any_cast?
2754 return true;
2755 }
2756 }
2757 return false;
2758 }
2759
2760 /// Determine whether ')' is ending a cast.
2761 bool rParenEndsCast(const FormatToken &Tok) {
2762 assert(Tok.is(tok::r_paren));
2763
2764 if (!Tok.MatchingParen || !Tok.Previous)
2765 return false;
2766
2767 // C-style casts are only used in C++, C# and Java.
2768 if (!IsCpp && !Style.isCSharp() && !Style.isJava())
2769 return false;
2770
2771 const auto *LParen = Tok.MatchingParen;
2772 const auto *BeforeRParen = Tok.Previous;
2773 const auto *AfterRParen = Tok.Next;
2774
2775 // Empty parens aren't casts and there are no casts at the end of the line.
2776 if (BeforeRParen == LParen || !AfterRParen)
2777 return false;
2778
2779 if (LParen->isOneOf(TT_OverloadedOperatorLParen, TT_FunctionTypeLParen))
2780 return false;
2781
2782 auto *LeftOfParens = LParen->getPreviousNonComment();
2783 if (LeftOfParens) {
2784 // If there is a closing parenthesis left of the current
2785 // parentheses, look past it as these might be chained casts.
2786 if (LeftOfParens->is(tok::r_paren) &&
2787 LeftOfParens->isNot(TT_CastRParen)) {
2788 if (!LeftOfParens->MatchingParen ||
2789 !LeftOfParens->MatchingParen->Previous) {
2790 return false;
2791 }
2792 LeftOfParens = LeftOfParens->MatchingParen->Previous;
2793 }
2794
2795 if (LeftOfParens->is(tok::r_square)) {
2796 // delete[] (void *)ptr;
2797 auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
2798 if (Tok->isNot(tok::r_square))
2799 return nullptr;
2800
2801 Tok = Tok->getPreviousNonComment();
2802 if (!Tok || Tok->isNot(tok::l_square))
2803 return nullptr;
2804
2805 Tok = Tok->getPreviousNonComment();
2806 if (!Tok || Tok->isNot(tok::kw_delete))
2807 return nullptr;
2808 return Tok;
2809 };
2810 if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens))
2811 LeftOfParens = MaybeDelete;
2812 }
2813
2814 // The Condition directly below this one will see the operator arguments
2815 // as a (void *foo) cast.
2816 // void operator delete(void *foo) ATTRIB;
2817 if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous &&
2818 LeftOfParens->Previous->is(tok::kw_operator)) {
2819 return false;
2820 }
2821
2822 // If there is an identifier (or with a few exceptions a keyword) right
2823 // before the parentheses, this is unlikely to be a cast.
2824 if (LeftOfParens->Tok.getIdentifierInfo() &&
2825 LeftOfParens->isNoneOf(TT_ObjCForIn, tok::kw_return, tok::kw_case,
2826 tok::kw_delete, tok::kw_throw)) {
2827 return false;
2828 }
2829
2830 // Certain other tokens right before the parentheses are also signals that
2831 // this cannot be a cast.
2832 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
2833 TT_TemplateCloser, tok::ellipsis)) {
2834 return false;
2835 }
2836 }
2837
2838 if (AfterRParen->is(tok::question) ||
2839 (AfterRParen->is(tok::ampamp) && !BeforeRParen->isTypeName(LangOpts))) {
2840 return false;
2841 }
2842
2843 // `foreach((A a, B b) in someList)` should not be seen as a cast.
2844 if (AfterRParen->is(Keywords.kw_in) && Style.isCSharp())
2845 return false;
2846
2847 // Functions which end with decorations like volatile, noexcept are unlikely
2848 // to be casts.
2849 if (AfterRParen->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
2850 tok::kw_requires, tok::kw_throw, tok::arrow,
2851 Keywords.kw_override, Keywords.kw_final) ||
2852 isCppAttribute(IsCpp, *AfterRParen)) {
2853 return false;
2854 }
2855
2856 // As Java has no function types, a "(" after the ")" likely means that this
2857 // is a cast.
2858 if (Style.isJava() && AfterRParen->is(tok::l_paren))
2859 return true;
2860
2861 // If a (non-string) literal follows, this is likely a cast.
2862 if (AfterRParen->isOneOf(tok::kw_sizeof, tok::kw_alignof) ||
2863 (AfterRParen->Tok.isLiteral() &&
2864 AfterRParen->isNot(tok::string_literal))) {
2865 return true;
2866 }
2867
2868 auto IsNonVariableTemplate = [](const FormatToken &Tok) {
2869 if (Tok.isNot(TT_TemplateCloser))
2870 return false;
2871 const auto *Less = Tok.MatchingParen;
2872 if (!Less)
2873 return false;
2874 const auto *BeforeLess = Less->getPreviousNonComment();
2875 return BeforeLess && BeforeLess->isNot(TT_VariableTemplate);
2876 };
2877
2878 // Heuristically try to determine whether the parentheses contain a type.
2879 auto IsQualifiedPointerOrReference = [](const FormatToken *T,
2880 const LangOptions &LangOpts) {
2881 // This is used to handle cases such as x = (foo *const)&y;
2882 assert(!T->isTypeName(LangOpts) && "Should have already been checked");
2883 // Strip trailing qualifiers such as const or volatile when checking
2884 // whether the parens could be a cast to a pointer/reference type.
2885 while (T) {
2886 if (T->is(TT_AttributeRParen)) {
2887 // Handle `x = (foo *__attribute__((foo)))&v;`:
2888 assert(T->is(tok::r_paren));
2889 assert(T->MatchingParen);
2890 assert(T->MatchingParen->is(tok::l_paren));
2891 assert(T->MatchingParen->is(TT_AttributeLParen));
2892 if (const auto *Tok = T->MatchingParen->Previous;
2893 Tok && Tok->isAttribute()) {
2894 T = Tok->Previous;
2895 continue;
2896 }
2897 } else if (T->is(TT_AttributeRSquare)) {
2898 // Handle `x = (foo *[[clang::foo]])&v;`:
2899 if (T->MatchingParen && T->MatchingParen->Previous) {
2900 T = T->MatchingParen->Previous;
2901 continue;
2902 }
2903 } else if (T->canBePointerOrReferenceQualifier()) {
2904 T = T->Previous;
2905 continue;
2906 }
2907 break;
2908 }
2909 return T && T->is(TT_PointerOrReference);
2910 };
2911
2912 bool ParensAreType = IsNonVariableTemplate(*BeforeRParen) ||
2913 BeforeRParen->is(TT_TypeDeclarationParen) ||
2914 BeforeRParen->isTypeName(LangOpts) ||
2915 IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
2916 bool ParensCouldEndDecl =
2917 AfterRParen->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
2918 if (ParensAreType && !ParensCouldEndDecl)
2919 return true;
2920
2921 // At this point, we heuristically assume that there are no casts at the
2922 // start of the line. We assume that we have found most cases where there
2923 // are by the logic above, e.g. "(void)x;".
2924 if (!LeftOfParens)
2925 return false;
2926
2927 // Certain token types inside the parentheses mean that this can't be a
2928 // cast.
2929 for (const auto *Token = LParen->Next; Token != &Tok; Token = Token->Next)
2930 if (Token->is(TT_BinaryOperator))
2931 return false;
2932
2933 // If the following token is an identifier or 'this', this is a cast. All
2934 // cases where this can be something else are handled above.
2935 if (AfterRParen->isOneOf(tok::identifier, tok::kw_this))
2936 return true;
2937
2938 // Look for a cast `( x ) (`, where x may be a qualified identifier.
2939 if (AfterRParen->is(tok::l_paren)) {
2940 for (const auto *Prev = BeforeRParen; Prev->is(tok::identifier);) {
2941 Prev = Prev->Previous;
2942 if (Prev->is(tok::coloncolon))
2943 Prev = Prev->Previous;
2944 if (Prev == LParen)
2945 return true;
2946 }
2947 }
2948
2949 if (!AfterRParen->Next)
2950 return false;
2951
2952 // A pair of parentheses before an l_brace in C starts a compound literal
2953 // and is not a cast.
2954 if (Style.Language != FormatStyle::LK_C && AfterRParen->is(tok::l_brace) &&
2955 AfterRParen->getBlockKind() == BK_BracedInit) {
2956 return true;
2957 }
2958
2959 // If the next token after the parenthesis is a unary operator, assume
2960 // that this is cast, unless there are unexpected tokens inside the
2961 // parenthesis.
2962 const bool NextIsAmpOrStar = AfterRParen->isOneOf(tok::amp, tok::star);
2963 if (!(AfterRParen->isUnaryOperator() || NextIsAmpOrStar) ||
2964 AfterRParen->is(tok::plus) ||
2965 AfterRParen->Next->isNoneOf(tok::identifier, tok::numeric_constant)) {
2966 return false;
2967 }
2968
2969 if (NextIsAmpOrStar &&
2970 (AfterRParen->Next->is(tok::numeric_constant) || Line.InPPDirective)) {
2971 return false;
2972 }
2973
2974 if (Line.InPPDirective && AfterRParen->is(tok::minus))
2975 return false;
2976
2977 const auto *Prev = BeforeRParen;
2978
2979 // Look for a function pointer type, e.g. `(*)()`.
2980 if (Prev->is(tok::r_paren)) {
2981 if (Prev->is(TT_CastRParen))
2982 return false;
2983 Prev = Prev->MatchingParen;
2984 if (!Prev)
2985 return false;
2986 Prev = Prev->Previous;
2987 if (!Prev || Prev->isNot(tok::r_paren))
2988 return false;
2989 Prev = Prev->MatchingParen;
2990 return Prev && Prev->is(TT_FunctionTypeLParen);
2991 }
2992
2993 // Search for unexpected tokens.
2994 for (Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous)
2995 if (Prev->isNoneOf(tok::kw_const, tok::identifier, tok::coloncolon))
2996 return false;
2997
2998 return true;
2999 }
3000
3001 /// Returns true if the token is used as a unary operator.
3002 bool determineUnaryOperatorByUsage(const FormatToken &Tok) {
3003 const FormatToken *PrevToken = Tok.getPreviousNonComment();
3004 if (!PrevToken)
3005 return true;
3006
3007 // These keywords are deliberately not included here because they may
3008 // precede only one of unary star/amp and plus/minus but not both. They are
3009 // either included in determineStarAmpUsage or determinePlusMinusCaretUsage.
3010 //
3011 // @ - It may be followed by a unary `-` in Objective-C literals. We don't
3012 // know how they can be followed by a star or amp.
3013 if (PrevToken->isOneOf(
3014 TT_ConditionalExpr, tok::l_paren, tok::comma, tok::colon, tok::semi,
3015 tok::equal, tok::question, tok::l_square, tok::l_brace,
3016 tok::kw_case, tok::kw_co_await, tok::kw_co_return, tok::kw_co_yield,
3017 tok::kw_delete, tok::kw_return, tok::kw_throw)) {
3018 return true;
3019 }
3020
3021 // We put sizeof here instead of only in determineStarAmpUsage. In the cases
3022 // where the unary `+` operator is overloaded, it is reasonable to write
3023 // things like `sizeof +x`. Like commit 446d6ec996c6c3.
3024 if (PrevToken->is(tok::kw_sizeof))
3025 return true;
3026
3027 // A sequence of leading unary operators.
3028 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
3029 return true;
3030
3031 // There can't be two consecutive binary operators.
3032 if (PrevToken->is(TT_BinaryOperator))
3033 return true;
3034
3035 return false;
3036 }
3037
3038 /// Return the type of the given token assuming it is * or &.
3039 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
3040 bool InTemplateArgument) {
3041 if (Style.isJavaScript())
3042 return TT_BinaryOperator;
3043
3044 // && in C# must be a binary operator.
3045 if (Style.isCSharp() && Tok.is(tok::ampamp))
3046 return TT_BinaryOperator;
3047
3048 if (Style.isVerilog()) {
3049 // In Verilog, `*` can only be a binary operator. `&` can be either unary
3050 // or binary. `*` also includes `*>` in module path declarations in
3051 // specify blocks because merged tokens take the type of the first one by
3052 // default.
3053 if (Tok.is(tok::star))
3054 return TT_BinaryOperator;
3055 return determineUnaryOperatorByUsage(Tok) ? TT_UnaryOperator
3056 : TT_BinaryOperator;
3057 }
3058
3059 const FormatToken *PrevToken = Tok.getPreviousNonComment();
3060 if (!PrevToken)
3061 return TT_UnaryOperator;
3062 if (PrevToken->isTypeName(LangOpts))
3063 return TT_PointerOrReference;
3064 if (PrevToken->isPlacementOperator() && Tok.is(tok::ampamp))
3065 return TT_BinaryOperator;
3066
3067 auto *NextToken = Tok.getNextNonComment();
3068 if (!NextToken)
3069 return TT_PointerOrReference;
3070 if (NextToken->is(tok::greater))
3071 return TT_PointerOrReference;
3072
3073 if (InTemplateArgument && NextToken->is(tok::kw_noexcept))
3074 return TT_BinaryOperator;
3075
3076 if (NextToken->isOneOf(tok::arrow, tok::equal, tok::comma, tok::r_paren,
3077 tok::semi, TT_RequiresClause) ||
3078 (NextToken->is(tok::kw_noexcept) && !IsExpression) ||
3079 NextToken->canBePointerOrReferenceQualifier() ||
3080 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) {
3081 return TT_PointerOrReference;
3082 }
3083
3084 if (PrevToken->is(tok::coloncolon))
3085 return TT_PointerOrReference;
3086
3087 if (PrevToken->is(tok::r_paren) && PrevToken->is(TT_TypeDeclarationParen))
3088 return TT_PointerOrReference;
3089
3090 if (determineUnaryOperatorByUsage(Tok))
3091 return TT_UnaryOperator;
3092
3093 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
3094 return TT_PointerOrReference;
3095 if (NextToken->is(tok::kw_operator) && !IsExpression)
3096 return TT_PointerOrReference;
3097
3098 // After right braces, star tokens are likely to be pointers to struct,
3099 // union, or class.
3100 // struct {} *ptr;
3101 // This by itself is not sufficient to distinguish from multiplication
3102 // following a brace-initialized expression, as in:
3103 // int i = int{42} * 2;
3104 // In the struct case, the part of the struct declaration until the `{` and
3105 // the `}` are put on separate unwrapped lines; in the brace-initialized
3106 // case, the matching `{` is on the same unwrapped line, so check for the
3107 // presence of the matching brace to distinguish between those.
3108 if (PrevToken->is(tok::r_brace) && Tok.is(tok::star) &&
3109 !PrevToken->MatchingParen) {
3110 return TT_PointerOrReference;
3111 }
3112
3113 if (PrevToken->endsSequence(tok::r_square, tok::l_square, tok::kw_delete))
3114 return TT_UnaryOperator;
3115
3116 if (PrevToken->Tok.isLiteral() ||
3117 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
3118 tok::kw_false, tok::r_brace)) {
3119 return TT_BinaryOperator;
3120 }
3121
3122 const FormatToken *NextNonParen = NextToken;
3123 while (NextNonParen && NextNonParen->is(tok::l_paren))
3124 NextNonParen = NextNonParen->getNextNonComment();
3125 if (NextNonParen && (NextNonParen->Tok.isLiteral() ||
3126 NextNonParen->isOneOf(tok::kw_true, tok::kw_false) ||
3127 NextNonParen->isUnaryOperator())) {
3128 return TT_BinaryOperator;
3129 }
3130
3131 // If we know we're in a template argument, there are no named declarations.
3132 // Thus, having an identifier on the right-hand side indicates a binary
3133 // operator.
3134 if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
3135 return TT_BinaryOperator;
3136
3137 // "&&" followed by "(", "*", or "&" is quite unlikely to be two successive
3138 // unary "&".
3139 if (Tok.is(tok::ampamp) &&
3140 NextToken->isOneOf(tok::l_paren, tok::star, tok::amp)) {
3141 return TT_BinaryOperator;
3142 }
3143
3144 // This catches some cases where evaluation order is used as control flow:
3145 // aaa && aaa->f();
3146 // Or expressions like:
3147 // width * height * length
3148 if (NextToken->Tok.isAnyIdentifier()) {
3149 auto *NextNextToken = NextToken->getNextNonComment();
3150 if (NextNextToken) {
3151 if (NextNextToken->is(tok::arrow))
3152 return TT_BinaryOperator;
3153 if (NextNextToken->isPointerOrReference() &&
3154 !NextToken->isObjCLifetimeQualifier(Style)) {
3155 NextNextToken->setFinalizedType(TT_BinaryOperator);
3156 return TT_BinaryOperator;
3157 }
3158 }
3159 }
3160
3161 // It is very unlikely that we are going to find a pointer or reference type
3162 // definition on the RHS of an assignment.
3163 if (IsExpression && !Contexts.back().CaretFound &&
3164 Line.getFirstNonComment()->isNot(
3165 TT_RequiresClauseInARequiresExpression)) {
3166 return TT_BinaryOperator;
3167 }
3168
3169 // Opeartors at class scope are likely pointer or reference members.
3170 if (!Scopes.empty() && Scopes.back() == ST_Class)
3171 return TT_PointerOrReference;
3172
3173 // Tokens that indicate member access or chained operator& use.
3174 auto IsChainedOperatorAmpOrMember = [](const FormatToken *token) {
3175 return !token || token->isOneOf(tok::amp, tok::period, tok::arrow,
3176 tok::arrowstar, tok::periodstar);
3177 };
3178
3179 // It's more likely that & represents operator& than an uninitialized
3180 // reference.
3181 if (Tok.is(tok::amp) && PrevToken->Tok.isAnyIdentifier() &&
3182 IsChainedOperatorAmpOrMember(PrevToken->getPreviousNonComment()) &&
3183 NextToken && NextToken->Tok.isAnyIdentifier()) {
3184 if (auto NextNext = NextToken->getNextNonComment();
3185 NextNext &&
3186 (IsChainedOperatorAmpOrMember(NextNext) || NextNext->is(tok::semi))) {
3187 return TT_BinaryOperator;
3188 }
3189 }
3190
3191 if (Line.Type == LT_SimpleRequirement ||
3192 (!Scopes.empty() && Scopes.back() == ST_CompoundRequirement)) {
3193 return TT_BinaryOperator;
3194 }
3195
3196 return TT_PointerOrReference;
3197 }
3198
3199 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
3200 if (determineUnaryOperatorByUsage(Tok))
3201 return TT_UnaryOperator;
3202
3203 const FormatToken *PrevToken = Tok.getPreviousNonComment();
3204 if (!PrevToken)
3205 return TT_UnaryOperator;
3206
3207 if (PrevToken->is(tok::at))
3208 return TT_UnaryOperator;
3209
3210 // Fall back to marking the token as binary operator.
3211 return TT_BinaryOperator;
3212 }
3213
3214 /// Determine whether ++/-- are pre- or post-increments/-decrements.
3215 TokenType determineIncrementUsage(const FormatToken &Tok) {
3216 const FormatToken *PrevToken = Tok.getPreviousNonComment();
3217 if (!PrevToken || PrevToken->is(TT_CastRParen))
3218 return TT_UnaryOperator;
3219 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
3220 return TT_TrailingUnaryOperator;
3221
3222 return TT_UnaryOperator;
3223 }
3224
3225 SmallVector<Context, 8> Contexts;
3226
3227 const FormatStyle &Style;
3228 AnnotatedLine &Line;
3229 FormatToken *CurrentToken;
3230 bool AutoFound;
3231 bool IsCpp;
3232 LangOptions LangOpts;
3233 const AdditionalKeywords &Keywords;
3234
3235 SmallVector<ScopeType> &Scopes;
3236
3237 // Set of "<" tokens that do not open a template parameter list. If parseAngle
3238 // determines that a specific token can't be a template opener, it will make
3239 // same decision irrespective of the decisions for tokens leading up to it.
3240 // Store this information to prevent this from causing exponential runtime.
3241 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
3242
3243 int TemplateDeclarationDepth;
3244};
3245
3246static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
3247static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
3248
3249/// Parses binary expressions by inserting fake parenthesis based on
3250/// operator precedence.
3251class ExpressionParser {
3252public:
3253 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
3254 AnnotatedLine &Line)
3255 : Style(Style), Keywords(Keywords), Line(Line), Current(Line.First) {}
3256
3257 /// Parse expressions with the given operator precedence.
3258 void parse(int Precedence = 0) {
3259 // Skip 'return' and ObjC selector colons as they are not part of a binary
3260 // expression.
3261 while (Current && (Current->is(tok::kw_return) ||
3262 (Current->is(tok::colon) &&
3263 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) {
3264 next();
3265 }
3266
3267 if (!Current || Precedence > PrecedenceArrowAndPeriod)
3268 return;
3269
3270 // Conditional expressions need to be parsed separately for proper nesting.
3271 if (Precedence == prec::Conditional) {
3272 parseConditionalExpr();
3273 return;
3274 }
3275
3276 // Parse unary operators, which all have a higher precedence than binary
3277 // operators.
3278 if (Precedence == PrecedenceUnaryOperator) {
3279 parseUnaryOperator();
3280 return;
3281 }
3282
3283 FormatToken *Start = Current;
3284 FormatToken *LatestOperator = nullptr;
3285 unsigned OperatorIndex = 0;
3286 // The first name of the current type in a port list.
3287 FormatToken *VerilogFirstOfType = nullptr;
3288
3289 while (Current) {
3290 // In Verilog ports in a module header that don't have a type take the
3291 // type of the previous one. For example,
3292 // module a(output b,
3293 // c,
3294 // output d);
3295 // In this case there need to be fake parentheses around b and c.
3296 if (Style.isVerilog() && Precedence == prec::Comma) {
3297 VerilogFirstOfType =
3298 verilogGroupDecl(VerilogFirstOfType, LatestOperator);
3299 }
3300
3301 // Consume operators with higher precedence.
3302 parse(Precedence + 1);
3303
3304 int CurrentPrecedence = getCurrentPrecedence();
3305 if (CurrentPrecedence > prec::Conditional &&
3306 CurrentPrecedence < prec::PointerToMember) {
3307 // When BreakBinaryOperations is globally OnePerLine (no per-operator
3308 // rules), flatten all precedence levels so that every operator is
3309 // treated equally for line-breaking purposes. With per-operator rules
3310 // we must preserve natural precedence so that higher-precedence
3311 // sub-expressions (e.g. `x << 8` inside a `|` chain) stay grouped;
3312 // mustBreakBinaryOperation() handles the forced breaks instead.
3313 if (Style.BreakBinaryOperations.PerOperator.empty() &&
3314 Style.BreakBinaryOperations.Default ==
3315 FormatStyle::BBO_OnePerLine) {
3316 CurrentPrecedence = prec::Additive;
3317 }
3318 }
3319
3320 if (Precedence == CurrentPrecedence && Current &&
3321 Current->is(TT_SelectorName)) {
3322 if (LatestOperator)
3323 addFakeParenthesis(Start, prec::Level(Precedence));
3324 Start = Current;
3325 }
3326
3327 if ((Style.isCSharp() || Style.isJavaScript() || Style.isJava()) &&
3328 Precedence == prec::Additive && Current) {
3329 // A string can be broken without parentheses around it when it is
3330 // already in a sequence of strings joined by `+` signs.
3331 FormatToken *Prev = Current->getPreviousNonComment();
3332 if (Prev && Prev->is(tok::string_literal) &&
3333 (Prev == Start || Prev->endsSequence(tok::string_literal, tok::plus,
3334 TT_StringInConcatenation))) {
3335 Prev->setType(TT_StringInConcatenation);
3336 }
3337 }
3338
3339 // At the end of the line or when an operator with lower precedence is
3340 // found, insert fake parenthesis and return.
3341 if (!Current ||
3342 (Current->closesScope() &&
3343 (Current->MatchingParen || Current->is(TT_TemplateString))) ||
3344 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
3345 (CurrentPrecedence == prec::Conditional &&
3346 Precedence == prec::Assignment && Current->is(tok::colon))) {
3347 break;
3348 }
3349
3350 // Consume scopes: (), [], <> and {}
3351 // In addition to that we handle require clauses as scope, so that the
3352 // constraints in that are correctly indented.
3353 if (Current->opensScope() ||
3354 Current->isOneOf(TT_RequiresClause,
3355 TT_RequiresClauseInARequiresExpression)) {
3356 // In fragment of a JavaScript template string can look like '}..${' and
3357 // thus close a scope and open a new one at the same time.
3358 while (Current && (!Current->closesScope() || Current->opensScope())) {
3359 next();
3360 parse();
3361 }
3362 next();
3363 } else {
3364 // Operator found.
3365 if (CurrentPrecedence == Precedence) {
3366 if (LatestOperator)
3367 LatestOperator->NextOperator = Current;
3368 LatestOperator = Current;
3369 Current->OperatorIndex = OperatorIndex;
3370 ++OperatorIndex;
3371 }
3372 next(/*SkipPastLeadingComments=*/Precedence > 0);
3373 }
3374 }
3375
3376 // Group variables of the same type.
3377 if (Style.isVerilog() && Precedence == prec::Comma && VerilogFirstOfType)
3378 addFakeParenthesis(VerilogFirstOfType, prec::Comma);
3379
3380 if (LatestOperator && (Current || Precedence > 0)) {
3381 // The requires clauses do not neccessarily end in a semicolon or a brace,
3382 // but just go over to struct/class or a function declaration, we need to
3383 // intervene so that the fake right paren is inserted correctly.
3384 auto End =
3385 (Start->Previous &&
3386 Start->Previous->isOneOf(TT_RequiresClause,
3387 TT_RequiresClauseInARequiresExpression))
3388 ? [this]() {
3389 auto Ret = Current ? Current : Line.Last;
3390 while (!Ret->ClosesRequiresClause && Ret->Previous)
3391 Ret = Ret->Previous;
3392 return Ret;
3393 }()
3394 : nullptr;
3395
3396 if (Precedence == PrecedenceArrowAndPeriod) {
3397 // Call expressions don't have a binary operator precedence.
3398 addFakeParenthesis(Start, prec::Unknown, End);
3399 } else {
3400 addFakeParenthesis(Start, prec::Level(Precedence), End);
3401 }
3402 }
3403 }
3404
3405private:
3406 /// Gets the precedence (+1) of the given token for binary operators
3407 /// and other tokens that we treat like binary operators.
3408 int getCurrentPrecedence() {
3409 if (Current) {
3410 const FormatToken *NextNonComment = Current->getNextNonComment();
3411 if (Current->is(TT_ConditionalExpr))
3412 return prec::Conditional;
3413 if (NextNonComment && Current->is(TT_SelectorName) &&
3414 (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
3415 (Style.isProto() && NextNonComment->is(tok::less)))) {
3416 return prec::Assignment;
3417 }
3418 if (Current->is(TT_JsComputedPropertyName))
3419 return prec::Assignment;
3420 if (Current->is(TT_LambdaArrow))
3421 return prec::Comma;
3422 if (Current->is(TT_FatArrow))
3423 return prec::Assignment;
3424 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
3425 (Current->is(tok::comment) && NextNonComment &&
3426 NextNonComment->is(TT_SelectorName))) {
3427 return 0;
3428 }
3429 if (Current->is(TT_RangeBasedForLoopColon))
3430 return prec::Comma;
3431 if ((Style.isJava() || Style.isJavaScript()) &&
3432 Current->is(Keywords.kw_instanceof)) {
3433 return prec::Relational;
3434 }
3435 if (Style.isJavaScript() &&
3436 Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) {
3437 return prec::Relational;
3438 }
3439 if (Current->isOneOf(TT_BinaryOperator, tok::comma))
3440 return Current->getPrecedence();
3441 if (Current->isOneOf(tok::period, tok::arrow) &&
3442 Current->isNot(TT_TrailingReturnArrow)) {
3443 return PrecedenceArrowAndPeriod;
3444 }
3445 if ((Style.isJava() || Style.isJavaScript()) &&
3446 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
3447 Keywords.kw_throws)) {
3448 return 0;
3449 }
3450 // In Verilog case labels are not on separate lines straight out of
3451 // UnwrappedLineParser. The colon is not part of an expression.
3452 if (Style.isVerilog() && Current->is(tok::colon))
3453 return 0;
3454 }
3455 return -1;
3456 }
3457
3458 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence,
3459 FormatToken *End = nullptr) {
3460 // Do not assign fake parenthesis to tokens that are part of an
3461 // unexpanded macro call. The line within the macro call contains
3462 // the parenthesis and commas, and we will not find operators within
3463 // that structure.
3464 if (Start->MacroParent)
3465 return;
3466
3467 Start->FakeLParens.push_back(Precedence);
3468 if (Precedence > prec::Unknown)
3469 Start->StartsBinaryExpression = true;
3470 if (!End && Current)
3471 End = Current->getPreviousNonComment();
3472 if (End) {
3473 ++End->FakeRParens;
3474 if (Precedence > prec::Unknown)
3475 End->EndsBinaryExpression = true;
3476 }
3477 }
3478
3479 /// Parse unary operator expressions and surround them with fake
3480 /// parentheses if appropriate.
3481 void parseUnaryOperator() {
3482 SmallVector<FormatToken *, 2> Tokens;
3483 while (Current && Current->is(TT_UnaryOperator)) {
3484 Tokens.push_back(Current);
3485 next();
3486 }
3487 parse(PrecedenceArrowAndPeriod);
3488 for (FormatToken *Token : reverse(Tokens)) {
3489 // The actual precedence doesn't matter.
3490 addFakeParenthesis(Token, prec::Unknown);
3491 }
3492 }
3493
3494 void parseConditionalExpr() {
3495 while (Current && Current->isTrailingComment())
3496 next();
3497 FormatToken *Start = Current;
3498 parse(prec::LogicalOr);
3499 if (!Current || Current->isNot(tok::question))
3500 return;
3501 next();
3502 parse(prec::Assignment);
3503 if (!Current || Current->isNot(TT_ConditionalExpr))
3504 return;
3505 next();
3506 parse(prec::Assignment);
3507 addFakeParenthesis(Start, prec::Conditional);
3508 }
3509
3510 void next(bool SkipPastLeadingComments = true) {
3511 if (Current)
3512 Current = Current->Next;
3513 while (Current &&
3514 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
3515 Current->isTrailingComment()) {
3516 Current = Current->Next;
3517 }
3518 }
3519
3520 // Add fake parenthesis around declarations of the same type for example in a
3521 // module prototype. Return the first port / variable of the current type.
3522 FormatToken *verilogGroupDecl(FormatToken *FirstOfType,
3523 FormatToken *PreviousComma) {
3524 if (!Current)
3525 return nullptr;
3526
3527 FormatToken *Start = Current;
3528
3529 // Skip attributes.
3530 while (Start->startsSequence(tok::l_paren, tok::star)) {
3531 if (!(Start = Start->MatchingParen) ||
3532 !(Start = Start->getNextNonComment())) {
3533 return nullptr;
3534 }
3535 }
3536
3537 FormatToken *Tok = Start;
3538
3539 if (Tok->is(Keywords.kw_assign))
3540 Tok = Tok->getNextNonComment();
3541
3542 // Skip any type qualifiers to find the first identifier. It may be either a
3543 // new type name or a variable name. There can be several type qualifiers
3544 // preceding a variable name, and we can not tell them apart by looking at
3545 // the word alone since a macro can be defined as either a type qualifier or
3546 // a variable name. Thus we use the last word before the dimensions instead
3547 // of the first word as the candidate for the variable or type name.
3548 FormatToken *First = nullptr;
3549 while (Tok) {
3550 FormatToken *Next = Tok->getNextNonComment();
3551
3552 if (Tok->is(tok::hash)) {
3553 // Start of a macro expansion.
3554 First = Tok;
3555 Tok = Next;
3556 if (Tok)
3557 Tok = Tok->getNextNonComment();
3558 } else if (Tok->is(tok::hashhash)) {
3559 // Concatenation. Skip.
3560 Tok = Next;
3561 if (Tok)
3562 Tok = Tok->getNextNonComment();
3563 } else if (Keywords.isVerilogQualifier(*Tok) ||
3564 Keywords.isVerilogIdentifier(*Tok)) {
3565 First = Tok;
3566 Tok = Next;
3567 // The name may have dots like `interface_foo.modport_foo`.
3568 while (Tok && Tok->isOneOf(tok::period, tok::coloncolon) &&
3569 (Tok = Tok->getNextNonComment())) {
3570 if (Keywords.isVerilogIdentifier(*Tok))
3571 Tok = Tok->getNextNonComment();
3572 }
3573 } else if (!Next) {
3574 Tok = nullptr;
3575 } else if (Tok->is(tok::l_paren)) {
3576 // Make sure the parenthesized list is a drive strength. Otherwise the
3577 // statement may be a module instantiation in which case we have already
3578 // found the instance name.
3579 if (Next->isOneOf(
3580 Keywords.kw_highz0, Keywords.kw_highz1, Keywords.kw_large,
3581 Keywords.kw_medium, Keywords.kw_pull0, Keywords.kw_pull1,
3582 Keywords.kw_small, Keywords.kw_strong0, Keywords.kw_strong1,
3583 Keywords.kw_supply0, Keywords.kw_supply1, Keywords.kw_weak0,
3584 Keywords.kw_weak1)) {
3585 Tok->setType(TT_VerilogStrength);
3586 Tok = Tok->MatchingParen;
3587 if (Tok) {
3588 Tok->setType(TT_VerilogStrength);
3589 Tok = Tok->getNextNonComment();
3590 }
3591 } else {
3592 break;
3593 }
3594 } else if (Tok->is(Keywords.kw_verilogHash)) {
3595 // Delay control.
3596 if (Next->is(tok::l_paren))
3597 Next = Next->MatchingParen;
3598 if (Next)
3599 Tok = Next->getNextNonComment();
3600 } else {
3601 break;
3602 }
3603 }
3604
3605 // Find the second identifier. If it exists it will be the name.
3606 FormatToken *Second = nullptr;
3607 // Dimensions.
3608 while (Tok && Tok->is(tok::l_square) && (Tok = Tok->MatchingParen))
3609 Tok = Tok->getNextNonComment();
3610 if (Tok && (Tok->is(tok::hash) || Keywords.isVerilogIdentifier(*Tok)))
3611 Second = Tok;
3612
3613 // If the second identifier doesn't exist and there are qualifiers, the type
3614 // is implied.
3615 FormatToken *TypedName = nullptr;
3616 if (Second) {
3617 TypedName = Second;
3618 if (First && First->is(TT_Unknown))
3619 First->setType(TT_VerilogDimensionedTypeName);
3620 } else if (First != Start) {
3621 // If 'First' is null, then this isn't a declaration, 'TypedName' gets set
3622 // to null as intended.
3623 TypedName = First;
3624 }
3625
3626 if (TypedName) {
3627 // This is a declaration with a new type.
3628 if (TypedName->is(TT_Unknown))
3629 TypedName->setType(TT_StartOfName);
3630 // Group variables of the previous type.
3631 if (FirstOfType && PreviousComma) {
3632 PreviousComma->setType(TT_VerilogTypeComma);
3633 addFakeParenthesis(FirstOfType, prec::Comma, PreviousComma->Previous);
3634 }
3635
3636 FirstOfType = TypedName;
3637
3638 // Don't let higher precedence handle the qualifiers. For example if we
3639 // have:
3640 // parameter x = 0
3641 // We skip `parameter` here. This way the fake parentheses for the
3642 // assignment will be around `x = 0`.
3643 while (Current && Current != FirstOfType) {
3644 if (Current->opensScope()) {
3645 next();
3646 parse();
3647 }
3648 next();
3649 }
3650 }
3651
3652 return FirstOfType;
3653 }
3654
3655 const FormatStyle &Style;
3656 const AdditionalKeywords &Keywords;
3657 const AnnotatedLine &Line;
3658 FormatToken *Current;
3659};
3660
3661} // end anonymous namespace
3662
3664 SmallVectorImpl<AnnotatedLine *> &Lines) const {
3665 const AnnotatedLine *NextNonCommentLine = nullptr;
3666 for (AnnotatedLine *Line : reverse(Lines)) {
3667 assert(Line->First);
3668
3669 // If the comment is currently aligned with the line immediately following
3670 // it, that's probably intentional and we should keep it.
3671 if (const auto Column = Line->First->OriginalColumn;
3672 NextNonCommentLine && NextNonCommentLine->First->NewlinesBefore < 2 &&
3673 Line->isComment() && !isClangFormatOff(Line->First->TokenText) &&
3674 NextNonCommentLine->First->OriginalColumn == Column) {
3675 const bool PPDirectiveOrImportStmt =
3676 NextNonCommentLine->Type == LT_PreprocessorDirective ||
3677 NextNonCommentLine->Type == LT_ImportStatement;
3678 if (PPDirectiveOrImportStmt)
3680 if (const auto IndentWidth = Style.IndentWidth;
3681 NextNonCommentLine->First->Finalized && IndentWidth > 0 &&
3682 Column % IndentWidth == 0) {
3683 Line->Level = Column / IndentWidth;
3684 } else {
3685 // Align comments for preprocessor lines with the # in column 0 if
3686 // preprocessor lines are not indented. Otherwise, align with the next
3687 // line.
3688 Line->Level =
3689 Style.IndentPPDirectives < FormatStyle::PPDIS_BeforeHash &&
3690 PPDirectiveOrImportStmt
3691 ? 0
3692 : NextNonCommentLine->Level;
3693 }
3694 } else {
3695 NextNonCommentLine = Line->First->isNot(tok::r_brace) ? Line : nullptr;
3696 }
3697
3698 setCommentLineLevels(Line->Children);
3699 }
3700}
3701
3702static unsigned maxNestingDepth(const AnnotatedLine &Line) {
3703 unsigned Result = 0;
3704 for (const auto *Tok = Line.First; Tok; Tok = Tok->Next)
3705 Result = std::max(Result, Tok->NestingLevel);
3706 return Result;
3707}
3708
3709// Returns the token after the first qualifier of the name, or nullptr if there
3710// is no qualifier.
3712 assert(Tok);
3713
3714 // Qualified names must start with an identifier.
3715 if (Tok->isNot(tok::identifier))
3716 return nullptr;
3717
3718 Tok = Tok->getNextNonComment();
3719 if (!Tok)
3720 return nullptr;
3721
3722 // Consider: A::B::B()
3723 // Tok --^
3724 if (Tok->is(tok::coloncolon))
3725 return Tok->getNextNonComment();
3726
3727 // Consider: A<float>::B<int>::B()
3728 // Tok --^
3729 if (Tok->is(TT_TemplateOpener)) {
3730 Tok = Tok->MatchingParen;
3731 if (!Tok)
3732 return nullptr;
3733
3734 Tok = Tok->getNextNonComment();
3735 if (!Tok)
3736 return nullptr;
3737 }
3738
3739 return Tok->is(tok::coloncolon) ? Tok->getNextNonComment() : nullptr;
3740}
3741
3742// Returns the name of a function with no return type, e.g. a constructor or
3743// destructor.
3745 FormatToken *&OpeningParen) {
3746 for (FormatToken *Tok = Line.getFirstNonComment(), *Name = nullptr; Tok;
3747 Tok = Tok->getNextNonComment()) {
3748 // Skip C++11 attributes both before and after the function name.
3749 if (Tok->is(TT_AttributeLSquare)) {
3750 Tok = Tok->MatchingParen;
3751 if (!Tok)
3752 return nullptr;
3753 continue;
3754 }
3755
3756 // Make sure the name is followed by a pair of parentheses.
3757 if (Name) {
3758 if (Tok->is(tok::l_paren) && Tok->is(TT_Unknown) && Tok->MatchingParen) {
3759 OpeningParen = Tok;
3760 return Name;
3761 }
3762 return nullptr;
3763 }
3764
3765 // Skip keywords that may precede the constructor/destructor name.
3766 if (Tok->isOneOf(tok::kw_friend, tok::kw_inline, tok::kw_virtual,
3767 tok::kw_constexpr, tok::kw_consteval, tok::kw_explicit)) {
3768 continue;
3769 }
3770
3771 // Skip past template typename declarations that may precede the
3772 // constructor/destructor name.
3773 if (Tok->is(tok::kw_template)) {
3774 Tok = Tok->getNextNonComment();
3775 if (!Tok)
3776 return nullptr;
3777
3778 // If the next token after the template keyword is not an opening bracket,
3779 // it is a template instantiation, and not a function.
3780 if (Tok->isNot(TT_TemplateOpener))
3781 return nullptr;
3782
3783 Tok = Tok->MatchingParen;
3784 if (!Tok)
3785 return nullptr;
3786
3787 continue;
3788 }
3789
3790 // A qualified name may start from the global namespace.
3791 if (Tok->is(tok::coloncolon)) {
3792 Tok = Tok->Next;
3793 if (!Tok)
3794 return nullptr;
3795 }
3796
3797 // Skip to the unqualified part of the name.
3798 while (auto *Next = skipNameQualifier(Tok))
3799 Tok = Next;
3800
3801 // Skip the `~` if a destructor name.
3802 if (Tok->is(tok::tilde)) {
3803 Tok = Tok->Next;
3804 if (!Tok)
3805 return nullptr;
3806 }
3807
3808 // Make sure the name is not already annotated, e.g. as NamespaceMacro.
3809 if (Tok->isNot(tok::identifier) || Tok->isNot(TT_Unknown))
3810 return nullptr;
3811
3812 Name = Tok;
3813 }
3814
3815 return nullptr;
3816}
3817
3818// Checks if Tok is a constructor/destructor name qualified by its class name.
3819static bool isCtorOrDtorName(const FormatToken *Tok) {
3820 assert(Tok && Tok->is(tok::identifier));
3821 const auto *Prev = Tok->Previous;
3822
3823 if (Prev && Prev->is(tok::tilde))
3824 Prev = Prev->Previous;
3825
3826 // Consider: A::A() and A<int>::A()
3827 if (!Prev || (!Prev->endsSequence(tok::coloncolon, tok::identifier) &&
3828 !Prev->endsSequence(tok::coloncolon, TT_TemplateCloser))) {
3829 return false;
3830 }
3831
3832 assert(Prev->Previous);
3833 if (Prev->Previous->is(TT_TemplateCloser) && Prev->Previous->MatchingParen) {
3834 Prev = Prev->Previous->MatchingParen;
3835 assert(Prev->Previous);
3836 }
3837
3838 return Prev->Previous->TokenText == Tok->TokenText;
3839}
3840
3842 if (!Line.InMacroBody)
3843 MacroBodyScopes.clear();
3844
3845 auto &ScopeStack = Line.InMacroBody ? MacroBodyScopes : Scopes;
3846 AnnotatingParser Parser(Style, Line, Keywords, ScopeStack);
3847 Line.Type = Parser.parseLine();
3848
3849 if (!Line.Children.empty()) {
3850 ScopeStack.push_back(ST_Other);
3851 const bool InRequiresExpression = Line.Type == LT_RequiresExpression;
3852 for (auto &Child : Line.Children) {
3853 if (InRequiresExpression &&
3854 Child->First->isNoneOf(tok::kw_typename, tok::kw_requires,
3855 TT_CompoundRequirementLBrace)) {
3856 Child->Type = LT_SimpleRequirement;
3857 }
3858 annotate(*Child);
3859 }
3860 // ScopeStack can become empty if Child has an unmatched `}`.
3861 if (!ScopeStack.empty())
3862 ScopeStack.pop_back();
3863 }
3864
3865 // With very deep nesting, ExpressionParser uses lots of stack and the
3866 // formatting algorithm is very slow. We're not going to do a good job here
3867 // anyway - it's probably generated code being formatted by mistake.
3868 // Just skip the whole line.
3869 if (maxNestingDepth(Line) > 50)
3870 Line.Type = LT_Invalid;
3871
3872 if (Line.Type == LT_Invalid)
3873 return;
3874
3875 ExpressionParser ExprParser(Style, Keywords, Line);
3876 ExprParser.parse();
3877
3878 if (IsCpp) {
3879 FormatToken *OpeningParen = nullptr;
3880 auto *Tok = getFunctionName(Line, OpeningParen);
3881 if (Tok && ((!ScopeStack.empty() && ScopeStack.back() == ST_Class) ||
3882 Line.endsWith(TT_FunctionLBrace) || isCtorOrDtorName(Tok))) {
3883 Tok->setFinalizedType(TT_CtorDtorDeclName);
3884 assert(OpeningParen);
3885 OpeningParen->setFinalizedType(TT_FunctionDeclarationLParen);
3886 }
3887 }
3888
3889 if (Line.startsWith(TT_ObjCMethodSpecifier))
3890 Line.Type = LT_ObjCMethodDecl;
3891 else if (Line.startsWith(TT_ObjCDecl))
3892 Line.Type = LT_ObjCDecl;
3893 else if (Line.startsWith(TT_ObjCProperty))
3894 Line.Type = LT_ObjCProperty;
3895
3896 auto *First = Line.First;
3897 First->SpacesRequiredBefore = 1;
3898 First->CanBreakBefore = First->MustBreakBefore;
3899}
3900
3901// This function heuristically determines whether 'Current' starts the name of a
3902// function declaration.
3903static bool isFunctionDeclarationName(const LangOptions &LangOpts,
3904 const FormatToken &Current,
3905 const AnnotatedLine &Line,
3906 FormatToken *&ClosingParen) {
3907 if (Current.is(TT_FunctionDeclarationName))
3908 return true;
3909
3910 if (Current.isNoneOf(tok::identifier, tok::kw_operator))
3911 return false;
3912
3913 const auto *Prev = Current.getPreviousNonComment();
3914 assert(Prev);
3915
3916 const auto &Previous = *Prev;
3917
3918 if (const auto *PrevPrev = Previous.getPreviousNonComment();
3919 PrevPrev && PrevPrev->is(TT_ObjCDecl)) {
3920 return false;
3921 }
3922
3923 auto skipOperatorName =
3924 [&LangOpts](const FormatToken *Next) -> const FormatToken * {
3925 for (; Next; Next = Next->Next) {
3926 if (Next->is(TT_OverloadedOperatorLParen))
3927 return Next;
3928 if (Next->is(TT_OverloadedOperator))
3929 continue;
3930 if (Next->isPlacementOperator() || Next->is(tok::kw_co_await)) {
3931 // For 'new[]' and 'delete[]'.
3932 if (Next->Next &&
3933 Next->Next->startsSequence(tok::l_square, tok::r_square)) {
3934 Next = Next->Next->Next;
3935 }
3936 continue;
3937 }
3938 if (Next->startsSequence(tok::l_square, tok::r_square)) {
3939 // For operator[]().
3940 Next = Next->Next;
3941 continue;
3942 }
3943 if ((Next->isTypeName(LangOpts) || Next->is(tok::identifier)) &&
3944 Next->Next && Next->Next->isPointerOrReference()) {
3945 // For operator void*(), operator char*(), operator Foo*().
3946 Next = Next->Next;
3947 continue;
3948 }
3949 if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
3950 Next = Next->MatchingParen;
3951 continue;
3952 }
3953
3954 break;
3955 }
3956 return nullptr;
3957 };
3958
3959 const auto *Next = Current.Next;
3960 const bool IsCpp = LangOpts.CXXOperatorNames || LangOpts.C11;
3961
3962 // Find parentheses of parameter list.
3963 if (Current.is(tok::kw_operator)) {
3964 if (Line.startsWith(tok::kw_friend))
3965 return true;
3966 if (Previous.Tok.getIdentifierInfo() &&
3967 Previous.isNoneOf(tok::kw_return, tok::kw_co_return)) {
3968 return true;
3969 }
3970 if (Previous.is(tok::r_paren) && Previous.is(TT_TypeDeclarationParen)) {
3971 assert(Previous.MatchingParen);
3972 assert(Previous.MatchingParen->is(tok::l_paren));
3973 assert(Previous.MatchingParen->is(TT_TypeDeclarationParen));
3974 return true;
3975 }
3976 if (!Previous.isPointerOrReference() && Previous.isNot(TT_TemplateCloser))
3977 return false;
3978 Next = skipOperatorName(Next);
3979 } else {
3980 if (Current.isNot(TT_StartOfName) || Current.NestingLevel != 0)
3981 return false;
3982 while (Next && Next->startsSequence(tok::hashhash, tok::identifier))
3983 Next = Next->Next->Next;
3984 for (; Next; Next = Next->Next) {
3985 if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
3986 Next = Next->MatchingParen;
3987 } else if (Next->is(tok::coloncolon)) {
3988 Next = Next->Next;
3989 if (!Next)
3990 return false;
3991 if (Next->is(tok::kw_operator)) {
3992 Next = skipOperatorName(Next->Next);
3993 break;
3994 }
3995 if (Next->isNot(tok::identifier))
3996 return false;
3997 } else if (isCppAttribute(IsCpp, *Next)) {
3998 Next = Next->MatchingParen;
3999 if (!Next)
4000 return false;
4001 } else if (Next->is(tok::l_paren)) {
4002 break;
4003 } else {
4004 return false;
4005 }
4006 }
4007 }
4008
4009 // Check whether parameter list can belong to a function declaration.
4010 if (!Next || Next->isNot(tok::l_paren) || !Next->MatchingParen)
4011 return false;
4012 ClosingParen = Next->MatchingParen;
4013 assert(ClosingParen->is(tok::r_paren));
4014 // If the lines ends with "{", this is likely a function definition.
4015 if (Line.Last->is(tok::l_brace))
4016 return true;
4017 if (Next->Next == ClosingParen)
4018 return true; // Empty parentheses.
4019 // If there is an &/&& after the r_paren, this is likely a function.
4020 if (ClosingParen->Next && ClosingParen->Next->is(TT_PointerOrReference))
4021 return true;
4022
4023 // Check for K&R C function definitions (and C++ function definitions with
4024 // unnamed parameters), e.g.:
4025 // int f(i)
4026 // {
4027 // return i + 1;
4028 // }
4029 // bool g(size_t = 0, bool b = false)
4030 // {
4031 // return !b;
4032 // }
4033 if (IsCpp && Next->Next && Next->Next->is(tok::identifier) &&
4034 !Line.endsWith(tok::semi)) {
4035 return true;
4036 }
4037
4038 for (const FormatToken *Tok = Next->Next; Tok && Tok != ClosingParen;
4039 Tok = Tok->Next) {
4040 if (Tok->is(TT_TypeDeclarationParen))
4041 return true;
4042 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
4043 Tok = Tok->MatchingParen;
4044 continue;
4045 }
4046 if (Tok->is(tok::kw_const) || Tok->isTypeName(LangOpts) ||
4047 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) {
4048 return true;
4049 }
4050 if (Tok->isOneOf(tok::l_brace, TT_ObjCMethodExpr) || Tok->Tok.isLiteral())
4051 return false;
4052 }
4053 return false;
4054}
4055
4056bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
4057 assert(Line.MightBeFunctionDecl);
4058
4059 if ((Style.BreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
4060 Style.BreakAfterReturnType == FormatStyle::RTBS_TopLevelDefinitions) &&
4061 Line.Level > 0) {
4062 return false;
4063 }
4064
4065 switch (Style.BreakAfterReturnType) {
4066 case FormatStyle::RTBS_None:
4067 case FormatStyle::RTBS_Automatic:
4068 case FormatStyle::RTBS_ExceptShortType:
4069 return false;
4070 case FormatStyle::RTBS_All:
4071 case FormatStyle::RTBS_TopLevel:
4072 return true;
4073 case FormatStyle::RTBS_AllDefinitions:
4074 case FormatStyle::RTBS_TopLevelDefinitions:
4075 return Line.mightBeFunctionDefinition();
4076 }
4077
4078 return false;
4079}
4080
4081bool TokenAnnotator::mustBreakBeforeReturnType(
4082 const AnnotatedLine &Line) const {
4083 assert(Line.MightBeFunctionDecl);
4084
4085 switch (Style.BreakBeforeReturnType) {
4086 case FormatStyle::BBRTS_None:
4087 return false;
4088 case FormatStyle::BBRTS_All:
4089 return true;
4090 case FormatStyle::BBRTS_TopLevel:
4091 return Line.Level == 0;
4092 case FormatStyle::BBRTS_AllDefinitions:
4093 return Line.mightBeFunctionDefinition();
4094 case FormatStyle::BBRTS_TopLevelDefinitions:
4095 return Line.Level == 0 && Line.mightBeFunctionDefinition();
4096 }
4097
4098 return false;
4099}
4100
4102 auto *Tok = Line.getFirstNonComment();
4103 if (!Tok)
4104 return nullptr;
4105
4106 if (Tok->is(tok::kw_template)) {
4107 auto *Opener = Tok->Next;
4108 while (Opener && Opener->isNot(TT_TemplateOpener))
4109 Opener = Opener->Next;
4110 if (!Opener || !Opener->MatchingParen)
4111 return nullptr;
4112 Tok = Opener->MatchingParen->Next;
4113 }
4114
4115 if (Tok && Tok->is(TT_RequiresClause)) {
4116 while (Tok && !Tok->ClosesRequiresClause)
4117 Tok = Tok->Next;
4118 if (Tok)
4119 Tok = Tok->Next;
4120 }
4121
4122 while (Tok) {
4124 Tok->isOneOf(tok::kw___attribute, tok::kw___declspec,
4125 TT_AttributeMacro)) {
4126 auto *Next = Tok->Next;
4127 if (Next && Next->is(tok::l_paren) && Next->MatchingParen)
4128 Tok = Next->MatchingParen->Next;
4129 else
4130 Tok = Next;
4131 continue;
4132 }
4133 if (Tok->is(TT_AttributeLSquare) && Tok->MatchingParen) {
4134 Tok = Tok->MatchingParen->Next;
4135 continue;
4136 }
4137 break;
4138 }
4139 return Tok;
4140}
4141
4143 if (Line.Computed)
4144 return;
4145
4146 Line.Computed = true;
4147
4148 for (AnnotatedLine *ChildLine : Line.Children)
4150
4151 auto *First = Line.First;
4152 First->TotalLength = First->IsMultiline
4153 ? Style.ColumnLimit
4154 : Line.FirstStartColumn + First->ColumnWidth;
4155 bool AlignArrayOfStructures =
4156 (Style.AlignArrayOfStructures != FormatStyle::AIAS_None &&
4158 if (AlignArrayOfStructures)
4159 calculateArrayInitializerColumnList(Line);
4160
4161 const auto *FirstNonComment = Line.getFirstNonComment();
4162 bool SeenName = false;
4163 bool LineIsFunctionDeclaration = false;
4164 FormatToken *AfterLastAttribute = nullptr;
4165 FormatToken *ClosingParen = nullptr;
4166
4167 for (auto *Tok = FirstNonComment && FirstNonComment->isNot(tok::kw_using)
4168 ? FirstNonComment->Next
4169 : nullptr;
4170 Tok && Tok->isNot(BK_BracedInit); Tok = Tok->Next) {
4171 if (Tok->is(TT_StartOfName))
4172 SeenName = true;
4173 if (Tok->Previous->EndsCppAttributeGroup)
4174 AfterLastAttribute = Tok;
4175 if (const bool IsCtorOrDtor = Tok->is(TT_CtorDtorDeclName);
4176 IsCtorOrDtor ||
4177 isFunctionDeclarationName(LangOpts, *Tok, Line, ClosingParen)) {
4178 if (!IsCtorOrDtor)
4179 Tok->setFinalizedType(TT_FunctionDeclarationName);
4180 LineIsFunctionDeclaration = true;
4181 SeenName = true;
4182 if (ClosingParen) {
4183 auto *OpeningParen = ClosingParen->MatchingParen;
4184 assert(OpeningParen);
4185 if (OpeningParen->is(TT_Unknown))
4186 OpeningParen->setType(TT_FunctionDeclarationLParen);
4187 }
4188 break;
4189 }
4190 }
4191
4192 if (IsCpp) {
4193 if ((LineIsFunctionDeclaration ||
4194 (FirstNonComment && FirstNonComment->is(TT_CtorDtorDeclName))) &&
4195 Line.endsWith(tok::semi, tok::r_brace)) {
4196 auto *Tok = Line.Last->Previous;
4197 while (Tok->isNot(tok::r_brace))
4198 Tok = Tok->Previous;
4199 if (auto *LBrace = Tok->MatchingParen; LBrace && LBrace->is(TT_Unknown)) {
4200 assert(LBrace->is(tok::l_brace));
4201 Tok->setBlockKind(BK_Block);
4202 LBrace->setBlockKind(BK_Block);
4203 LBrace->setFinalizedType(TT_FunctionLBrace);
4204 }
4205 }
4206
4207 if (SeenName && AfterLastAttribute &&
4208 mustBreakAfterAttributes(*AfterLastAttribute, Style)) {
4209 AfterLastAttribute->MustBreakBefore = true;
4210 if (LineIsFunctionDeclaration)
4211 Line.ReturnTypeWrapped = true;
4212 }
4213
4214 if (!LineIsFunctionDeclaration) {
4215 Line.ReturnTypeWrapped = false;
4216 // Annotate */&/&& in `operator` function calls as binary operators.
4217 for (const auto *Tok = FirstNonComment; Tok; Tok = Tok->Next) {
4218 if (Tok->isNot(tok::kw_operator))
4219 continue;
4220 do {
4221 Tok = Tok->Next;
4222 } while (Tok && Tok->isNot(TT_OverloadedOperatorLParen));
4223 if (!Tok || !Tok->MatchingParen)
4224 break;
4225 const auto *LeftParen = Tok;
4226 for (Tok = Tok->Next; Tok && Tok != LeftParen->MatchingParen;
4227 Tok = Tok->Next) {
4228 if (Tok->isNot(tok::identifier))
4229 continue;
4230 auto *Next = Tok->Next;
4231 const bool NextIsBinaryOperator =
4232 Next && Next->isPointerOrReference() && Next->Next &&
4233 Next->Next->is(tok::identifier);
4234 if (!NextIsBinaryOperator)
4235 continue;
4236 Next->setType(TT_BinaryOperator);
4237 Tok = Next;
4238 }
4239 }
4240 } else if (ClosingParen) {
4241 for (auto *Tok = ClosingParen->Next; Tok; Tok = Tok->Next) {
4242 if (Tok->is(TT_CtorInitializerColon))
4243 break;
4244 if (Tok->is(tok::arrow)) {
4245 Tok->overwriteFixedType(TT_TrailingReturnArrow);
4246 break;
4247 }
4248 if (Tok->isNot(TT_TrailingAnnotation))
4249 continue;
4250 const auto *Next = Tok->Next;
4251 if (!Next || Next->isNot(tok::l_paren))
4252 continue;
4253 Tok = Next->MatchingParen;
4254 if (!Tok)
4255 break;
4256 }
4257 }
4258 }
4259
4260 if (Line.MightBeFunctionDecl && LineIsFunctionDeclaration &&
4261 mustBreakBeforeReturnType(Line)) {
4262 if (auto *ReturnTypeStart = findReturnTypeStart(Line);
4263 ReturnTypeStart && ReturnTypeStart != FirstNonComment &&
4264 ReturnTypeStart->isNoneOf(TT_FunctionDeclarationName,
4265 TT_CtorDtorDeclName, tok::tilde)) {
4266 ReturnTypeStart->MustBreakBefore = true;
4267 Line.ReturnTypeWrapped = true;
4268 }
4269 }
4270
4271 if (First->is(TT_ElseLBrace)) {
4272 First->CanBreakBefore = true;
4273 First->MustBreakBefore = true;
4274 }
4275
4276 bool InFunctionDecl = Line.MightBeFunctionDecl;
4277 bool InParameterList = false;
4278 for (auto *Current = First->Next; Current; Current = Current->Next) {
4279 const FormatToken *Prev = Current->Previous;
4280 if (Current->is(TT_LineComment)) {
4281 if (Prev->is(BK_BracedInit) && Prev->opensScope()) {
4282 Current->SpacesRequiredBefore =
4283 (Style.Cpp11BracedListStyle == FormatStyle::BLS_AlignFirstComment &&
4284 !Style.SpacesInParensOptions.Other)
4285 ? 0
4286 : 1;
4287 } else if (Prev->is(TT_VerilogMultiLineListLParen)) {
4288 Current->SpacesRequiredBefore = 0;
4289 } else {
4290 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
4291 }
4292
4293 // If we find a trailing comment, iterate backwards to determine whether
4294 // it seems to relate to a specific parameter. If so, break before that
4295 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
4296 // to the previous line in:
4297 // SomeFunction(a,
4298 // b, // comment
4299 // c);
4300 if (!Current->HasUnescapedNewline) {
4301 for (FormatToken *Parameter = Current->Previous; Parameter;
4302 Parameter = Parameter->Previous) {
4303 if (Parameter->isOneOf(tok::comment, tok::r_brace))
4304 break;
4305 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
4306 if (Parameter->Previous->isNot(TT_CtorInitializerComma) &&
4307 Parameter->HasUnescapedNewline) {
4308 Parameter->MustBreakBefore = true;
4309 }
4310 break;
4311 }
4312 }
4313 }
4314 } else if (!Current->Finalized && Current->SpacesRequiredBefore == 0 &&
4315 spaceRequiredBefore(Line, *Current)) {
4316 Current->SpacesRequiredBefore = 1;
4317 }
4318
4319 const auto &Children = Prev->Children;
4320 if (!Children.empty() && Children.back()->Last->is(TT_LineComment)) {
4321 Current->MustBreakBefore = true;
4322 } else {
4323 Current->MustBreakBefore =
4324 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
4325 if (!Current->MustBreakBefore && InFunctionDecl &&
4326 Current->is(TT_FunctionDeclarationName)) {
4327 Current->MustBreakBefore = mustBreakForReturnType(Line);
4328 }
4329 }
4330
4331 Current->CanBreakBefore =
4332 !Line.IsModuleOrImportDecl &&
4333 (Current->MustBreakBefore || canBreakBefore(Line, *Current));
4334
4335 if (Current->is(TT_FunctionDeclarationLParen)) {
4336 InParameterList = true;
4337 } else if (Current->is(tok::r_paren)) {
4338 const auto *LParen = Current->MatchingParen;
4339 if (LParen && LParen->is(TT_FunctionDeclarationLParen))
4340 InParameterList = false;
4341 } else if (InParameterList &&
4342 Current->endsSequence(TT_AttributeMacro,
4343 TT_PointerOrReference)) {
4344 Current->CanBreakBefore = false;
4345 }
4346
4347 unsigned ChildSize = 0;
4348 if (Prev->Children.size() == 1) {
4349 FormatToken &LastOfChild = *Prev->Children[0]->Last;
4350 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
4351 : LastOfChild.TotalLength + 1;
4352 }
4353 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
4354 (Prev->Children.size() == 1 &&
4355 Prev->Children[0]->First->MustBreakBefore) ||
4356 Current->IsMultiline) {
4357 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
4358 } else {
4359 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
4360 ChildSize + Current->SpacesRequiredBefore;
4361 }
4362
4363 if ((Style.PackParameters.BinPack == FormatStyle::BPPS_UseBreakAfter &&
4365 Prev->ParameterCount > Style.PackParameters.BreakAfter) ||
4366 (Style.PackArguments.BinPack == FormatStyle::BPAS_UseBreakAfter &&
4367 !Prev->MightBeFunctionDeclParen &&
4368 Prev->isOneOf(tok::l_paren, tok::l_brace,
4369 TT_ArrayInitializerLSquare) &&
4370 Prev->ParameterCount > Style.PackArguments.BreakAfter)) {
4371 const auto *RParen = Prev->MatchingParen;
4372 for (auto *ParamTok = Current; ParamTok && ParamTok != RParen;
4373 ParamTok = ParamTok->Next) {
4374 if (ParamTok->opensScope()) {
4375 ParamTok = ParamTok->MatchingParen;
4376 continue;
4377 }
4378
4379 if (startsNextParameter(*ParamTok, Style)) {
4380 ParamTok->MustBreakBefore = true;
4381 ParamTok->CanBreakBefore = true;
4382 }
4383 }
4384 }
4385
4386 if (Current->is(TT_ControlStatementLBrace)) {
4387 if (Style.ColumnLimit > 0 &&
4388 Style.BraceWrapping.AfterControlStatement ==
4389 FormatStyle::BWACS_MultiLine &&
4390 Line.Level * Style.IndentWidth + Line.Last->TotalLength >
4391 Style.ColumnLimit) {
4392 Current->CanBreakBefore = true;
4393 Current->MustBreakBefore = true;
4394 }
4395 } else if (Current->is(TT_CtorInitializerColon)) {
4396 InFunctionDecl = false;
4397 }
4398
4399 // FIXME: Only calculate this if CanBreakBefore is true once static
4400 // initializers etc. are sorted out.
4401 // FIXME: Move magic numbers to a better place.
4402
4403 // Reduce penalty for aligning ObjC method arguments using the colon
4404 // alignment as this is the canonical way (still prefer fitting everything
4405 // into one line if possible). Trying to fit a whole expression into one
4406 // line should not force other line breaks (e.g. when ObjC method
4407 // expression is a part of other expression).
4408 Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
4409 if (Style.Language == FormatStyle::LK_ObjC &&
4410 Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
4411 if (Current->ParameterIndex == 1)
4412 Current->SplitPenalty += 5 * Current->BindingStrength;
4413 } else {
4414 Current->SplitPenalty += 20 * Current->BindingStrength;
4415 }
4416 }
4417
4418 calculateUnbreakableTailLengths(Line);
4419 unsigned IndentLevel = Line.Level;
4420 for (auto *Current = First; Current; Current = Current->Next) {
4421 if (Current->Role)
4422 Current->Role->precomputeFormattingInfos(Current);
4423 if (Current->MatchingParen &&
4424 Current->MatchingParen->opensBlockOrBlockTypeList(Style) &&
4425 IndentLevel > 0) {
4426 --IndentLevel;
4427 }
4428 Current->IndentLevel = IndentLevel;
4429 if (Current->opensBlockOrBlockTypeList(Style))
4430 ++IndentLevel;
4431 }
4432
4433 LLVM_DEBUG({ printDebugInfo(Line); });
4434}
4435
4436void TokenAnnotator::calculateUnbreakableTailLengths(
4437 AnnotatedLine &Line) const {
4438 unsigned UnbreakableTailLength = 0;
4439 FormatToken *Current = Line.Last;
4440 while (Current) {
4442 if (Current->CanBreakBefore ||
4443 Current->isOneOf(tok::comment, tok::string_literal)) {
4445 } else {
4447 Current->ColumnWidth + Current->SpacesRequiredBefore;
4448 }
4449 Current = Current->Previous;
4450 }
4451}
4452
4453void TokenAnnotator::calculateArrayInitializerColumnList(
4454 AnnotatedLine &Line) const {
4455 if (Line.First == Line.Last)
4456 return;
4457 auto *CurrentToken = Line.First;
4458 CurrentToken->ArrayInitializerLineStart = true;
4459 unsigned Depth = 0;
4460 while (CurrentToken && CurrentToken != Line.Last) {
4461 if (CurrentToken->is(tok::l_brace)) {
4462 CurrentToken->IsArrayInitializer = true;
4463 if (CurrentToken->Next)
4464 CurrentToken->Next->MustBreakBefore = true;
4465 CurrentToken =
4466 calculateInitializerColumnList(Line, CurrentToken->Next, Depth + 1);
4467 } else {
4468 CurrentToken = CurrentToken->Next;
4469 }
4470 }
4471}
4472
4473FormatToken *TokenAnnotator::calculateInitializerColumnList(
4474 AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) const {
4475 while (CurrentToken && CurrentToken != Line.Last) {
4476 if (CurrentToken->is(tok::l_brace))
4477 ++Depth;
4478 else if (CurrentToken->is(tok::r_brace))
4479 --Depth;
4480 if (Depth == 2 && CurrentToken->isOneOf(tok::l_brace, tok::comma)) {
4481 CurrentToken = CurrentToken->Next;
4482 if (!CurrentToken)
4483 break;
4484 CurrentToken->StartsColumn = true;
4485 CurrentToken = CurrentToken->Previous;
4486 }
4487 CurrentToken = CurrentToken->Next;
4488 }
4489 return CurrentToken;
4490}
4491
4492unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
4493 const FormatToken &Tok,
4494 bool InFunctionDecl) const {
4495 const FormatToken &Left = *Tok.Previous;
4496 const FormatToken &Right = Tok;
4497
4498 if (Left.is(tok::semi))
4499 return 0;
4500
4501 // Language specific handling.
4502 if (Style.isJava()) {
4503 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
4504 return 1;
4505 if (Right.is(Keywords.kw_implements))
4506 return 2;
4507 if (Left.is(tok::comma) && Left.NestingLevel == 0)
4508 return 3;
4509 } else if (Style.isJavaScript()) {
4510 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
4511 return 100;
4512 if (Left.is(TT_JsTypeColon))
4513 return 35;
4514 if ((Left.is(TT_TemplateString) && Left.TokenText.ends_with("${")) ||
4515 (Right.is(TT_TemplateString) && Right.TokenText.starts_with("}"))) {
4516 return 100;
4517 }
4518 // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
4519 if (Left.opensScope() && Right.closesScope())
4520 return 200;
4521 } else if (Style.Language == FormatStyle::LK_Proto) {
4522 if (Right.is(tok::l_square))
4523 return 1;
4524 if (Right.is(tok::period))
4525 return 500;
4526 }
4527
4528 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
4529 return 1;
4530 if (Right.is(tok::l_square)) {
4531 if (Left.is(tok::r_square))
4532 return 200;
4533 // Slightly prefer formatting local lambda definitions like functions.
4534 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
4535 return 35;
4536 if (Right.isNoneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
4537 TT_ArrayInitializerLSquare,
4538 TT_DesignatedInitializerLSquare, TT_AttributeLSquare)) {
4539 return 500;
4540 }
4541 }
4542
4543 if (Left.is(tok::coloncolon))
4544 return Style.PenaltyBreakScopeResolution;
4545 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
4546 tok::kw_operator)) {
4547 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
4548 return 3;
4549 if (Left.is(TT_StartOfName))
4550 return 110;
4551 if (InFunctionDecl && Right.NestingLevel == 0)
4552 return Style.PenaltyReturnTypeOnItsOwnLine;
4553 return 200;
4554 }
4555 if (Right.is(TT_PointerOrReference))
4556 return 190;
4557 if (Right.is(TT_LambdaArrow))
4558 return 110;
4559 if (Left.is(tok::equal) && Right.is(tok::l_brace))
4560 return 160;
4561 if (Left.is(TT_CastRParen))
4562 return 100;
4563 if (Left.isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union))
4564 return 5000;
4565 if (Left.is(tok::comment))
4566 return 1000;
4567
4568 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
4569 TT_CtorInitializerColon)) {
4570 return 2;
4571 }
4572
4573 if (Right.isMemberAccess()) {
4574 // Breaking before the "./->" of a chained call/member access is reasonably
4575 // cheap, as formatting those with one call per line is generally
4576 // desirable. In particular, it should be cheaper to break before the call
4577 // than it is to break inside a call's parameters, which could lead to weird
4578 // "hanging" indents. The exception is the very last "./->" to support this
4579 // frequent pattern:
4580 //
4581 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
4582 // dddddddd);
4583 //
4584 // which might otherwise be blown up onto many lines. Here, clang-format
4585 // won't produce "hanging" indents anyway as there is no other trailing
4586 // call.
4587 //
4588 // Also apply higher penalty is not a call as that might lead to a wrapping
4589 // like:
4590 //
4591 // aaaaaaa
4592 // .aaaaaaaaa.bbbbbbbb(cccccccc);
4593 const auto *NextOperator = Right.NextOperator;
4594 const auto Penalty = Style.PenaltyBreakBeforeMemberAccess;
4595 return NextOperator && NextOperator->Previous->closesScope()
4596 ? std::min(Penalty, 35u)
4597 : Penalty;
4598 }
4599
4600 if (Right.is(TT_TrailingAnnotation) &&
4601 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
4602 // Moving trailing annotations to the next line is fine for ObjC method
4603 // declarations.
4604 if (Line.startsWith(TT_ObjCMethodSpecifier))
4605 return 10;
4606 // Generally, breaking before a trailing annotation is bad unless it is
4607 // function-like. It seems to be especially preferable to keep standard
4608 // annotations (i.e. "const", "final" and "override") on the same line.
4609 // Use a slightly higher penalty after ")" so that annotations like
4610 // "const override" are kept together.
4611 bool is_short_annotation = Right.TokenText.size() < 10;
4612 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
4613 }
4614
4615 // In for-loops, prefer breaking at ',' and ';'.
4616 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
4617 return 4;
4618
4619 // In Objective-C method expressions, prefer breaking before "param:" over
4620 // breaking after it.
4621 if (Right.is(TT_SelectorName))
4622 return 0;
4623 if (Left.is(tok::colon)) {
4624 if (Left.is(TT_ObjCMethodExpr))
4625 return Line.MightBeFunctionDecl ? 50 : 500;
4626 if (Left.is(TT_ObjCSelector))
4627 return 500;
4628 }
4629
4630 // In Objective-C type declarations, avoid breaking after the category's
4631 // open paren (we'll prefer breaking after the protocol list's opening
4632 // angle bracket, if present).
4633 if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
4634 Left.Previous->isOneOf(tok::identifier, tok::greater)) {
4635 return 500;
4636 }
4637
4638 if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0)
4639 return Style.PenaltyBreakOpenParenthesis;
4640 if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
4641 return 100;
4642 if (Left.is(tok::l_paren) && Left.Previous &&
4643 (Left.Previous->isOneOf(tok::kw_for, tok::kw__Generic) ||
4644 Left.Previous->isIf())) {
4645 return 1000;
4646 }
4647 if (Left.is(tok::equal) && InFunctionDecl)
4648 return 110;
4649 if (Right.is(tok::r_brace))
4650 return 1;
4651 if (Left.is(TT_TemplateOpener))
4652 return 100;
4653 if (Left.opensScope()) {
4654 // If we aren't aligning after opening parens/braces we can always break
4655 // here unless the style does not want us to place all arguments on the
4656 // next line.
4657 if (!Style.AlignAfterOpenBracket &&
4658 (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) {
4659 return 0;
4660 }
4661 if (Left.is(tok::l_brace) &&
4662 Style.Cpp11BracedListStyle == FormatStyle::BLS_Block) {
4663 return 19;
4664 }
4665 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
4666 : 19;
4667 }
4668 if (Left.is(TT_JavaAnnotation))
4669 return 50;
4670
4671 if (Left.is(TT_UnaryOperator))
4672 return 60;
4673 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
4674 Left.Previous->isLabelString() &&
4675 (Left.NextOperator || Left.OperatorIndex != 0)) {
4676 return 50;
4677 }
4678 if (Right.is(tok::plus) && Left.isLabelString() &&
4679 (Right.NextOperator || Right.OperatorIndex != 0)) {
4680 return 25;
4681 }
4682 if (Left.is(tok::comma))
4683 return 1;
4684 if (Right.is(tok::lessless) && Left.isLabelString() &&
4685 (Right.NextOperator || Right.OperatorIndex != 1)) {
4686 return 25;
4687 }
4688 if (Right.is(tok::lessless)) {
4689 // Breaking at a << is really cheap.
4690 if (Left.isNot(tok::r_paren) || Right.OperatorIndex > 0) {
4691 // Slightly prefer to break before the first one in log-like statements.
4692 return 2;
4693 }
4694 return 1;
4695 }
4696 if (Left.ClosesTemplateDeclaration)
4697 return Style.PenaltyBreakTemplateDeclaration;
4698 if (Left.ClosesRequiresClause)
4699 return 0;
4700 if (Left.is(TT_ConditionalExpr))
4701 return prec::Conditional;
4702 prec::Level Level = Left.getPrecedence();
4703 if (Level == prec::Unknown)
4704 Level = Right.getPrecedence();
4705 if (Level == prec::Assignment)
4706 return Style.PenaltyBreakAssignment;
4707 if (Level != prec::Unknown)
4708 return Level;
4709
4710 return 3;
4711}
4712
4713bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
4714 if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always)
4715 return true;
4716 if (Right.is(TT_OverloadedOperatorLParen) &&
4717 Style.SpaceBeforeParensOptions.AfterOverloadedOperator) {
4718 return true;
4719 }
4720 if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses &&
4721 Right.ParameterCount > 0) {
4722 return true;
4723 }
4724 return false;
4725}
4726
4727bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
4728 const FormatToken &Left,
4729 const FormatToken &Right) const {
4730 if (Left.is(tok::kw_return) &&
4731 Right.isNoneOf(tok::semi, tok::r_paren, tok::hashhash)) {
4732 return true;
4733 }
4734 if (Left.is(tok::kw_throw) && Right.is(tok::l_paren) && Right.MatchingParen &&
4735 Right.MatchingParen->is(TT_CastRParen)) {
4736 return true;
4737 }
4738 if (Left.is(Keywords.kw_assert) && Style.isJava())
4739 return true;
4740 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
4741 Left.is(tok::objc_property)) {
4742 return true;
4743 }
4744 if (Right.is(tok::hashhash))
4745 return Left.is(tok::hash);
4746 if (Left.isOneOf(tok::hashhash, tok::hash))
4747 return Right.is(tok::hash);
4748 if (Style.SpacesInParens == FormatStyle::SIPO_Custom) {
4749 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
4750 return Style.SpacesInParensOptions.InEmptyParentheses;
4751 if (Style.SpacesInParensOptions.ExceptDoubleParentheses &&
4752 Left.is(tok::r_paren) && Right.is(tok::r_paren)) {
4753 auto *InnerLParen = Left.MatchingParen;
4754 if (InnerLParen && InnerLParen->Previous == Right.MatchingParen) {
4755 InnerLParen->SpacesRequiredBefore = 0;
4756 return false;
4757 }
4758 }
4759 const FormatToken *LeftParen = nullptr;
4760 if (Left.is(tok::l_paren))
4761 LeftParen = &Left;
4762 else if (Right.is(tok::r_paren) && Right.MatchingParen)
4763 LeftParen = Right.MatchingParen;
4764 if (LeftParen && (LeftParen->is(TT_ConditionLParen) ||
4765 (LeftParen->Previous &&
4766 isKeywordWithCondition(*LeftParen->Previous)))) {
4767 return Style.SpacesInParensOptions.InConditionalStatements;
4768 }
4769 }
4770
4771 // trailing return type 'auto': []() -> auto {}, auto foo() -> auto {}
4772 if (Left.is(tok::kw_auto) && Right.isOneOf(TT_LambdaLBrace, TT_FunctionLBrace,
4773 // function return type 'auto'
4774 TT_FunctionTypeLParen)) {
4775 return true;
4776 }
4777
4778 // auto{x} auto(x)
4779 if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace))
4780 return false;
4781
4782 const auto *BeforeLeft = Left.Previous;
4783
4784 // operator co_await(x)
4785 if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && BeforeLeft &&
4786 BeforeLeft->is(tok::kw_operator)) {
4787 return false;
4788 }
4789 // co_await (x), co_yield (x), co_return (x)
4790 if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) &&
4791 Right.isNoneOf(tok::semi, tok::r_paren)) {
4792 return true;
4793 }
4794
4795 if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) {
4796 return (Right.is(TT_CastRParen) ||
4797 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
4798 ? Style.SpacesInParensOptions.InCStyleCasts
4799 : Style.SpacesInParensOptions.Other;
4800 }
4801 if (Right.isOneOf(tok::semi, tok::comma))
4802 return false;
4803 if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
4804 bool IsLightweightGeneric = Right.MatchingParen &&
4805 Right.MatchingParen->Next &&
4806 Right.MatchingParen->Next->is(tok::colon);
4807 return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
4808 }
4809 if (Right.is(tok::less) && Left.is(tok::kw_template))
4810 return Style.SpaceAfterTemplateKeyword;
4811 if (Left.isOneOf(tok::exclaim, tok::tilde))
4812 return false;
4813 if (Left.is(tok::at) &&
4814 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
4815 tok::numeric_constant, tok::l_paren, tok::l_brace,
4816 tok::kw_true, tok::kw_false)) {
4817 return false;
4818 }
4819 if (Left.is(tok::colon))
4820 return Left.isNoneOf(TT_ObjCSelector, TT_ObjCMethodExpr);
4821 if (Left.is(tok::coloncolon))
4822 return false;
4823 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
4824 if (Style.isTextProto() ||
4825 (Style.Language == FormatStyle::LK_Proto &&
4826 (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
4827 // Format empty list as `<>`.
4828 if (Left.is(tok::less) && Right.is(tok::greater))
4829 return false;
4830 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
4831 }
4832 // Don't attempt to format operator<(), as it is handled later.
4833 if (Right.isNot(TT_OverloadedOperatorLParen))
4834 return false;
4835 }
4836 if (Right.is(tok::ellipsis)) {
4837 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && BeforeLeft &&
4838 BeforeLeft->is(tok::kw_case));
4839 }
4840 if (Left.is(tok::l_square) && Right.is(tok::amp))
4841 return Style.SpacesInSquareBrackets;
4842 if (Right.is(TT_PointerOrReference)) {
4843 if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
4844 if (!Left.MatchingParen)
4845 return true;
4846 FormatToken *TokenBeforeMatchingParen =
4847 Left.MatchingParen->getPreviousNonComment();
4848 if (!TokenBeforeMatchingParen || Left.isNot(TT_TypeDeclarationParen))
4849 return true;
4850 }
4851 // Add a space if the previous token is a pointer qualifier or the closing
4852 // parenthesis of __attribute__(()) expression and the style requires spaces
4853 // after pointer qualifiers.
4854 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After ||
4855 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
4856 (Left.is(TT_AttributeRParen) ||
4857 Left.canBePointerOrReferenceQualifier())) {
4858 return true;
4859 }
4860 if (Left.Tok.isLiteral())
4861 return true;
4862 // for (auto a = 0, b = 0; const auto & c : {1, 2, 3})
4863 if (Left.isTypeOrIdentifier(LangOpts) && Right.Next && Right.Next->Next &&
4864 Right.Next->Next->is(TT_RangeBasedForLoopColon)) {
4865 return getTokenPointerOrReferenceAlignment(Right) !=
4866 FormatStyle::PAS_Left;
4867 }
4868 return Left.isNoneOf(TT_PointerOrReference, tok::l_paren) &&
4869 (getTokenPointerOrReferenceAlignment(Right) !=
4870 FormatStyle::PAS_Left ||
4871 (Line.IsMultiVariableDeclStmt &&
4872 (Left.NestingLevel == 0 ||
4873 (Left.NestingLevel == 1 && startsWithInitStatement(Line)))));
4874 }
4875 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
4876 (Left.isNot(TT_PointerOrReference) ||
4877 (getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right &&
4878 !Line.IsMultiVariableDeclStmt))) {
4879 return true;
4880 }
4881 if (Left.is(TT_PointerOrReference)) {
4882 // Add a space if the next token is a pointer qualifier and the style
4883 // requires spaces before pointer qualifiers.
4884 if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before ||
4885 Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
4886 Right.canBePointerOrReferenceQualifier()) {
4887 return true;
4888 }
4889 // & 1
4890 if (Right.Tok.isLiteral())
4891 return true;
4892 // & /* comment
4893 if (Right.is(TT_BlockComment))
4894 return true;
4895 // foo() -> const Bar * override/final
4896 // S::foo() & noexcept/requires
4897 if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final, tok::kw_noexcept,
4898 TT_RequiresClause) &&
4899 Right.isNot(TT_StartOfName)) {
4900 return true;
4901 }
4902 // & {
4903 if (Right.is(tok::l_brace) && Right.is(BK_Block))
4904 return true;
4905 // for (auto a = 0, b = 0; const auto& c : {1, 2, 3})
4906 if (BeforeLeft && BeforeLeft->isTypeOrIdentifier(LangOpts) && Right.Next &&
4907 Right.Next->is(TT_RangeBasedForLoopColon)) {
4908 return getTokenPointerOrReferenceAlignment(Left) !=
4909 FormatStyle::PAS_Right;
4910 }
4911 if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
4912 tok::l_paren)) {
4913 return false;
4914 }
4915 if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right)
4916 return false;
4917 // FIXME: Setting IsMultiVariableDeclStmt for the whole line is error-prone,
4918 // because it does not take into account nested scopes like lambdas.
4919 // In multi-variable declaration statements, attach */& to the variable
4920 // independently of the style. However, avoid doing it if we are in a nested
4921 // scope, e.g. lambda. We still need to special-case statements with
4922 // initializers.
4923 if (Line.IsMultiVariableDeclStmt &&
4924 (Left.NestingLevel == Line.First->NestingLevel ||
4925 ((Left.NestingLevel == Line.First->NestingLevel + 1) &&
4926 startsWithInitStatement(Line)))) {
4927 return false;
4928 }
4929 if (!BeforeLeft)
4930 return false;
4931 if (BeforeLeft->is(tok::coloncolon)) {
4932 if (Left.isNot(tok::star))
4933 return false;
4934 assert(Style.PointerAlignment != FormatStyle::PAS_Right);
4935 if (!Right.startsSequence(tok::identifier, tok::r_paren))
4936 return true;
4937 assert(Right.Next);
4938 const auto *LParen = Right.Next->MatchingParen;
4939 return !LParen || LParen->isNot(TT_FunctionTypeLParen);
4940 }
4941 return BeforeLeft->isNoneOf(tok::l_paren, tok::l_square);
4942 }
4943 // Ensure right pointer alignment with ellipsis e.g. int *...P
4944 if (Left.is(tok::ellipsis) && BeforeLeft &&
4945 BeforeLeft->isPointerOrReference()) {
4946 return Style.PointerAlignment != FormatStyle::PAS_Right;
4947 }
4948
4949 if (Right.is(tok::star) && Left.is(tok::l_paren))
4950 return false;
4951 if (Left.is(tok::star) && Right.isPointerOrReference())
4952 return false;
4953 if (Right.isPointerOrReference()) {
4954 const FormatToken *Previous = &Left;
4955 while (Previous && Previous->isNot(tok::kw_operator)) {
4956 if (Previous->is(tok::identifier) || Previous->isTypeName(LangOpts)) {
4957 Previous = Previous->getPreviousNonComment();
4958 continue;
4959 }
4960 if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) {
4961 Previous = Previous->MatchingParen->getPreviousNonComment();
4962 continue;
4963 }
4964 if (Previous->is(tok::coloncolon)) {
4965 Previous = Previous->getPreviousNonComment();
4966 continue;
4967 }
4968 break;
4969 }
4970 // Space between the type and the * in:
4971 // operator void*()
4972 // operator char*()
4973 // operator void const*()
4974 // operator void volatile*()
4975 // operator /*comment*/ const char*()
4976 // operator volatile /*comment*/ char*()
4977 // operator Foo*()
4978 // operator C<T>*()
4979 // operator std::Foo*()
4980 // operator C<T>::D<U>*()
4981 // dependent on PointerAlignment style.
4982 if (Previous) {
4983 if (Previous->endsSequence(tok::kw_operator))
4984 return Style.PointerAlignment != FormatStyle::PAS_Left;
4985 if (Previous->isOneOf(tok::kw_const, tok::kw_volatile)) {
4986 return (Style.PointerAlignment != FormatStyle::PAS_Left) ||
4987 (Style.SpaceAroundPointerQualifiers ==
4988 FormatStyle::SAPQ_After) ||
4989 (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both);
4990 }
4991 }
4992 }
4993 if (Style.isCSharp() && Left.is(Keywords.kw_is) && Right.is(tok::l_square))
4994 return true;
4995 const auto SpaceRequiredForArrayInitializerLSquare =
4996 [](const FormatToken &LSquareTok, const FormatStyle &Style) {
4997 return Style.SpacesInContainerLiterals ||
4998 (Style.isProto() &&
4999 Style.Cpp11BracedListStyle == FormatStyle::BLS_Block &&
5000 LSquareTok.endsSequence(tok::l_square, tok::colon,
5001 TT_SelectorName));
5002 };
5003 if (Left.is(tok::l_square)) {
5004 return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
5005 SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
5006 (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare,
5007 TT_LambdaLSquare) &&
5008 Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
5009 }
5010 if (Right.is(tok::r_square)) {
5011 return Right.MatchingParen &&
5012 ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
5013 SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
5014 Style)) ||
5015 (Style.SpacesInSquareBrackets &&
5016 Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
5017 TT_StructuredBindingLSquare,
5018 TT_LambdaLSquare)));
5019 }
5020 if (Right.is(tok::l_square) &&
5021 Right.isNoneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
5022 TT_DesignatedInitializerLSquare,
5023 TT_StructuredBindingLSquare, TT_AttributeLSquare) &&
5024 Left.isNoneOf(tok::numeric_constant, TT_DictLiteral) &&
5025 !(Left.isNot(tok::r_square) && Style.SpaceBeforeSquareBrackets &&
5026 Right.is(TT_ArraySubscriptLSquare))) {
5027 return false;
5028 }
5029 if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) ||
5030 (Right.is(tok::r_brace) && Right.MatchingParen &&
5031 Right.MatchingParen->isNot(BK_Block))) {
5032 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block ||
5033 Style.SpacesInParensOptions.Other;
5034 }
5035 if (Left.is(TT_BlockComment)) {
5036 // No whitespace in x(/*foo=*/1), except for JavaScript.
5037 return Style.isJavaScript() || !Left.TokenText.ends_with("=*/");
5038 }
5039
5040 // Space between template and attribute.
5041 // e.g. template <typename T> [[nodiscard]] ...
5042 if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeLSquare))
5043 return true;
5044 // Space before parentheses common for all languages
5045 if (Right.is(tok::l_paren)) {
5046 // Function declaration or definition
5047 if (Line.MightBeFunctionDecl && Right.is(TT_FunctionDeclarationLParen)) {
5048 if (spaceRequiredBeforeParens(Right))
5049 return true;
5050 const auto &Options = Style.SpaceBeforeParensOptions;
5051 return Line.mightBeFunctionDefinition()
5052 ? Options.AfterFunctionDefinitionName
5053 : Options.AfterFunctionDeclarationName;
5054 }
5055 if (Left.is(TT_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen))
5056 return spaceRequiredBeforeParens(Right);
5057 if (Left.isOneOf(TT_RequiresClause,
5058 TT_RequiresClauseInARequiresExpression)) {
5059 return Style.SpaceBeforeParensOptions.AfterRequiresInClause ||
5060 spaceRequiredBeforeParens(Right);
5061 }
5062 if (Left.is(TT_RequiresExpression)) {
5063 return Style.SpaceBeforeParensOptions.AfterRequiresInExpression ||
5064 spaceRequiredBeforeParens(Right);
5065 }
5066 if (Left.isOneOf(TT_AttributeRParen, TT_AttributeRSquare))
5067 return true;
5068 if (Left.is(TT_ForEachMacro)) {
5069 return Style.SpaceBeforeParensOptions.AfterForeachMacros ||
5070 spaceRequiredBeforeParens(Right);
5071 }
5072 if (Left.is(TT_IfMacro)) {
5073 return Style.SpaceBeforeParensOptions.AfterIfMacros ||
5074 spaceRequiredBeforeParens(Right);
5075 }
5076 if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
5077 Left.isPlacementOperator() &&
5078 Right.isNot(TT_OverloadedOperatorLParen) &&
5079 !(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
5080 const auto *RParen = Right.MatchingParen;
5081 return Style.SpaceBeforeParensOptions.AfterPlacementOperator ||
5082 (RParen && RParen->is(TT_CastRParen));
5083 }
5084 if (Line.Type == LT_ObjCDecl)
5085 return true;
5086 if (Left.is(tok::semi))
5087 return true;
5088 if (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, tok::kw_switch,
5089 tok::kw_case, TT_ForEachMacro, TT_ObjCForIn) ||
5090 Left.isIf(Line.Type != LT_PreprocessorDirective) ||
5091 Right.is(TT_ConditionLParen)) {
5092 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5093 spaceRequiredBeforeParens(Right);
5094 }
5095
5096 // TODO add Operator overloading specific Options to
5097 // SpaceBeforeParensOptions
5098 if (Right.is(TT_OverloadedOperatorLParen))
5099 return spaceRequiredBeforeParens(Right);
5100
5101 // Lambda
5102 if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) &&
5103 Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare)) {
5104 return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
5105 spaceRequiredBeforeParens(Right);
5106 }
5107 if (!BeforeLeft || BeforeLeft->isNoneOf(tok::period, tok::arrow)) {
5108 if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) {
5109 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5110 spaceRequiredBeforeParens(Right);
5111 }
5112 if (Left.isPlacementOperator() ||
5113 (Left.is(tok::r_square) && Left.MatchingParen &&
5114 Left.MatchingParen->Previous &&
5115 Left.MatchingParen->Previous->is(tok::kw_delete))) {
5116 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
5117 spaceRequiredBeforeParens(Right);
5118 }
5119 }
5120 auto CompoundLiteral = [](const FormatToken &Tok) {
5121 if (Tok.isNot(tok::l_paren))
5122 return false;
5123 const auto *RParen = Tok.MatchingParen;
5124 if (!RParen)
5125 return false;
5126 const auto *Next = RParen->Next;
5127 return Next && Next->is(tok::l_brace) && Next->is(BK_BracedInit);
5128 };
5129 if (Left.is(tok::kw_sizeof) && CompoundLiteral(Right))
5130 return true;
5131 // Handle builtins like identifiers.
5132 if (Line.Type != LT_PreprocessorDirective &&
5133 (Left.Tok.getIdentifierInfo() || Left.is(tok::r_paren))) {
5134 return spaceRequiredBeforeParens(Right);
5135 }
5136 return false;
5137 }
5138 if (Left.is(tok::at) && Right.isNot(tok::objc_not_keyword))
5139 return false;
5140 if (Right.is(TT_UnaryOperator)) {
5141 return Left.isNoneOf(tok::l_paren, tok::l_square, tok::at) &&
5142 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
5143 }
5144 // No space between the variable name and the initializer list.
5145 // A a1{1};
5146 // Verilog doesn't have such syntax, but it has word operators that are C++
5147 // identifiers like `a inside {b, c}`. So the rule is not applicable.
5148 if (!Style.isVerilog() &&
5149 (Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
5150 tok::r_paren) ||
5151 Left.isTypeName(LangOpts)) &&
5152 Right.is(tok::l_brace) && Right.getNextNonComment() &&
5153 Right.isNot(BK_Block)) {
5154 return false;
5155 }
5156 if (Left.is(tok::period) || Right.is(tok::period))
5157 return false;
5158 // u#str, U#str, L#str, u8#str
5159 // uR#str, UR#str, LR#str, u8R#str
5160 if (Right.is(tok::hash) && Left.is(tok::identifier) &&
5161 (Left.TokenText == "L" || Left.TokenText == "u" ||
5162 Left.TokenText == "U" || Left.TokenText == "u8" ||
5163 Left.TokenText == "LR" || Left.TokenText == "uR" ||
5164 Left.TokenText == "UR" || Left.TokenText == "u8R")) {
5165 return false;
5166 }
5167 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
5168 Left.MatchingParen->Previous &&
5169 Left.MatchingParen->Previous->isOneOf(tok::period, tok::coloncolon)) {
5170 // Java call to generic function with explicit type:
5171 // A.<B<C<...>>>DoSomething();
5172 // A::<B<C<...>>>DoSomething(); // With a Java 8 method reference.
5173 return false;
5174 }
5175 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
5176 return false;
5177 if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at)) {
5178 // Objective-C dictionary literal -> no space after opening brace.
5179 return false;
5180 }
5181 if (Right.is(tok::r_brace) && Right.MatchingParen &&
5182 Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) {
5183 // Objective-C dictionary literal -> no space before closing brace.
5184 return false;
5185 }
5186 if (Right.is(TT_TrailingAnnotation) && Right.isOneOf(tok::amp, tok::ampamp) &&
5187 Left.isOneOf(tok::kw_const, tok::kw_volatile) &&
5188 (!Right.Next || Right.Next->is(tok::semi))) {
5189 // Match const and volatile ref-qualifiers without any additional
5190 // qualifiers such as
5191 // void Fn() const &;
5192 return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
5193 }
5194
5195 return true;
5196}
5197
5198bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
5199 const FormatToken &Right) const {
5200 const FormatToken &Left = *Right.Previous;
5201
5202 // If the token is finalized don't touch it (as it could be in a
5203 // clang-format-off section).
5204 if (Left.Finalized)
5205 return Right.hasWhitespaceBefore();
5206
5207 const bool IsVerilog = Style.isVerilog();
5208 assert(!IsVerilog || !IsCpp);
5209
5210 // Never ever merge two words.
5211 if (Keywords.isWordLike(Right, IsVerilog) &&
5212 Keywords.isWordLike(Left, IsVerilog)) {
5213 return true;
5214 }
5215
5216 // Leave a space between * and /* to avoid C4138 `comment end` found outside
5217 // of comment.
5218 if (Left.is(tok::star) && Right.is(tok::comment))
5219 return true;
5220
5221 if (Left.is(tok::l_brace) && Right.is(tok::r_brace) &&
5222 Left.Children.empty()) {
5223 if (Left.is(BK_Block))
5224 return Style.SpaceInEmptyBraces != FormatStyle::SIEB_Never;
5225 if (Style.Cpp11BracedListStyle != FormatStyle::BLS_Block) {
5226 return Style.SpacesInParens == FormatStyle::SIPO_Custom &&
5227 Style.SpacesInParensOptions.InEmptyParentheses;
5228 }
5229 return Style.SpaceInEmptyBraces == FormatStyle::SIEB_Always;
5230 }
5231
5232 const auto *BeforeLeft = Left.Previous;
5233
5234 if (IsCpp) {
5235 if (Left.is(TT_OverloadedOperator) &&
5236 Right.isOneOf(TT_TemplateOpener, TT_TemplateCloser)) {
5237 return true;
5238 }
5239 // Space between UDL and dot: auto b = 4s .count();
5240 if (Right.is(tok::period) && Left.is(tok::numeric_constant))
5241 return true;
5242 // Space between import <iostream>.
5243 // or import .....;
5244 if (Left.is(Keywords.kw_import) &&
5245 Right.isOneOf(tok::less, tok::ellipsis) &&
5246 (!BeforeLeft || BeforeLeft->is(tok::kw_export))) {
5247 return true;
5248 }
5249 // Space between `import :`.
5250 if (Left.is(Keywords.kw_import) && Right.is(TT_ModulePartitionColon))
5251 return true;
5252
5253 if (Right.is(TT_AfterPPDirective))
5254 return true;
5255
5256 // No space between `module foo:bar`.
5257 if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon))
5258 return false;
5259 // No space between :bar;
5260 if (Left.is(TT_ModulePartitionColon) && Right.is(tok::identifier))
5261 return false;
5262 if (Left.is(tok::ellipsis) && Right.is(tok::identifier) &&
5263 Line.First->is(Keywords.kw_import)) {
5264 return false;
5265 }
5266 // Space in __attribute__((attr)) ::type.
5267 if (Left.isOneOf(TT_AttributeRParen, TT_AttributeMacro) &&
5268 Right.is(tok::coloncolon)) {
5269 return true;
5270 }
5271
5272 if (Left.is(tok::kw_operator))
5273 return Right.is(tok::coloncolon) || Style.SpaceAfterOperatorKeyword;
5274 if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) &&
5275 !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) {
5276 return true;
5277 }
5278 if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) &&
5279 Right.is(TT_TemplateOpener)) {
5280 return true;
5281 }
5282 // C++ Core Guidelines suppression tag, e.g. `[[suppress(type.5)]]`.
5283 if (Left.is(tok::identifier) && Right.is(tok::numeric_constant))
5284 return Right.TokenText[0] != '.';
5285 // `Left` is a keyword (including C++ alternative operator) or identifier.
5286 if (Left.Tok.getIdentifierInfo() && Right.Tok.isLiteral())
5287 return true;
5288 } else if (Style.isProto()) {
5289 if (Right.is(tok::period) && !(BeforeLeft && BeforeLeft->is(tok::period)) &&
5290 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
5291 Keywords.kw_repeated, Keywords.kw_extend)) {
5292 return true;
5293 }
5294 if (Right.is(tok::l_paren) &&
5295 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) {
5296 return true;
5297 }
5298 if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
5299 return true;
5300 // Slashes occur in text protocol extension syntax: [type/type] { ... }.
5301 if (Left.is(tok::slash) || Right.is(tok::slash))
5302 return false;
5303 if (Left.MatchingParen &&
5304 Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
5305 Right.isOneOf(tok::l_brace, tok::less)) {
5306 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
5307 }
5308 // A percent is probably part of a formatting specification, such as %lld.
5309 if (Left.is(tok::percent))
5310 return false;
5311 // Preserve the existence of a space before a percent for cases like 0x%04x
5312 // and "%d %d"
5313 if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
5314 return Right.hasWhitespaceBefore();
5315 } else if (Style.isJson()) {
5316 if (Right.is(tok::colon) && Left.is(tok::string_literal))
5317 return Style.SpaceBeforeJsonColon;
5318 } else if (Style.isCSharp()) {
5319 // Require spaces around '{' and before '}' unless they appear in
5320 // interpolated strings. Interpolated strings are merged into a single token
5321 // so cannot have spaces inserted by this function.
5322
5323 // No space between 'this' and '['
5324 if (Left.is(tok::kw_this) && Right.is(tok::l_square))
5325 return false;
5326
5327 // No space between 'new' and '('
5328 if (Left.is(tok::kw_new) && Right.is(tok::l_paren))
5329 return false;
5330
5331 // Space before { (including space within '{ {').
5332 if (Right.is(tok::l_brace))
5333 return true;
5334
5335 // Spaces inside braces.
5336 if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace))
5337 return true;
5338
5339 if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace))
5340 return true;
5341
5342 // Spaces around '=>'.
5343 if (Left.is(TT_FatArrow) || Right.is(TT_FatArrow))
5344 return true;
5345
5346 // No spaces around attribute target colons
5347 if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon))
5348 return false;
5349
5350 // space between type and variable e.g. Dictionary<string,string> foo;
5351 if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
5352 return true;
5353
5354 // spaces inside square brackets.
5355 if (Left.is(tok::l_square) || Right.is(tok::r_square))
5356 return Style.SpacesInSquareBrackets;
5357
5358 // No space before ? in nullable types.
5359 if (Right.is(TT_CSharpNullable))
5360 return false;
5361
5362 // No space before null forgiving '!'.
5363 if (Right.is(TT_NonNullAssertion))
5364 return false;
5365
5366 // No space between consecutive commas '[,,]'.
5367 if (Left.is(tok::comma) && Right.is(tok::comma))
5368 return false;
5369
5370 // space after var in `var (key, value)`
5371 if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren))
5372 return true;
5373
5374 // space between keywords and paren e.g. "using ("
5375 if (Right.is(tok::l_paren)) {
5376 if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when,
5377 Keywords.kw_lock)) {
5378 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5379 spaceRequiredBeforeParens(Right);
5380 }
5381 }
5382
5383 // space between method modifier and opening parenthesis of a tuple return
5384 // type
5385 if ((Left.isAccessSpecifierKeyword() ||
5386 Left.isOneOf(tok::kw_virtual, tok::kw_extern, tok::kw_static,
5387 Keywords.kw_internal, Keywords.kw_abstract,
5388 Keywords.kw_sealed, Keywords.kw_override,
5389 Keywords.kw_async, Keywords.kw_unsafe)) &&
5390 Right.is(tok::l_paren)) {
5391 return true;
5392 }
5393 } else if (Style.isJavaScript()) {
5394 if (Left.is(TT_FatArrow))
5395 return true;
5396 // for await ( ...
5397 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && BeforeLeft &&
5398 BeforeLeft->is(tok::kw_for)) {
5399 return true;
5400 }
5401 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
5402 Right.MatchingParen) {
5403 const FormatToken *Next = Right.MatchingParen->getNextNonComment();
5404 // An async arrow function, for example: `x = async () => foo();`,
5405 // as opposed to calling a function called async: `x = async();`
5406 if (Next && Next->is(TT_FatArrow))
5407 return true;
5408 }
5409 if ((Left.is(TT_TemplateString) && Left.TokenText.ends_with("${")) ||
5410 (Right.is(TT_TemplateString) && Right.TokenText.starts_with("}"))) {
5411 return false;
5412 }
5413 // In tagged template literals ("html`bar baz`"), there is no space between
5414 // the tag identifier and the template string.
5415 if (Keywords.isJavaScriptIdentifier(Left,
5416 /* AcceptIdentifierName= */ false) &&
5417 Right.is(TT_TemplateString)) {
5418 return false;
5419 }
5420 if (Right.is(tok::star) &&
5421 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield)) {
5422 return false;
5423 }
5424 if (Right.isOneOf(tok::l_brace, tok::l_square) &&
5425 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
5426 Keywords.kw_extends, Keywords.kw_implements)) {
5427 return true;
5428 }
5429 if (Right.is(tok::l_paren)) {
5430 // JS methods can use some keywords as names (e.g. `delete()`).
5431 if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
5432 return false;
5433 // Valid JS method names can include keywords, e.g. `foo.delete()` or
5434 // `bar.instanceof()`. Recognize call positions by preceding period.
5435 if (BeforeLeft && BeforeLeft->is(tok::period) &&
5436 Left.Tok.getIdentifierInfo()) {
5437 return false;
5438 }
5439 // Additional unary JavaScript operators that need a space after.
5440 if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
5441 tok::kw_void)) {
5442 return true;
5443 }
5444 }
5445 // `foo as const;` casts into a const type.
5446 if (Left.endsSequence(tok::kw_const, Keywords.kw_as))
5447 return false;
5448 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
5449 tok::kw_const) ||
5450 // "of" is only a keyword if it appears after another identifier
5451 // (e.g. as "const x of y" in a for loop), or after a destructuring
5452 // operation (const [x, y] of z, const {a, b} of c).
5453 (Left.is(Keywords.kw_of) && BeforeLeft &&
5454 BeforeLeft->isOneOf(tok::identifier, tok::r_square, tok::r_brace))) &&
5455 (!BeforeLeft || BeforeLeft->isNot(tok::period))) {
5456 return true;
5457 }
5458 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && BeforeLeft &&
5459 BeforeLeft->is(tok::period) && Right.is(tok::l_paren)) {
5460 return false;
5461 }
5462 if (Left.is(Keywords.kw_as) &&
5463 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren)) {
5464 return true;
5465 }
5466 if (Left.is(tok::kw_default) && BeforeLeft &&
5467 BeforeLeft->is(tok::kw_export)) {
5468 return true;
5469 }
5470 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
5471 return true;
5472 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
5473 return false;
5474 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
5475 return false;
5476 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
5477 Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) {
5478 return false;
5479 }
5480 if (Left.is(tok::ellipsis))
5481 return false;
5482 if (Left.is(TT_TemplateCloser) &&
5483 Right.isNoneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
5484 Keywords.kw_implements, Keywords.kw_extends)) {
5485 // Type assertions ('<type>expr') are not followed by whitespace. Other
5486 // locations that should have whitespace following are identified by the
5487 // above set of follower tokens.
5488 return false;
5489 }
5490 if (Right.is(TT_NonNullAssertion))
5491 return false;
5492 if (Left.is(TT_NonNullAssertion) &&
5493 Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) {
5494 return true; // "x! as string", "x! in y"
5495 }
5496 } else if (Style.isJava()) {
5497 if (Left.is(TT_CaseLabelArrow) || Right.is(TT_CaseLabelArrow))
5498 return true;
5499 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
5500 return true;
5501 // spaces inside square brackets.
5502 if (Left.is(tok::l_square) || Right.is(tok::r_square))
5503 return Style.SpacesInSquareBrackets;
5504
5505 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) {
5506 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
5507 spaceRequiredBeforeParens(Right);
5508 }
5509 if ((Left.isAccessSpecifierKeyword() ||
5510 Left.isOneOf(tok::kw_static, Keywords.kw_final, Keywords.kw_abstract,
5511 Keywords.kw_native)) &&
5512 Right.is(TT_TemplateOpener)) {
5513 return true;
5514 }
5515 } else if (IsVerilog) {
5516 // An escaped identifier ends with whitespace.
5517 if (Left.is(tok::identifier) && Left.TokenText[0] == '\\')
5518 return true;
5519 // Add space between things in a primitive's state table unless in a
5520 // transition like `(0?)`.
5521 if ((Left.is(TT_VerilogTableItem) &&
5522 Right.isNoneOf(tok::r_paren, tok::semi)) ||
5523 (Right.is(TT_VerilogTableItem) && Left.isNot(tok::l_paren))) {
5524 const FormatToken *Next = Right.getNextNonComment();
5525 return !(Next && Next->is(tok::r_paren));
5526 }
5527 // Don't add space within a delay like `#0`.
5528 if (Left.isNot(TT_BinaryOperator) &&
5529 Left.isOneOf(Keywords.kw_verilogHash, Keywords.kw_verilogHashHash)) {
5530 return false;
5531 }
5532 // Add space after a delay.
5533 if (Right.isNot(tok::semi) &&
5534 (Left.endsSequence(tok::numeric_constant, Keywords.kw_verilogHash) ||
5535 Left.endsSequence(tok::numeric_constant,
5536 Keywords.kw_verilogHashHash) ||
5537 (Left.is(tok::r_paren) && Left.MatchingParen &&
5538 Left.MatchingParen->endsSequence(tok::l_paren, tok::at)))) {
5539 return true;
5540 }
5541 // Don't add embedded spaces in a number literal like `16'h1?ax` or an array
5542 // literal like `'{}`.
5543 if (Left.is(Keywords.kw_apostrophe) ||
5544 (Left.is(TT_VerilogNumberBase) && Right.is(tok::numeric_constant))) {
5545 return false;
5546 }
5547 // Add spaces around the implication operator `->`.
5548 if (Left.is(tok::arrow) || Right.is(tok::arrow))
5549 return true;
5550 // Don't add spaces between two at signs. Like in a coverage event.
5551 // Don't add spaces between at and a sensitivity list like
5552 // `@(posedge clk)`.
5553 if (Left.is(tok::at) && Right.isOneOf(tok::l_paren, tok::star, tok::at))
5554 return false;
5555 // Add space between the type name and dimension like `logic [1:0]`.
5556 if (Right.is(tok::l_square) &&
5557 Left.isOneOf(TT_VerilogDimensionedTypeName, Keywords.kw_function)) {
5558 return true;
5559 }
5560 // In a tagged union expression, there should be a space after the tag.
5561 if (Right.isOneOf(tok::period, Keywords.kw_apostrophe) &&
5562 Keywords.isVerilogIdentifier(Left) && Left.getPreviousNonComment() &&
5563 Left.getPreviousNonComment()->is(Keywords.kw_tagged)) {
5564 return true;
5565 }
5566 // Don't add spaces between a casting type and the quote or repetition count
5567 // and the brace. The case of tagged union expressions is handled by the
5568 // previous rule.
5569 if ((Right.is(Keywords.kw_apostrophe) ||
5570 (Right.is(BK_BracedInit) && Right.is(tok::l_brace))) &&
5571 Left.isNoneOf(Keywords.kw_assign, Keywords.kw_unique) &&
5572 !Keywords.isVerilogWordOperator(Left) &&
5573 (Left.isOneOf(tok::r_square, tok::r_paren, tok::r_brace,
5574 tok::numeric_constant) ||
5575 Keywords.isWordLike(Left))) {
5576 return false;
5577 }
5578 // Don't add spaces in imports like `import foo::*;`.
5579 if ((Right.is(tok::star) && Left.is(tok::coloncolon)) ||
5580 (Left.is(tok::star) && Right.is(tok::semi))) {
5581 return false;
5582 }
5583 // Add space in attribute like `(* ASYNC_REG = "TRUE" *)`.
5584 if (Left.endsSequence(tok::star, tok::l_paren) && Right.is(tok::identifier))
5585 return true;
5586 // Add space before drive strength like in `wire (strong1, pull0)`.
5587 if (Right.is(tok::l_paren) && Right.is(TT_VerilogStrength))
5588 return true;
5589 // Don't add space in a streaming concatenation like `{>>{j}}`.
5590 if ((Left.is(tok::l_brace) &&
5591 Right.isOneOf(tok::lessless, tok::greatergreater)) ||
5592 (Left.endsSequence(tok::lessless, tok::l_brace) ||
5593 Left.endsSequence(tok::greatergreater, tok::l_brace))) {
5594 return false;
5595 }
5596 } else if (Style.isTableGen()) {
5597 // Avoid to connect [ and {. [{ is start token of multiline string.
5598 if (Left.is(tok::l_square) && Right.is(tok::l_brace))
5599 return true;
5600 if (Left.is(tok::r_brace) && Right.is(tok::r_square))
5601 return true;
5602 // Do not insert around colon in DAGArg and cond operator.
5603 if (Right.isOneOf(TT_TableGenDAGArgListColon,
5604 TT_TableGenDAGArgListColonToAlign) ||
5605 Left.isOneOf(TT_TableGenDAGArgListColon,
5606 TT_TableGenDAGArgListColonToAlign)) {
5607 return false;
5608 }
5609 if (Right.is(TT_TableGenCondOperatorColon))
5610 return false;
5611 if (Left.isOneOf(TT_TableGenDAGArgOperatorID,
5612 TT_TableGenDAGArgOperatorToBreak) &&
5613 Right.isNot(TT_TableGenDAGArgCloser)) {
5614 return true;
5615 }
5616 // Do not insert bang operators and consequent openers.
5617 if (Right.isOneOf(tok::l_paren, tok::less) &&
5618 Left.isOneOf(TT_TableGenBangOperator, TT_TableGenCondOperator)) {
5619 return false;
5620 }
5621 // Trailing paste requires space before '{' or ':', the case in name values.
5622 // Not before ';', the case in normal values.
5623 if (Left.is(TT_TableGenTrailingPasteOperator) &&
5624 Right.isOneOf(tok::l_brace, tok::colon)) {
5625 return true;
5626 }
5627 // Otherwise paste operator does not prefer space around.
5628 if (Left.is(tok::hash) || Right.is(tok::hash))
5629 return false;
5630 // Sure not to connect after defining keywords.
5631 if (Keywords.isTableGenDefinition(Left))
5632 return true;
5633 }
5634
5635 if (Left.is(TT_ImplicitStringLiteral))
5636 return Right.hasWhitespaceBefore();
5637 if (Line.Type == LT_ObjCMethodDecl) {
5638 if (Left.is(TT_ObjCMethodSpecifier))
5639 return Style.ObjCSpaceAfterMethodDeclarationPrefix;
5640 if (Left.is(tok::r_paren) && Left.isNot(TT_AttributeRParen) &&
5641 canBeObjCSelectorComponent(Right)) {
5642 // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
5643 // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
5644 // method declaration.
5645 return false;
5646 }
5647 }
5648 if (Line.Type == LT_ObjCProperty &&
5649 (Right.is(tok::equal) || Left.is(tok::equal))) {
5650 return false;
5651 }
5652
5653 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
5654 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) {
5655 return true;
5656 }
5657 if (Left.is(tok::comma) && Right.isNot(TT_OverloadedOperatorLParen) &&
5658 // In an unexpanded macro call we only find the parentheses and commas
5659 // in a line; the commas and closing parenthesis do not require a space.
5660 (Left.Children.empty() || !Left.MacroParent)) {
5661 return true;
5662 }
5663 if (Right.is(tok::comma))
5664 return false;
5665 if (Right.is(TT_ObjCBlockLParen))
5666 return true;
5667 if (Right.is(TT_CtorInitializerColon))
5668 return Style.SpaceBeforeCtorInitializerColon;
5669 if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
5670 return false;
5671 if (Right.is(TT_EnumUnderlyingTypeColon) &&
5672 !Style.SpaceBeforeEnumUnderlyingTypeColon) {
5673 return false;
5674 }
5675 if (Right.is(TT_RangeBasedForLoopColon) &&
5676 !Style.SpaceBeforeRangeBasedForLoopColon) {
5677 return false;
5678 }
5679 if (Left.is(TT_BitFieldColon)) {
5680 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
5681 Style.BitFieldColonSpacing == FormatStyle::BFCS_After;
5682 }
5683 if (Right.is(tok::colon)) {
5684 if (Right.is(TT_CaseLabelColon))
5685 return Style.SpaceBeforeCaseColon;
5686 if (Right.is(TT_GotoLabelColon))
5687 return false;
5688 // `private:` and `public:`.
5689 if (!Right.getNextNonComment())
5690 return false;
5691 if (Right.isOneOf(TT_ObjCSelector, TT_ObjCMethodExpr))
5692 return false;
5693 if (Left.is(tok::question))
5694 return false;
5695 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
5696 return false;
5697 if (Right.is(TT_DictLiteral))
5698 return Style.SpacesInContainerLiterals;
5699 if (Right.is(TT_AttributeColon))
5700 return false;
5701 if (Right.is(TT_CSharpNamedArgumentColon))
5702 return false;
5703 if (Right.is(TT_GenericSelectionColon))
5704 return false;
5705 if (Right.is(TT_BitFieldColon)) {
5706 return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
5707 Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
5708 }
5709 return true;
5710 }
5711 // Do not merge "- -" into "--".
5712 if ((Left.isOneOf(tok::minus, tok::minusminus) &&
5713 Right.isOneOf(tok::minus, tok::minusminus)) ||
5714 (Left.isOneOf(tok::plus, tok::plusplus) &&
5715 Right.isOneOf(tok::plus, tok::plusplus))) {
5716 return true;
5717 }
5718 if (Left.is(TT_UnaryOperator)) {
5719 // Lambda captures allow for a lone &, so "&]" needs to be properly
5720 // handled.
5721 if (Left.is(tok::amp) && Right.is(tok::r_square))
5722 return Style.SpacesInSquareBrackets;
5723 if (Left.isNot(tok::exclaim))
5724 return false;
5725 if (Left.TokenText == "!")
5726 return Style.SpaceAfterLogicalNot;
5727 assert(Left.TokenText == "not");
5728 return Right.isOneOf(tok::coloncolon, TT_UnaryOperator) ||
5729 (Right.is(tok::l_paren) && Style.SpaceBeforeParensOptions.AfterNot);
5730 }
5731
5732 // If the next token is a binary operator or a selector name, we have
5733 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
5734 if (Left.is(TT_CastRParen)) {
5735 return Style.SpaceAfterCStyleCast ||
5736 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
5737 }
5738
5739 auto ShouldAddSpacesInAngles = [this, &Right]() {
5740 if (this->Style.SpacesInAngles == FormatStyle::SIAS_Always)
5741 return true;
5742 if (this->Style.SpacesInAngles == FormatStyle::SIAS_Leave)
5743 return Right.hasWhitespaceBefore();
5744 return false;
5745 };
5746
5747 if (Left.is(tok::greater) && Right.is(tok::greater)) {
5748 if (Style.isTextProto() ||
5749 (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral))) {
5750 return Style.Cpp11BracedListStyle == FormatStyle::BLS_Block;
5751 }
5752 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
5753 ((Style.Standard < FormatStyle::LS_Cpp11) ||
5754 ShouldAddSpacesInAngles());
5755 }
5756 if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
5757 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
5758 (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod))) {
5759 return false;
5760 }
5761 if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) &&
5762 Right.getPrecedence() == prec::Assignment) {
5763 return false;
5764 }
5765 if (Style.isJava() && Right.is(tok::coloncolon) &&
5766 Left.isOneOf(tok::identifier, tok::kw_this)) {
5767 return false;
5768 }
5769 if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) {
5770 // Preserve the space in constructs such as ALWAYS_INLINE ::std::string.
5771 return Left.isPossibleMacro(/*AllowFollowingColonColon=*/true) &&
5772 Right.hasWhitespaceBefore();
5773 }
5774 if (Right.is(tok::coloncolon) &&
5775 Left.isNoneOf(tok::l_brace, tok::comment, tok::l_paren)) {
5776 // Put a space between < and :: in vector< ::std::string >
5777 return (Left.is(TT_TemplateOpener) &&
5778 ((Style.Standard < FormatStyle::LS_Cpp11) ||
5779 ShouldAddSpacesInAngles())) ||
5780 Left.isNoneOf(tok::l_paren, tok::r_paren, tok::l_square,
5781 tok::kw___super, TT_TemplateOpener,
5782 TT_TemplateCloser) ||
5783 (Left.is(tok::l_paren) && Style.SpacesInParensOptions.Other);
5784 }
5785 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
5786 return ShouldAddSpacesInAngles();
5787 if (Left.is(tok::r_paren) && Left.isNot(TT_TypeDeclarationParen) &&
5788 Right.is(TT_PointerOrReference) && Right.isOneOf(tok::amp, tok::ampamp)) {
5789 return true;
5790 }
5791 // Space before TT_StructuredBindingLSquare.
5792 if (Right.is(TT_StructuredBindingLSquare)) {
5793 return Left.isNoneOf(tok::amp, tok::ampamp) ||
5794 getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right;
5795 }
5796 // Space before & or && following a TT_StructuredBindingLSquare.
5797 if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
5798 Right.isOneOf(tok::amp, tok::ampamp)) {
5799 return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
5800 }
5801 if ((Right.is(TT_BinaryOperator) && Left.isNot(tok::l_paren)) ||
5802 (Left.isOneOf(TT_BinaryOperator, TT_EnumEqual, TT_ConditionalExpr) &&
5803 Right.isNot(tok::r_paren))) {
5804 return true;
5805 }
5806 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
5807 Left.MatchingParen &&
5808 Left.MatchingParen->is(TT_OverloadedOperatorLParen)) {
5809 return false;
5810 }
5811 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
5812 Line.Type == LT_ImportStatement) {
5813 return true;
5814 }
5815 if (Right.is(TT_TrailingUnaryOperator))
5816 return false;
5817 if (Left.is(TT_RegexLiteral))
5818 return false;
5819 return spaceRequiredBetween(Line, Left, Right);
5820}
5821
5822// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
5823static bool isAllmanBrace(const FormatToken &Tok) {
5824 return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
5825 Tok.isNoneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
5826}
5827
5828// Returns 'true' if 'Tok' is a function argument.
5830 return Tok.MatchingParen && Tok.MatchingParen->Next &&
5831 Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren,
5832 tok::r_brace);
5833}
5834
5835static bool
5837 FormatStyle::ShortLambdaStyle ShortLambdaOption) {
5838 return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None;
5839}
5840
5842 return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
5843 Tok.isNoneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
5844}
5845
5846bool TokenAnnotator::mustBreakBefore(AnnotatedLine &Line,
5847 const FormatToken &Right) const {
5848 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0 &&
5849 (!Style.RemoveEmptyLinesInUnwrappedLines || &Right == Line.First)) {
5850 return true;
5851 }
5852
5853 const FormatToken &Left = *Right.Previous;
5854
5855 if (Style.BreakFunctionDeclarationParameters && Line.MightBeFunctionDecl &&
5856 !Line.mightBeFunctionDefinition() && Left.MightBeFunctionDeclParen &&
5857 Left.ParameterCount > 0) {
5858 return true;
5859 }
5860
5861 if (Style.BreakFunctionDefinitionParameters && Line.MightBeFunctionDecl &&
5862 Line.mightBeFunctionDefinition() && Left.MightBeFunctionDeclParen &&
5863 Left.ParameterCount > 0) {
5864 return true;
5865 }
5866
5867 // Ignores the first parameter as this will be handled separately by
5868 // BreakFunctionDefinitionParameters or AlignAfterOpenBracket.
5869 if (Style.PackParameters.BinPack == FormatStyle::BPPS_AlwaysOnePerLine &&
5870 Line.MightBeFunctionDecl && !Left.opensScope() &&
5871 startsNextParameter(Right, Style)) {
5872 return true;
5873 }
5874
5875 const auto *BeforeLeft = Left.Previous;
5876 const auto *AfterRight = Right.Next;
5877
5878 if (Style.isCSharp()) {
5879 if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) &&
5880 Style.BraceWrapping.AfterFunction) {
5881 return true;
5882 }
5883 if (Right.is(TT_CSharpNamedArgumentColon) ||
5884 Left.is(TT_CSharpNamedArgumentColon)) {
5885 return false;
5886 }
5887 if (Right.is(TT_CSharpGenericTypeConstraint))
5888 return true;
5889 if (AfterRight && AfterRight->is(TT_FatArrow) &&
5890 (Right.is(tok::numeric_constant) ||
5891 (Right.is(tok::identifier) && Right.TokenText == "_"))) {
5892 return true;
5893 }
5894
5895 // Break after C# [...] and before public/protected/private/internal.
5896 if (Left.is(TT_AttributeRSquare) &&
5897 (Right.isAccessSpecifier(/*ColonRequired=*/false) ||
5898 Right.is(Keywords.kw_internal))) {
5899 return true;
5900 }
5901 // Break between ] and [ but only when there are really 2 attributes.
5902 if (Left.is(TT_AttributeRSquare) && Right.is(TT_AttributeLSquare))
5903 return true;
5904 } else if (Style.isJavaScript()) {
5905 // FIXME: This might apply to other languages and token kinds.
5906 if (Right.is(tok::string_literal) && Left.is(tok::plus) && BeforeLeft &&
5907 BeforeLeft->is(tok::string_literal)) {
5908 return true;
5909 }
5910 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
5911 BeforeLeft && BeforeLeft->is(tok::equal) &&
5912 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
5913 tok::kw_const) &&
5914 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
5915 // above.
5916 Line.First->isNoneOf(Keywords.kw_var, Keywords.kw_let)) {
5917 // Object literals on the top level of a file are treated as "enum-style".
5918 // Each key/value pair is put on a separate line, instead of bin-packing.
5919 return true;
5920 }
5921 if (Left.is(tok::l_brace) && Line.Level == 0 &&
5922 (Line.startsWith(tok::kw_enum) ||
5923 Line.startsWith(tok::kw_const, tok::kw_enum) ||
5924 Line.startsWith(tok::kw_export, tok::kw_enum) ||
5925 Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) {
5926 // JavaScript top-level enum key/value pairs are put on separate lines
5927 // instead of bin-packing.
5928 return true;
5929 }
5930 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && BeforeLeft &&
5931 BeforeLeft->is(TT_FatArrow)) {
5932 // JS arrow function (=> {...}).
5933 switch (Style.AllowShortLambdasOnASingleLine) {
5934 case FormatStyle::SLS_All:
5935 return false;
5936 case FormatStyle::SLS_None:
5937 return true;
5938 case FormatStyle::SLS_Empty:
5939 return !Left.Children.empty();
5940 case FormatStyle::SLS_Inline:
5941 // allow one-lining inline (e.g. in function call args) and empty arrow
5942 // functions.
5943 return (Left.NestingLevel == 0 && Line.Level == 0) &&
5944 !Left.Children.empty();
5945 }
5946 llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum");
5947 }
5948
5949 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
5950 !Left.Children.empty()) {
5951 // Support AllowShortFunctionsOnASingleLine for JavaScript.
5952 if (Left.NestingLevel == 0 && Line.Level == 0)
5953 return !Style.AllowShortFunctionsOnASingleLine.Other;
5954
5955 return !Style.AllowShortFunctionsOnASingleLine.Inline;
5956 }
5957 } else if (Style.isJava()) {
5958 if (Right.is(tok::plus) && Left.is(tok::string_literal) && AfterRight &&
5959 AfterRight->is(tok::string_literal)) {
5960 return true;
5961 }
5962 } else if (Style.isVerilog()) {
5963 // Break between assignments.
5964 if (Left.is(TT_VerilogAssignComma))
5965 return true;
5966 // Break between ports of different types.
5967 if (Left.is(TT_VerilogTypeComma))
5968 return true;
5969 // Break between ports in a module instantiation and after the parameter
5970 // list.
5971 if (Style.VerilogBreakBetweenInstancePorts &&
5972 (Left.is(TT_VerilogInstancePortComma) ||
5973 (Left.is(tok::r_paren) && Keywords.isVerilogIdentifier(Right) &&
5974 Left.MatchingParen &&
5975 Left.MatchingParen->is(TT_VerilogInstancePortLParen)))) {
5976 return true;
5977 }
5978 // Break after labels. In Verilog labels don't have the 'case' keyword, so
5979 // it is hard to identify them in UnwrappedLineParser.
5980 if (!Keywords.isVerilogBegin(Right) && Keywords.isVerilogEndOfLabel(Left))
5981 return true;
5982 } else if (Style.BreakAdjacentStringLiterals &&
5983 (IsCpp || Style.isProto() || Style.isTableGen())) {
5984 if (Left.isStringLiteral() && Right.isStringLiteral())
5985 return true;
5986 }
5987
5988 // Basic JSON newline processing.
5989 if (Style.isJson()) {
5990 // Always break after a JSON record opener.
5991 // {
5992 // }
5993 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace))
5994 return true;
5995 // Always break after a JSON array opener based on BreakArrays.
5996 if ((Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) &&
5997 Right.isNot(tok::r_square)) ||
5998 Left.is(tok::comma)) {
5999 if (Right.is(tok::l_brace))
6000 return true;
6001 // scan to the right if an we see an object or an array inside
6002 // then break.
6003 for (const auto *Tok = &Right; Tok; Tok = Tok->Next) {
6004 if (Tok->isOneOf(tok::l_brace, tok::l_square))
6005 return true;
6006 if (Tok->isOneOf(tok::r_brace, tok::r_square))
6007 break;
6008 }
6009 return Style.BreakArrays;
6010 }
6011 } else if (Style.isTableGen()) {
6012 // Break the comma in side cond operators.
6013 // !cond(case1:1,
6014 // case2:0);
6015 if (Left.is(TT_TableGenCondOperatorComma))
6016 return true;
6017 if (Left.is(TT_TableGenDAGArgOperatorToBreak) &&
6018 Right.isNot(TT_TableGenDAGArgCloser)) {
6019 return true;
6020 }
6021 if (Left.is(TT_TableGenDAGArgListCommaToBreak))
6022 return true;
6023 if (Right.is(TT_TableGenDAGArgCloser) && Right.MatchingParen &&
6024 Right.MatchingParen->is(TT_TableGenDAGArgOpenerToBreak) &&
6025 &Left != Right.MatchingParen->Next) {
6026 // Check to avoid empty DAGArg such as (ins).
6027 return Style.TableGenBreakInsideDAGArg == FormatStyle::DAS_BreakAll;
6028 }
6029 }
6030
6031 if (Line.startsWith(tok::kw_asm) && Right.is(TT_InlineASMColon) &&
6032 Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always) {
6033 return true;
6034 }
6035
6036 // If the last token before a '}', ']', or ')' is a comma or a trailing
6037 // comment, the intention is to insert a line break after it in order to make
6038 // shuffling around entries easier. Import statements, especially in
6039 // JavaScript, can be an exception to this rule.
6040 if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
6041 const FormatToken *BeforeClosingBrace = nullptr;
6042 if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
6043 (Style.isJavaScript() && Left.is(tok::l_paren))) &&
6044 Left.isNot(BK_Block) && Left.MatchingParen) {
6045 BeforeClosingBrace = Left.MatchingParen->Previous;
6046 } else if (Right.MatchingParen &&
6047 (Right.MatchingParen->isOneOf(tok::l_brace,
6048 TT_ArrayInitializerLSquare) ||
6049 (Style.isJavaScript() &&
6050 Right.MatchingParen->is(tok::l_paren)))) {
6051 BeforeClosingBrace = &Left;
6052 }
6053 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
6054 BeforeClosingBrace->isTrailingComment())) {
6055 return true;
6056 }
6057 }
6058
6059 if (Right.is(tok::comment)) {
6060 return Left.isNoneOf(BK_BracedInit, TT_CtorInitializerColon) &&
6061 Right.NewlinesBefore > 0 && Right.HasUnescapedNewline;
6062 }
6063 if (Left.isTrailingComment())
6064 return true;
6065 if (Left.IsUnterminatedLiteral)
6066 return true;
6067
6068 if (BeforeLeft && BeforeLeft->is(tok::lessless) &&
6069 Left.is(tok::string_literal) && Right.is(tok::lessless) && AfterRight &&
6070 AfterRight->is(tok::string_literal)) {
6071 return Right.NewlinesBefore > 0;
6072 }
6073
6074 if (Right.is(TT_RequiresClause)) {
6075 switch (Style.RequiresClausePosition) {
6076 case FormatStyle::RCPS_OwnLine:
6077 case FormatStyle::RCPS_OwnLineWithBrace:
6078 case FormatStyle::RCPS_WithFollowing:
6079 return true;
6080 default:
6081 break;
6082 }
6083 }
6084 // Can break after template<> declaration
6085 if (Left.ClosesTemplateDeclaration && Left.MatchingParen &&
6086 Left.MatchingParen->NestingLevel == 0) {
6087 // Put concepts on the next line e.g.
6088 // template<typename T>
6089 // concept ...
6090 if (Right.is(tok::kw_concept))
6091 return Style.BreakBeforeConceptDeclarations == FormatStyle::BBCDS_Always;
6092 return Style.BreakTemplateDeclarations == FormatStyle::BTDS_Yes ||
6093 (Style.BreakTemplateDeclarations == FormatStyle::BTDS_Leave &&
6094 Right.NewlinesBefore > 0);
6095 }
6096 if (Left.ClosesRequiresClause) {
6097 switch (Style.RequiresClausePosition) {
6098 case FormatStyle::RCPS_OwnLine:
6099 case FormatStyle::RCPS_WithPreceding:
6100 return Right.isNot(tok::semi);
6101 case FormatStyle::RCPS_OwnLineWithBrace:
6102 return Right.isNoneOf(tok::semi, tok::l_brace);
6103 default:
6104 break;
6105 }
6106 }
6107 if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) {
6108 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon &&
6109 (Left.is(TT_CtorInitializerComma) ||
6110 Right.is(TT_CtorInitializerColon))) {
6111 return true;
6112 }
6113
6114 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
6115 Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma)) {
6116 return true;
6117 }
6118
6119 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterComma &&
6120 Left.is(TT_CtorInitializerComma)) {
6121 return true;
6122 }
6123 }
6124 if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine &&
6125 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
6126 Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) {
6127 return true;
6128 }
6129 if (Style.PackConstructorInitializers == FormatStyle::PCIS_NextLineOnly) {
6130 if ((Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon ||
6131 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) &&
6132 Right.is(TT_CtorInitializerColon)) {
6133 return true;
6134 }
6135
6136 if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
6137 Left.is(TT_CtorInitializerColon)) {
6138 return true;
6139 }
6140 }
6141 // Break only if we have multiple inheritance.
6142 if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
6143 Right.is(TT_InheritanceComma)) {
6144 return true;
6145 }
6146 if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma &&
6147 Left.is(TT_InheritanceComma)) {
6148 return true;
6149 }
6150 if (Right.is(tok::string_literal) && Right.TokenText.starts_with("R\"")) {
6151 // Multiline raw string literals are special wrt. line breaks. The author
6152 // has made a deliberate choice and might have aligned the contents of the
6153 // string literal accordingly. Thus, we try keep existing line breaks.
6154 return Right.IsMultiline && Right.NewlinesBefore > 0;
6155 }
6156 if ((Left.is(tok::l_brace) ||
6157 (Left.is(tok::less) && BeforeLeft && BeforeLeft->is(tok::equal))) &&
6158 Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
6159 // Don't put enums or option definitions onto single lines in protocol
6160 // buffers.
6161 return true;
6162 }
6163 if (Right.is(TT_InlineASMBrace))
6164 return Right.HasUnescapedNewline;
6165
6166 if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
6167 auto *FirstNonComment = Line.getFirstNonComment();
6168 bool AccessSpecifier =
6169 FirstNonComment && (FirstNonComment->is(Keywords.kw_internal) ||
6170 FirstNonComment->isAccessSpecifierKeyword());
6171
6172 if (Style.BraceWrapping.AfterEnum) {
6173 if (Line.startsWith(tok::kw_enum) ||
6174 Line.startsWith(tok::kw_typedef, tok::kw_enum) ||
6175 Line.startsWith(tok::kw_export, tok::kw_enum)) {
6176 return true;
6177 }
6178 // Ensure BraceWrapping for `public enum A {`.
6179 if (AccessSpecifier && FirstNonComment->Next &&
6180 FirstNonComment->Next->is(tok::kw_enum)) {
6181 return true;
6182 }
6183 }
6184
6185 // Ensure BraceWrapping for `public interface A {`.
6186 if (Style.BraceWrapping.AfterClass &&
6187 ((AccessSpecifier && FirstNonComment->Next &&
6188 FirstNonComment->Next->is(Keywords.kw_interface)) ||
6189 Line.startsWith(Keywords.kw_interface))) {
6190 return true;
6191 }
6192
6193 // Don't attempt to interpret record return types as records.
6194 if (Right.isNot(TT_FunctionLBrace)) {
6195 return Style.AllowShortRecordOnASingleLine == FormatStyle::SRS_Never &&
6196 ((Line.startsWith(tok::kw_class) &&
6197 Style.BraceWrapping.AfterClass) ||
6198 (Line.startsWith(tok::kw_struct) &&
6199 Style.BraceWrapping.AfterStruct) ||
6200 (Line.startsWith(tok::kw_union) &&
6201 Style.BraceWrapping.AfterUnion));
6202 }
6203 }
6204
6205 if (Left.is(TT_ObjCBlockLBrace) &&
6206 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
6207 return true;
6208 }
6209
6210 // Ensure wrapping after __attribute__((XX)) and @interface etc.
6211 if (Left.isOneOf(TT_AttributeRParen, TT_AttributeMacro) &&
6212 Right.is(TT_ObjCDecl)) {
6213 return true;
6214 }
6215
6216 if (Left.is(TT_LambdaLBrace)) {
6217 if (IsFunctionArgument(Left) &&
6218 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline) {
6219 return false;
6220 }
6221
6222 if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
6223 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
6224 (!Left.Children.empty() &&
6225 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty)) {
6226 return true;
6227 }
6228 }
6229
6230 if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace) &&
6231 (Left.isPointerOrReference() || Left.is(TT_TemplateCloser))) {
6232 return true;
6233 }
6234
6235 // Put multiple Java annotation on a new line.
6236 if ((Style.isJava() || Style.isJavaScript()) &&
6237 Left.is(TT_LeadingJavaAnnotation) &&
6238 Right.isNoneOf(TT_LeadingJavaAnnotation, tok::l_paren) &&
6239 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) {
6240 return true;
6241 }
6242
6243 if (Right.is(TT_ProtoExtensionLSquare))
6244 return true;
6245
6246 // In text proto instances if a submessage contains at least 2 entries and at
6247 // least one of them is a submessage, like A { ... B { ... } ... },
6248 // put all of the entries of A on separate lines by forcing the selector of
6249 // the submessage B to be put on a newline.
6250 //
6251 // Example: these can stay on one line:
6252 // a { scalar_1: 1 scalar_2: 2 }
6253 // a { b { key: value } }
6254 //
6255 // and these entries need to be on a new line even if putting them all in one
6256 // line is under the column limit:
6257 // a {
6258 // scalar: 1
6259 // b { key: value }
6260 // }
6261 //
6262 // We enforce this by breaking before a submessage field that has previous
6263 // siblings, *and* breaking before a field that follows a submessage field.
6264 //
6265 // Be careful to exclude the case [proto.ext] { ... } since the `]` is
6266 // the TT_SelectorName there, but we don't want to break inside the brackets.
6267 //
6268 // Another edge case is @submessage { key: value }, which is a common
6269 // substitution placeholder. In this case we want to keep `@` and `submessage`
6270 // together.
6271 //
6272 // We ensure elsewhere that extensions are always on their own line.
6273 if (Style.isProto() && Right.is(TT_SelectorName) &&
6274 Right.isNot(tok::r_square) && AfterRight) {
6275 // Keep `@submessage` together in:
6276 // @submessage { key: value }
6277 if (Left.is(tok::at))
6278 return false;
6279 // Look for the scope opener after selector in cases like:
6280 // selector { ...
6281 // selector: { ...
6282 // selector: @base { ...
6283 const auto *LBrace = AfterRight;
6284 if (LBrace && LBrace->is(tok::colon)) {
6285 LBrace = LBrace->Next;
6286 if (LBrace && LBrace->is(tok::at)) {
6287 LBrace = LBrace->Next;
6288 if (LBrace)
6289 LBrace = LBrace->Next;
6290 }
6291 }
6292 if (LBrace &&
6293 // The scope opener is one of {, [, <:
6294 // selector { ... }
6295 // selector [ ... ]
6296 // selector < ... >
6297 //
6298 // In case of selector { ... }, the l_brace is TT_DictLiteral.
6299 // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
6300 // so we check for immediately following r_brace.
6301 ((LBrace->is(tok::l_brace) &&
6302 (LBrace->is(TT_DictLiteral) ||
6303 (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
6304 LBrace->isOneOf(TT_ArrayInitializerLSquare, tok::less))) {
6305 // If Left.ParameterCount is 0, then this submessage entry is not the
6306 // first in its parent submessage, and we want to break before this entry.
6307 // If Left.ParameterCount is greater than 0, then its parent submessage
6308 // might contain 1 or more entries and we want to break before this entry
6309 // if it contains at least 2 entries. We deal with this case later by
6310 // detecting and breaking before the next entry in the parent submessage.
6311 if (Left.ParameterCount == 0)
6312 return true;
6313 // However, if this submessage is the first entry in its parent
6314 // submessage, Left.ParameterCount might be 1 in some cases.
6315 // We deal with this case later by detecting an entry
6316 // following a closing paren of this submessage.
6317 }
6318
6319 // If this is an entry immediately following a submessage, it will be
6320 // preceded by a closing paren of that submessage, like in:
6321 // left---. .---right
6322 // v v
6323 // sub: { ... } key: value
6324 // If there was a comment between `}` an `key` above, then `key` would be
6325 // put on a new line anyways.
6326 if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
6327 return true;
6328 }
6329
6330 if (Style.BreakAfterAttributes == FormatStyle::ABS_LeaveAll &&
6331 Left.is(TT_AttributeRSquare) && Right.NewlinesBefore > 0) {
6332 Line.ReturnTypeWrapped = true;
6333 return true;
6334 }
6335
6336 return false;
6337}
6338
6339bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
6340 const FormatToken &Right) const {
6341 const FormatToken &Left = *Right.Previous;
6342 // Language-specific stuff.
6343 if (Style.isCSharp()) {
6344 if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
6345 Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) {
6346 return false;
6347 }
6348 // Only break after commas for generic type constraints.
6349 if (Line.First->is(TT_CSharpGenericTypeConstraint))
6350 return Left.is(TT_CSharpGenericTypeConstraintComma);
6351 // Keep nullable operators attached to their identifiers.
6352 if (Right.is(TT_CSharpNullable))
6353 return false;
6354 } else if (Style.isJava()) {
6355 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
6356 Keywords.kw_implements)) {
6357 return false;
6358 }
6359 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
6360 Keywords.kw_implements)) {
6361 return true;
6362 }
6363 } else if (Style.isJavaScript()) {
6364 const FormatToken *NonComment = Right.getPreviousNonComment();
6365 if (NonComment &&
6366 (NonComment->isAccessSpecifierKeyword() ||
6367 NonComment->isOneOf(
6368 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
6369 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
6370 tok::kw_static, Keywords.kw_readonly, Keywords.kw_override,
6371 Keywords.kw_abstract, Keywords.kw_get, Keywords.kw_set,
6372 Keywords.kw_async, Keywords.kw_await))) {
6373 return false; // Otherwise automatic semicolon insertion would trigger.
6374 }
6375 if (Right.NestingLevel == 0 &&
6376 (Left.Tok.getIdentifierInfo() ||
6377 Left.isOneOf(tok::r_square, tok::r_paren)) &&
6378 Right.isOneOf(tok::l_square, tok::l_paren)) {
6379 return false; // Otherwise automatic semicolon insertion would trigger.
6380 }
6381 if (NonComment && NonComment->is(tok::identifier) &&
6382 NonComment->TokenText == "asserts") {
6383 return false;
6384 }
6385 if (Left.is(TT_FatArrow) && Right.is(tok::l_brace))
6386 return false;
6387 if (Left.is(TT_JsTypeColon))
6388 return true;
6389 // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
6390 if (Left.is(tok::exclaim) && Right.is(tok::colon))
6391 return false;
6392 // Look for is type annotations like:
6393 // function f(): a is B { ... }
6394 // Do not break before is in these cases.
6395 if (Right.is(Keywords.kw_is)) {
6396 const FormatToken *Next = Right.getNextNonComment();
6397 // If `is` is followed by a colon, it's likely that it's a dict key, so
6398 // ignore it for this check.
6399 // For example this is common in Polymer:
6400 // Polymer({
6401 // is: 'name',
6402 // ...
6403 // });
6404 if (!Next || Next->isNot(tok::colon))
6405 return false;
6406 }
6407 if (Left.is(Keywords.kw_in))
6408 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
6409 if (Right.is(Keywords.kw_in))
6410 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
6411 if (Right.is(Keywords.kw_as))
6412 return false; // must not break before as in 'x as type' casts
6413 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
6414 // extends and infer can appear as keywords in conditional types:
6415 // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
6416 // do not break before them, as the expressions are subject to ASI.
6417 return false;
6418 }
6419 if (Left.is(Keywords.kw_as))
6420 return true;
6421 if (Left.is(TT_NonNullAssertion))
6422 return true;
6423 if (Left.is(Keywords.kw_declare) &&
6424 Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
6425 Keywords.kw_function, tok::kw_class, tok::kw_enum,
6426 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
6427 Keywords.kw_let, tok::kw_const)) {
6428 // See grammar for 'declare' statements at:
6429 // https://github.com/Microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md#A.10
6430 return false;
6431 }
6432 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
6433 Right.isOneOf(tok::identifier, tok::string_literal)) {
6434 return false; // must not break in "module foo { ...}"
6435 }
6436 if (Right.is(TT_TemplateString) && Right.closesScope())
6437 return false;
6438 // Don't split tagged template literal so there is a break between the tag
6439 // identifier and template string.
6440 if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
6441 return false;
6442 if (Left.is(TT_TemplateString) && Left.opensScope())
6443 return true;
6444 } else if (Style.isTableGen()) {
6445 // Avoid to break after "def", "class", "let" and so on.
6446 if (Keywords.isTableGenDefinition(Left))
6447 return false;
6448 // Avoid to break after '(' in the cases that is in bang operators.
6449 if (Right.is(tok::l_paren)) {
6450 return Left.isNoneOf(TT_TableGenBangOperator, TT_TableGenCondOperator,
6451 TT_TemplateCloser);
6452 }
6453 // Avoid to break between the value and its suffix part.
6454 if (Left.is(TT_TableGenValueSuffix))
6455 return false;
6456 // Avoid to break around paste operator.
6457 if (Left.is(tok::hash) || Right.is(tok::hash))
6458 return false;
6459 if (Left.isOneOf(TT_TableGenBangOperator, TT_TableGenCondOperator))
6460 return false;
6461 }
6462
6463 // We can break before an r_brace if there was a break after the matching
6464 // l_brace, which is tracked by BreakBeforeClosingBrace, or if we are in a
6465 // block-indented initialization list.
6466 if (Right.is(tok::r_brace)) {
6467 return Right.MatchingParen && (Right.MatchingParen->is(BK_Block) ||
6468 (Right.isBlockIndentedInitRBrace(Style)));
6469 }
6470
6471 // We can break before r_paren if we're in a block indented context or
6472 // a control statement with an explicit style option.
6473 if (Right.is(tok::r_paren)) {
6474 if (!Right.MatchingParen)
6475 return false;
6476 auto Next = Right.Next;
6477 if (Next && Next->is(tok::r_paren))
6478 Next = Next->Next;
6479 if (Next && Next->is(tok::l_paren))
6480 return false;
6481 const FormatToken *Previous = Right.MatchingParen->Previous;
6482 if (!Previous)
6483 return false;
6484 if (Previous->isIf())
6485 return Style.BreakBeforeCloseBracketIf;
6486 if (Previous->isLoop(Style))
6487 return Style.BreakBeforeCloseBracketLoop;
6488 if (Previous->is(tok::kw_switch))
6489 return Style.BreakBeforeCloseBracketSwitch;
6490 return Style.BreakBeforeCloseBracketFunction;
6491 }
6492
6493 if (Left.isOneOf(tok::r_paren, TT_TrailingAnnotation) &&
6494 Right.is(TT_TrailingAnnotation) &&
6495 Style.BreakBeforeCloseBracketFunction) {
6496 return false;
6497 }
6498
6499 if (Right.is(TT_TemplateCloser))
6500 return Style.BreakBeforeTemplateCloser;
6501
6502 if (Left.isOneOf(tok::at, tok::objc_interface))
6503 return false;
6504 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
6505 return Right.isNot(tok::l_paren);
6506 if (Right.is(TT_PointerOrReference)) {
6507 return Line.IsMultiVariableDeclStmt ||
6508 (getTokenPointerOrReferenceAlignment(Right) ==
6509 FormatStyle::PAS_Right &&
6510 !(Right.Next &&
6511 Right.Next->isOneOf(TT_FunctionDeclarationName, tok::kw_const)));
6512 }
6513 if (Left.is(tok::hashhash) || Right.is(tok::hashhash))
6514 return false;
6515 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
6516 TT_ClassHeadName, TT_QtProperty, tok::kw_operator)) {
6517 return true;
6518 }
6519 if (Left.is(TT_PointerOrReference))
6520 return false;
6521 if (Right.isTrailingComment()) {
6522 // We rely on MustBreakBefore being set correctly here as we should not
6523 // change the "binding" behavior of a comment.
6524 // The first comment in a braced lists is always interpreted as belonging to
6525 // the first list element. Otherwise, it should be placed outside of the
6526 // list.
6527 return Left.is(BK_BracedInit) ||
6528 (Left.is(TT_CtorInitializerColon) && Right.NewlinesBefore > 0 &&
6529 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
6530 }
6531 if (Left.is(tok::question) && Right.is(tok::colon))
6532 return false;
6533 if (Right.isOneOf(TT_ConditionalExpr, tok::question))
6534 return Style.BreakBeforeTernaryOperators;
6535 if (Left.isOneOf(TT_ConditionalExpr, tok::question))
6536 return !Style.BreakBeforeTernaryOperators;
6537 if (Left.is(TT_InheritanceColon))
6538 return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
6539 if (Right.is(TT_InheritanceColon))
6540 return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
6541 // When the method parameter has no name, allow breaking before the colon.
6542 if (Right.is(TT_ObjCMethodExpr) && Right.isNot(tok::r_square) &&
6543 Left.isNot(TT_SelectorName)) {
6544 return true;
6545 }
6546
6547 if (Right.is(tok::colon) &&
6548 Right.isNoneOf(TT_CtorInitializerColon, TT_InlineASMColon,
6549 TT_BitFieldColon)) {
6550 return false;
6551 }
6552 if (Left.is(tok::colon) && Left.isOneOf(TT_ObjCSelector, TT_ObjCMethodExpr))
6553 return true;
6554 if (Left.is(tok::colon) && Left.is(TT_DictLiteral)) {
6555 if (Style.isProto()) {
6556 if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
6557 return false;
6558 // Prevent cases like:
6559 //
6560 // submessage:
6561 // { key: valueeeeeeeeeeee }
6562 //
6563 // when the snippet does not fit into one line.
6564 // Prefer:
6565 //
6566 // submessage: {
6567 // key: valueeeeeeeeeeee
6568 // }
6569 //
6570 // instead, even if it is longer by one line.
6571 //
6572 // Note that this allows the "{" to go over the column limit
6573 // when the column limit is just between ":" and "{", but that does
6574 // not happen too often and alternative formattings in this case are
6575 // not much better.
6576 //
6577 // The code covers the cases:
6578 //
6579 // submessage: { ... }
6580 // submessage: < ... >
6581 // repeated: [ ... ]
6582 if ((Right.isOneOf(tok::l_brace, tok::less) &&
6583 Right.is(TT_DictLiteral)) ||
6584 Right.is(TT_ArrayInitializerLSquare)) {
6585 return false;
6586 }
6587 }
6588 return true;
6589 }
6590 if (Right.is(tok::r_square) && Right.MatchingParen &&
6591 Right.MatchingParen->is(TT_ProtoExtensionLSquare)) {
6592 return false;
6593 }
6594 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
6595 Right.Next->is(TT_ObjCMethodExpr))) {
6596 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
6597 }
6598 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
6599 return true;
6600 if (Right.is(tok::kw_concept))
6601 return Style.BreakBeforeConceptDeclarations != FormatStyle::BBCDS_Never;
6602 if (Right.is(TT_RequiresClause))
6603 return true;
6604 if (Left.ClosesTemplateDeclaration) {
6605 return Style.BreakTemplateDeclarations != FormatStyle::BTDS_Leave ||
6606 Right.NewlinesBefore > 0;
6607 }
6608 if (Left.is(TT_FunctionAnnotationRParen))
6609 return true;
6610 if (Left.ClosesRequiresClause)
6611 return true;
6612 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
6613 TT_OverloadedOperator)) {
6614 return false;
6615 }
6616 if (Left.is(TT_RangeBasedForLoopColon))
6617 return true;
6618 if (Right.is(TT_RangeBasedForLoopColon))
6619 return false;
6620 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
6621 return true;
6622 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
6623 (Left.is(tok::less) && Right.is(tok::less))) {
6624 return false;
6625 }
6626 if (Right.is(TT_BinaryOperator) &&
6627 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
6628 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
6629 Right.getPrecedence() != prec::Assignment)) {
6630 return true;
6631 }
6632 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator, tok::kw_operator))
6633 return false;
6634 if (Left.is(tok::equal) && Right.isNoneOf(tok::kw_default, tok::kw_delete) &&
6635 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) {
6636 return false;
6637 }
6638 if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
6639 Style.Cpp11BracedListStyle == FormatStyle::BLS_Block) {
6640 return false;
6641 }
6642 if (Left.is(TT_AttributeLParen) ||
6643 (Left.is(tok::l_paren) && Left.is(TT_TypeDeclarationParen))) {
6644 return false;
6645 }
6646 if (Left.is(tok::l_paren) && Left.Previous &&
6647 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) {
6648 return false;
6649 }
6650 if (Right.is(TT_ImplicitStringLiteral))
6651 return false;
6652
6653 if (Right.is(tok::r_square) && Right.MatchingParen &&
6654 Right.MatchingParen->is(TT_LambdaLSquare)) {
6655 return false;
6656 }
6657
6658 // Allow breaking after a trailing annotation, e.g. after a method
6659 // declaration.
6660 if (Left.is(TT_TrailingAnnotation)) {
6661 return Right.isNoneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
6662 tok::less, tok::coloncolon);
6663 }
6664
6665 if (Right.isAttribute())
6666 return true;
6667
6668 if (Right.is(TT_AttributeLSquare)) {
6669 assert(Left.isNot(tok::l_square));
6670 return true;
6671 }
6672
6673 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
6674 return true;
6675
6676 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
6677 return true;
6678
6679 if (Left.is(TT_CtorInitializerColon)) {
6680 return (Style.BreakConstructorInitializers ==
6681 FormatStyle::BCIS_AfterColon ||
6682 Style.BreakConstructorInitializers ==
6683 FormatStyle::BCIS_AfterComma) &&
6684 (!Right.isTrailingComment() || Right.NewlinesBefore > 0);
6685 }
6686 if (Right.is(TT_CtorInitializerColon)) {
6687 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon &&
6688 Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterComma;
6689 }
6690 if (Left.is(TT_CtorInitializerComma) &&
6691 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
6692 return false;
6693 }
6694 if (Right.is(TT_CtorInitializerComma) &&
6695 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
6696 return true;
6697 }
6698 if (Left.is(TT_InheritanceComma) &&
6699 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
6700 return false;
6701 }
6702 if (Right.is(TT_InheritanceComma) &&
6703 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
6704 return true;
6705 }
6706 if (Left.is(TT_ArrayInitializerLSquare))
6707 return true;
6708 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
6709 return true;
6710 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
6711 Left.isNoneOf(tok::arrowstar, tok::lessless) &&
6712 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
6713 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
6714 Left.getPrecedence() == prec::Assignment)) {
6715 return true;
6716 }
6717 if (Left.is(TT_AttributeLSquare) && Right.is(tok::l_square)) {
6718 assert(Right.isNot(TT_AttributeLSquare));
6719 return false;
6720 }
6721 if (Left.is(tok::r_square) && Right.is(TT_AttributeRSquare)) {
6722 assert(Left.isNot(TT_AttributeRSquare));
6723 return false;
6724 }
6725
6726 auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
6727 if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) {
6728 if (isAllmanLambdaBrace(Left))
6729 return !isEmptyLambdaAllowed(Left, ShortLambdaOption);
6730 if (isAllmanLambdaBrace(Right))
6731 return !isEmptyLambdaAllowed(Right, ShortLambdaOption);
6732 }
6733
6734 if (Right.is(tok::kw_noexcept) && Right.is(TT_TrailingAnnotation)) {
6735 switch (Style.AllowBreakBeforeNoexceptSpecifier) {
6736 case FormatStyle::BBNSS_Never:
6737 return false;
6738 case FormatStyle::BBNSS_Always:
6739 return true;
6740 case FormatStyle::BBNSS_OnlyWithParen:
6741 return Right.Next && Right.Next->is(tok::l_paren);
6742 }
6743 }
6744
6745 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
6746 tok::kw_class, tok::kw_struct, tok::comment) ||
6747 Right.isMemberAccess() ||
6748 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
6749 tok::colon, tok::l_square, tok::at) ||
6750 (Left.is(tok::r_paren) &&
6751 Right.isOneOf(tok::identifier, tok::kw_const)) ||
6752 (Left.is(tok::l_paren) && Right.isNot(tok::r_paren)) ||
6753 (Left.is(TT_TemplateOpener) && Right.isNot(TT_TemplateCloser));
6754}
6755
6756void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) const {
6757 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << ", P=" << Line.PPLevel
6758 << ", T=" << Line.Type << ", C=" << Line.IsContinuation
6759 << "):\n";
6760 const FormatToken *Tok = Line.First;
6761 while (Tok) {
6762 llvm::errs() << " I=" << Tok->IndentLevel << " M=" << Tok->MustBreakBefore
6763 << " C=" << Tok->CanBreakBefore
6764 << " T=" << getTokenTypeName(Tok->getType())
6765 << " S=" << Tok->SpacesRequiredBefore
6766 << " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount
6767 << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty
6768 << " Name=" << Tok->Tok.getName() << " N=" << Tok->NestingLevel
6769 << " L=" << Tok->TotalLength
6770 << " PPK=" << Tok->getPackingKind() << " FakeLParens=";
6771 for (prec::Level LParen : Tok->FakeLParens)
6772 llvm::errs() << LParen << "/";
6773 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
6774 llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
6775 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
6776 if (!Tok->Next)
6777 assert(Tok == Line.Last);
6778 Tok = Tok->Next;
6779 }
6780 llvm::errs() << "----\n";
6781}
6782
6783FormatStyle::PointerAlignmentStyle
6784TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) const {
6785 assert(Reference.isOneOf(tok::amp, tok::ampamp));
6786 switch (Style.ReferenceAlignment) {
6787 case FormatStyle::RAS_Pointer:
6788 return Style.PointerAlignment;
6789 case FormatStyle::RAS_Left:
6790 return FormatStyle::PAS_Left;
6791 case FormatStyle::RAS_Right:
6792 return FormatStyle::PAS_Right;
6793 case FormatStyle::RAS_Middle:
6794 return FormatStyle::PAS_Middle;
6795 }
6796 assert(0); //"Unhandled value of ReferenceAlignment"
6797 return Style.PointerAlignment;
6798}
6799
6800FormatStyle::PointerAlignmentStyle
6801TokenAnnotator::getTokenPointerOrReferenceAlignment(
6802 const FormatToken &PointerOrReference) const {
6803 if (PointerOrReference.isOneOf(tok::amp, tok::ampamp))
6804 return getTokenReferenceAlignment(PointerOrReference);
6805 assert(PointerOrReference.is(tok::star));
6806 return Style.PointerAlignment;
6807}
6808
6809} // namespace format
6810} // 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:4904
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.
LangOptions getFormattingLangOpts(const FormatStyle &Style)
Definition Format.cpp:4498
bool startsNextParameter(const FormatToken &Current, const FormatStyle &Style)
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:272
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
The JSON file list parser is used to communicate input to InstallAPI.
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',...
bool isCpp() const
Definition Format.h:3843
@ 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:564
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
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.