1 //===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements a token annotator, i.e. creates
12 /// \c AnnotatedTokens out of \c FormatTokens with required extra information.
14 //===----------------------------------------------------------------------===//
16 #include "TokenAnnotator.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/Support/Debug.h"
21 #define DEBUG_TYPE "format-token-annotator"
28 /// \brief A parser that gathers additional information about tokens.
30 /// The \c TokenAnnotator tries to match parenthesis and square brakets and
31 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
32 /// into template parameter lists.
33 class AnnotatingParser {
35 AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
36 const AdditionalKeywords &Keywords)
37 : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
39 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
40 resetTokenMetadata(CurrentToken);
45 if (!CurrentToken || !CurrentToken->Previous)
47 if (NonTemplateLess.count(CurrentToken->Previous))
50 const FormatToken& Previous = *CurrentToken->Previous;
51 if (Previous.Previous) {
52 if (Previous.Previous->Tok.isLiteral())
54 if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
55 (!Previous.Previous->MatchingParen ||
56 !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
60 FormatToken *Left = CurrentToken->Previous;
61 Left->ParentBracket = Contexts.back().ContextKind;
62 ScopedContextCreator ContextCreator(*this, tok::less, 12);
64 // If this angle is in the context of an expression, we need to be more
65 // hesitant to detect it as opening template parameters.
66 bool InExprContext = Contexts.back().IsExpression;
68 Contexts.back().IsExpression = false;
69 // If there's a template keyword before the opening angle bracket, this is a
70 // template parameter, not an argument.
71 Contexts.back().InTemplateArgument =
72 Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
74 if (Style.Language == FormatStyle::LK_Java &&
75 CurrentToken->is(tok::question))
78 while (CurrentToken) {
79 if (CurrentToken->is(tok::greater)) {
80 Left->MatchingParen = CurrentToken;
81 CurrentToken->MatchingParen = Left;
82 CurrentToken->Type = TT_TemplateCloser;
86 if (CurrentToken->is(tok::question) &&
87 Style.Language == FormatStyle::LK_Java) {
91 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
92 (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext))
94 // If a && or || is found and interpreted as a binary operator, this set
95 // of angles is likely part of something like "a < b && c > d". If the
96 // angles are inside an expression, the ||/&& might also be a binary
97 // operator that was misinterpreted because we are parsing template
99 // FIXME: This is getting out of hand, write a decent parser.
100 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
101 CurrentToken->Previous->is(TT_BinaryOperator) &&
102 Contexts[Contexts.size() - 2].IsExpression &&
103 !Line.startsWith(tok::kw_template))
105 updateParameterCount(Left, CurrentToken);
112 bool parseParens(bool LookForDecls = false) {
115 FormatToken *Left = CurrentToken->Previous;
116 Left->ParentBracket = Contexts.back().ContextKind;
117 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
119 // FIXME: This is a bit of a hack. Do better.
120 Contexts.back().ColonIsForRangeExpr =
121 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
123 bool StartsObjCMethodExpr = false;
124 if (CurrentToken->is(tok::caret)) {
125 // (^ can start a block type.
126 Left->Type = TT_ObjCBlockLParen;
127 } else if (FormatToken *MaybeSel = Left->Previous) {
128 // @selector( starts a selector.
129 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
130 MaybeSel->Previous->is(tok::at)) {
131 StartsObjCMethodExpr = true;
135 if (Left->is(TT_OverloadedOperatorLParen)) {
136 Contexts.back().IsExpression = false;
137 } else if (Style.Language == FormatStyle::LK_JavaScript &&
138 Line.startsWith(Keywords.kw_type, tok::identifier)) {
140 Contexts.back().IsExpression = false;
141 } else if (Left->Previous &&
142 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
143 tok::kw_if, tok::kw_while, tok::l_paren,
145 Left->Previous->is(TT_BinaryOperator))) {
146 // static_assert, if and while usually contain expressions.
147 Contexts.back().IsExpression = true;
148 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
149 (Left->Previous->is(Keywords.kw_function) ||
150 (Left->Previous->endsSequence(tok::identifier,
151 Keywords.kw_function)))) {
152 // function(...) or function f(...)
153 Contexts.back().IsExpression = false;
154 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
155 Left->Previous->is(TT_JsTypeColon)) {
156 // let x: (SomeType);
157 Contexts.back().IsExpression = false;
158 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
159 Left->Previous->MatchingParen &&
160 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
161 // This is a parameter list of a lambda expression.
162 Contexts.back().IsExpression = false;
163 } else if (Line.InPPDirective &&
164 (!Left->Previous || !Left->Previous->is(tok::identifier))) {
165 Contexts.back().IsExpression = true;
166 } else if (Contexts[Contexts.size() - 2].CaretFound) {
167 // This is the parameter list of an ObjC block.
168 Contexts.back().IsExpression = false;
169 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
170 Left->Type = TT_AttributeParen;
171 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
172 // The first argument to a foreach macro is a declaration.
173 Contexts.back().IsForEachMacro = true;
174 Contexts.back().IsExpression = false;
175 } else if (Left->Previous && Left->Previous->MatchingParen &&
176 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
177 Contexts.back().IsExpression = false;
178 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
180 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
181 Contexts.back().IsExpression = !IsForOrCatch;
184 if (StartsObjCMethodExpr) {
185 Contexts.back().ColonIsObjCMethodExpr = true;
186 Left->Type = TT_ObjCMethodExpr;
189 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
190 bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
191 bool HasMultipleLines = false;
192 bool HasMultipleParametersOnALine = false;
193 bool MightBeObjCForRangeLoop =
194 Left->Previous && Left->Previous->is(tok::kw_for);
195 while (CurrentToken) {
196 // LookForDecls is set when "if (" has been seen. Check for
197 // 'identifier' '*' 'identifier' followed by not '=' -- this
198 // '*' has to be a binary operator but determineStarAmpUsage() will
199 // categorize it as an unary operator, so set the right type here.
200 if (LookForDecls && CurrentToken->Next) {
201 FormatToken *Prev = CurrentToken->getPreviousNonComment();
203 FormatToken *PrevPrev = Prev->getPreviousNonComment();
204 FormatToken *Next = CurrentToken->Next;
205 if (PrevPrev && PrevPrev->is(tok::identifier) &&
206 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
207 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
208 Prev->Type = TT_BinaryOperator;
209 LookForDecls = false;
214 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
215 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
217 ProbablyFunctionType = true;
218 if (CurrentToken->is(tok::comma))
219 MightBeFunctionType = false;
220 if (CurrentToken->Previous->is(TT_BinaryOperator))
221 Contexts.back().IsExpression = true;
222 if (CurrentToken->is(tok::r_paren)) {
223 if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
224 (CurrentToken->Next->is(tok::l_paren) ||
225 (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
226 Left->Type = TT_FunctionTypeLParen;
227 Left->MatchingParen = CurrentToken;
228 CurrentToken->MatchingParen = Left;
230 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
231 Left->Previous && Left->Previous->is(tok::l_paren)) {
232 // Detect the case where macros are used to generate lambdas or
233 // function bodies, e.g.:
234 // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
235 for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
236 if (Tok->is(TT_BinaryOperator) &&
237 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
238 Tok->Type = TT_PointerOrReference;
242 if (StartsObjCMethodExpr) {
243 CurrentToken->Type = TT_ObjCMethodExpr;
244 if (Contexts.back().FirstObjCSelectorName) {
245 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
246 Contexts.back().LongestObjCSelectorName;
250 if (Left->is(TT_AttributeParen))
251 CurrentToken->Type = TT_AttributeParen;
252 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
253 CurrentToken->Type = TT_JavaAnnotation;
254 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
255 CurrentToken->Type = TT_LeadingJavaAnnotation;
257 if (!HasMultipleLines)
258 Left->PackingKind = PPK_Inconclusive;
259 else if (HasMultipleParametersOnALine)
260 Left->PackingKind = PPK_BinPacked;
262 Left->PackingKind = PPK_OnePerLine;
267 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
270 if (CurrentToken->is(tok::l_brace))
271 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
272 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
273 !CurrentToken->Next->HasUnescapedNewline &&
274 !CurrentToken->Next->isTrailingComment())
275 HasMultipleParametersOnALine = true;
276 if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
277 CurrentToken->Previous->isSimpleTypeSpecifier()) &&
278 !CurrentToken->is(tok::l_brace))
279 Contexts.back().IsExpression = false;
280 if (CurrentToken->isOneOf(tok::semi, tok::colon))
281 MightBeObjCForRangeLoop = false;
282 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
283 CurrentToken->Type = TT_ObjCForIn;
284 // When we discover a 'new', we set CanBeExpression to 'false' in order to
285 // parse the type correctly. Reset that after a comma.
286 if (CurrentToken->is(tok::comma))
287 Contexts.back().CanBeExpression = true;
289 FormatToken *Tok = CurrentToken;
292 updateParameterCount(Left, Tok);
293 if (CurrentToken && CurrentToken->HasUnescapedNewline)
294 HasMultipleLines = true;
303 // A '[' could be an index subscript (after an identifier or after
304 // ')' or ']'), it could be the start of an Objective-C method
305 // expression, or it could the start of an Objective-C array literal.
306 FormatToken *Left = CurrentToken->Previous;
307 Left->ParentBracket = Contexts.back().ContextKind;
308 FormatToken *Parent = Left->getPreviousNonComment();
310 // Cases where '>' is followed by '['.
311 // In C++, this can happen either in array of templates (foo<int>[10])
312 // or when array is a nested template type (unique_ptr<type1<type2>[]>).
313 bool CppArrayTemplates =
314 Style.isCpp() && Parent &&
315 Parent->is(TT_TemplateCloser) &&
316 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
317 Contexts.back().InTemplateArgument);
319 bool StartsObjCMethodExpr =
320 !CppArrayTemplates && Style.isCpp() &&
321 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
322 CurrentToken->isNot(tok::l_brace) &&
324 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
325 tok::kw_return, tok::kw_throw) ||
326 Parent->isUnaryOperator() ||
327 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
328 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
329 bool ColonFound = false;
331 unsigned BindingIncrease = 1;
332 if (Left->is(TT_Unknown)) {
333 if (StartsObjCMethodExpr) {
334 Left->Type = TT_ObjCMethodExpr;
335 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
336 Contexts.back().ContextKind == tok::l_brace &&
337 Parent->isOneOf(tok::l_brace, tok::comma)) {
338 Left->Type = TT_JsComputedPropertyName;
339 } else if (CurrentToken->is(tok::r_square) && Parent &&
340 Parent->is(TT_TemplateCloser)) {
341 Left->Type = TT_ArraySubscriptLSquare;
342 } else if (Style.Language == FormatStyle::LK_Proto ||
343 (!CppArrayTemplates && Parent &&
344 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
345 tok::comma, tok::l_paren, tok::l_square,
346 tok::question, tok::colon, tok::kw_return,
347 // Should only be relevant to JavaScript:
349 Left->Type = TT_ArrayInitializerLSquare;
351 BindingIncrease = 10;
352 Left->Type = TT_ArraySubscriptLSquare;
356 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
357 Contexts.back().IsExpression = true;
358 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
360 while (CurrentToken) {
361 if (CurrentToken->is(tok::r_square)) {
362 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
363 Left->is(TT_ObjCMethodExpr)) {
364 // An ObjC method call is rarely followed by an open parenthesis.
365 // FIXME: Do we incorrectly label ":" with this?
366 StartsObjCMethodExpr = false;
367 Left->Type = TT_Unknown;
369 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
370 CurrentToken->Type = TT_ObjCMethodExpr;
371 // determineStarAmpUsage() thinks that '*' '[' is allocating an
372 // array of pointers, but if '[' starts a selector then '*' is a
374 if (Parent && Parent->is(TT_PointerOrReference))
375 Parent->Type = TT_BinaryOperator;
377 Left->MatchingParen = CurrentToken;
378 CurrentToken->MatchingParen = Left;
379 if (Contexts.back().FirstObjCSelectorName) {
380 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
381 Contexts.back().LongestObjCSelectorName;
382 if (Left->BlockParameterCount > 1)
383 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
388 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
390 if (CurrentToken->is(tok::colon)) {
391 if (Left->is(TT_ArraySubscriptLSquare)) {
392 Left->Type = TT_ObjCMethodExpr;
393 StartsObjCMethodExpr = true;
394 Contexts.back().ColonIsObjCMethodExpr = true;
395 if (Parent && Parent->is(tok::r_paren))
396 Parent->Type = TT_CastRParen;
400 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
402 Left->Type = TT_ArrayInitializerLSquare;
403 FormatToken *Tok = CurrentToken;
406 updateParameterCount(Left, Tok);
413 FormatToken *Left = CurrentToken->Previous;
414 Left->ParentBracket = Contexts.back().ContextKind;
416 if (Contexts.back().CaretFound)
417 Left->Type = TT_ObjCBlockLBrace;
418 Contexts.back().CaretFound = false;
420 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
421 Contexts.back().ColonIsDictLiteral = true;
422 if (Left->BlockKind == BK_BracedInit)
423 Contexts.back().IsExpression = true;
425 while (CurrentToken) {
426 if (CurrentToken->is(tok::r_brace)) {
427 Left->MatchingParen = CurrentToken;
428 CurrentToken->MatchingParen = Left;
432 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
434 updateParameterCount(Left, CurrentToken);
435 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
436 FormatToken *Previous = CurrentToken->getPreviousNonComment();
437 if (((CurrentToken->is(tok::colon) &&
438 (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
439 Style.Language == FormatStyle::LK_Proto) &&
440 (Previous->Tok.getIdentifierInfo() ||
441 Previous->is(tok::string_literal)))
442 Previous->Type = TT_SelectorName;
443 if (CurrentToken->is(tok::colon) ||
444 Style.Language == FormatStyle::LK_JavaScript)
445 Left->Type = TT_DictLiteral;
447 if (CurrentToken->is(tok::comma) &&
448 Style.Language == FormatStyle::LK_JavaScript)
449 Left->Type = TT_DictLiteral;
457 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
458 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
459 ++Left->BlockParameterCount;
460 if (Current->is(tok::comma)) {
461 ++Left->ParameterCount;
463 Left->Role.reset(new CommaSeparatedList(Style));
464 Left->Role->CommaFound(Current);
465 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
466 Left->ParameterCount = 1;
470 bool parseConditional() {
471 while (CurrentToken) {
472 if (CurrentToken->is(tok::colon)) {
473 CurrentToken->Type = TT_ConditionalExpr;
483 bool parseTemplateDeclaration() {
484 if (CurrentToken && CurrentToken->is(tok::less)) {
485 CurrentToken->Type = TT_TemplateOpener;
490 CurrentToken->Previous->ClosesTemplateDeclaration = true;
496 bool consumeToken() {
497 FormatToken *Tok = CurrentToken;
499 switch (Tok->Tok.getKind()) {
502 if (!Tok->Previous && Line.MustBeDeclaration)
503 Tok->Type = TT_ObjCMethodSpecifier;
508 // Colons from ?: are handled in parseConditional().
509 if (Style.Language == FormatStyle::LK_JavaScript) {
510 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
511 (Contexts.size() == 1 && // switch/case labels
512 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
513 Contexts.back().ContextKind == tok::l_paren || // function params
514 Contexts.back().ContextKind == tok::l_square || // array type
515 (Contexts.size() == 1 &&
516 Line.MustBeDeclaration)) { // method/property declaration
517 Tok->Type = TT_JsTypeColon;
521 if (Contexts.back().ColonIsDictLiteral ||
522 Style.Language == FormatStyle::LK_Proto) {
523 Tok->Type = TT_DictLiteral;
524 } else if (Contexts.back().ColonIsObjCMethodExpr ||
525 Line.startsWith(TT_ObjCMethodSpecifier)) {
526 Tok->Type = TT_ObjCMethodExpr;
527 const FormatToken *BeforePrevious = Tok->Previous->Previous;
528 if (!BeforePrevious ||
529 !(BeforePrevious->is(TT_CastRParen) ||
530 (BeforePrevious->is(TT_ObjCMethodExpr) &&
531 BeforePrevious->is(tok::colon))) ||
532 BeforePrevious->is(tok::r_square) ||
533 Contexts.back().LongestObjCSelectorName == 0) {
534 Tok->Previous->Type = TT_SelectorName;
535 if (Tok->Previous->ColumnWidth >
536 Contexts.back().LongestObjCSelectorName)
537 Contexts.back().LongestObjCSelectorName =
538 Tok->Previous->ColumnWidth;
539 if (!Contexts.back().FirstObjCSelectorName)
540 Contexts.back().FirstObjCSelectorName = Tok->Previous;
542 } else if (Contexts.back().ColonIsForRangeExpr) {
543 Tok->Type = TT_RangeBasedForLoopColon;
544 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
545 Tok->Type = TT_BitFieldColon;
546 } else if (Contexts.size() == 1 &&
547 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
548 if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
550 Tok->Type = TT_CtorInitializerColon;
552 Tok->Type = TT_InheritanceColon;
553 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
554 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
555 // This handles a special macro in ObjC code where selectors including
556 // the colon are passed as macro arguments.
557 Tok->Type = TT_ObjCMethodExpr;
558 } else if (Contexts.back().ContextKind == tok::l_paren) {
559 Tok->Type = TT_InlineASMColon;
564 // | and & in declarations/type expressions represent union and
565 // intersection types, respectively.
566 if (Style.Language == FormatStyle::LK_JavaScript &&
567 !Contexts.back().IsExpression)
568 Tok->Type = TT_JsTypeOperator;
572 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
574 if (!parseParens(/*LookForDecls=*/true))
579 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Previous &&
580 Tok->Previous->is(tok::period))
582 Contexts.back().ColonIsForRangeExpr = true;
588 // When faced with 'operator()()', the kw_operator handler incorrectly
589 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
590 // the first two parens OverloadedOperators and the second l_paren an
591 // OverloadedOperatorLParen.
593 Tok->Previous->is(tok::r_paren) &&
594 Tok->Previous->MatchingParen &&
595 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
596 Tok->Previous->Type = TT_OverloadedOperator;
597 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
598 Tok->Type = TT_OverloadedOperatorLParen;
603 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
604 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
606 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
607 TT_LeadingJavaAnnotation)))
608 Line.MightBeFunctionDecl = true;
620 Tok->Type = TT_TemplateOpener;
622 Tok->Type = TT_BinaryOperator;
623 NonTemplateLess.insert(Tok);
632 // Lines can start with '}'.
637 Tok->Type = TT_BinaryOperator;
639 case tok::kw_operator:
640 while (CurrentToken &&
641 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
642 if (CurrentToken->isOneOf(tok::star, tok::amp))
643 CurrentToken->Type = TT_PointerOrReference;
646 CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma))
647 CurrentToken->Previous->Type = TT_OverloadedOperator;
650 CurrentToken->Type = TT_OverloadedOperatorLParen;
651 if (CurrentToken->Previous->is(TT_BinaryOperator))
652 CurrentToken->Previous->Type = TT_OverloadedOperator;
656 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
657 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
659 // Question marks before semicolons, colons, etc. indicate optional
660 // types (fields, parameters), e.g.
661 // function(x?: string, y?) {...}
663 Tok->Type = TT_JsTypeOptionalQuestion;
666 // Declarations cannot be conditional expressions, this can only be part
667 // of a type declaration.
668 if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
669 Style.Language == FormatStyle::LK_JavaScript)
673 case tok::kw_template:
674 parseTemplateDeclaration();
677 if (Contexts.back().InCtorInitializer)
678 Tok->Type = TT_CtorInitializerComma;
679 else if (Contexts.back().InInheritanceList)
680 Tok->Type = TT_InheritanceComma;
681 else if (Contexts.back().FirstStartOfName &&
682 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
683 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
684 Line.IsMultiVariableDeclStmt = true;
686 if (Contexts.back().IsForEachMacro)
687 Contexts.back().IsExpression = true;
689 case tok::identifier:
690 if (Tok->isOneOf(Keywords.kw___has_include,
691 Keywords.kw___has_include_next)) {
701 void parseIncludeDirective() {
702 if (CurrentToken && CurrentToken->is(tok::less)) {
704 while (CurrentToken) {
705 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
706 CurrentToken->Type = TT_ImplicitStringLiteral;
712 void parseWarningOrError() {
714 // We still want to format the whitespace left of the first token of the
717 while (CurrentToken) {
718 CurrentToken->Type = TT_ImplicitStringLiteral;
724 next(); // Consume "pragma".
726 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
727 bool IsMark = CurrentToken->is(Keywords.kw_mark);
728 next(); // Consume "mark".
729 next(); // Consume first token (so we fix leading whitespace).
730 while (CurrentToken) {
731 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
732 CurrentToken->Type = TT_ImplicitStringLiteral;
738 void parseHasInclude() {
739 if (!CurrentToken || !CurrentToken->is(tok::l_paren))
742 parseIncludeDirective();
746 LineType parsePreprocessorDirective() {
747 bool IsFirstToken = CurrentToken->IsFirst;
748 LineType Type = LT_PreprocessorDirective;
753 if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
754 // JavaScript files can contain shebang lines of the form:
755 // #!/usr/bin/env node
756 // Treat these like C++ #include directives.
757 while (CurrentToken) {
758 // Tokens cannot be comments here.
759 CurrentToken->Type = TT_ImplicitStringLiteral;
762 return LT_ImportStatement;
765 if (CurrentToken->Tok.is(tok::numeric_constant)) {
766 CurrentToken->SpacesRequiredBefore = 1;
769 // Hashes in the middle of a line can lead to any strange token
771 if (!CurrentToken->Tok.getIdentifierInfo())
773 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
774 case tok::pp_include:
775 case tok::pp_include_next:
778 parseIncludeDirective();
779 Type = LT_ImportStatement;
782 case tok::pp_warning:
783 parseWarningOrError();
790 Contexts.back().IsExpression = true;
796 while (CurrentToken) {
797 FormatToken *Tok = CurrentToken;
799 if (Tok->is(tok::l_paren))
801 else if (Tok->isOneOf(Keywords.kw___has_include,
802 Keywords.kw___has_include_next))
809 LineType parseLine() {
810 NonTemplateLess.clear();
811 if (CurrentToken->is(tok::hash))
812 return parsePreprocessorDirective();
814 // Directly allow to 'import <string-literal>' to support protocol buffer
815 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
816 // should not break the line).
817 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
818 if ((Style.Language == FormatStyle::LK_Java &&
819 CurrentToken->is(Keywords.kw_package)) ||
820 (Info && Info->getPPKeywordID() == tok::pp_import &&
821 CurrentToken->Next &&
822 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
825 parseIncludeDirective();
826 return LT_ImportStatement;
829 // If this line starts and ends in '<' and '>', respectively, it is likely
830 // part of "#define <a/b.h>".
831 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
832 parseIncludeDirective();
833 return LT_ImportStatement;
836 // In .proto files, top-level options are very similar to import statements
837 // and should not be line-wrapped.
838 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
839 CurrentToken->is(Keywords.kw_option)) {
841 if (CurrentToken && CurrentToken->is(tok::identifier))
842 return LT_ImportStatement;
845 bool KeywordVirtualFound = false;
846 bool ImportStatement = false;
848 // import {...} from '...';
849 if (Style.Language == FormatStyle::LK_JavaScript &&
850 CurrentToken->is(Keywords.kw_import))
851 ImportStatement = true;
853 while (CurrentToken) {
854 if (CurrentToken->is(tok::kw_virtual))
855 KeywordVirtualFound = true;
856 if (Style.Language == FormatStyle::LK_JavaScript) {
857 // export {...} from '...';
858 // An export followed by "from 'some string';" is a re-export from
859 // another module identified by a URI and is treated as a
860 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
861 // Just "export {...};" or "export class ..." should not be treated as
862 // an import in this sense.
863 if (Line.First->is(tok::kw_export) &&
864 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
865 CurrentToken->Next->isStringLiteral())
866 ImportStatement = true;
867 if (isClosureImportStatement(*CurrentToken))
868 ImportStatement = true;
873 if (KeywordVirtualFound)
874 return LT_VirtualFunctionDecl;
876 return LT_ImportStatement;
878 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
879 if (Contexts.back().FirstObjCSelectorName)
880 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
881 Contexts.back().LongestObjCSelectorName;
882 return LT_ObjCMethodDecl;
889 bool isClosureImportStatement(const FormatToken &Tok) {
890 // FIXME: Closure-library specific stuff should not be hard-coded but be
892 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
893 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
894 Tok.Next->Next->TokenText == "provide" ||
895 Tok.Next->Next->TokenText == "require" ||
896 Tok.Next->Next->TokenText == "setTestOnly" ||
897 Tok.Next->Next->TokenText == "forwardDeclare") &&
898 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
901 void resetTokenMetadata(FormatToken *Token) {
905 // Reset token type in case we have already looked at it and then
906 // recovered from an error (e.g. failure to find the matching >).
907 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
908 TT_FunctionLBrace, TT_ImplicitStringLiteral,
909 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
910 TT_OverloadedOperator, TT_RegexLiteral,
911 TT_TemplateString, TT_ObjCStringLiteral))
912 CurrentToken->Type = TT_Unknown;
913 CurrentToken->Role.reset();
914 CurrentToken->MatchingParen = nullptr;
915 CurrentToken->FakeLParens.clear();
916 CurrentToken->FakeRParens = 0;
921 CurrentToken->NestingLevel = Contexts.size() - 1;
922 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
923 modifyContext(*CurrentToken);
924 determineTokenType(*CurrentToken);
925 CurrentToken = CurrentToken->Next;
928 resetTokenMetadata(CurrentToken);
931 /// \brief A struct to hold information valid in a specific context, e.g.
932 /// a pair of parenthesis.
934 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
936 : ContextKind(ContextKind), BindingStrength(BindingStrength),
937 IsExpression(IsExpression) {}
939 tok::TokenKind ContextKind;
940 unsigned BindingStrength;
942 unsigned LongestObjCSelectorName = 0;
943 bool ColonIsForRangeExpr = false;
944 bool ColonIsDictLiteral = false;
945 bool ColonIsObjCMethodExpr = false;
946 FormatToken *FirstObjCSelectorName = nullptr;
947 FormatToken *FirstStartOfName = nullptr;
948 bool CanBeExpression = true;
949 bool InTemplateArgument = false;
950 bool InCtorInitializer = false;
951 bool InInheritanceList = false;
952 bool CaretFound = false;
953 bool IsForEachMacro = false;
956 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
957 /// of each instance.
958 struct ScopedContextCreator {
961 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
964 P.Contexts.push_back(Context(ContextKind,
965 P.Contexts.back().BindingStrength + Increase,
966 P.Contexts.back().IsExpression));
969 ~ScopedContextCreator() { P.Contexts.pop_back(); }
972 void modifyContext(const FormatToken &Current) {
973 if (Current.getPrecedence() == prec::Assignment &&
974 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
975 // Type aliases use `type X = ...;` in TypeScript.
976 !(Style.Language == FormatStyle::LK_JavaScript &&
977 Line.startsWith(Keywords.kw_type, tok::identifier)) &&
978 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
979 Contexts.back().IsExpression = true;
980 if (!Line.startsWith(TT_UnaryOperator)) {
981 for (FormatToken *Previous = Current.Previous;
982 Previous && Previous->Previous &&
983 !Previous->Previous->isOneOf(tok::comma, tok::semi);
984 Previous = Previous->Previous) {
985 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
986 Previous = Previous->MatchingParen;
990 if (Previous->opensScope())
992 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
993 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
994 Previous->Previous && Previous->Previous->isNot(tok::equal))
995 Previous->Type = TT_PointerOrReference;
998 } else if (Current.is(tok::lessless) &&
999 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1000 Contexts.back().IsExpression = true;
1001 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1002 Contexts.back().IsExpression = true;
1003 } else if (Current.is(TT_TrailingReturnArrow)) {
1004 Contexts.back().IsExpression = false;
1005 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1006 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1007 } else if (Current.Previous &&
1008 Current.Previous->is(TT_CtorInitializerColon)) {
1009 Contexts.back().IsExpression = true;
1010 Contexts.back().InCtorInitializer = true;
1011 } else if (Current.Previous &&
1012 Current.Previous->is(TT_InheritanceColon)) {
1013 Contexts.back().InInheritanceList = true;
1014 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1015 for (FormatToken *Previous = Current.Previous;
1016 Previous && Previous->isOneOf(tok::star, tok::amp);
1017 Previous = Previous->Previous)
1018 Previous->Type = TT_PointerOrReference;
1019 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1020 Contexts.back().IsExpression = false;
1021 } else if (Current.is(tok::kw_new)) {
1022 Contexts.back().CanBeExpression = false;
1023 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
1024 // This should be the condition or increment in a for-loop.
1025 Contexts.back().IsExpression = true;
1029 void determineTokenType(FormatToken &Current) {
1030 if (!Current.is(TT_Unknown))
1031 // The token type is already known.
1034 if (Style.Language == FormatStyle::LK_JavaScript) {
1035 if (Current.is(tok::exclaim)) {
1036 if (Current.Previous &&
1037 (Current.Previous->isOneOf(tok::identifier, tok::r_paren,
1038 tok::r_square, tok::r_brace) ||
1039 Current.Previous->Tok.isLiteral())) {
1040 Current.Type = TT_JsNonNullAssertion;
1044 Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1045 Current.Type = TT_JsNonNullAssertion;
1051 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1052 // function declaration have been found. In this case, 'Current' is a
1053 // trailing token of this declaration and thus cannot be a name.
1054 if (Current.is(Keywords.kw_instanceof)) {
1055 Current.Type = TT_BinaryOperator;
1056 } else if (isStartOfName(Current) &&
1057 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1058 Contexts.back().FirstStartOfName = &Current;
1059 Current.Type = TT_StartOfName;
1060 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1062 } else if (Current.is(tok::arrow) &&
1063 Style.Language == FormatStyle::LK_Java) {
1064 Current.Type = TT_LambdaArrow;
1065 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1066 Current.NestingLevel == 0) {
1067 Current.Type = TT_TrailingReturnArrow;
1068 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1070 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
1071 Contexts.back().IsExpression,
1072 Contexts.back().InTemplateArgument);
1073 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1074 Current.Type = determinePlusMinusCaretUsage(Current);
1075 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1076 Contexts.back().CaretFound = true;
1077 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1078 Current.Type = determineIncrementUsage(Current);
1079 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1080 Current.Type = TT_UnaryOperator;
1081 } else if (Current.is(tok::question)) {
1082 if (Style.Language == FormatStyle::LK_JavaScript &&
1083 Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1084 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1085 // on the interface, not a ternary expression.
1086 Current.Type = TT_JsTypeOptionalQuestion;
1088 Current.Type = TT_ConditionalExpr;
1090 } else if (Current.isBinaryOperator() &&
1091 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
1092 Current.Type = TT_BinaryOperator;
1093 } else if (Current.is(tok::comment)) {
1094 if (Current.TokenText.startswith("/*")) {
1095 if (Current.TokenText.endswith("*/"))
1096 Current.Type = TT_BlockComment;
1098 // The lexer has for some reason determined a comment here. But we
1099 // cannot really handle it, if it isn't properly terminated.
1100 Current.Tok.setKind(tok::unknown);
1102 Current.Type = TT_LineComment;
1104 } else if (Current.is(tok::r_paren)) {
1105 if (rParenEndsCast(Current))
1106 Current.Type = TT_CastRParen;
1107 if (Current.MatchingParen && Current.Next &&
1108 !Current.Next->isBinaryOperator() &&
1109 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1110 tok::comma, tok::period, tok::arrow,
1112 if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1113 // Make sure this isn't the return type of an Obj-C block declaration
1114 if (AfterParen->Tok.isNot(tok::caret)) {
1115 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1116 if (BeforeParen->is(tok::identifier) &&
1117 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1118 (!BeforeParen->Previous ||
1119 BeforeParen->Previous->ClosesTemplateDeclaration))
1120 Current.Type = TT_FunctionAnnotationRParen;
1123 } else if (Current.is(tok::at) && Current.Next) {
1124 switch (Current.Next->Tok.getObjCKeywordID()) {
1125 case tok::objc_interface:
1126 case tok::objc_implementation:
1127 case tok::objc_protocol:
1128 Current.Type = TT_ObjCDecl;
1130 case tok::objc_property:
1131 Current.Type = TT_ObjCProperty;
1136 } else if (Current.is(tok::period)) {
1137 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1138 if (PreviousNoComment &&
1139 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1140 Current.Type = TT_DesignatedInitializerPeriod;
1141 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1142 Current.Previous->isOneOf(TT_JavaAnnotation,
1143 TT_LeadingJavaAnnotation)) {
1144 Current.Type = Current.Previous->Type;
1146 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1148 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1149 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1150 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1151 // function declaration have been found.
1152 Current.Type = TT_TrailingAnnotation;
1153 } else if ((Style.Language == FormatStyle::LK_Java ||
1154 Style.Language == FormatStyle::LK_JavaScript) &&
1156 if (Current.Previous->is(tok::at) &&
1157 Current.isNot(Keywords.kw_interface)) {
1158 const FormatToken &AtToken = *Current.Previous;
1159 const FormatToken *Previous = AtToken.getPreviousNonComment();
1160 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1161 Current.Type = TT_LeadingJavaAnnotation;
1163 Current.Type = TT_JavaAnnotation;
1164 } else if (Current.Previous->is(tok::period) &&
1165 Current.Previous->isOneOf(TT_JavaAnnotation,
1166 TT_LeadingJavaAnnotation)) {
1167 Current.Type = Current.Previous->Type;
1172 /// \brief Take a guess at whether \p Tok starts a name of a function or
1173 /// variable declaration.
1175 /// This is a heuristic based on whether \p Tok is an identifier following
1176 /// something that is likely a type.
1177 bool isStartOfName(const FormatToken &Tok) {
1178 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1181 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1184 if (Style.Language == FormatStyle::LK_JavaScript &&
1185 Tok.Previous->is(Keywords.kw_in))
1188 // Skip "const" as it does not have an influence on whether this is a name.
1189 FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1190 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1191 PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1193 if (!PreviousNotConst)
1196 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1197 PreviousNotConst->Previous &&
1198 PreviousNotConst->Previous->is(tok::hash);
1200 if (PreviousNotConst->is(TT_TemplateCloser))
1201 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1202 PreviousNotConst->MatchingParen->Previous &&
1203 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1204 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1206 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1207 PreviousNotConst->MatchingParen->Previous &&
1208 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1211 return (!IsPPKeyword &&
1212 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1213 PreviousNotConst->is(TT_PointerOrReference) ||
1214 PreviousNotConst->isSimpleTypeSpecifier();
1217 /// \brief Determine whether ')' is ending a cast.
1218 bool rParenEndsCast(const FormatToken &Tok) {
1219 // C-style casts are only used in C++ and Java.
1220 if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
1223 // Empty parens aren't casts and there are no casts at the end of the line.
1224 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1227 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1229 // If there is a closing parenthesis left of the current parentheses,
1230 // look past it as these might be chained casts.
1231 if (LeftOfParens->is(tok::r_paren)) {
1232 if (!LeftOfParens->MatchingParen ||
1233 !LeftOfParens->MatchingParen->Previous)
1235 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1238 // If there is an identifier (or with a few exceptions a keyword) right
1239 // before the parentheses, this is unlikely to be a cast.
1240 if (LeftOfParens->Tok.getIdentifierInfo() &&
1241 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1245 // Certain other tokens right before the parentheses are also signals that
1246 // this cannot be a cast.
1247 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1248 TT_TemplateCloser, tok::ellipsis))
1252 if (Tok.Next->is(tok::question))
1255 // As Java has no function types, a "(" after the ")" likely means that this
1257 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1260 // If a (non-string) literal follows, this is likely a cast.
1261 if (Tok.Next->isNot(tok::string_literal) &&
1262 (Tok.Next->Tok.isLiteral() ||
1263 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1266 // Heuristically try to determine whether the parentheses contain a type.
1267 bool ParensAreType =
1269 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1270 Tok.Previous->isSimpleTypeSpecifier();
1271 bool ParensCouldEndDecl =
1272 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1273 if (ParensAreType && !ParensCouldEndDecl)
1276 // At this point, we heuristically assume that there are no casts at the
1277 // start of the line. We assume that we have found most cases where there
1278 // are by the logic above, e.g. "(void)x;".
1282 // Certain token types inside the parentheses mean that this can't be a
1284 for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1285 Token = Token->Next)
1286 if (Token->is(TT_BinaryOperator))
1289 // If the following token is an identifier or 'this', this is a cast. All
1290 // cases where this can be something else are handled above.
1291 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1294 if (!Tok.Next->Next)
1297 // If the next token after the parenthesis is a unary operator, assume
1298 // that this is cast, unless there are unexpected tokens inside the
1301 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1302 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1303 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1305 // Search for unexpected tokens.
1306 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1307 Prev = Prev->Previous) {
1308 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1314 /// \brief Return the type of the given token assuming it is * or &.
1315 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1316 bool InTemplateArgument) {
1317 if (Style.Language == FormatStyle::LK_JavaScript)
1318 return TT_BinaryOperator;
1320 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1322 return TT_UnaryOperator;
1324 const FormatToken *NextToken = Tok.getNextNonComment();
1326 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
1327 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1328 return TT_PointerOrReference;
1330 if (PrevToken->is(tok::coloncolon))
1331 return TT_PointerOrReference;
1333 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1334 tok::comma, tok::semi, tok::kw_return, tok::colon,
1335 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1336 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1337 TT_UnaryOperator, TT_CastRParen))
1338 return TT_UnaryOperator;
1340 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1341 return TT_PointerOrReference;
1342 if (NextToken->is(tok::kw_operator) && !IsExpression)
1343 return TT_PointerOrReference;
1344 if (NextToken->isOneOf(tok::comma, tok::semi))
1345 return TT_PointerOrReference;
1347 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1348 PrevToken->MatchingParen->Previous &&
1349 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1351 return TT_PointerOrReference;
1353 if (PrevToken->Tok.isLiteral() ||
1354 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1355 tok::kw_false, tok::r_brace) ||
1356 NextToken->Tok.isLiteral() ||
1357 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1358 NextToken->isUnaryOperator() ||
1359 // If we know we're in a template argument, there are no named
1360 // declarations. Thus, having an identifier on the right-hand side
1361 // indicates a binary operator.
1362 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1363 return TT_BinaryOperator;
1365 // "&&(" is quite unlikely to be two successive unary "&".
1366 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1367 return TT_BinaryOperator;
1369 // This catches some cases where evaluation order is used as control flow:
1371 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1372 if (NextNextToken && NextNextToken->is(tok::arrow))
1373 return TT_BinaryOperator;
1375 // It is very unlikely that we are going to find a pointer or reference type
1376 // definition on the RHS of an assignment.
1377 if (IsExpression && !Contexts.back().CaretFound)
1378 return TT_BinaryOperator;
1380 return TT_PointerOrReference;
1383 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1384 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1386 return TT_UnaryOperator;
1388 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
1389 !PrevToken->is(tok::exclaim))
1390 // There aren't any trailing unary operators except for TypeScript's
1391 // non-null operator (!). Thus, this must be squence of leading operators.
1392 return TT_UnaryOperator;
1394 // Use heuristics to recognize unary operators.
1395 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1396 tok::question, tok::colon, tok::kw_return,
1397 tok::kw_case, tok::at, tok::l_brace))
1398 return TT_UnaryOperator;
1400 // There can't be two consecutive binary operators.
1401 if (PrevToken->is(TT_BinaryOperator))
1402 return TT_UnaryOperator;
1404 // Fall back to marking the token as binary operator.
1405 return TT_BinaryOperator;
1408 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1409 TokenType determineIncrementUsage(const FormatToken &Tok) {
1410 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1411 if (!PrevToken || PrevToken->is(TT_CastRParen))
1412 return TT_UnaryOperator;
1413 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1414 return TT_TrailingUnaryOperator;
1416 return TT_UnaryOperator;
1419 SmallVector<Context, 8> Contexts;
1421 const FormatStyle &Style;
1422 AnnotatedLine &Line;
1423 FormatToken *CurrentToken;
1425 const AdditionalKeywords &Keywords;
1427 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1428 // determines that a specific token can't be a template opener, it will make
1429 // same decision irrespective of the decisions for tokens leading up to it.
1430 // Store this information to prevent this from causing exponential runtime.
1431 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1434 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1435 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1437 /// \brief Parses binary expressions by inserting fake parenthesis based on
1438 /// operator precedence.
1439 class ExpressionParser {
1441 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1442 AnnotatedLine &Line)
1443 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1445 /// \brief Parse expressions with the given operatore precedence.
1446 void parse(int Precedence = 0) {
1447 // Skip 'return' and ObjC selector colons as they are not part of a binary
1449 while (Current && (Current->is(tok::kw_return) ||
1450 (Current->is(tok::colon) &&
1451 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1454 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1457 // Conditional expressions need to be parsed separately for proper nesting.
1458 if (Precedence == prec::Conditional) {
1459 parseConditionalExpr();
1463 // Parse unary operators, which all have a higher precedence than binary
1465 if (Precedence == PrecedenceUnaryOperator) {
1466 parseUnaryOperator();
1470 FormatToken *Start = Current;
1471 FormatToken *LatestOperator = nullptr;
1472 unsigned OperatorIndex = 0;
1475 // Consume operators with higher precedence.
1476 parse(Precedence + 1);
1478 int CurrentPrecedence = getCurrentPrecedence();
1480 if (Current && Current->is(TT_SelectorName) &&
1481 Precedence == CurrentPrecedence) {
1483 addFakeParenthesis(Start, prec::Level(Precedence));
1487 // At the end of the line or when an operator with higher precedence is
1488 // found, insert fake parenthesis and return.
1490 (Current->closesScope() &&
1491 (Current->MatchingParen || Current->is(TT_TemplateString))) ||
1492 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1493 (CurrentPrecedence == prec::Conditional &&
1494 Precedence == prec::Assignment && Current->is(tok::colon))) {
1498 // Consume scopes: (), [], <> and {}
1499 if (Current->opensScope()) {
1500 // In fragment of a JavaScript template string can look like '}..${' and
1501 // thus close a scope and open a new one at the same time.
1502 while (Current && (!Current->closesScope() || Current->opensScope())) {
1509 if (CurrentPrecedence == Precedence) {
1511 LatestOperator->NextOperator = Current;
1512 LatestOperator = Current;
1513 Current->OperatorIndex = OperatorIndex;
1516 next(/*SkipPastLeadingComments=*/Precedence > 0);
1520 if (LatestOperator && (Current || Precedence > 0)) {
1521 // LatestOperator->LastOperator = true;
1522 if (Precedence == PrecedenceArrowAndPeriod) {
1523 // Call expressions don't have a binary operator precedence.
1524 addFakeParenthesis(Start, prec::Unknown);
1526 addFakeParenthesis(Start, prec::Level(Precedence));
1532 /// \brief Gets the precedence (+1) of the given token for binary operators
1533 /// and other tokens that we treat like binary operators.
1534 int getCurrentPrecedence() {
1536 const FormatToken *NextNonComment = Current->getNextNonComment();
1537 if (Current->is(TT_ConditionalExpr))
1538 return prec::Conditional;
1539 if (NextNonComment && NextNonComment->is(tok::colon) &&
1540 NextNonComment->is(TT_DictLiteral))
1541 return prec::Assignment;
1542 if (Current->is(TT_JsComputedPropertyName))
1543 return prec::Assignment;
1544 if (Current->is(TT_LambdaArrow))
1546 if (Current->is(TT_JsFatArrow))
1547 return prec::Assignment;
1548 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
1549 (Current->is(tok::comment) && NextNonComment &&
1550 NextNonComment->is(TT_SelectorName)))
1552 if (Current->is(TT_RangeBasedForLoopColon))
1554 if ((Style.Language == FormatStyle::LK_Java ||
1555 Style.Language == FormatStyle::LK_JavaScript) &&
1556 Current->is(Keywords.kw_instanceof))
1557 return prec::Relational;
1558 if (Style.Language == FormatStyle::LK_JavaScript &&
1559 Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
1560 return prec::Relational;
1561 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1562 return Current->getPrecedence();
1563 if (Current->isOneOf(tok::period, tok::arrow))
1564 return PrecedenceArrowAndPeriod;
1565 if ((Style.Language == FormatStyle::LK_Java ||
1566 Style.Language == FormatStyle::LK_JavaScript) &&
1567 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1568 Keywords.kw_throws))
1574 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1575 Start->FakeLParens.push_back(Precedence);
1576 if (Precedence > prec::Unknown)
1577 Start->StartsBinaryExpression = true;
1579 FormatToken *Previous = Current->Previous;
1580 while (Previous->is(tok::comment) && Previous->Previous)
1581 Previous = Previous->Previous;
1582 ++Previous->FakeRParens;
1583 if (Precedence > prec::Unknown)
1584 Previous->EndsBinaryExpression = true;
1588 /// \brief Parse unary operator expressions and surround them with fake
1589 /// parentheses if appropriate.
1590 void parseUnaryOperator() {
1591 if (!Current || Current->isNot(TT_UnaryOperator)) {
1592 parse(PrecedenceArrowAndPeriod);
1596 FormatToken *Start = Current;
1598 parseUnaryOperator();
1600 // The actual precedence doesn't matter.
1601 addFakeParenthesis(Start, prec::Unknown);
1604 void parseConditionalExpr() {
1605 while (Current && Current->isTrailingComment()) {
1608 FormatToken *Start = Current;
1609 parse(prec::LogicalOr);
1610 if (!Current || !Current->is(tok::question))
1613 parse(prec::Assignment);
1614 if (!Current || Current->isNot(TT_ConditionalExpr))
1617 parse(prec::Assignment);
1618 addFakeParenthesis(Start, prec::Conditional);
1621 void next(bool SkipPastLeadingComments = true) {
1623 Current = Current->Next;
1625 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1626 Current->isTrailingComment())
1627 Current = Current->Next;
1630 const FormatStyle &Style;
1631 const AdditionalKeywords &Keywords;
1632 FormatToken *Current;
1635 } // end anonymous namespace
1637 void TokenAnnotator::setCommentLineLevels(
1638 SmallVectorImpl<AnnotatedLine *> &Lines) {
1639 const AnnotatedLine *NextNonCommentLine = nullptr;
1640 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1643 bool CommentLine = (*I)->First;
1644 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
1645 if (!Tok->is(tok::comment)) {
1646 CommentLine = false;
1650 if (NextNonCommentLine && CommentLine)
1651 (*I)->Level = NextNonCommentLine->Level;
1653 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1655 setCommentLineLevels((*I)->Children);
1659 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
1660 unsigned Result = 0;
1661 for (const auto* Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
1662 Result = std::max(Result, Tok->NestingLevel);
1666 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1667 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1668 E = Line.Children.end();
1672 AnnotatingParser Parser(Style, Line, Keywords);
1673 Line.Type = Parser.parseLine();
1675 // With very deep nesting, ExpressionParser uses lots of stack and the
1676 // formatting algorithm is very slow. We're not going to do a good job here
1677 // anyway - it's probably generated code being formatted by mistake.
1678 // Just skip the whole line.
1679 if (maxNestingDepth(Line) > 50)
1680 Line.Type = LT_Invalid;
1682 if (Line.Type == LT_Invalid)
1685 ExpressionParser ExprParser(Style, Keywords, Line);
1688 if (Line.startsWith(TT_ObjCMethodSpecifier))
1689 Line.Type = LT_ObjCMethodDecl;
1690 else if (Line.startsWith(TT_ObjCDecl))
1691 Line.Type = LT_ObjCDecl;
1692 else if (Line.startsWith(TT_ObjCProperty))
1693 Line.Type = LT_ObjCProperty;
1695 Line.First->SpacesRequiredBefore = 1;
1696 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1699 // This function heuristically determines whether 'Current' starts the name of a
1700 // function declaration.
1701 static bool isFunctionDeclarationName(const FormatToken &Current,
1702 const AnnotatedLine &Line) {
1703 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1704 for (; Next; Next = Next->Next) {
1705 if (Next->is(TT_OverloadedOperatorLParen))
1707 if (Next->is(TT_OverloadedOperator))
1709 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1710 // For 'new[]' and 'delete[]'.
1711 if (Next->Next && Next->Next->is(tok::l_square) &&
1712 Next->Next->Next && Next->Next->Next->is(tok::r_square))
1713 Next = Next->Next->Next;
1722 // Find parentheses of parameter list.
1723 const FormatToken *Next = Current.Next;
1724 if (Current.is(tok::kw_operator)) {
1725 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1727 Next = skipOperatorName(Next);
1729 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1731 for (; Next; Next = Next->Next) {
1732 if (Next->is(TT_TemplateOpener)) {
1733 Next = Next->MatchingParen;
1734 } else if (Next->is(tok::coloncolon)) {
1738 if (Next->is(tok::kw_operator)) {
1739 Next = skipOperatorName(Next->Next);
1742 if (!Next->is(tok::identifier))
1744 } else if (Next->is(tok::l_paren)) {
1752 // Check whether parameter list can belong to a function declaration.
1753 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
1755 // If the lines ends with "{", this is likely an function definition.
1756 if (Line.Last->is(tok::l_brace))
1758 if (Next->Next == Next->MatchingParen)
1759 return true; // Empty parentheses.
1760 // If there is an &/&& after the r_paren, this is likely a function.
1761 if (Next->MatchingParen->Next &&
1762 Next->MatchingParen->Next->is(TT_PointerOrReference))
1764 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1766 if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
1767 Tok = Tok->MatchingParen;
1770 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1771 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
1773 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1774 Tok->Tok.isLiteral())
1780 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1781 assert(Line.MightBeFunctionDecl);
1783 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1784 Style.AlwaysBreakAfterReturnType ==
1785 FormatStyle::RTBS_TopLevelDefinitions) &&
1789 switch (Style.AlwaysBreakAfterReturnType) {
1790 case FormatStyle::RTBS_None:
1792 case FormatStyle::RTBS_All:
1793 case FormatStyle::RTBS_TopLevel:
1795 case FormatStyle::RTBS_AllDefinitions:
1796 case FormatStyle::RTBS_TopLevelDefinitions:
1797 return Line.mightBeFunctionDefinition();
1803 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1804 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1805 E = Line.Children.end();
1807 calculateFormattingInformation(**I);
1810 Line.First->TotalLength =
1811 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1812 FormatToken *Current = Line.First->Next;
1813 bool InFunctionDecl = Line.MightBeFunctionDecl;
1815 if (isFunctionDeclarationName(*Current, Line))
1816 Current->Type = TT_FunctionDeclarationName;
1817 if (Current->is(TT_LineComment)) {
1818 if (Current->Previous->BlockKind == BK_BracedInit &&
1819 Current->Previous->opensScope())
1820 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1822 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1824 // If we find a trailing comment, iterate backwards to determine whether
1825 // it seems to relate to a specific parameter. If so, break before that
1826 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1827 // to the previous line in:
1831 if (!Current->HasUnescapedNewline) {
1832 for (FormatToken *Parameter = Current->Previous; Parameter;
1833 Parameter = Parameter->Previous) {
1834 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1836 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1837 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1838 Parameter->HasUnescapedNewline)
1839 Parameter->MustBreakBefore = true;
1844 } else if (Current->SpacesRequiredBefore == 0 &&
1845 spaceRequiredBefore(Line, *Current)) {
1846 Current->SpacesRequiredBefore = 1;
1849 Current->MustBreakBefore =
1850 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1852 if (!Current->MustBreakBefore && InFunctionDecl &&
1853 Current->is(TT_FunctionDeclarationName))
1854 Current->MustBreakBefore = mustBreakForReturnType(Line);
1856 Current->CanBreakBefore =
1857 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1858 unsigned ChildSize = 0;
1859 if (Current->Previous->Children.size() == 1) {
1860 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1861 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1862 : LastOfChild.TotalLength + 1;
1864 const FormatToken *Prev = Current->Previous;
1865 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1866 (Prev->Children.size() == 1 &&
1867 Prev->Children[0]->First->MustBreakBefore) ||
1868 Current->IsMultiline)
1869 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1871 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1872 ChildSize + Current->SpacesRequiredBefore;
1874 if (Current->is(TT_CtorInitializerColon))
1875 InFunctionDecl = false;
1877 // FIXME: Only calculate this if CanBreakBefore is true once static
1878 // initializers etc. are sorted out.
1879 // FIXME: Move magic numbers to a better place.
1880 Current->SplitPenalty = 20 * Current->BindingStrength +
1881 splitPenalty(Line, *Current, InFunctionDecl);
1883 Current = Current->Next;
1886 calculateUnbreakableTailLengths(Line);
1887 unsigned IndentLevel = Line.Level;
1888 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1890 Current->Role->precomputeFormattingInfos(Current);
1891 if (Current->MatchingParen &&
1892 Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
1893 assert(IndentLevel > 0);
1896 Current->IndentLevel = IndentLevel;
1897 if (Current->opensBlockOrBlockTypeList(Style))
1901 DEBUG({ printDebugInfo(Line); });
1904 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1905 unsigned UnbreakableTailLength = 0;
1906 FormatToken *Current = Line.Last;
1908 Current->UnbreakableTailLength = UnbreakableTailLength;
1909 if (Current->CanBreakBefore ||
1910 Current->isOneOf(tok::comment, tok::string_literal)) {
1911 UnbreakableTailLength = 0;
1913 UnbreakableTailLength +=
1914 Current->ColumnWidth + Current->SpacesRequiredBefore;
1916 Current = Current->Previous;
1920 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1921 const FormatToken &Tok,
1922 bool InFunctionDecl) {
1923 const FormatToken &Left = *Tok.Previous;
1924 const FormatToken &Right = Tok;
1926 if (Left.is(tok::semi))
1929 if (Style.Language == FormatStyle::LK_Java) {
1930 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1932 if (Right.is(Keywords.kw_implements))
1934 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1936 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1937 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1939 if (Left.is(TT_JsTypeColon))
1941 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
1942 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
1946 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
1948 if (Right.is(tok::l_square)) {
1949 if (Style.Language == FormatStyle::LK_Proto)
1951 if (Left.is(tok::r_square))
1953 // Slightly prefer formatting local lambda definitions like functions.
1954 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1956 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1957 TT_ArrayInitializerLSquare))
1961 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1962 Right.is(tok::kw_operator)) {
1963 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1965 if (Left.is(TT_StartOfName))
1967 if (InFunctionDecl && Right.NestingLevel == 0)
1968 return Style.PenaltyReturnTypeOnItsOwnLine;
1971 if (Right.is(TT_PointerOrReference))
1973 if (Right.is(TT_LambdaArrow))
1975 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1977 if (Left.is(TT_CastRParen))
1979 if (Left.is(tok::coloncolon) ||
1980 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1982 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1984 if (Left.is(tok::comment))
1987 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1990 if (Right.isMemberAccess()) {
1991 // Breaking before the "./->" of a chained call/member access is reasonably
1992 // cheap, as formatting those with one call per line is generally
1993 // desirable. In particular, it should be cheaper to break before the call
1994 // than it is to break inside a call's parameters, which could lead to weird
1995 // "hanging" indents. The exception is the very last "./->" to support this
1996 // frequent pattern:
1998 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2001 // which might otherwise be blown up onto many lines. Here, clang-format
2002 // won't produce "hanging" indents anyway as there is no other trailing
2005 // Also apply higher penalty is not a call as that might lead to a wrapping
2009 // .aaaaaaaaa.bbbbbbbb(cccccccc);
2010 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2015 if (Right.is(TT_TrailingAnnotation) &&
2016 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2017 // Moving trailing annotations to the next line is fine for ObjC method
2019 if (Line.startsWith(TT_ObjCMethodSpecifier))
2021 // Generally, breaking before a trailing annotation is bad unless it is
2022 // function-like. It seems to be especially preferable to keep standard
2023 // annotations (i.e. "const", "final" and "override") on the same line.
2024 // Use a slightly higher penalty after ")" so that annotations like
2025 // "const override" are kept together.
2026 bool is_short_annotation = Right.TokenText.size() < 10;
2027 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2030 // In for-loops, prefer breaking at ',' and ';'.
2031 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2034 // In Objective-C method expressions, prefer breaking before "param:" over
2035 // breaking after it.
2036 if (Right.is(TT_SelectorName))
2038 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2039 return Line.MightBeFunctionDecl ? 50 : 500;
2041 if (Left.is(tok::l_paren) && InFunctionDecl &&
2042 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2044 if (Left.is(tok::l_paren) && Left.Previous &&
2045 Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
2047 if (Left.is(tok::equal) && InFunctionDecl)
2049 if (Right.is(tok::r_brace))
2051 if (Left.is(TT_TemplateOpener))
2053 if (Left.opensScope()) {
2054 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
2056 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2059 if (Left.is(TT_JavaAnnotation))
2062 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2063 Left.Previous->isLabelString() &&
2064 (Left.NextOperator || Left.OperatorIndex != 0))
2066 if (Right.is(tok::plus) && Left.isLabelString() &&
2067 (Right.NextOperator || Right.OperatorIndex != 0))
2069 if (Left.is(tok::comma))
2071 if (Right.is(tok::lessless) && Left.isLabelString() &&
2072 (Right.NextOperator || Right.OperatorIndex != 1))
2074 if (Right.is(tok::lessless)) {
2075 // Breaking at a << is really cheap.
2076 if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2077 // Slightly prefer to break before the first one in log-like statements.
2081 if (Left.is(TT_ConditionalExpr))
2082 return prec::Conditional;
2083 prec::Level Level = Left.getPrecedence();
2084 if (Level != prec::Unknown)
2086 Level = Right.getPrecedence();
2087 if (Level != prec::Unknown)
2093 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2094 const FormatToken &Left,
2095 const FormatToken &Right) {
2096 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2098 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2099 Left.Tok.getObjCKeywordID() == tok::objc_property)
2101 if (Right.is(tok::hashhash))
2102 return Left.is(tok::hash);
2103 if (Left.isOneOf(tok::hashhash, tok::hash))
2104 return Right.is(tok::hash);
2105 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2106 return Style.SpaceInEmptyParentheses;
2107 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2108 return (Right.is(TT_CastRParen) ||
2109 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2110 ? Style.SpacesInCStyleCastParentheses
2111 : Style.SpacesInParentheses;
2112 if (Right.isOneOf(tok::semi, tok::comma))
2114 if (Right.is(tok::less) &&
2115 Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)
2117 if (Right.is(tok::less) && Left.is(tok::kw_template))
2118 return Style.SpaceAfterTemplateKeyword;
2119 if (Left.isOneOf(tok::exclaim, tok::tilde))
2121 if (Left.is(tok::at) &&
2122 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2123 tok::numeric_constant, tok::l_paren, tok::l_brace,
2124 tok::kw_true, tok::kw_false))
2126 if (Left.is(tok::colon))
2127 return !Left.is(TT_ObjCMethodExpr);
2128 if (Left.is(tok::coloncolon))
2130 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
2132 if (Right.is(tok::ellipsis))
2133 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2134 Left.Previous->is(tok::kw_case));
2135 if (Left.is(tok::l_square) && Right.is(tok::amp))
2137 if (Right.is(TT_PointerOrReference))
2138 return (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) ||
2139 (Left.Tok.isLiteral() || (Left.is(tok::kw_const) && Left.Previous &&
2140 Left.Previous->is(tok::r_paren)) ||
2141 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2142 (Style.PointerAlignment != FormatStyle::PAS_Left ||
2143 (Line.IsMultiVariableDeclStmt &&
2144 (Left.NestingLevel == 0 ||
2145 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2146 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2147 (!Left.is(TT_PointerOrReference) ||
2148 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2149 !Line.IsMultiVariableDeclStmt)))
2151 if (Left.is(TT_PointerOrReference))
2152 return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2153 (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2154 !Right.is(TT_StartOfName)) ||
2155 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2156 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2158 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2159 !Line.IsMultiVariableDeclStmt) &&
2161 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2162 if (Right.is(tok::star) && Left.is(tok::l_paren))
2164 if (Left.is(tok::l_square))
2165 return (Left.is(TT_ArrayInitializerLSquare) &&
2166 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
2167 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
2168 Right.isNot(tok::r_square));
2169 if (Right.is(tok::r_square))
2170 return Right.MatchingParen &&
2171 ((Style.SpacesInContainerLiterals &&
2172 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
2173 (Style.SpacesInSquareBrackets &&
2174 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
2175 if (Right.is(tok::l_square) &&
2176 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
2177 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2179 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2180 return !Left.Children.empty(); // No spaces in "{}".
2181 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2182 (Right.is(tok::r_brace) && Right.MatchingParen &&
2183 Right.MatchingParen->BlockKind != BK_Block))
2184 return !Style.Cpp11BracedListStyle;
2185 if (Left.is(TT_BlockComment))
2186 return !Left.TokenText.endswith("=*/");
2187 if (Right.is(tok::l_paren)) {
2188 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
2190 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2191 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2192 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2193 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2195 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2196 tok::kw_new, tok::kw_delete) &&
2197 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2198 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2199 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2200 Left.is(tok::r_paren)) &&
2201 Line.Type != LT_PreprocessorDirective);
2203 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2205 if (Right.is(TT_UnaryOperator))
2206 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2207 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2208 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2210 Left.isSimpleTypeSpecifier()) &&
2211 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2212 Right.BlockKind != BK_Block)
2214 if (Left.is(tok::period) || Right.is(tok::period))
2216 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2218 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2219 Left.MatchingParen->Previous &&
2220 Left.MatchingParen->Previous->is(tok::period))
2221 // A.<B>DoSomething();
2223 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2228 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2229 const FormatToken &Right) {
2230 const FormatToken &Left = *Right.Previous;
2231 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2232 return true; // Never ever merge two identifiers.
2233 if (Style.isCpp()) {
2234 if (Left.is(tok::kw_operator))
2235 return Right.is(tok::coloncolon);
2236 } else if (Style.Language == FormatStyle::LK_Proto) {
2237 if (Right.is(tok::period) &&
2238 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2239 Keywords.kw_repeated, Keywords.kw_extend))
2241 if (Right.is(tok::l_paren) &&
2242 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2244 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2245 if (Left.is(TT_JsFatArrow))
2247 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
2248 Right.MatchingParen) {
2249 const FormatToken *Next = Right.MatchingParen->getNextNonComment();
2250 // An async arrow function, for example: `x = async () => foo();`,
2251 // as opposed to calling a function called async: `x = async();`
2252 if (Next && Next->is(TT_JsFatArrow))
2255 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2256 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2258 if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
2260 if (Right.is(tok::star) &&
2261 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2263 if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2264 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2266 // JS methods can use some keywords as names (e.g. `delete()`).
2267 if (Right.is(tok::l_paren) && Line.MustBeDeclaration &&
2268 Left.Tok.getIdentifierInfo())
2270 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2272 // "of" is only a keyword if it appears after another identifier
2273 // (e.g. as "const x of y" in a for loop).
2274 (Left.is(Keywords.kw_of) && Left.Previous &&
2275 Left.Previous->Tok.getIdentifierInfo())) &&
2276 (!Left.Previous || !Left.Previous->is(tok::period)))
2278 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2279 Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2281 if (Left.is(Keywords.kw_as) &&
2282 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2284 if (Left.is(tok::kw_default) && Left.Previous &&
2285 Left.Previous->is(tok::kw_export))
2287 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2289 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2291 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2293 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2294 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2296 if (Left.is(tok::ellipsis))
2298 if (Left.is(TT_TemplateCloser) &&
2299 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2300 Keywords.kw_implements, Keywords.kw_extends))
2301 // Type assertions ('<type>expr') are not followed by whitespace. Other
2302 // locations that should have whitespace following are identified by the
2303 // above set of follower tokens.
2305 if (Right.is(TT_JsNonNullAssertion))
2307 if (Left.is(TT_JsNonNullAssertion) && Right.is(Keywords.kw_as))
2308 return true; // "x! as string"
2309 } else if (Style.Language == FormatStyle::LK_Java) {
2310 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2312 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2313 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2314 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2315 tok::kw_protected) ||
2316 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2317 Keywords.kw_native)) &&
2318 Right.is(TT_TemplateOpener))
2321 if (Left.is(TT_ImplicitStringLiteral))
2322 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2323 if (Line.Type == LT_ObjCMethodDecl) {
2324 if (Left.is(TT_ObjCMethodSpecifier))
2326 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2327 // Don't space between ')' and <id>
2330 if (Line.Type == LT_ObjCProperty &&
2331 (Right.is(tok::equal) || Left.is(tok::equal)))
2334 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2335 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2337 if (Right.is(TT_OverloadedOperatorLParen))
2338 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2339 if (Left.is(tok::comma))
2341 if (Right.is(tok::comma))
2343 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2345 if (Right.is(tok::colon)) {
2346 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2347 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2349 if (Right.is(TT_ObjCMethodExpr))
2351 if (Left.is(tok::question))
2353 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2355 if (Right.is(TT_DictLiteral))
2356 return Style.SpacesInContainerLiterals;
2359 if (Left.is(TT_UnaryOperator))
2360 return Right.is(TT_BinaryOperator);
2362 // If the next token is a binary operator or a selector name, we have
2363 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2364 if (Left.is(TT_CastRParen))
2365 return Style.SpaceAfterCStyleCast ||
2366 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2368 if (Left.is(tok::greater) && Right.is(tok::greater))
2369 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2370 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2371 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2372 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2374 if (!Style.SpaceBeforeAssignmentOperators &&
2375 Right.getPrecedence() == prec::Assignment)
2377 if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
2378 // Generally don't remove existing spaces between an identifier and "::".
2379 // The identifier might actually be a macro name such as ALWAYS_INLINE. If
2380 // this turns out to be too lenient, add analysis of the identifier itself.
2381 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2382 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2383 return (Left.is(TT_TemplateOpener) &&
2384 Style.Standard == FormatStyle::LS_Cpp03) ||
2385 !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
2386 tok::kw___super, TT_TemplateCloser, TT_TemplateOpener));
2387 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2388 return Style.SpacesInAngles;
2389 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2390 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2391 !Right.is(tok::r_paren)))
2393 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2394 Right.isNot(TT_FunctionTypeLParen))
2395 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2396 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2397 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2399 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2400 Line.startsWith(tok::hash))
2402 if (Right.is(TT_TrailingUnaryOperator))
2404 if (Left.is(TT_RegexLiteral))
2406 return spaceRequiredBetween(Line, Left, Right);
2409 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2410 static bool isAllmanBrace(const FormatToken &Tok) {
2411 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2412 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2415 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2416 const FormatToken &Right) {
2417 const FormatToken &Left = *Right.Previous;
2418 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2421 if (Style.Language == FormatStyle::LK_JavaScript) {
2422 // FIXME: This might apply to other languages and token kinds.
2423 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2424 Left.Previous->is(tok::string_literal))
2426 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2427 Left.Previous && Left.Previous->is(tok::equal) &&
2428 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2430 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2432 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2433 // Object literals on the top level of a file are treated as "enum-style".
2434 // Each key/value pair is put on a separate line, instead of bin-packing.
2436 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2437 (Line.startsWith(tok::kw_enum) ||
2438 Line.startsWith(tok::kw_export, tok::kw_enum)))
2439 // JavaScript top-level enum key/value pairs are put on separate lines
2440 // instead of bin-packing.
2442 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2443 !Left.Children.empty())
2444 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2445 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2446 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2447 (Left.NestingLevel == 0 && Line.Level == 0 &&
2448 Style.AllowShortFunctionsOnASingleLine ==
2449 FormatStyle::SFS_Inline);
2450 } else if (Style.Language == FormatStyle::LK_Java) {
2451 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2452 Right.Next->is(tok::string_literal))
2454 } else if (Style.Language == FormatStyle::LK_Cpp ||
2455 Style.Language == FormatStyle::LK_ObjC ||
2456 Style.Language == FormatStyle::LK_Proto) {
2457 if (Left.isStringLiteral() && Right.isStringLiteral())
2461 // If the last token before a '}' is a comma or a trailing comment, the
2462 // intention is to insert a line break after it in order to make shuffling
2463 // around entries easier.
2464 const FormatToken *BeforeClosingBrace = nullptr;
2465 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2466 Left.BlockKind != BK_Block && Left.MatchingParen)
2467 BeforeClosingBrace = Left.MatchingParen->Previous;
2468 else if (Right.MatchingParen &&
2469 Right.MatchingParen->isOneOf(tok::l_brace,
2470 TT_ArrayInitializerLSquare))
2471 BeforeClosingBrace = &Left;
2472 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2473 BeforeClosingBrace->isTrailingComment()))
2476 if (Right.is(tok::comment))
2477 return Left.BlockKind != BK_BracedInit &&
2478 Left.isNot(TT_CtorInitializerColon) &&
2479 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2480 if (Left.isTrailingComment())
2482 if (Right.Previous->IsUnterminatedLiteral)
2484 if (Right.is(tok::lessless) && Right.Next &&
2485 Right.Previous->is(tok::string_literal) &&
2486 Right.Next->is(tok::string_literal))
2488 if (Right.Previous->ClosesTemplateDeclaration &&
2489 Right.Previous->MatchingParen &&
2490 Right.Previous->MatchingParen->NestingLevel == 0 &&
2491 Style.AlwaysBreakTemplateDeclarations)
2493 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2494 Style.BreakConstructorInitializersBeforeComma &&
2495 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2497 // Break only if we have multiple inheritance.
2498 if (Style.BreakBeforeInheritanceComma &&
2499 Right.is(TT_InheritanceComma))
2501 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2502 // Raw string literals are special wrt. line breaks. The author has made a
2503 // deliberate choice and might have aligned the contents of the string
2504 // literal accordingly. Thus, we try keep existing line breaks.
2505 return Right.NewlinesBefore > 0;
2506 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2507 Style.Language == FormatStyle::LK_Proto)
2508 // Don't put enums onto single lines in protocol buffers.
2510 if (Right.is(TT_InlineASMBrace))
2511 return Right.HasUnescapedNewline;
2512 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2513 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2514 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2515 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2516 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2519 if ((Style.Language == FormatStyle::LK_Java ||
2520 Style.Language == FormatStyle::LK_JavaScript) &&
2521 Left.is(TT_LeadingJavaAnnotation) &&
2522 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2523 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2529 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2530 const FormatToken &Right) {
2531 const FormatToken &Left = *Right.Previous;
2533 // Language-specific stuff.
2534 if (Style.Language == FormatStyle::LK_Java) {
2535 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2536 Keywords.kw_implements))
2538 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2539 Keywords.kw_implements))
2541 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2542 const FormatToken *NonComment = Right.getPreviousNonComment();
2544 NonComment->isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
2545 tok::kw_throw, Keywords.kw_interface,
2547 return false; // Otherwise a semicolon is inserted.
2548 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2550 if (Left.is(TT_JsTypeColon))
2552 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2554 if (Left.is(Keywords.kw_in))
2555 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
2556 if (Right.is(Keywords.kw_in))
2557 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
2558 if (Right.is(Keywords.kw_as))
2559 return false; // must not break before as in 'x as type' casts
2560 if (Left.is(Keywords.kw_as))
2562 if (Left.is(TT_JsNonNullAssertion))
2564 if (Left.is(Keywords.kw_declare) &&
2565 Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
2566 Keywords.kw_function, tok::kw_class, tok::kw_enum,
2567 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
2568 Keywords.kw_let, tok::kw_const))
2569 // See grammar for 'declare' statements at:
2570 // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
2572 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
2573 Right.isOneOf(tok::identifier, tok::string_literal))
2574 return false; // must not break in "module foo { ...}"
2575 if (Right.is(TT_TemplateString) && Right.closesScope())
2577 if (Left.is(TT_TemplateString) && Left.opensScope())
2581 if (Left.is(tok::at))
2583 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2585 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2586 return !Right.is(tok::l_paren);
2587 if (Right.is(TT_PointerOrReference))
2588 return Line.IsMultiVariableDeclStmt ||
2589 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2590 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2591 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2592 Right.is(tok::kw_operator))
2594 if (Left.is(TT_PointerOrReference))
2596 if (Right.isTrailingComment())
2597 // We rely on MustBreakBefore being set correctly here as we should not
2598 // change the "binding" behavior of a comment.
2599 // The first comment in a braced lists is always interpreted as belonging to
2600 // the first list element. Otherwise, it should be placed outside of the
2602 return Left.BlockKind == BK_BracedInit;
2603 if (Left.is(tok::question) && Right.is(tok::colon))
2605 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2606 return Style.BreakBeforeTernaryOperators;
2607 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2608 return !Style.BreakBeforeTernaryOperators;
2609 if (Right.is(TT_InheritanceColon))
2611 if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
2612 Left.isNot(TT_SelectorName))
2614 if (Right.is(tok::colon) &&
2615 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2617 if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr))
2619 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2620 Right.Next->is(TT_ObjCMethodExpr)))
2621 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2622 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2624 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2626 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2627 TT_OverloadedOperator))
2629 if (Left.is(TT_RangeBasedForLoopColon))
2631 if (Right.is(TT_RangeBasedForLoopColon))
2633 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
2635 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2636 Left.is(tok::kw_operator))
2638 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2639 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2641 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2643 if (Left.is(tok::l_paren) && Left.Previous &&
2644 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2646 if (Right.is(TT_ImplicitStringLiteral))
2649 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2651 if (Right.is(tok::r_square) && Right.MatchingParen &&
2652 Right.MatchingParen->is(TT_LambdaLSquare))
2655 // We only break before r_brace if there was a corresponding break before
2656 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2657 if (Right.is(tok::r_brace))
2658 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2660 // Allow breaking after a trailing annotation, e.g. after a method
2662 if (Left.is(TT_TrailingAnnotation))
2663 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2664 tok::less, tok::coloncolon);
2666 if (Right.is(tok::kw___attribute))
2669 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2672 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2675 if (Left.is(TT_CtorInitializerComma) &&
2676 Style.BreakConstructorInitializersBeforeComma)
2678 if (Right.is(TT_CtorInitializerComma) &&
2679 Style.BreakConstructorInitializersBeforeComma)
2681 if (Left.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
2683 if (Right.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
2685 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2686 (Left.is(tok::less) && Right.is(tok::less)))
2688 if (Right.is(TT_BinaryOperator) &&
2689 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2690 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2691 Right.getPrecedence() != prec::Assignment))
2693 if (Left.is(TT_ArrayInitializerLSquare))
2695 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2697 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2698 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2699 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2700 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2701 Left.getPrecedence() == prec::Assignment))
2703 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2704 tok::kw_class, tok::kw_struct, tok::comment) ||
2705 Right.isMemberAccess() ||
2706 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2707 tok::colon, tok::l_square, tok::at) ||
2708 (Left.is(tok::r_paren) &&
2709 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2710 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
2711 (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
2714 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2715 llvm::errs() << "AnnotatedTokens:\n";
2716 const FormatToken *Tok = Line.First;
2718 llvm::errs() << " M=" << Tok->MustBreakBefore
2719 << " C=" << Tok->CanBreakBefore
2720 << " T=" << getTokenTypeName(Tok->Type)
2721 << " S=" << Tok->SpacesRequiredBefore
2722 << " B=" << Tok->BlockParameterCount
2723 << " BK=" << Tok->BlockKind
2724 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2725 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2727 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2728 llvm::errs() << Tok->FakeLParens[i] << "/";
2729 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
2730 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
2732 assert(Tok == Line.Last);
2735 llvm::errs() << "----\n";
2738 } // namespace format
2739 } // namespace clang