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