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 (Left->Previous &&
138 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
139 tok::kw_if, tok::kw_while, tok::l_paren,
141 Left->Previous->is(TT_BinaryOperator))) {
142 // static_assert, if and while usually contain expressions.
143 Contexts.back().IsExpression = true;
144 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
145 Left->Previous->is(Keywords.kw_function)) {
146 Contexts.back().IsExpression = false;
147 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
148 Left->Previous->MatchingParen &&
149 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
150 // This is a parameter list of a lambda expression.
151 Contexts.back().IsExpression = false;
152 } else if (Line.InPPDirective &&
153 (!Left->Previous || !Left->Previous->is(tok::identifier))) {
154 Contexts.back().IsExpression = true;
155 } else if (Contexts[Contexts.size() - 2].CaretFound) {
156 // This is the parameter list of an ObjC block.
157 Contexts.back().IsExpression = false;
158 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
159 Left->Type = TT_AttributeParen;
160 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
161 // The first argument to a foreach macro is a declaration.
162 Contexts.back().IsForEachMacro = true;
163 Contexts.back().IsExpression = false;
164 } else if (Left->Previous && Left->Previous->MatchingParen &&
165 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
166 Contexts.back().IsExpression = false;
167 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
169 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
170 Contexts.back().IsExpression = !IsForOrCatch;
173 if (StartsObjCMethodExpr) {
174 Contexts.back().ColonIsObjCMethodExpr = true;
175 Left->Type = TT_ObjCMethodExpr;
178 bool MightBeFunctionType = CurrentToken->isOneOf(tok::star, tok::amp) &&
179 !Contexts[Contexts.size() - 2].IsExpression;
180 bool HasMultipleLines = false;
181 bool HasMultipleParametersOnALine = false;
182 bool MightBeObjCForRangeLoop =
183 Left->Previous && Left->Previous->is(tok::kw_for);
184 while (CurrentToken) {
185 // LookForDecls is set when "if (" has been seen. Check for
186 // 'identifier' '*' 'identifier' followed by not '=' -- this
187 // '*' has to be a binary operator but determineStarAmpUsage() will
188 // categorize it as an unary operator, so set the right type here.
189 if (LookForDecls && CurrentToken->Next) {
190 FormatToken *Prev = CurrentToken->getPreviousNonComment();
192 FormatToken *PrevPrev = Prev->getPreviousNonComment();
193 FormatToken *Next = CurrentToken->Next;
194 if (PrevPrev && PrevPrev->is(tok::identifier) &&
195 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
196 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
197 Prev->Type = TT_BinaryOperator;
198 LookForDecls = false;
203 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
204 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
206 MightBeFunctionType = true;
207 if (CurrentToken->Previous->is(TT_BinaryOperator))
208 Contexts.back().IsExpression = true;
209 if (CurrentToken->is(tok::r_paren)) {
210 if (MightBeFunctionType && CurrentToken->Next &&
211 (CurrentToken->Next->is(tok::l_paren) ||
212 (CurrentToken->Next->is(tok::l_square) &&
213 Line.MustBeDeclaration)))
214 Left->Type = TT_FunctionTypeLParen;
215 Left->MatchingParen = CurrentToken;
216 CurrentToken->MatchingParen = Left;
218 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
219 Left->Previous && Left->Previous->is(tok::l_paren)) {
220 // Detect the case where macros are used to generate lambdas or
221 // function bodies, e.g.:
222 // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
223 for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
224 if (Tok->is(TT_BinaryOperator) &&
225 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
226 Tok->Type = TT_PointerOrReference;
230 if (StartsObjCMethodExpr) {
231 CurrentToken->Type = TT_ObjCMethodExpr;
232 if (Contexts.back().FirstObjCSelectorName) {
233 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
234 Contexts.back().LongestObjCSelectorName;
238 if (Left->is(TT_AttributeParen))
239 CurrentToken->Type = TT_AttributeParen;
240 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
241 CurrentToken->Type = TT_JavaAnnotation;
242 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
243 CurrentToken->Type = TT_LeadingJavaAnnotation;
245 if (!HasMultipleLines)
246 Left->PackingKind = PPK_Inconclusive;
247 else if (HasMultipleParametersOnALine)
248 Left->PackingKind = PPK_BinPacked;
250 Left->PackingKind = PPK_OnePerLine;
255 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
258 if (CurrentToken->is(tok::l_brace))
259 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
260 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
261 !CurrentToken->Next->HasUnescapedNewline &&
262 !CurrentToken->Next->isTrailingComment())
263 HasMultipleParametersOnALine = true;
264 if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
265 CurrentToken->isSimpleTypeSpecifier())
266 Contexts.back().IsExpression = false;
267 if (CurrentToken->isOneOf(tok::semi, tok::colon))
268 MightBeObjCForRangeLoop = false;
269 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
270 CurrentToken->Type = TT_ObjCForIn;
271 // When we discover a 'new', we set CanBeExpression to 'false' in order to
272 // parse the type correctly. Reset that after a comma.
273 if (CurrentToken->is(tok::comma))
274 Contexts.back().CanBeExpression = true;
276 FormatToken *Tok = CurrentToken;
279 updateParameterCount(Left, Tok);
280 if (CurrentToken && CurrentToken->HasUnescapedNewline)
281 HasMultipleLines = true;
290 // A '[' could be an index subscript (after an identifier or after
291 // ')' or ']'), it could be the start of an Objective-C method
292 // expression, or it could the start of an Objective-C array literal.
293 FormatToken *Left = CurrentToken->Previous;
294 Left->ParentBracket = Contexts.back().ContextKind;
295 FormatToken *Parent = Left->getPreviousNonComment();
296 bool StartsObjCMethodExpr =
297 Style.Language == FormatStyle::LK_Cpp &&
298 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
299 CurrentToken->isNot(tok::l_brace) &&
301 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
302 tok::kw_return, tok::kw_throw) ||
303 Parent->isUnaryOperator() ||
304 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
305 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
306 bool ColonFound = false;
308 unsigned BindingIncrease = 1;
309 if (Left->is(TT_Unknown)) {
310 if (StartsObjCMethodExpr) {
311 Left->Type = TT_ObjCMethodExpr;
312 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
313 Contexts.back().ContextKind == tok::l_brace &&
314 Parent->isOneOf(tok::l_brace, tok::comma)) {
315 Left->Type = TT_JsComputedPropertyName;
316 } else if (Style.Language == FormatStyle::LK_Proto ||
318 Parent->isOneOf(TT_BinaryOperator, tok::at, tok::comma,
319 tok::l_paren, tok::l_square, tok::question,
320 tok::colon, tok::kw_return,
321 // Should only be relevant to JavaScript:
323 Left->Type = TT_ArrayInitializerLSquare;
325 BindingIncrease = 10;
326 Left->Type = TT_ArraySubscriptLSquare;
330 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
331 Contexts.back().IsExpression = true;
332 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
334 while (CurrentToken) {
335 if (CurrentToken->is(tok::r_square)) {
336 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
337 Left->is(TT_ObjCMethodExpr)) {
338 // An ObjC method call is rarely followed by an open parenthesis.
339 // FIXME: Do we incorrectly label ":" with this?
340 StartsObjCMethodExpr = false;
341 Left->Type = TT_Unknown;
343 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
344 CurrentToken->Type = TT_ObjCMethodExpr;
345 // determineStarAmpUsage() thinks that '*' '[' is allocating an
346 // array of pointers, but if '[' starts a selector then '*' is a
348 if (Parent && Parent->is(TT_PointerOrReference))
349 Parent->Type = TT_BinaryOperator;
351 Left->MatchingParen = CurrentToken;
352 CurrentToken->MatchingParen = Left;
353 if (Contexts.back().FirstObjCSelectorName) {
354 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
355 Contexts.back().LongestObjCSelectorName;
356 if (Left->BlockParameterCount > 1)
357 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
362 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
364 if (CurrentToken->is(tok::colon)) {
365 if (Left->is(TT_ArraySubscriptLSquare)) {
366 Left->Type = TT_ObjCMethodExpr;
367 StartsObjCMethodExpr = true;
368 Contexts.back().ColonIsObjCMethodExpr = true;
369 if (Parent && Parent->is(tok::r_paren))
370 Parent->Type = TT_CastRParen;
374 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
376 Left->Type = TT_ArrayInitializerLSquare;
377 FormatToken *Tok = CurrentToken;
380 updateParameterCount(Left, Tok);
387 FormatToken *Left = CurrentToken->Previous;
388 Left->ParentBracket = Contexts.back().ContextKind;
390 if (Contexts.back().CaretFound)
391 Left->Type = TT_ObjCBlockLBrace;
392 Contexts.back().CaretFound = false;
394 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
395 Contexts.back().ColonIsDictLiteral = true;
396 if (Left->BlockKind == BK_BracedInit)
397 Contexts.back().IsExpression = true;
399 while (CurrentToken) {
400 if (CurrentToken->is(tok::r_brace)) {
401 Left->MatchingParen = CurrentToken;
402 CurrentToken->MatchingParen = Left;
406 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
408 updateParameterCount(Left, CurrentToken);
409 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
410 FormatToken *Previous = CurrentToken->getPreviousNonComment();
411 if (((CurrentToken->is(tok::colon) &&
412 (!Contexts.back().ColonIsDictLiteral ||
413 Style.Language != FormatStyle::LK_Cpp)) ||
414 Style.Language == FormatStyle::LK_Proto) &&
415 (Previous->Tok.getIdentifierInfo() ||
416 Previous->is(tok::string_literal)))
417 Previous->Type = TT_SelectorName;
418 if (CurrentToken->is(tok::colon) ||
419 Style.Language == FormatStyle::LK_JavaScript)
420 Left->Type = TT_DictLiteral;
429 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
430 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
431 ++Left->BlockParameterCount;
432 if (Current->is(tok::comma)) {
433 ++Left->ParameterCount;
435 Left->Role.reset(new CommaSeparatedList(Style));
436 Left->Role->CommaFound(Current);
437 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
438 Left->ParameterCount = 1;
442 bool parseConditional() {
443 while (CurrentToken) {
444 if (CurrentToken->is(tok::colon)) {
445 CurrentToken->Type = TT_ConditionalExpr;
455 bool parseTemplateDeclaration() {
456 if (CurrentToken && CurrentToken->is(tok::less)) {
457 CurrentToken->Type = TT_TemplateOpener;
462 CurrentToken->Previous->ClosesTemplateDeclaration = true;
468 bool consumeToken() {
469 FormatToken *Tok = CurrentToken;
471 switch (Tok->Tok.getKind()) {
474 if (!Tok->Previous && Line.MustBeDeclaration)
475 Tok->Type = TT_ObjCMethodSpecifier;
480 // Colons from ?: are handled in parseConditional().
481 if (Style.Language == FormatStyle::LK_JavaScript) {
482 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
483 (Contexts.size() == 1 && // switch/case labels
484 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
485 Contexts.back().ContextKind == tok::l_paren || // function params
486 Contexts.back().ContextKind == tok::l_square || // array type
487 (Contexts.size() == 1 &&
488 Line.MustBeDeclaration)) { // method/property declaration
489 Tok->Type = TT_JsTypeColon;
493 if (Contexts.back().ColonIsDictLiteral ||
494 Style.Language == FormatStyle::LK_Proto) {
495 Tok->Type = TT_DictLiteral;
496 } else if (Contexts.back().ColonIsObjCMethodExpr ||
497 Line.startsWith(TT_ObjCMethodSpecifier)) {
498 Tok->Type = TT_ObjCMethodExpr;
499 Tok->Previous->Type = TT_SelectorName;
500 if (Tok->Previous->ColumnWidth >
501 Contexts.back().LongestObjCSelectorName)
502 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
503 if (!Contexts.back().FirstObjCSelectorName)
504 Contexts.back().FirstObjCSelectorName = Tok->Previous;
505 } else if (Contexts.back().ColonIsForRangeExpr) {
506 Tok->Type = TT_RangeBasedForLoopColon;
507 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
508 Tok->Type = TT_BitFieldColon;
509 } else if (Contexts.size() == 1 &&
510 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
511 if (Tok->Previous->isOneOf(tok::r_paren, tok::kw_noexcept))
512 Tok->Type = TT_CtorInitializerColon;
514 Tok->Type = TT_InheritanceColon;
515 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
516 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
517 // This handles a special macro in ObjC code where selectors including
518 // the colon are passed as macro arguments.
519 Tok->Type = TT_ObjCMethodExpr;
520 } else if (Contexts.back().ContextKind == tok::l_paren) {
521 Tok->Type = TT_InlineASMColon;
526 // | and & in declarations/type expressions represent union and
527 // intersection types, respectively.
528 if (Style.Language == FormatStyle::LK_JavaScript &&
529 !Contexts.back().IsExpression)
530 Tok->Type = TT_JsTypeOperator;
534 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
536 if (!parseParens(/*LookForDecls=*/true))
541 Contexts.back().ColonIsForRangeExpr = true;
547 // When faced with 'operator()()', the kw_operator handler incorrectly
548 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
549 // the first two parens OverloadedOperators and the second l_paren an
550 // OverloadedOperatorLParen.
552 Tok->Previous->is(tok::r_paren) &&
553 Tok->Previous->MatchingParen &&
554 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
555 Tok->Previous->Type = TT_OverloadedOperator;
556 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
557 Tok->Type = TT_OverloadedOperatorLParen;
562 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
563 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
565 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
566 TT_LeadingJavaAnnotation)))
567 Line.MightBeFunctionDecl = true;
579 Tok->Type = TT_TemplateOpener;
581 Tok->Type = TT_BinaryOperator;
582 NonTemplateLess.insert(Tok);
591 // Lines can start with '}'.
596 Tok->Type = TT_BinaryOperator;
598 case tok::kw_operator:
599 while (CurrentToken &&
600 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
601 if (CurrentToken->isOneOf(tok::star, tok::amp))
602 CurrentToken->Type = TT_PointerOrReference;
605 CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma))
606 CurrentToken->Previous->Type = TT_OverloadedOperator;
609 CurrentToken->Type = TT_OverloadedOperatorLParen;
610 if (CurrentToken->Previous->is(TT_BinaryOperator))
611 CurrentToken->Previous->Type = TT_OverloadedOperator;
615 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
616 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
618 // Question marks before semicolons, colons, etc. indicate optional
619 // types (fields, parameters), e.g.
620 // function(x?: string, y?) {...}
622 Tok->Type = TT_JsTypeOptionalQuestion;
625 // Declarations cannot be conditional expressions, this can only be part
626 // of a type declaration.
627 if (Line.MustBeDeclaration &&
628 Style.Language == FormatStyle::LK_JavaScript)
632 case tok::kw_template:
633 parseTemplateDeclaration();
636 if (Contexts.back().InCtorInitializer)
637 Tok->Type = TT_CtorInitializerComma;
638 else if (Contexts.back().FirstStartOfName &&
639 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
640 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
641 Line.IsMultiVariableDeclStmt = true;
643 if (Contexts.back().IsForEachMacro)
644 Contexts.back().IsExpression = true;
652 void parseIncludeDirective() {
653 if (CurrentToken && CurrentToken->is(tok::less)) {
655 while (CurrentToken) {
656 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
657 CurrentToken->Type = TT_ImplicitStringLiteral;
663 void parseWarningOrError() {
665 // We still want to format the whitespace left of the first token of the
668 while (CurrentToken) {
669 CurrentToken->Type = TT_ImplicitStringLiteral;
675 next(); // Consume "pragma".
677 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
678 bool IsMark = CurrentToken->is(Keywords.kw_mark);
679 next(); // Consume "mark".
680 next(); // Consume first token (so we fix leading whitespace).
681 while (CurrentToken) {
682 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
683 CurrentToken->Type = TT_ImplicitStringLiteral;
689 LineType parsePreprocessorDirective() {
690 LineType Type = LT_PreprocessorDirective;
694 if (CurrentToken->Tok.is(tok::numeric_constant)) {
695 CurrentToken->SpacesRequiredBefore = 1;
698 // Hashes in the middle of a line can lead to any strange token
700 if (!CurrentToken->Tok.getIdentifierInfo())
702 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
703 case tok::pp_include:
704 case tok::pp_include_next:
707 parseIncludeDirective();
708 Type = LT_ImportStatement;
711 case tok::pp_warning:
712 parseWarningOrError();
719 Contexts.back().IsExpression = true;
731 LineType parseLine() {
732 NonTemplateLess.clear();
733 if (CurrentToken->is(tok::hash))
734 return parsePreprocessorDirective();
736 // Directly allow to 'import <string-literal>' to support protocol buffer
737 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
738 // should not break the line).
739 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
740 if ((Style.Language == FormatStyle::LK_Java &&
741 CurrentToken->is(Keywords.kw_package)) ||
742 (Info && Info->getPPKeywordID() == tok::pp_import &&
743 CurrentToken->Next &&
744 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
747 parseIncludeDirective();
748 return LT_ImportStatement;
751 // If this line starts and ends in '<' and '>', respectively, it is likely
752 // part of "#define <a/b.h>".
753 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
754 parseIncludeDirective();
755 return LT_ImportStatement;
758 // In .proto files, top-level options are very similar to import statements
759 // and should not be line-wrapped.
760 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
761 CurrentToken->is(Keywords.kw_option)) {
763 if (CurrentToken && CurrentToken->is(tok::identifier))
764 return LT_ImportStatement;
767 // import {...} from '...';
768 if (Style.Language == FormatStyle::LK_JavaScript &&
769 CurrentToken->is(Keywords.kw_import))
770 return LT_ImportStatement;
772 bool KeywordVirtualFound = false;
773 bool ImportStatement = false;
774 while (CurrentToken) {
775 if (CurrentToken->is(tok::kw_virtual))
776 KeywordVirtualFound = true;
777 if (Style.Language == FormatStyle::LK_JavaScript) {
778 // export {...} from '...';
779 // An export followed by "from 'some string';" is a re-export from
780 // another module identified by a URI and is treated as a
781 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
782 // Just "export {...};" or "export class ..." should not be treated as
783 // an import in this sense.
784 if (Line.First->is(tok::kw_export) &&
785 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
786 CurrentToken->Next->isStringLiteral())
787 ImportStatement = true;
788 if (isClosureImportStatement(*CurrentToken))
789 ImportStatement = true;
794 if (KeywordVirtualFound)
795 return LT_VirtualFunctionDecl;
797 return LT_ImportStatement;
799 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
800 if (Contexts.back().FirstObjCSelectorName)
801 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
802 Contexts.back().LongestObjCSelectorName;
803 return LT_ObjCMethodDecl;
810 bool isClosureImportStatement(const FormatToken &Tok) {
811 // FIXME: Closure-library specific stuff should not be hard-coded but be
813 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
814 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
815 Tok.Next->Next->TokenText == "provide" ||
816 Tok.Next->Next->TokenText == "require" ||
817 Tok.Next->Next->TokenText == "setTestOnly" ||
818 Tok.Next->Next->TokenText == "forwardDeclare") &&
819 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
822 void resetTokenMetadata(FormatToken *Token) {
826 // Reset token type in case we have already looked at it and then
827 // recovered from an error (e.g. failure to find the matching >).
828 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
829 TT_FunctionLBrace, TT_ImplicitStringLiteral,
830 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
832 CurrentToken->Type = TT_Unknown;
833 CurrentToken->Role.reset();
834 CurrentToken->MatchingParen = nullptr;
835 CurrentToken->FakeLParens.clear();
836 CurrentToken->FakeRParens = 0;
841 CurrentToken->NestingLevel = Contexts.size() - 1;
842 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
843 modifyContext(*CurrentToken);
844 determineTokenType(*CurrentToken);
845 CurrentToken = CurrentToken->Next;
848 resetTokenMetadata(CurrentToken);
851 /// \brief A struct to hold information valid in a specific context, e.g.
852 /// a pair of parenthesis.
854 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
856 : ContextKind(ContextKind), BindingStrength(BindingStrength),
857 IsExpression(IsExpression) {}
859 tok::TokenKind ContextKind;
860 unsigned BindingStrength;
862 unsigned LongestObjCSelectorName = 0;
863 bool ColonIsForRangeExpr = false;
864 bool ColonIsDictLiteral = false;
865 bool ColonIsObjCMethodExpr = false;
866 FormatToken *FirstObjCSelectorName = nullptr;
867 FormatToken *FirstStartOfName = nullptr;
868 bool CanBeExpression = true;
869 bool InTemplateArgument = false;
870 bool InCtorInitializer = false;
871 bool CaretFound = false;
872 bool IsForEachMacro = false;
875 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
876 /// of each instance.
877 struct ScopedContextCreator {
880 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
883 P.Contexts.push_back(Context(ContextKind,
884 P.Contexts.back().BindingStrength + Increase,
885 P.Contexts.back().IsExpression));
888 ~ScopedContextCreator() { P.Contexts.pop_back(); }
891 void modifyContext(const FormatToken &Current) {
892 if (Current.getPrecedence() == prec::Assignment &&
893 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
894 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
895 Contexts.back().IsExpression = true;
896 if (!Line.startsWith(TT_UnaryOperator)) {
897 for (FormatToken *Previous = Current.Previous;
898 Previous && Previous->Previous &&
899 !Previous->Previous->isOneOf(tok::comma, tok::semi);
900 Previous = Previous->Previous) {
901 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
902 Previous = Previous->MatchingParen;
906 if (Previous->opensScope())
908 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
909 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
910 Previous->Previous && Previous->Previous->isNot(tok::equal))
911 Previous->Type = TT_PointerOrReference;
914 } else if (Current.is(tok::lessless) &&
915 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
916 Contexts.back().IsExpression = true;
917 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
918 Contexts.back().IsExpression = true;
919 } else if (Current.is(TT_TrailingReturnArrow)) {
920 Contexts.back().IsExpression = false;
921 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
922 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
923 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
924 for (FormatToken *Previous = Current.Previous;
925 Previous && Previous->isOneOf(tok::star, tok::amp);
926 Previous = Previous->Previous)
927 Previous->Type = TT_PointerOrReference;
928 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
929 Contexts.back().IsExpression = false;
930 } else if (Current.Previous &&
931 Current.Previous->is(TT_CtorInitializerColon)) {
932 Contexts.back().IsExpression = true;
933 Contexts.back().InCtorInitializer = true;
934 } else if (Current.is(tok::kw_new)) {
935 Contexts.back().CanBeExpression = false;
936 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
937 // This should be the condition or increment in a for-loop.
938 Contexts.back().IsExpression = true;
942 void determineTokenType(FormatToken &Current) {
943 if (!Current.is(TT_Unknown))
944 // The token type is already known.
947 // Line.MightBeFunctionDecl can only be true after the parentheses of a
948 // function declaration have been found. In this case, 'Current' is a
949 // trailing token of this declaration and thus cannot be a name.
950 if (Current.is(Keywords.kw_instanceof)) {
951 Current.Type = TT_BinaryOperator;
952 } else if (isStartOfName(Current) &&
953 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
954 Contexts.back().FirstStartOfName = &Current;
955 Current.Type = TT_StartOfName;
956 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
958 } else if (Current.is(tok::arrow) &&
959 Style.Language == FormatStyle::LK_Java) {
960 Current.Type = TT_LambdaArrow;
961 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
962 Current.NestingLevel == 0) {
963 Current.Type = TT_TrailingReturnArrow;
964 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
966 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
967 Contexts.back().IsExpression,
968 Contexts.back().InTemplateArgument);
969 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
970 Current.Type = determinePlusMinusCaretUsage(Current);
971 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
972 Contexts.back().CaretFound = true;
973 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
974 Current.Type = determineIncrementUsage(Current);
975 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
976 Current.Type = TT_UnaryOperator;
977 } else if (Current.is(tok::question)) {
978 if (Style.Language == FormatStyle::LK_JavaScript &&
979 Line.MustBeDeclaration) {
980 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
981 // on the interface, not a ternary expression.
982 Current.Type = TT_JsTypeOptionalQuestion;
984 Current.Type = TT_ConditionalExpr;
986 } else if (Current.isBinaryOperator() &&
987 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
988 Current.Type = TT_BinaryOperator;
989 } else if (Current.is(tok::comment)) {
990 if (Current.TokenText.startswith("/*")) {
991 if (Current.TokenText.endswith("*/"))
992 Current.Type = TT_BlockComment;
994 // The lexer has for some reason determined a comment here. But we
995 // cannot really handle it, if it isn't properly terminated.
996 Current.Tok.setKind(tok::unknown);
998 Current.Type = TT_LineComment;
1000 } else if (Current.is(tok::r_paren)) {
1001 if (rParenEndsCast(Current))
1002 Current.Type = TT_CastRParen;
1003 if (Current.MatchingParen && Current.Next &&
1004 !Current.Next->isBinaryOperator() &&
1005 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1006 tok::period, tok::arrow, tok::coloncolon))
1007 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1008 if (BeforeParen->is(tok::identifier) &&
1009 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1010 (!BeforeParen->Previous ||
1011 BeforeParen->Previous->ClosesTemplateDeclaration))
1012 Current.Type = TT_FunctionAnnotationRParen;
1013 } else if (Current.is(tok::at) && Current.Next) {
1014 if (Current.Next->isStringLiteral()) {
1015 Current.Type = TT_ObjCStringLiteral;
1017 switch (Current.Next->Tok.getObjCKeywordID()) {
1018 case tok::objc_interface:
1019 case tok::objc_implementation:
1020 case tok::objc_protocol:
1021 Current.Type = TT_ObjCDecl;
1023 case tok::objc_property:
1024 Current.Type = TT_ObjCProperty;
1030 } else if (Current.is(tok::period)) {
1031 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1032 if (PreviousNoComment &&
1033 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1034 Current.Type = TT_DesignatedInitializerPeriod;
1035 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1036 Current.Previous->isOneOf(TT_JavaAnnotation,
1037 TT_LeadingJavaAnnotation)) {
1038 Current.Type = Current.Previous->Type;
1040 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1042 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1043 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1044 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1045 // function declaration have been found.
1046 Current.Type = TT_TrailingAnnotation;
1047 } else if ((Style.Language == FormatStyle::LK_Java ||
1048 Style.Language == FormatStyle::LK_JavaScript) &&
1050 if (Current.Previous->is(tok::at) &&
1051 Current.isNot(Keywords.kw_interface)) {
1052 const FormatToken &AtToken = *Current.Previous;
1053 const FormatToken *Previous = AtToken.getPreviousNonComment();
1054 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1055 Current.Type = TT_LeadingJavaAnnotation;
1057 Current.Type = TT_JavaAnnotation;
1058 } else if (Current.Previous->is(tok::period) &&
1059 Current.Previous->isOneOf(TT_JavaAnnotation,
1060 TT_LeadingJavaAnnotation)) {
1061 Current.Type = Current.Previous->Type;
1066 /// \brief Take a guess at whether \p Tok starts a name of a function or
1067 /// variable declaration.
1069 /// This is a heuristic based on whether \p Tok is an identifier following
1070 /// something that is likely a type.
1071 bool isStartOfName(const FormatToken &Tok) {
1072 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1075 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
1077 if (Style.Language == FormatStyle::LK_JavaScript &&
1078 Tok.Previous->is(Keywords.kw_in))
1081 // Skip "const" as it does not have an influence on whether this is a name.
1082 FormatToken *PreviousNotConst = Tok.Previous;
1083 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1084 PreviousNotConst = PreviousNotConst->Previous;
1086 if (!PreviousNotConst)
1089 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1090 PreviousNotConst->Previous &&
1091 PreviousNotConst->Previous->is(tok::hash);
1093 if (PreviousNotConst->is(TT_TemplateCloser))
1094 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1095 PreviousNotConst->MatchingParen->Previous &&
1096 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1097 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1099 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1100 PreviousNotConst->MatchingParen->Previous &&
1101 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1104 return (!IsPPKeyword &&
1105 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1106 PreviousNotConst->is(TT_PointerOrReference) ||
1107 PreviousNotConst->isSimpleTypeSpecifier();
1110 /// \brief Determine whether ')' is ending a cast.
1111 bool rParenEndsCast(const FormatToken &Tok) {
1112 // C-style casts are only used in C++ and Java.
1113 if (Style.Language != FormatStyle::LK_Cpp &&
1114 Style.Language != FormatStyle::LK_Java)
1117 // Empty parens aren't casts and there are no casts at the end of the line.
1118 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1121 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1123 // If there is an opening parenthesis left of the current parentheses,
1124 // look past it as these might be chained casts.
1125 if (LeftOfParens->is(tok::r_paren)) {
1126 if (!LeftOfParens->MatchingParen ||
1127 !LeftOfParens->MatchingParen->Previous)
1129 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1132 // If there is an identifier (or with a few exceptions a keyword) right
1133 // before the parentheses, this is unlikely to be a cast.
1134 if (LeftOfParens->Tok.getIdentifierInfo() &&
1135 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1139 // Certain other tokens right before the parentheses are also signals that
1140 // this cannot be a cast.
1141 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1146 if (Tok.Next->is(tok::question))
1149 // As Java has no function types, a "(" after the ")" likely means that this
1151 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1154 // If a (non-string) literal follows, this is likely a cast.
1155 if (Tok.Next->isNot(tok::string_literal) &&
1156 (Tok.Next->Tok.isLiteral() ||
1157 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1160 // Heuristically try to determine whether the parentheses contain a type.
1161 bool ParensAreType =
1163 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1164 Tok.Previous->isSimpleTypeSpecifier();
1165 bool ParensCouldEndDecl =
1166 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1167 if (ParensAreType && !ParensCouldEndDecl)
1170 // At this point, we heuristically assume that there are no casts at the
1171 // start of the line. We assume that we have found most cases where there
1172 // are by the logic above, e.g. "(void)x;".
1176 // If the following token is an identifier or 'this', this is a cast. All
1177 // cases where this can be something else are handled above.
1178 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1181 if (!Tok.Next->Next)
1184 // If the next token after the parenthesis is a unary operator, assume
1185 // that this is cast, unless there are unexpected tokens inside the
1188 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1189 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1190 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1192 // Search for unexpected tokens.
1193 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1194 Prev = Prev->Previous) {
1195 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1201 /// \brief Return the type of the given token assuming it is * or &.
1202 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1203 bool InTemplateArgument) {
1204 if (Style.Language == FormatStyle::LK_JavaScript)
1205 return TT_BinaryOperator;
1207 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1209 return TT_UnaryOperator;
1211 const FormatToken *NextToken = Tok.getNextNonComment();
1213 NextToken->isOneOf(tok::arrow, Keywords.kw_final,
1214 Keywords.kw_override) ||
1215 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1216 return TT_PointerOrReference;
1218 if (PrevToken->is(tok::coloncolon))
1219 return TT_PointerOrReference;
1221 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1222 tok::comma, tok::semi, tok::kw_return, tok::colon,
1223 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1224 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1225 TT_UnaryOperator, TT_CastRParen))
1226 return TT_UnaryOperator;
1228 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1229 return TT_PointerOrReference;
1230 if (NextToken->is(tok::kw_operator) && !IsExpression)
1231 return TT_PointerOrReference;
1232 if (NextToken->isOneOf(tok::comma, tok::semi))
1233 return TT_PointerOrReference;
1235 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1236 PrevToken->MatchingParen->Previous &&
1237 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1239 return TT_PointerOrReference;
1241 if (PrevToken->Tok.isLiteral() ||
1242 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1243 tok::kw_false, tok::r_brace) ||
1244 NextToken->Tok.isLiteral() ||
1245 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1246 NextToken->isUnaryOperator() ||
1247 // If we know we're in a template argument, there are no named
1248 // declarations. Thus, having an identifier on the right-hand side
1249 // indicates a binary operator.
1250 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1251 return TT_BinaryOperator;
1253 // "&&(" is quite unlikely to be two successive unary "&".
1254 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1255 return TT_BinaryOperator;
1257 // This catches some cases where evaluation order is used as control flow:
1259 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1260 if (NextNextToken && NextNextToken->is(tok::arrow))
1261 return TT_BinaryOperator;
1263 // It is very unlikely that we are going to find a pointer or reference type
1264 // definition on the RHS of an assignment.
1265 if (IsExpression && !Contexts.back().CaretFound)
1266 return TT_BinaryOperator;
1268 return TT_PointerOrReference;
1271 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1272 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1273 if (!PrevToken || PrevToken->is(TT_CastRParen))
1274 return TT_UnaryOperator;
1276 // Use heuristics to recognize unary operators.
1277 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1278 tok::question, tok::colon, tok::kw_return,
1279 tok::kw_case, tok::at, tok::l_brace))
1280 return TT_UnaryOperator;
1282 // There can't be two consecutive binary operators.
1283 if (PrevToken->is(TT_BinaryOperator))
1284 return TT_UnaryOperator;
1286 // Fall back to marking the token as binary operator.
1287 return TT_BinaryOperator;
1290 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1291 TokenType determineIncrementUsage(const FormatToken &Tok) {
1292 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1293 if (!PrevToken || PrevToken->is(TT_CastRParen))
1294 return TT_UnaryOperator;
1295 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1296 return TT_TrailingUnaryOperator;
1298 return TT_UnaryOperator;
1301 SmallVector<Context, 8> Contexts;
1303 const FormatStyle &Style;
1304 AnnotatedLine &Line;
1305 FormatToken *CurrentToken;
1307 const AdditionalKeywords &Keywords;
1309 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1310 // determines that a specific token can't be a template opener, it will make
1311 // same decision irrespective of the decisions for tokens leading up to it.
1312 // Store this information to prevent this from causing exponential runtime.
1313 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1316 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1317 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1319 /// \brief Parses binary expressions by inserting fake parenthesis based on
1320 /// operator precedence.
1321 class ExpressionParser {
1323 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1324 AnnotatedLine &Line)
1325 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1327 /// \brief Parse expressions with the given operatore precedence.
1328 void parse(int Precedence = 0) {
1329 // Skip 'return' and ObjC selector colons as they are not part of a binary
1331 while (Current && (Current->is(tok::kw_return) ||
1332 (Current->is(tok::colon) &&
1333 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1336 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1339 // Conditional expressions need to be parsed separately for proper nesting.
1340 if (Precedence == prec::Conditional) {
1341 parseConditionalExpr();
1345 // Parse unary operators, which all have a higher precedence than binary
1347 if (Precedence == PrecedenceUnaryOperator) {
1348 parseUnaryOperator();
1352 FormatToken *Start = Current;
1353 FormatToken *LatestOperator = nullptr;
1354 unsigned OperatorIndex = 0;
1357 // Consume operators with higher precedence.
1358 parse(Precedence + 1);
1360 int CurrentPrecedence = getCurrentPrecedence();
1362 if (Current && Current->is(TT_SelectorName) &&
1363 Precedence == CurrentPrecedence) {
1365 addFakeParenthesis(Start, prec::Level(Precedence));
1369 // At the end of the line or when an operator with higher precedence is
1370 // found, insert fake parenthesis and return.
1371 if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1372 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1373 (CurrentPrecedence == prec::Conditional &&
1374 Precedence == prec::Assignment && Current->is(tok::colon))) {
1378 // Consume scopes: (), [], <> and {}
1379 if (Current->opensScope()) {
1380 while (Current && !Current->closesScope()) {
1387 if (CurrentPrecedence == Precedence) {
1389 LatestOperator->NextOperator = Current;
1390 LatestOperator = Current;
1391 Current->OperatorIndex = OperatorIndex;
1394 next(/*SkipPastLeadingComments=*/Precedence > 0);
1398 if (LatestOperator && (Current || Precedence > 0)) {
1399 // LatestOperator->LastOperator = true;
1400 if (Precedence == PrecedenceArrowAndPeriod) {
1401 // Call expressions don't have a binary operator precedence.
1402 addFakeParenthesis(Start, prec::Unknown);
1404 addFakeParenthesis(Start, prec::Level(Precedence));
1410 /// \brief Gets the precedence (+1) of the given token for binary operators
1411 /// and other tokens that we treat like binary operators.
1412 int getCurrentPrecedence() {
1414 const FormatToken *NextNonComment = Current->getNextNonComment();
1415 if (Current->is(TT_ConditionalExpr))
1416 return prec::Conditional;
1417 if (NextNonComment && NextNonComment->is(tok::colon) &&
1418 NextNonComment->is(TT_DictLiteral))
1420 if (Current->is(TT_LambdaArrow))
1422 if (Current->is(TT_JsFatArrow))
1423 return prec::Assignment;
1424 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
1425 TT_JsComputedPropertyName) ||
1426 (Current->is(tok::comment) && NextNonComment &&
1427 NextNonComment->is(TT_SelectorName)))
1429 if (Current->is(TT_RangeBasedForLoopColon))
1431 if ((Style.Language == FormatStyle::LK_Java ||
1432 Style.Language == FormatStyle::LK_JavaScript) &&
1433 Current->is(Keywords.kw_instanceof))
1434 return prec::Relational;
1435 if (Style.Language == FormatStyle::LK_JavaScript &&
1436 Current->is(Keywords.kw_in))
1437 return prec::Relational;
1438 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1439 return Current->getPrecedence();
1440 if (Current->isOneOf(tok::period, tok::arrow))
1441 return PrecedenceArrowAndPeriod;
1442 if (Style.Language == FormatStyle::LK_Java &&
1443 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1444 Keywords.kw_throws))
1450 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1451 Start->FakeLParens.push_back(Precedence);
1452 if (Precedence > prec::Unknown)
1453 Start->StartsBinaryExpression = true;
1455 FormatToken *Previous = Current->Previous;
1456 while (Previous->is(tok::comment) && Previous->Previous)
1457 Previous = Previous->Previous;
1458 ++Previous->FakeRParens;
1459 if (Precedence > prec::Unknown)
1460 Previous->EndsBinaryExpression = true;
1464 /// \brief Parse unary operator expressions and surround them with fake
1465 /// parentheses if appropriate.
1466 void parseUnaryOperator() {
1467 if (!Current || Current->isNot(TT_UnaryOperator)) {
1468 parse(PrecedenceArrowAndPeriod);
1472 FormatToken *Start = Current;
1474 parseUnaryOperator();
1476 // The actual precedence doesn't matter.
1477 addFakeParenthesis(Start, prec::Unknown);
1480 void parseConditionalExpr() {
1481 while (Current && Current->isTrailingComment()) {
1484 FormatToken *Start = Current;
1485 parse(prec::LogicalOr);
1486 if (!Current || !Current->is(tok::question))
1489 parse(prec::Assignment);
1490 if (!Current || Current->isNot(TT_ConditionalExpr))
1493 parse(prec::Assignment);
1494 addFakeParenthesis(Start, prec::Conditional);
1497 void next(bool SkipPastLeadingComments = true) {
1499 Current = Current->Next;
1501 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1502 Current->isTrailingComment())
1503 Current = Current->Next;
1506 const FormatStyle &Style;
1507 const AdditionalKeywords &Keywords;
1508 FormatToken *Current;
1511 } // end anonymous namespace
1513 void TokenAnnotator::setCommentLineLevels(
1514 SmallVectorImpl<AnnotatedLine *> &Lines) {
1515 const AnnotatedLine *NextNonCommentLine = nullptr;
1516 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1519 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1520 (*I)->First->Next == nullptr)
1521 (*I)->Level = NextNonCommentLine->Level;
1523 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1525 setCommentLineLevels((*I)->Children);
1529 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1530 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1531 E = Line.Children.end();
1535 AnnotatingParser Parser(Style, Line, Keywords);
1536 Line.Type = Parser.parseLine();
1537 if (Line.Type == LT_Invalid)
1540 ExpressionParser ExprParser(Style, Keywords, Line);
1543 if (Line.startsWith(TT_ObjCMethodSpecifier))
1544 Line.Type = LT_ObjCMethodDecl;
1545 else if (Line.startsWith(TT_ObjCDecl))
1546 Line.Type = LT_ObjCDecl;
1547 else if (Line.startsWith(TT_ObjCProperty))
1548 Line.Type = LT_ObjCProperty;
1550 Line.First->SpacesRequiredBefore = 1;
1551 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1554 // This function heuristically determines whether 'Current' starts the name of a
1555 // function declaration.
1556 static bool isFunctionDeclarationName(const FormatToken &Current,
1557 const AnnotatedLine &Line) {
1558 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1559 for (; Next; Next = Next->Next) {
1560 if (Next->is(TT_OverloadedOperatorLParen))
1562 if (Next->is(TT_OverloadedOperator))
1564 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1565 // For 'new[]' and 'delete[]'.
1566 if (Next->Next && Next->Next->is(tok::l_square) &&
1567 Next->Next->Next && Next->Next->Next->is(tok::r_square))
1568 Next = Next->Next->Next;
1577 // Find parentheses of parameter list.
1578 const FormatToken *Next = Current.Next;
1579 if (Current.is(tok::kw_operator)) {
1580 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1582 Next = skipOperatorName(Next);
1584 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1586 for (; Next; Next = Next->Next) {
1587 if (Next->is(TT_TemplateOpener)) {
1588 Next = Next->MatchingParen;
1589 } else if (Next->is(tok::coloncolon)) {
1593 if (Next->is(tok::kw_operator)) {
1594 Next = skipOperatorName(Next->Next);
1597 if (!Next->is(tok::identifier))
1599 } else if (Next->is(tok::l_paren)) {
1607 // Check whether parameter list can be long to a function declaration.
1608 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
1610 // If the lines ends with "{", this is likely an function definition.
1611 if (Line.Last->is(tok::l_brace))
1613 if (Next->Next == Next->MatchingParen)
1614 return true; // Empty parentheses.
1615 // If there is an &/&& after the r_paren, this is likely a function.
1616 if (Next->MatchingParen->Next &&
1617 Next->MatchingParen->Next->is(TT_PointerOrReference))
1619 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1621 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1622 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
1624 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1625 Tok->Tok.isLiteral())
1631 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1632 assert(Line.MightBeFunctionDecl);
1634 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1635 Style.AlwaysBreakAfterReturnType ==
1636 FormatStyle::RTBS_TopLevelDefinitions) &&
1640 switch (Style.AlwaysBreakAfterReturnType) {
1641 case FormatStyle::RTBS_None:
1643 case FormatStyle::RTBS_All:
1644 case FormatStyle::RTBS_TopLevel:
1646 case FormatStyle::RTBS_AllDefinitions:
1647 case FormatStyle::RTBS_TopLevelDefinitions:
1648 return Line.mightBeFunctionDefinition();
1654 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1655 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1656 E = Line.Children.end();
1658 calculateFormattingInformation(**I);
1661 Line.First->TotalLength =
1662 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1663 if (!Line.First->Next)
1665 FormatToken *Current = Line.First->Next;
1666 bool InFunctionDecl = Line.MightBeFunctionDecl;
1668 if (isFunctionDeclarationName(*Current, Line))
1669 Current->Type = TT_FunctionDeclarationName;
1670 if (Current->is(TT_LineComment)) {
1671 if (Current->Previous->BlockKind == BK_BracedInit &&
1672 Current->Previous->opensScope())
1673 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1675 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1677 // If we find a trailing comment, iterate backwards to determine whether
1678 // it seems to relate to a specific parameter. If so, break before that
1679 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1680 // to the previous line in:
1684 if (!Current->HasUnescapedNewline) {
1685 for (FormatToken *Parameter = Current->Previous; Parameter;
1686 Parameter = Parameter->Previous) {
1687 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1689 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1690 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1691 Parameter->HasUnescapedNewline)
1692 Parameter->MustBreakBefore = true;
1697 } else if (Current->SpacesRequiredBefore == 0 &&
1698 spaceRequiredBefore(Line, *Current)) {
1699 Current->SpacesRequiredBefore = 1;
1702 Current->MustBreakBefore =
1703 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1705 if (!Current->MustBreakBefore && InFunctionDecl &&
1706 Current->is(TT_FunctionDeclarationName))
1707 Current->MustBreakBefore = mustBreakForReturnType(Line);
1709 Current->CanBreakBefore =
1710 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1711 unsigned ChildSize = 0;
1712 if (Current->Previous->Children.size() == 1) {
1713 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1714 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1715 : LastOfChild.TotalLength + 1;
1717 const FormatToken *Prev = Current->Previous;
1718 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1719 (Prev->Children.size() == 1 &&
1720 Prev->Children[0]->First->MustBreakBefore) ||
1721 Current->IsMultiline)
1722 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1724 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1725 ChildSize + Current->SpacesRequiredBefore;
1727 if (Current->is(TT_CtorInitializerColon))
1728 InFunctionDecl = false;
1730 // FIXME: Only calculate this if CanBreakBefore is true once static
1731 // initializers etc. are sorted out.
1732 // FIXME: Move magic numbers to a better place.
1733 Current->SplitPenalty = 20 * Current->BindingStrength +
1734 splitPenalty(Line, *Current, InFunctionDecl);
1736 Current = Current->Next;
1739 calculateUnbreakableTailLengths(Line);
1740 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1742 Current->Role->precomputeFormattingInfos(Current);
1745 DEBUG({ printDebugInfo(Line); });
1748 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1749 unsigned UnbreakableTailLength = 0;
1750 FormatToken *Current = Line.Last;
1752 Current->UnbreakableTailLength = UnbreakableTailLength;
1753 if (Current->CanBreakBefore ||
1754 Current->isOneOf(tok::comment, tok::string_literal)) {
1755 UnbreakableTailLength = 0;
1757 UnbreakableTailLength +=
1758 Current->ColumnWidth + Current->SpacesRequiredBefore;
1760 Current = Current->Previous;
1764 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1765 const FormatToken &Tok,
1766 bool InFunctionDecl) {
1767 const FormatToken &Left = *Tok.Previous;
1768 const FormatToken &Right = Tok;
1770 if (Left.is(tok::semi))
1773 if (Style.Language == FormatStyle::LK_Java) {
1774 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1776 if (Right.is(Keywords.kw_implements))
1778 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1780 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1781 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1783 if (Left.is(TT_JsTypeColon))
1787 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1788 Right.Next->is(TT_DictLiteral)))
1790 if (Right.is(tok::l_square)) {
1791 if (Style.Language == FormatStyle::LK_Proto)
1793 if (Left.is(tok::r_square))
1795 // Slightly prefer formatting local lambda definitions like functions.
1796 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1798 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1799 TT_ArrayInitializerLSquare))
1803 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1804 Right.is(tok::kw_operator)) {
1805 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1807 if (Left.is(TT_StartOfName))
1809 if (InFunctionDecl && Right.NestingLevel == 0)
1810 return Style.PenaltyReturnTypeOnItsOwnLine;
1813 if (Right.is(TT_PointerOrReference))
1815 if (Right.is(TT_LambdaArrow))
1817 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1819 if (Left.is(TT_CastRParen))
1821 if (Left.is(tok::coloncolon) ||
1822 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1824 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1827 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1830 if (Right.isMemberAccess()) {
1831 // Breaking before the "./->" of a chained call/member access is reasonably
1832 // cheap, as formatting those with one call per line is generally
1833 // desirable. In particular, it should be cheaper to break before the call
1834 // than it is to break inside a call's parameters, which could lead to weird
1835 // "hanging" indents. The exception is the very last "./->" to support this
1836 // frequent pattern:
1838 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
1841 // which might otherwise be blown up onto many lines. Here, clang-format
1842 // won't produce "hanging" indents anyway as there is no other trailing
1845 // Also apply higher penalty is not a call as that might lead to a wrapping
1849 // .aaaaaaaaa.bbbbbbbb(cccccccc);
1850 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
1855 if (Right.is(TT_TrailingAnnotation) &&
1856 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1857 // Moving trailing annotations to the next line is fine for ObjC method
1859 if (Line.startsWith(TT_ObjCMethodSpecifier))
1861 // Generally, breaking before a trailing annotation is bad unless it is
1862 // function-like. It seems to be especially preferable to keep standard
1863 // annotations (i.e. "const", "final" and "override") on the same line.
1864 // Use a slightly higher penalty after ")" so that annotations like
1865 // "const override" are kept together.
1866 bool is_short_annotation = Right.TokenText.size() < 10;
1867 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1870 // In for-loops, prefer breaking at ',' and ';'.
1871 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1874 // In Objective-C method expressions, prefer breaking before "param:" over
1875 // breaking after it.
1876 if (Right.is(TT_SelectorName))
1878 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1879 return Line.MightBeFunctionDecl ? 50 : 500;
1881 if (Left.is(tok::l_paren) && InFunctionDecl &&
1882 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1884 if (Left.is(tok::l_paren) && Left.Previous &&
1885 Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
1887 if (Left.is(tok::equal) && InFunctionDecl)
1889 if (Right.is(tok::r_brace))
1891 if (Left.is(TT_TemplateOpener))
1893 if (Left.opensScope()) {
1894 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
1896 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1899 if (Left.is(TT_JavaAnnotation))
1902 if (Right.is(tok::lessless)) {
1903 if (Left.is(tok::string_literal) &&
1904 (Right.NextOperator || Right.OperatorIndex != 1)) {
1905 StringRef Content = Left.TokenText;
1906 if (Content.startswith("\""))
1907 Content = Content.drop_front(1);
1908 if (Content.endswith("\""))
1909 Content = Content.drop_back(1);
1910 Content = Content.trim();
1911 if (Content.size() > 1 &&
1912 (Content.back() == ':' || Content.back() == '='))
1915 return 1; // Breaking at a << is really cheap.
1917 if (Left.is(TT_ConditionalExpr))
1918 return prec::Conditional;
1919 prec::Level Level = Left.getPrecedence();
1920 if (Level != prec::Unknown)
1922 Level = Right.getPrecedence();
1923 if (Level != prec::Unknown)
1929 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1930 const FormatToken &Left,
1931 const FormatToken &Right) {
1932 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1934 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1935 Left.Tok.getObjCKeywordID() == tok::objc_property)
1937 if (Right.is(tok::hashhash))
1938 return Left.is(tok::hash);
1939 if (Left.isOneOf(tok::hashhash, tok::hash))
1940 return Right.is(tok::hash);
1941 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1942 return Style.SpaceInEmptyParentheses;
1943 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1944 return (Right.is(TT_CastRParen) ||
1945 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1946 ? Style.SpacesInCStyleCastParentheses
1947 : Style.SpacesInParentheses;
1948 if (Right.isOneOf(tok::semi, tok::comma))
1950 if (Right.is(tok::less) &&
1951 (Left.is(tok::kw_template) ||
1952 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1954 if (Left.isOneOf(tok::exclaim, tok::tilde))
1956 if (Left.is(tok::at) &&
1957 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1958 tok::numeric_constant, tok::l_paren, tok::l_brace,
1959 tok::kw_true, tok::kw_false))
1961 if (Left.is(tok::colon))
1962 return !Left.is(TT_ObjCMethodExpr);
1963 if (Left.is(tok::coloncolon))
1965 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1967 if (Right.is(tok::ellipsis))
1968 return Left.Tok.isLiteral();
1969 if (Left.is(tok::l_square) && Right.is(tok::amp))
1971 if (Right.is(TT_PointerOrReference))
1972 return (Left.is(tok::r_paren) && Left.MatchingParen &&
1973 (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
1974 (Left.MatchingParen->Previous &&
1975 Left.MatchingParen->Previous->is(TT_FunctionDeclarationName)))) ||
1976 (Left.Tok.isLiteral() ||
1977 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1978 (Style.PointerAlignment != FormatStyle::PAS_Left ||
1979 Line.IsMultiVariableDeclStmt)));
1980 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
1981 (!Left.is(TT_PointerOrReference) ||
1982 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1983 !Line.IsMultiVariableDeclStmt)))
1985 if (Left.is(TT_PointerOrReference))
1986 return Right.Tok.isLiteral() ||
1987 Right.isOneOf(TT_BlockComment, Keywords.kw_final,
1988 Keywords.kw_override) ||
1989 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
1990 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
1992 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1993 !Line.IsMultiVariableDeclStmt) &&
1995 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1996 if (Right.is(tok::star) && Left.is(tok::l_paren))
1998 if (Left.is(tok::l_square))
1999 return (Left.is(TT_ArrayInitializerLSquare) &&
2000 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
2001 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
2002 Right.isNot(tok::r_square));
2003 if (Right.is(tok::r_square))
2004 return Right.MatchingParen &&
2005 ((Style.SpacesInContainerLiterals &&
2006 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
2007 (Style.SpacesInSquareBrackets &&
2008 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
2009 if (Right.is(tok::l_square) &&
2010 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
2011 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2013 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2014 return !Left.Children.empty(); // No spaces in "{}".
2015 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2016 (Right.is(tok::r_brace) && Right.MatchingParen &&
2017 Right.MatchingParen->BlockKind != BK_Block))
2018 return !Style.Cpp11BracedListStyle;
2019 if (Left.is(TT_BlockComment))
2020 return !Left.TokenText.endswith("=*/");
2021 if (Right.is(tok::l_paren)) {
2022 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
2024 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2025 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2026 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2027 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2029 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2030 tok::kw_new, tok::kw_delete) &&
2031 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2032 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2033 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2034 Left.is(tok::r_paren)) &&
2035 Line.Type != LT_PreprocessorDirective);
2037 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2039 if (Right.is(TT_UnaryOperator))
2040 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2041 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2042 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2044 Left.isSimpleTypeSpecifier()) &&
2045 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2046 Right.BlockKind != BK_Block)
2048 if (Left.is(tok::period) || Right.is(tok::period))
2050 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2052 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2053 Left.MatchingParen->Previous &&
2054 Left.MatchingParen->Previous->is(tok::period))
2055 // A.<B>DoSomething();
2057 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2062 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2063 const FormatToken &Right) {
2064 const FormatToken &Left = *Right.Previous;
2065 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2066 return true; // Never ever merge two identifiers.
2067 if (Style.Language == FormatStyle::LK_Cpp) {
2068 if (Left.is(tok::kw_operator))
2069 return Right.is(tok::coloncolon);
2070 } else if (Style.Language == FormatStyle::LK_Proto) {
2071 if (Right.is(tok::period) &&
2072 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2073 Keywords.kw_repeated, Keywords.kw_extend))
2075 if (Right.is(tok::l_paren) &&
2076 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2078 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2079 if (Left.is(TT_JsFatArrow))
2081 if (Right.is(tok::star) &&
2082 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2084 if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2086 (!Left.Previous || !Left.Previous->is(tok::period)))
2088 if (Left.is(tok::kw_default) && Left.Previous &&
2089 Left.Previous->is(tok::kw_export))
2091 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2093 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2095 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2097 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2098 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2100 if (Left.is(tok::ellipsis))
2102 if (Left.is(TT_TemplateCloser) &&
2103 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2104 Keywords.kw_implements, Keywords.kw_extends))
2105 // Type assertions ('<type>expr') are not followed by whitespace. Other
2106 // locations that should have whitespace following are identified by the
2107 // above set of follower tokens.
2109 } else if (Style.Language == FormatStyle::LK_Java) {
2110 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2112 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2113 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2114 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2115 tok::kw_protected) ||
2116 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2117 Keywords.kw_native)) &&
2118 Right.is(TT_TemplateOpener))
2121 if (Left.is(TT_ImplicitStringLiteral))
2122 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2123 if (Line.Type == LT_ObjCMethodDecl) {
2124 if (Left.is(TT_ObjCMethodSpecifier))
2126 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2127 // Don't space between ')' and <id>
2130 if (Line.Type == LT_ObjCProperty &&
2131 (Right.is(tok::equal) || Left.is(tok::equal)))
2134 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2135 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2137 if (Right.is(TT_OverloadedOperatorLParen))
2138 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2139 if (Left.is(tok::comma))
2141 if (Right.is(tok::comma))
2143 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2145 if (Right.is(tok::colon)) {
2146 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2147 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2149 if (Right.is(TT_ObjCMethodExpr))
2151 if (Left.is(tok::question))
2153 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2155 if (Right.is(TT_DictLiteral))
2156 return Style.SpacesInContainerLiterals;
2159 if (Left.is(TT_UnaryOperator))
2160 return Right.is(TT_BinaryOperator);
2162 // If the next token is a binary operator or a selector name, we have
2163 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2164 if (Left.is(TT_CastRParen))
2165 return Style.SpaceAfterCStyleCast ||
2166 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2168 if (Left.is(tok::greater) && Right.is(tok::greater))
2169 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2170 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2171 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2172 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2174 if (!Style.SpaceBeforeAssignmentOperators &&
2175 Right.getPrecedence() == prec::Assignment)
2177 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2178 return (Left.is(TT_TemplateOpener) &&
2179 Style.Standard == FormatStyle::LS_Cpp03) ||
2180 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren,
2182 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
2183 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2184 return Style.SpacesInAngles;
2185 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2186 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2187 !Right.is(tok::r_paren)))
2189 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2190 Right.isNot(TT_FunctionTypeLParen))
2191 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2192 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2193 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2195 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2196 Line.startsWith(tok::hash))
2198 if (Right.is(TT_TrailingUnaryOperator))
2200 if (Left.is(TT_RegexLiteral))
2202 return spaceRequiredBetween(Line, Left, Right);
2205 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2206 static bool isAllmanBrace(const FormatToken &Tok) {
2207 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2208 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2211 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2212 const FormatToken &Right) {
2213 const FormatToken &Left = *Right.Previous;
2214 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2217 if (Style.Language == FormatStyle::LK_JavaScript) {
2218 // FIXME: This might apply to other languages and token kinds.
2219 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2220 Left.Previous->is(tok::string_literal))
2222 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2223 Left.Previous && Left.Previous->is(tok::equal) &&
2224 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2226 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2228 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2229 // Object literals on the top level of a file are treated as "enum-style".
2230 // Each key/value pair is put on a separate line, instead of bin-packing.
2232 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2233 (Line.startsWith(tok::kw_enum) ||
2234 Line.startsWith(tok::kw_export, tok::kw_enum)))
2235 // JavaScript top-level enum key/value pairs are put on separate lines
2236 // instead of bin-packing.
2238 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2239 !Left.Children.empty())
2240 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2241 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2242 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2243 (Left.NestingLevel == 0 && Line.Level == 0 &&
2244 Style.AllowShortFunctionsOnASingleLine ==
2245 FormatStyle::SFS_Inline);
2246 } else if (Style.Language == FormatStyle::LK_Java) {
2247 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2248 Right.Next->is(tok::string_literal))
2252 // If the last token before a '}' is a comma or a trailing comment, the
2253 // intention is to insert a line break after it in order to make shuffling
2254 // around entries easier.
2255 const FormatToken *BeforeClosingBrace = nullptr;
2256 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2257 Left.BlockKind != BK_Block && Left.MatchingParen)
2258 BeforeClosingBrace = Left.MatchingParen->Previous;
2259 else if (Right.MatchingParen &&
2260 Right.MatchingParen->isOneOf(tok::l_brace,
2261 TT_ArrayInitializerLSquare))
2262 BeforeClosingBrace = &Left;
2263 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2264 BeforeClosingBrace->isTrailingComment()))
2267 if (Right.is(tok::comment))
2268 return Left.BlockKind != BK_BracedInit &&
2269 Left.isNot(TT_CtorInitializerColon) &&
2270 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2271 if (Left.isTrailingComment())
2273 if (Left.isStringLiteral() &&
2274 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2276 if (Right.Previous->IsUnterminatedLiteral)
2278 if (Right.is(tok::lessless) && Right.Next &&
2279 Right.Previous->is(tok::string_literal) &&
2280 Right.Next->is(tok::string_literal))
2282 if (Right.Previous->ClosesTemplateDeclaration &&
2283 Right.Previous->MatchingParen &&
2284 Right.Previous->MatchingParen->NestingLevel == 0 &&
2285 Style.AlwaysBreakTemplateDeclarations)
2287 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2288 Style.BreakConstructorInitializersBeforeComma &&
2289 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2291 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2292 // Raw string literals are special wrt. line breaks. The author has made a
2293 // deliberate choice and might have aligned the contents of the string
2294 // literal accordingly. Thus, we try keep existing line breaks.
2295 return Right.NewlinesBefore > 0;
2296 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2297 Style.Language == FormatStyle::LK_Proto)
2298 // Don't put enums onto single lines in protocol buffers.
2300 if (Right.is(TT_InlineASMBrace))
2301 return Right.HasUnescapedNewline;
2302 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2303 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2304 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2305 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2306 if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2307 Right.is(TT_SelectorName))
2309 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2312 if ((Style.Language == FormatStyle::LK_Java ||
2313 Style.Language == FormatStyle::LK_JavaScript) &&
2314 Left.is(TT_LeadingJavaAnnotation) &&
2315 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2316 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2322 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2323 const FormatToken &Right) {
2324 const FormatToken &Left = *Right.Previous;
2326 // Language-specific stuff.
2327 if (Style.Language == FormatStyle::LK_Java) {
2328 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2329 Keywords.kw_implements))
2331 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2332 Keywords.kw_implements))
2334 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2335 if (Left.is(tok::kw_return))
2336 return false; // Otherwise a semicolon is inserted.
2337 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2339 if (Left.is(TT_JsTypeColon))
2341 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2343 if (Left.is(Keywords.kw_in))
2344 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
2345 if (Right.is(Keywords.kw_in))
2346 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
2349 if (Left.is(tok::at))
2351 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2353 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2354 return !Right.is(tok::l_paren);
2355 if (Right.is(TT_PointerOrReference))
2356 return Line.IsMultiVariableDeclStmt ||
2357 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2358 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2359 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2360 Right.is(tok::kw_operator))
2362 if (Left.is(TT_PointerOrReference))
2364 if (Right.isTrailingComment())
2365 // We rely on MustBreakBefore being set correctly here as we should not
2366 // change the "binding" behavior of a comment.
2367 // The first comment in a braced lists is always interpreted as belonging to
2368 // the first list element. Otherwise, it should be placed outside of the
2370 return Left.BlockKind == BK_BracedInit;
2371 if (Left.is(tok::question) && Right.is(tok::colon))
2373 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2374 return Style.BreakBeforeTernaryOperators;
2375 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2376 return !Style.BreakBeforeTernaryOperators;
2377 if (Right.is(TT_InheritanceColon))
2379 if (Right.is(tok::colon) &&
2380 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2382 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2384 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2385 Right.Next->is(TT_ObjCMethodExpr)))
2386 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2387 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2389 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2391 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2392 TT_OverloadedOperator))
2394 if (Left.is(TT_RangeBasedForLoopColon))
2396 if (Right.is(TT_RangeBasedForLoopColon))
2398 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2399 Left.is(tok::kw_operator))
2401 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2402 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2404 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2406 if (Left.is(tok::l_paren) && Left.Previous &&
2407 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2409 if (Right.is(TT_ImplicitStringLiteral))
2412 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2414 if (Right.is(tok::r_square) && Right.MatchingParen &&
2415 Right.MatchingParen->is(TT_LambdaLSquare))
2418 // We only break before r_brace if there was a corresponding break before
2419 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2420 if (Right.is(tok::r_brace))
2421 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2423 // Allow breaking after a trailing annotation, e.g. after a method
2425 if (Left.is(TT_TrailingAnnotation))
2426 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2427 tok::less, tok::coloncolon);
2429 if (Right.is(tok::kw___attribute))
2432 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2435 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2438 if (Left.is(TT_CtorInitializerComma) &&
2439 Style.BreakConstructorInitializersBeforeComma)
2441 if (Right.is(TT_CtorInitializerComma) &&
2442 Style.BreakConstructorInitializersBeforeComma)
2444 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2445 (Left.is(tok::less) && Right.is(tok::less)))
2447 if (Right.is(TT_BinaryOperator) &&
2448 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2449 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2450 Right.getPrecedence() != prec::Assignment))
2452 if (Left.is(TT_ArrayInitializerLSquare))
2454 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2456 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2457 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2458 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2459 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2460 Left.getPrecedence() == prec::Assignment))
2462 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2463 tok::kw_class, tok::kw_struct) ||
2464 Right.isMemberAccess() ||
2465 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2466 tok::colon, tok::l_square, tok::at) ||
2467 (Left.is(tok::r_paren) &&
2468 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2469 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2472 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2473 llvm::errs() << "AnnotatedTokens:\n";
2474 const FormatToken *Tok = Line.First;
2476 llvm::errs() << " M=" << Tok->MustBreakBefore
2477 << " C=" << Tok->CanBreakBefore
2478 << " T=" << getTokenTypeName(Tok->Type)
2479 << " S=" << Tok->SpacesRequiredBefore
2480 << " B=" << Tok->BlockParameterCount
2481 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2482 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2484 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2485 llvm::errs() << Tok->FakeLParens[i] << "/";
2486 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2488 assert(Tok == Line.Last);
2491 llvm::errs() << "----\n";
2494 } // namespace format
2495 } // namespace clang