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