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)
580 if (Tok->Previous && Tok->Previous->is(tok::period))
582 // JS' for async ( ...
583 if (CurrentToken->is(Keywords.kw_async))
585 Contexts.back().ColonIsForRangeExpr = true;
591 // When faced with 'operator()()', the kw_operator handler incorrectly
592 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
593 // the first two parens OverloadedOperators and the second l_paren an
594 // OverloadedOperatorLParen.
596 Tok->Previous->is(tok::r_paren) &&
597 Tok->Previous->MatchingParen &&
598 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
599 Tok->Previous->Type = TT_OverloadedOperator;
600 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
601 Tok->Type = TT_OverloadedOperatorLParen;
606 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
607 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
609 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
610 TT_LeadingJavaAnnotation)))
611 Line.MightBeFunctionDecl = true;
623 Tok->Type = TT_TemplateOpener;
625 Tok->Type = TT_BinaryOperator;
626 NonTemplateLess.insert(Tok);
635 // Lines can start with '}'.
640 Tok->Type = TT_BinaryOperator;
642 case tok::kw_operator:
643 while (CurrentToken &&
644 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
645 if (CurrentToken->isOneOf(tok::star, tok::amp))
646 CurrentToken->Type = TT_PointerOrReference;
649 CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma))
650 CurrentToken->Previous->Type = TT_OverloadedOperator;
653 CurrentToken->Type = TT_OverloadedOperatorLParen;
654 if (CurrentToken->Previous->is(TT_BinaryOperator))
655 CurrentToken->Previous->Type = TT_OverloadedOperator;
659 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
660 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
662 // Question marks before semicolons, colons, etc. indicate optional
663 // types (fields, parameters), e.g.
664 // function(x?: string, y?) {...}
666 Tok->Type = TT_JsTypeOptionalQuestion;
669 // Declarations cannot be conditional expressions, this can only be part
670 // of a type declaration.
671 if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
672 Style.Language == FormatStyle::LK_JavaScript)
676 case tok::kw_template:
677 parseTemplateDeclaration();
680 if (Contexts.back().InCtorInitializer)
681 Tok->Type = TT_CtorInitializerComma;
682 else if (Contexts.back().InInheritanceList)
683 Tok->Type = TT_InheritanceComma;
684 else if (Contexts.back().FirstStartOfName &&
685 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
686 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
687 Line.IsMultiVariableDeclStmt = true;
689 if (Contexts.back().IsForEachMacro)
690 Contexts.back().IsExpression = true;
692 case tok::identifier:
693 if (Tok->isOneOf(Keywords.kw___has_include,
694 Keywords.kw___has_include_next)) {
704 void parseIncludeDirective() {
705 if (CurrentToken && CurrentToken->is(tok::less)) {
707 while (CurrentToken) {
708 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
709 CurrentToken->Type = TT_ImplicitStringLiteral;
715 void parseWarningOrError() {
717 // We still want to format the whitespace left of the first token of the
720 while (CurrentToken) {
721 CurrentToken->Type = TT_ImplicitStringLiteral;
727 next(); // Consume "pragma".
729 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
730 bool IsMark = CurrentToken->is(Keywords.kw_mark);
731 next(); // Consume "mark".
732 next(); // Consume first token (so we fix leading whitespace).
733 while (CurrentToken) {
734 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
735 CurrentToken->Type = TT_ImplicitStringLiteral;
741 void parseHasInclude() {
742 if (!CurrentToken || !CurrentToken->is(tok::l_paren))
745 parseIncludeDirective();
749 LineType parsePreprocessorDirective() {
750 bool IsFirstToken = CurrentToken->IsFirst;
751 LineType Type = LT_PreprocessorDirective;
756 if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
757 // JavaScript files can contain shebang lines of the form:
758 // #!/usr/bin/env node
759 // Treat these like C++ #include directives.
760 while (CurrentToken) {
761 // Tokens cannot be comments here.
762 CurrentToken->Type = TT_ImplicitStringLiteral;
765 return LT_ImportStatement;
768 if (CurrentToken->Tok.is(tok::numeric_constant)) {
769 CurrentToken->SpacesRequiredBefore = 1;
772 // Hashes in the middle of a line can lead to any strange token
774 if (!CurrentToken->Tok.getIdentifierInfo())
776 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
777 case tok::pp_include:
778 case tok::pp_include_next:
781 parseIncludeDirective();
782 Type = LT_ImportStatement;
785 case tok::pp_warning:
786 parseWarningOrError();
793 Contexts.back().IsExpression = true;
799 while (CurrentToken) {
800 FormatToken *Tok = CurrentToken;
802 if (Tok->is(tok::l_paren))
804 else if (Tok->isOneOf(Keywords.kw___has_include,
805 Keywords.kw___has_include_next))
812 LineType parseLine() {
813 NonTemplateLess.clear();
814 if (CurrentToken->is(tok::hash))
815 return parsePreprocessorDirective();
817 // Directly allow to 'import <string-literal>' to support protocol buffer
818 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
819 // should not break the line).
820 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
821 if ((Style.Language == FormatStyle::LK_Java &&
822 CurrentToken->is(Keywords.kw_package)) ||
823 (Info && Info->getPPKeywordID() == tok::pp_import &&
824 CurrentToken->Next &&
825 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
828 parseIncludeDirective();
829 return LT_ImportStatement;
832 // If this line starts and ends in '<' and '>', respectively, it is likely
833 // part of "#define <a/b.h>".
834 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
835 parseIncludeDirective();
836 return LT_ImportStatement;
839 // In .proto files, top-level options are very similar to import statements
840 // and should not be line-wrapped.
841 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
842 CurrentToken->is(Keywords.kw_option)) {
844 if (CurrentToken && CurrentToken->is(tok::identifier))
845 return LT_ImportStatement;
848 bool KeywordVirtualFound = false;
849 bool ImportStatement = false;
851 // import {...} from '...';
852 if (Style.Language == FormatStyle::LK_JavaScript &&
853 CurrentToken->is(Keywords.kw_import))
854 ImportStatement = true;
856 while (CurrentToken) {
857 if (CurrentToken->is(tok::kw_virtual))
858 KeywordVirtualFound = true;
859 if (Style.Language == FormatStyle::LK_JavaScript) {
860 // export {...} from '...';
861 // An export followed by "from 'some string';" is a re-export from
862 // another module identified by a URI and is treated as a
863 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
864 // Just "export {...};" or "export class ..." should not be treated as
865 // an import in this sense.
866 if (Line.First->is(tok::kw_export) &&
867 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
868 CurrentToken->Next->isStringLiteral())
869 ImportStatement = true;
870 if (isClosureImportStatement(*CurrentToken))
871 ImportStatement = true;
876 if (KeywordVirtualFound)
877 return LT_VirtualFunctionDecl;
879 return LT_ImportStatement;
881 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
882 if (Contexts.back().FirstObjCSelectorName)
883 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
884 Contexts.back().LongestObjCSelectorName;
885 return LT_ObjCMethodDecl;
892 bool isClosureImportStatement(const FormatToken &Tok) {
893 // FIXME: Closure-library specific stuff should not be hard-coded but be
895 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
896 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
897 Tok.Next->Next->TokenText == "provide" ||
898 Tok.Next->Next->TokenText == "require" ||
899 Tok.Next->Next->TokenText == "setTestOnly" ||
900 Tok.Next->Next->TokenText == "forwardDeclare") &&
901 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
904 void resetTokenMetadata(FormatToken *Token) {
908 // Reset token type in case we have already looked at it and then
909 // recovered from an error (e.g. failure to find the matching >).
910 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
911 TT_FunctionLBrace, TT_ImplicitStringLiteral,
912 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
913 TT_OverloadedOperator, TT_RegexLiteral,
914 TT_TemplateString, TT_ObjCStringLiteral))
915 CurrentToken->Type = TT_Unknown;
916 CurrentToken->Role.reset();
917 CurrentToken->MatchingParen = nullptr;
918 CurrentToken->FakeLParens.clear();
919 CurrentToken->FakeRParens = 0;
924 CurrentToken->NestingLevel = Contexts.size() - 1;
925 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
926 modifyContext(*CurrentToken);
927 determineTokenType(*CurrentToken);
928 CurrentToken = CurrentToken->Next;
931 resetTokenMetadata(CurrentToken);
934 /// \brief A struct to hold information valid in a specific context, e.g.
935 /// a pair of parenthesis.
937 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
939 : ContextKind(ContextKind), BindingStrength(BindingStrength),
940 IsExpression(IsExpression) {}
942 tok::TokenKind ContextKind;
943 unsigned BindingStrength;
945 unsigned LongestObjCSelectorName = 0;
946 bool ColonIsForRangeExpr = false;
947 bool ColonIsDictLiteral = false;
948 bool ColonIsObjCMethodExpr = false;
949 FormatToken *FirstObjCSelectorName = nullptr;
950 FormatToken *FirstStartOfName = nullptr;
951 bool CanBeExpression = true;
952 bool InTemplateArgument = false;
953 bool InCtorInitializer = false;
954 bool InInheritanceList = false;
955 bool CaretFound = false;
956 bool IsForEachMacro = false;
959 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
960 /// of each instance.
961 struct ScopedContextCreator {
964 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
967 P.Contexts.push_back(Context(ContextKind,
968 P.Contexts.back().BindingStrength + Increase,
969 P.Contexts.back().IsExpression));
972 ~ScopedContextCreator() { P.Contexts.pop_back(); }
975 void modifyContext(const FormatToken &Current) {
976 if (Current.getPrecedence() == prec::Assignment &&
977 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
978 // Type aliases use `type X = ...;` in TypeScript.
979 !(Style.Language == FormatStyle::LK_JavaScript &&
980 Line.startsWith(Keywords.kw_type, tok::identifier)) &&
981 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
982 Contexts.back().IsExpression = true;
983 if (!Line.startsWith(TT_UnaryOperator)) {
984 for (FormatToken *Previous = Current.Previous;
985 Previous && Previous->Previous &&
986 !Previous->Previous->isOneOf(tok::comma, tok::semi);
987 Previous = Previous->Previous) {
988 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
989 Previous = Previous->MatchingParen;
993 if (Previous->opensScope())
995 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
996 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
997 Previous->Previous && Previous->Previous->isNot(tok::equal))
998 Previous->Type = TT_PointerOrReference;
1001 } else if (Current.is(tok::lessless) &&
1002 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1003 Contexts.back().IsExpression = true;
1004 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1005 Contexts.back().IsExpression = true;
1006 } else if (Current.is(TT_TrailingReturnArrow)) {
1007 Contexts.back().IsExpression = false;
1008 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1009 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1010 } else if (Current.Previous &&
1011 Current.Previous->is(TT_CtorInitializerColon)) {
1012 Contexts.back().IsExpression = true;
1013 Contexts.back().InCtorInitializer = true;
1014 } else if (Current.Previous &&
1015 Current.Previous->is(TT_InheritanceColon)) {
1016 Contexts.back().InInheritanceList = true;
1017 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1018 for (FormatToken *Previous = Current.Previous;
1019 Previous && Previous->isOneOf(tok::star, tok::amp);
1020 Previous = Previous->Previous)
1021 Previous->Type = TT_PointerOrReference;
1022 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1023 Contexts.back().IsExpression = false;
1024 } else if (Current.is(tok::kw_new)) {
1025 Contexts.back().CanBeExpression = false;
1026 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
1027 // This should be the condition or increment in a for-loop.
1028 Contexts.back().IsExpression = true;
1032 void determineTokenType(FormatToken &Current) {
1033 if (!Current.is(TT_Unknown))
1034 // The token type is already known.
1037 if (Style.Language == FormatStyle::LK_JavaScript) {
1038 if (Current.is(tok::exclaim)) {
1039 if (Current.Previous &&
1040 (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
1041 tok::r_paren, tok::r_square,
1043 Current.Previous->Tok.isLiteral())) {
1044 Current.Type = TT_JsNonNullAssertion;
1048 Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1049 Current.Type = TT_JsNonNullAssertion;
1055 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1056 // function declaration have been found. In this case, 'Current' is a
1057 // trailing token of this declaration and thus cannot be a name.
1058 if (Current.is(Keywords.kw_instanceof)) {
1059 Current.Type = TT_BinaryOperator;
1060 } else if (isStartOfName(Current) &&
1061 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1062 Contexts.back().FirstStartOfName = &Current;
1063 Current.Type = TT_StartOfName;
1064 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1066 } else if (Current.is(tok::arrow) &&
1067 Style.Language == FormatStyle::LK_Java) {
1068 Current.Type = TT_LambdaArrow;
1069 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1070 Current.NestingLevel == 0) {
1071 Current.Type = TT_TrailingReturnArrow;
1072 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1074 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
1075 Contexts.back().IsExpression,
1076 Contexts.back().InTemplateArgument);
1077 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1078 Current.Type = determinePlusMinusCaretUsage(Current);
1079 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1080 Contexts.back().CaretFound = true;
1081 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1082 Current.Type = determineIncrementUsage(Current);
1083 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1084 Current.Type = TT_UnaryOperator;
1085 } else if (Current.is(tok::question)) {
1086 if (Style.Language == FormatStyle::LK_JavaScript &&
1087 Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1088 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1089 // on the interface, not a ternary expression.
1090 Current.Type = TT_JsTypeOptionalQuestion;
1092 Current.Type = TT_ConditionalExpr;
1094 } else if (Current.isBinaryOperator() &&
1095 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
1096 Current.Type = TT_BinaryOperator;
1097 } else if (Current.is(tok::comment)) {
1098 if (Current.TokenText.startswith("/*")) {
1099 if (Current.TokenText.endswith("*/"))
1100 Current.Type = TT_BlockComment;
1102 // The lexer has for some reason determined a comment here. But we
1103 // cannot really handle it, if it isn't properly terminated.
1104 Current.Tok.setKind(tok::unknown);
1106 Current.Type = TT_LineComment;
1108 } else if (Current.is(tok::r_paren)) {
1109 if (rParenEndsCast(Current))
1110 Current.Type = TT_CastRParen;
1111 if (Current.MatchingParen && Current.Next &&
1112 !Current.Next->isBinaryOperator() &&
1113 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1114 tok::comma, tok::period, tok::arrow,
1116 if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1117 // Make sure this isn't the return type of an Obj-C block declaration
1118 if (AfterParen->Tok.isNot(tok::caret)) {
1119 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1120 if (BeforeParen->is(tok::identifier) &&
1121 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1122 (!BeforeParen->Previous ||
1123 BeforeParen->Previous->ClosesTemplateDeclaration))
1124 Current.Type = TT_FunctionAnnotationRParen;
1127 } else if (Current.is(tok::at) && Current.Next &&
1128 Style.Language != FormatStyle::LK_JavaScript &&
1129 Style.Language != FormatStyle::LK_Java) {
1130 // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1131 // marks declarations and properties that need special formatting.
1132 switch (Current.Next->Tok.getObjCKeywordID()) {
1133 case tok::objc_interface:
1134 case tok::objc_implementation:
1135 case tok::objc_protocol:
1136 Current.Type = TT_ObjCDecl;
1138 case tok::objc_property:
1139 Current.Type = TT_ObjCProperty;
1144 } else if (Current.is(tok::period)) {
1145 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1146 if (PreviousNoComment &&
1147 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1148 Current.Type = TT_DesignatedInitializerPeriod;
1149 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1150 Current.Previous->isOneOf(TT_JavaAnnotation,
1151 TT_LeadingJavaAnnotation)) {
1152 Current.Type = Current.Previous->Type;
1154 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1156 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1157 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1158 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1159 // function declaration have been found.
1160 Current.Type = TT_TrailingAnnotation;
1161 } else if ((Style.Language == FormatStyle::LK_Java ||
1162 Style.Language == FormatStyle::LK_JavaScript) &&
1164 if (Current.Previous->is(tok::at) &&
1165 Current.isNot(Keywords.kw_interface)) {
1166 const FormatToken &AtToken = *Current.Previous;
1167 const FormatToken *Previous = AtToken.getPreviousNonComment();
1168 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1169 Current.Type = TT_LeadingJavaAnnotation;
1171 Current.Type = TT_JavaAnnotation;
1172 } else if (Current.Previous->is(tok::period) &&
1173 Current.Previous->isOneOf(TT_JavaAnnotation,
1174 TT_LeadingJavaAnnotation)) {
1175 Current.Type = Current.Previous->Type;
1180 /// \brief Take a guess at whether \p Tok starts a name of a function or
1181 /// variable declaration.
1183 /// This is a heuristic based on whether \p Tok is an identifier following
1184 /// something that is likely a type.
1185 bool isStartOfName(const FormatToken &Tok) {
1186 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1189 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1192 if (Style.Language == FormatStyle::LK_JavaScript &&
1193 Tok.Previous->is(Keywords.kw_in))
1196 // Skip "const" as it does not have an influence on whether this is a name.
1197 FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1198 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1199 PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1201 if (!PreviousNotConst)
1204 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1205 PreviousNotConst->Previous &&
1206 PreviousNotConst->Previous->is(tok::hash);
1208 if (PreviousNotConst->is(TT_TemplateCloser))
1209 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1210 PreviousNotConst->MatchingParen->Previous &&
1211 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1212 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1214 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1215 PreviousNotConst->MatchingParen->Previous &&
1216 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1219 return (!IsPPKeyword &&
1220 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1221 PreviousNotConst->is(TT_PointerOrReference) ||
1222 PreviousNotConst->isSimpleTypeSpecifier();
1225 /// \brief Determine whether ')' is ending a cast.
1226 bool rParenEndsCast(const FormatToken &Tok) {
1227 // C-style casts are only used in C++ and Java.
1228 if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
1231 // Empty parens aren't casts and there are no casts at the end of the line.
1232 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1235 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1237 // If there is a closing parenthesis left of the current parentheses,
1238 // look past it as these might be chained casts.
1239 if (LeftOfParens->is(tok::r_paren)) {
1240 if (!LeftOfParens->MatchingParen ||
1241 !LeftOfParens->MatchingParen->Previous)
1243 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1246 // If there is an identifier (or with a few exceptions a keyword) right
1247 // before the parentheses, this is unlikely to be a cast.
1248 if (LeftOfParens->Tok.getIdentifierInfo() &&
1249 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1253 // Certain other tokens right before the parentheses are also signals that
1254 // this cannot be a cast.
1255 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1256 TT_TemplateCloser, tok::ellipsis))
1260 if (Tok.Next->is(tok::question))
1263 // As Java has no function types, a "(" after the ")" likely means that this
1265 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1268 // If a (non-string) literal follows, this is likely a cast.
1269 if (Tok.Next->isNot(tok::string_literal) &&
1270 (Tok.Next->Tok.isLiteral() ||
1271 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1274 // Heuristically try to determine whether the parentheses contain a type.
1275 bool ParensAreType =
1277 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1278 Tok.Previous->isSimpleTypeSpecifier();
1279 bool ParensCouldEndDecl =
1280 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1281 if (ParensAreType && !ParensCouldEndDecl)
1284 // At this point, we heuristically assume that there are no casts at the
1285 // start of the line. We assume that we have found most cases where there
1286 // are by the logic above, e.g. "(void)x;".
1290 // Certain token types inside the parentheses mean that this can't be a
1292 for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1293 Token = Token->Next)
1294 if (Token->is(TT_BinaryOperator))
1297 // If the following token is an identifier or 'this', this is a cast. All
1298 // cases where this can be something else are handled above.
1299 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1302 if (!Tok.Next->Next)
1305 // If the next token after the parenthesis is a unary operator, assume
1306 // that this is cast, unless there are unexpected tokens inside the
1309 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1310 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1311 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1313 // Search for unexpected tokens.
1314 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1315 Prev = Prev->Previous) {
1316 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1322 /// \brief Return the type of the given token assuming it is * or &.
1323 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1324 bool InTemplateArgument) {
1325 if (Style.Language == FormatStyle::LK_JavaScript)
1326 return TT_BinaryOperator;
1328 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1330 return TT_UnaryOperator;
1332 const FormatToken *NextToken = Tok.getNextNonComment();
1334 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
1335 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1336 return TT_PointerOrReference;
1338 if (PrevToken->is(tok::coloncolon))
1339 return TT_PointerOrReference;
1341 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1342 tok::comma, tok::semi, tok::kw_return, tok::colon,
1343 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1344 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1345 TT_UnaryOperator, TT_CastRParen))
1346 return TT_UnaryOperator;
1348 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1349 return TT_PointerOrReference;
1350 if (NextToken->is(tok::kw_operator) && !IsExpression)
1351 return TT_PointerOrReference;
1352 if (NextToken->isOneOf(tok::comma, tok::semi))
1353 return TT_PointerOrReference;
1355 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1356 PrevToken->MatchingParen->Previous &&
1357 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1359 return TT_PointerOrReference;
1361 if (PrevToken->Tok.isLiteral() ||
1362 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1363 tok::kw_false, tok::r_brace) ||
1364 NextToken->Tok.isLiteral() ||
1365 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1366 NextToken->isUnaryOperator() ||
1367 // If we know we're in a template argument, there are no named
1368 // declarations. Thus, having an identifier on the right-hand side
1369 // indicates a binary operator.
1370 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1371 return TT_BinaryOperator;
1373 // "&&(" is quite unlikely to be two successive unary "&".
1374 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1375 return TT_BinaryOperator;
1377 // This catches some cases where evaluation order is used as control flow:
1379 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1380 if (NextNextToken && NextNextToken->is(tok::arrow))
1381 return TT_BinaryOperator;
1383 // It is very unlikely that we are going to find a pointer or reference type
1384 // definition on the RHS of an assignment.
1385 if (IsExpression && !Contexts.back().CaretFound)
1386 return TT_BinaryOperator;
1388 return TT_PointerOrReference;
1391 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1392 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1394 return TT_UnaryOperator;
1396 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
1397 !PrevToken->is(tok::exclaim))
1398 // There aren't any trailing unary operators except for TypeScript's
1399 // non-null operator (!). Thus, this must be squence of leading operators.
1400 return TT_UnaryOperator;
1402 // Use heuristics to recognize unary operators.
1403 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1404 tok::question, tok::colon, tok::kw_return,
1405 tok::kw_case, tok::at, tok::l_brace))
1406 return TT_UnaryOperator;
1408 // There can't be two consecutive binary operators.
1409 if (PrevToken->is(TT_BinaryOperator))
1410 return TT_UnaryOperator;
1412 // Fall back to marking the token as binary operator.
1413 return TT_BinaryOperator;
1416 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1417 TokenType determineIncrementUsage(const FormatToken &Tok) {
1418 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1419 if (!PrevToken || PrevToken->is(TT_CastRParen))
1420 return TT_UnaryOperator;
1421 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1422 return TT_TrailingUnaryOperator;
1424 return TT_UnaryOperator;
1427 SmallVector<Context, 8> Contexts;
1429 const FormatStyle &Style;
1430 AnnotatedLine &Line;
1431 FormatToken *CurrentToken;
1433 const AdditionalKeywords &Keywords;
1435 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1436 // determines that a specific token can't be a template opener, it will make
1437 // same decision irrespective of the decisions for tokens leading up to it.
1438 // Store this information to prevent this from causing exponential runtime.
1439 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1442 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1443 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1445 /// \brief Parses binary expressions by inserting fake parenthesis based on
1446 /// operator precedence.
1447 class ExpressionParser {
1449 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1450 AnnotatedLine &Line)
1451 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1453 /// \brief Parse expressions with the given operatore precedence.
1454 void parse(int Precedence = 0) {
1455 // Skip 'return' and ObjC selector colons as they are not part of a binary
1457 while (Current && (Current->is(tok::kw_return) ||
1458 (Current->is(tok::colon) &&
1459 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1462 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1465 // Conditional expressions need to be parsed separately for proper nesting.
1466 if (Precedence == prec::Conditional) {
1467 parseConditionalExpr();
1471 // Parse unary operators, which all have a higher precedence than binary
1473 if (Precedence == PrecedenceUnaryOperator) {
1474 parseUnaryOperator();
1478 FormatToken *Start = Current;
1479 FormatToken *LatestOperator = nullptr;
1480 unsigned OperatorIndex = 0;
1483 // Consume operators with higher precedence.
1484 parse(Precedence + 1);
1486 int CurrentPrecedence = getCurrentPrecedence();
1488 if (Current && Current->is(TT_SelectorName) &&
1489 Precedence == CurrentPrecedence) {
1491 addFakeParenthesis(Start, prec::Level(Precedence));
1495 // At the end of the line or when an operator with higher precedence is
1496 // found, insert fake parenthesis and return.
1498 (Current->closesScope() &&
1499 (Current->MatchingParen || Current->is(TT_TemplateString))) ||
1500 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1501 (CurrentPrecedence == prec::Conditional &&
1502 Precedence == prec::Assignment && Current->is(tok::colon))) {
1506 // Consume scopes: (), [], <> and {}
1507 if (Current->opensScope()) {
1508 // In fragment of a JavaScript template string can look like '}..${' and
1509 // thus close a scope and open a new one at the same time.
1510 while (Current && (!Current->closesScope() || Current->opensScope())) {
1517 if (CurrentPrecedence == Precedence) {
1519 LatestOperator->NextOperator = Current;
1520 LatestOperator = Current;
1521 Current->OperatorIndex = OperatorIndex;
1524 next(/*SkipPastLeadingComments=*/Precedence > 0);
1528 if (LatestOperator && (Current || Precedence > 0)) {
1529 // LatestOperator->LastOperator = true;
1530 if (Precedence == PrecedenceArrowAndPeriod) {
1531 // Call expressions don't have a binary operator precedence.
1532 addFakeParenthesis(Start, prec::Unknown);
1534 addFakeParenthesis(Start, prec::Level(Precedence));
1540 /// \brief Gets the precedence (+1) of the given token for binary operators
1541 /// and other tokens that we treat like binary operators.
1542 int getCurrentPrecedence() {
1544 const FormatToken *NextNonComment = Current->getNextNonComment();
1545 if (Current->is(TT_ConditionalExpr))
1546 return prec::Conditional;
1547 if (NextNonComment && NextNonComment->is(tok::colon) &&
1548 NextNonComment->is(TT_DictLiteral))
1549 return prec::Assignment;
1550 if (Current->is(TT_JsComputedPropertyName))
1551 return prec::Assignment;
1552 if (Current->is(TT_LambdaArrow))
1554 if (Current->is(TT_JsFatArrow))
1555 return prec::Assignment;
1556 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
1557 (Current->is(tok::comment) && NextNonComment &&
1558 NextNonComment->is(TT_SelectorName)))
1560 if (Current->is(TT_RangeBasedForLoopColon))
1562 if ((Style.Language == FormatStyle::LK_Java ||
1563 Style.Language == FormatStyle::LK_JavaScript) &&
1564 Current->is(Keywords.kw_instanceof))
1565 return prec::Relational;
1566 if (Style.Language == FormatStyle::LK_JavaScript &&
1567 Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
1568 return prec::Relational;
1569 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1570 return Current->getPrecedence();
1571 if (Current->isOneOf(tok::period, tok::arrow))
1572 return PrecedenceArrowAndPeriod;
1573 if ((Style.Language == FormatStyle::LK_Java ||
1574 Style.Language == FormatStyle::LK_JavaScript) &&
1575 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1576 Keywords.kw_throws))
1582 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1583 Start->FakeLParens.push_back(Precedence);
1584 if (Precedence > prec::Unknown)
1585 Start->StartsBinaryExpression = true;
1587 FormatToken *Previous = Current->Previous;
1588 while (Previous->is(tok::comment) && Previous->Previous)
1589 Previous = Previous->Previous;
1590 ++Previous->FakeRParens;
1591 if (Precedence > prec::Unknown)
1592 Previous->EndsBinaryExpression = true;
1596 /// \brief Parse unary operator expressions and surround them with fake
1597 /// parentheses if appropriate.
1598 void parseUnaryOperator() {
1599 if (!Current || Current->isNot(TT_UnaryOperator)) {
1600 parse(PrecedenceArrowAndPeriod);
1604 FormatToken *Start = Current;
1606 parseUnaryOperator();
1608 // The actual precedence doesn't matter.
1609 addFakeParenthesis(Start, prec::Unknown);
1612 void parseConditionalExpr() {
1613 while (Current && Current->isTrailingComment()) {
1616 FormatToken *Start = Current;
1617 parse(prec::LogicalOr);
1618 if (!Current || !Current->is(tok::question))
1621 parse(prec::Assignment);
1622 if (!Current || Current->isNot(TT_ConditionalExpr))
1625 parse(prec::Assignment);
1626 addFakeParenthesis(Start, prec::Conditional);
1629 void next(bool SkipPastLeadingComments = true) {
1631 Current = Current->Next;
1633 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1634 Current->isTrailingComment())
1635 Current = Current->Next;
1638 const FormatStyle &Style;
1639 const AdditionalKeywords &Keywords;
1640 FormatToken *Current;
1643 } // end anonymous namespace
1645 void TokenAnnotator::setCommentLineLevels(
1646 SmallVectorImpl<AnnotatedLine *> &Lines) {
1647 const AnnotatedLine *NextNonCommentLine = nullptr;
1648 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1651 bool CommentLine = (*I)->First;
1652 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
1653 if (!Tok->is(tok::comment)) {
1654 CommentLine = false;
1658 if (NextNonCommentLine && CommentLine)
1659 (*I)->Level = NextNonCommentLine->Level;
1661 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1663 setCommentLineLevels((*I)->Children);
1667 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
1668 unsigned Result = 0;
1669 for (const auto* Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
1670 Result = std::max(Result, Tok->NestingLevel);
1674 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1675 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1676 E = Line.Children.end();
1680 AnnotatingParser Parser(Style, Line, Keywords);
1681 Line.Type = Parser.parseLine();
1683 // With very deep nesting, ExpressionParser uses lots of stack and the
1684 // formatting algorithm is very slow. We're not going to do a good job here
1685 // anyway - it's probably generated code being formatted by mistake.
1686 // Just skip the whole line.
1687 if (maxNestingDepth(Line) > 50)
1688 Line.Type = LT_Invalid;
1690 if (Line.Type == LT_Invalid)
1693 ExpressionParser ExprParser(Style, Keywords, Line);
1696 if (Line.startsWith(TT_ObjCMethodSpecifier))
1697 Line.Type = LT_ObjCMethodDecl;
1698 else if (Line.startsWith(TT_ObjCDecl))
1699 Line.Type = LT_ObjCDecl;
1700 else if (Line.startsWith(TT_ObjCProperty))
1701 Line.Type = LT_ObjCProperty;
1703 Line.First->SpacesRequiredBefore = 1;
1704 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1707 // This function heuristically determines whether 'Current' starts the name of a
1708 // function declaration.
1709 static bool isFunctionDeclarationName(const FormatToken &Current,
1710 const AnnotatedLine &Line) {
1711 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1712 for (; Next; Next = Next->Next) {
1713 if (Next->is(TT_OverloadedOperatorLParen))
1715 if (Next->is(TT_OverloadedOperator))
1717 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1718 // For 'new[]' and 'delete[]'.
1719 if (Next->Next && Next->Next->is(tok::l_square) &&
1720 Next->Next->Next && Next->Next->Next->is(tok::r_square))
1721 Next = Next->Next->Next;
1730 // Find parentheses of parameter list.
1731 const FormatToken *Next = Current.Next;
1732 if (Current.is(tok::kw_operator)) {
1733 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1735 Next = skipOperatorName(Next);
1737 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1739 for (; Next; Next = Next->Next) {
1740 if (Next->is(TT_TemplateOpener)) {
1741 Next = Next->MatchingParen;
1742 } else if (Next->is(tok::coloncolon)) {
1746 if (Next->is(tok::kw_operator)) {
1747 Next = skipOperatorName(Next->Next);
1750 if (!Next->is(tok::identifier))
1752 } else if (Next->is(tok::l_paren)) {
1760 // Check whether parameter list can belong to a function declaration.
1761 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
1763 // If the lines ends with "{", this is likely an function definition.
1764 if (Line.Last->is(tok::l_brace))
1766 if (Next->Next == Next->MatchingParen)
1767 return true; // Empty parentheses.
1768 // If there is an &/&& after the r_paren, this is likely a function.
1769 if (Next->MatchingParen->Next &&
1770 Next->MatchingParen->Next->is(TT_PointerOrReference))
1772 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1774 if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
1775 Tok = Tok->MatchingParen;
1778 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1779 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
1781 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1782 Tok->Tok.isLiteral())
1788 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1789 assert(Line.MightBeFunctionDecl);
1791 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1792 Style.AlwaysBreakAfterReturnType ==
1793 FormatStyle::RTBS_TopLevelDefinitions) &&
1797 switch (Style.AlwaysBreakAfterReturnType) {
1798 case FormatStyle::RTBS_None:
1800 case FormatStyle::RTBS_All:
1801 case FormatStyle::RTBS_TopLevel:
1803 case FormatStyle::RTBS_AllDefinitions:
1804 case FormatStyle::RTBS_TopLevelDefinitions:
1805 return Line.mightBeFunctionDefinition();
1811 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1812 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1813 E = Line.Children.end();
1815 calculateFormattingInformation(**I);
1818 Line.First->TotalLength =
1819 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1820 FormatToken *Current = Line.First->Next;
1821 bool InFunctionDecl = Line.MightBeFunctionDecl;
1823 if (isFunctionDeclarationName(*Current, Line))
1824 Current->Type = TT_FunctionDeclarationName;
1825 if (Current->is(TT_LineComment)) {
1826 if (Current->Previous->BlockKind == BK_BracedInit &&
1827 Current->Previous->opensScope())
1828 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1830 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1832 // If we find a trailing comment, iterate backwards to determine whether
1833 // it seems to relate to a specific parameter. If so, break before that
1834 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1835 // to the previous line in:
1839 if (!Current->HasUnescapedNewline) {
1840 for (FormatToken *Parameter = Current->Previous; Parameter;
1841 Parameter = Parameter->Previous) {
1842 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1844 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1845 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1846 Parameter->HasUnescapedNewline)
1847 Parameter->MustBreakBefore = true;
1852 } else if (Current->SpacesRequiredBefore == 0 &&
1853 spaceRequiredBefore(Line, *Current)) {
1854 Current->SpacesRequiredBefore = 1;
1857 Current->MustBreakBefore =
1858 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1860 if (!Current->MustBreakBefore && InFunctionDecl &&
1861 Current->is(TT_FunctionDeclarationName))
1862 Current->MustBreakBefore = mustBreakForReturnType(Line);
1864 Current->CanBreakBefore =
1865 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1866 unsigned ChildSize = 0;
1867 if (Current->Previous->Children.size() == 1) {
1868 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1869 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1870 : LastOfChild.TotalLength + 1;
1872 const FormatToken *Prev = Current->Previous;
1873 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1874 (Prev->Children.size() == 1 &&
1875 Prev->Children[0]->First->MustBreakBefore) ||
1876 Current->IsMultiline)
1877 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1879 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1880 ChildSize + Current->SpacesRequiredBefore;
1882 if (Current->is(TT_CtorInitializerColon))
1883 InFunctionDecl = false;
1885 // FIXME: Only calculate this if CanBreakBefore is true once static
1886 // initializers etc. are sorted out.
1887 // FIXME: Move magic numbers to a better place.
1888 Current->SplitPenalty = 20 * Current->BindingStrength +
1889 splitPenalty(Line, *Current, InFunctionDecl);
1891 Current = Current->Next;
1894 calculateUnbreakableTailLengths(Line);
1895 unsigned IndentLevel = Line.Level;
1896 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1898 Current->Role->precomputeFormattingInfos(Current);
1899 if (Current->MatchingParen &&
1900 Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
1901 assert(IndentLevel > 0);
1904 Current->IndentLevel = IndentLevel;
1905 if (Current->opensBlockOrBlockTypeList(Style))
1909 DEBUG({ printDebugInfo(Line); });
1912 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1913 unsigned UnbreakableTailLength = 0;
1914 FormatToken *Current = Line.Last;
1916 Current->UnbreakableTailLength = UnbreakableTailLength;
1917 if (Current->CanBreakBefore ||
1918 Current->isOneOf(tok::comment, tok::string_literal)) {
1919 UnbreakableTailLength = 0;
1921 UnbreakableTailLength +=
1922 Current->ColumnWidth + Current->SpacesRequiredBefore;
1924 Current = Current->Previous;
1928 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1929 const FormatToken &Tok,
1930 bool InFunctionDecl) {
1931 const FormatToken &Left = *Tok.Previous;
1932 const FormatToken &Right = Tok;
1934 if (Left.is(tok::semi))
1937 if (Style.Language == FormatStyle::LK_Java) {
1938 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1940 if (Right.is(Keywords.kw_implements))
1942 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1944 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1945 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1947 if (Left.is(TT_JsTypeColon))
1949 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
1950 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
1954 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
1956 if (Right.is(tok::l_square)) {
1957 if (Style.Language == FormatStyle::LK_Proto)
1959 if (Left.is(tok::r_square))
1961 // Slightly prefer formatting local lambda definitions like functions.
1962 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1964 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1965 TT_ArrayInitializerLSquare))
1969 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1970 Right.is(tok::kw_operator)) {
1971 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1973 if (Left.is(TT_StartOfName))
1975 if (InFunctionDecl && Right.NestingLevel == 0)
1976 return Style.PenaltyReturnTypeOnItsOwnLine;
1979 if (Right.is(TT_PointerOrReference))
1981 if (Right.is(TT_LambdaArrow))
1983 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1985 if (Left.is(TT_CastRParen))
1987 if (Left.is(tok::coloncolon) ||
1988 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1990 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1992 if (Left.is(tok::comment))
1995 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1998 if (Right.isMemberAccess()) {
1999 // Breaking before the "./->" of a chained call/member access is reasonably
2000 // cheap, as formatting those with one call per line is generally
2001 // desirable. In particular, it should be cheaper to break before the call
2002 // than it is to break inside a call's parameters, which could lead to weird
2003 // "hanging" indents. The exception is the very last "./->" to support this
2004 // frequent pattern:
2006 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2009 // which might otherwise be blown up onto many lines. Here, clang-format
2010 // won't produce "hanging" indents anyway as there is no other trailing
2013 // Also apply higher penalty is not a call as that might lead to a wrapping
2017 // .aaaaaaaaa.bbbbbbbb(cccccccc);
2018 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2023 if (Right.is(TT_TrailingAnnotation) &&
2024 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2025 // Moving trailing annotations to the next line is fine for ObjC method
2027 if (Line.startsWith(TT_ObjCMethodSpecifier))
2029 // Generally, breaking before a trailing annotation is bad unless it is
2030 // function-like. It seems to be especially preferable to keep standard
2031 // annotations (i.e. "const", "final" and "override") on the same line.
2032 // Use a slightly higher penalty after ")" so that annotations like
2033 // "const override" are kept together.
2034 bool is_short_annotation = Right.TokenText.size() < 10;
2035 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2038 // In for-loops, prefer breaking at ',' and ';'.
2039 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2042 // In Objective-C method expressions, prefer breaking before "param:" over
2043 // breaking after it.
2044 if (Right.is(TT_SelectorName))
2046 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2047 return Line.MightBeFunctionDecl ? 50 : 500;
2049 if (Left.is(tok::l_paren) && InFunctionDecl &&
2050 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2052 if (Left.is(tok::l_paren) && Left.Previous &&
2053 Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
2055 if (Left.is(tok::equal) && InFunctionDecl)
2057 if (Right.is(tok::r_brace))
2059 if (Left.is(TT_TemplateOpener))
2061 if (Left.opensScope()) {
2062 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
2064 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2067 if (Left.is(TT_JavaAnnotation))
2070 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2071 Left.Previous->isLabelString() &&
2072 (Left.NextOperator || Left.OperatorIndex != 0))
2074 if (Right.is(tok::plus) && Left.isLabelString() &&
2075 (Right.NextOperator || Right.OperatorIndex != 0))
2077 if (Left.is(tok::comma))
2079 if (Right.is(tok::lessless) && Left.isLabelString() &&
2080 (Right.NextOperator || Right.OperatorIndex != 1))
2082 if (Right.is(tok::lessless)) {
2083 // Breaking at a << is really cheap.
2084 if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2085 // Slightly prefer to break before the first one in log-like statements.
2089 if (Left.is(TT_ConditionalExpr))
2090 return prec::Conditional;
2091 prec::Level Level = Left.getPrecedence();
2092 if (Level != prec::Unknown)
2094 Level = Right.getPrecedence();
2095 if (Level != prec::Unknown)
2101 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2102 const FormatToken &Left,
2103 const FormatToken &Right) {
2104 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2106 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2107 Left.Tok.getObjCKeywordID() == tok::objc_property)
2109 if (Right.is(tok::hashhash))
2110 return Left.is(tok::hash);
2111 if (Left.isOneOf(tok::hashhash, tok::hash))
2112 return Right.is(tok::hash);
2113 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2114 return Style.SpaceInEmptyParentheses;
2115 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2116 return (Right.is(TT_CastRParen) ||
2117 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2118 ? Style.SpacesInCStyleCastParentheses
2119 : Style.SpacesInParentheses;
2120 if (Right.isOneOf(tok::semi, tok::comma))
2122 if (Right.is(tok::less) &&
2123 Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)
2125 if (Right.is(tok::less) && Left.is(tok::kw_template))
2126 return Style.SpaceAfterTemplateKeyword;
2127 if (Left.isOneOf(tok::exclaim, tok::tilde))
2129 if (Left.is(tok::at) &&
2130 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2131 tok::numeric_constant, tok::l_paren, tok::l_brace,
2132 tok::kw_true, tok::kw_false))
2134 if (Left.is(tok::colon))
2135 return !Left.is(TT_ObjCMethodExpr);
2136 if (Left.is(tok::coloncolon))
2138 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
2140 if (Right.is(tok::ellipsis))
2141 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2142 Left.Previous->is(tok::kw_case));
2143 if (Left.is(tok::l_square) && Right.is(tok::amp))
2145 if (Right.is(TT_PointerOrReference))
2146 return (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) ||
2147 (Left.Tok.isLiteral() || (Left.is(tok::kw_const) && Left.Previous &&
2148 Left.Previous->is(tok::r_paren)) ||
2149 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2150 (Style.PointerAlignment != FormatStyle::PAS_Left ||
2151 (Line.IsMultiVariableDeclStmt &&
2152 (Left.NestingLevel == 0 ||
2153 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2154 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2155 (!Left.is(TT_PointerOrReference) ||
2156 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2157 !Line.IsMultiVariableDeclStmt)))
2159 if (Left.is(TT_PointerOrReference))
2160 return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2161 (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2162 !Right.is(TT_StartOfName)) ||
2163 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2164 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2166 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2167 !Line.IsMultiVariableDeclStmt) &&
2169 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2170 if (Right.is(tok::star) && Left.is(tok::l_paren))
2172 if (Left.is(tok::l_square))
2173 return (Left.is(TT_ArrayInitializerLSquare) &&
2174 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
2175 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
2176 Right.isNot(tok::r_square));
2177 if (Right.is(tok::r_square))
2178 return Right.MatchingParen &&
2179 ((Style.SpacesInContainerLiterals &&
2180 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
2181 (Style.SpacesInSquareBrackets &&
2182 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
2183 if (Right.is(tok::l_square) &&
2184 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
2185 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2187 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2188 return !Left.Children.empty(); // No spaces in "{}".
2189 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2190 (Right.is(tok::r_brace) && Right.MatchingParen &&
2191 Right.MatchingParen->BlockKind != BK_Block))
2192 return !Style.Cpp11BracedListStyle;
2193 if (Left.is(TT_BlockComment))
2194 return !Left.TokenText.endswith("=*/");
2195 if (Right.is(tok::l_paren)) {
2196 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
2198 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2199 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2200 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2201 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2203 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2204 tok::kw_new, tok::kw_delete) &&
2205 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2206 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2207 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2208 Left.is(tok::r_paren)) &&
2209 Line.Type != LT_PreprocessorDirective);
2211 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2213 if (Right.is(TT_UnaryOperator))
2214 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2215 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2216 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2218 Left.isSimpleTypeSpecifier()) &&
2219 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2220 Right.BlockKind != BK_Block)
2222 if (Left.is(tok::period) || Right.is(tok::period))
2224 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2226 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2227 Left.MatchingParen->Previous &&
2228 Left.MatchingParen->Previous->is(tok::period))
2229 // A.<B>DoSomething();
2231 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2236 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2237 const FormatToken &Right) {
2238 const FormatToken &Left = *Right.Previous;
2239 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2240 return true; // Never ever merge two identifiers.
2241 if (Style.isCpp()) {
2242 if (Left.is(tok::kw_operator))
2243 return Right.is(tok::coloncolon);
2244 } else if (Style.Language == FormatStyle::LK_Proto) {
2245 if (Right.is(tok::period) &&
2246 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2247 Keywords.kw_repeated, Keywords.kw_extend))
2249 if (Right.is(tok::l_paren) &&
2250 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2252 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2253 if (Left.is(TT_JsFatArrow))
2256 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_async) &&
2257 Left.Previous && Left.Previous->is(tok::kw_for))
2259 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
2260 Right.MatchingParen) {
2261 const FormatToken *Next = Right.MatchingParen->getNextNonComment();
2262 // An async arrow function, for example: `x = async () => foo();`,
2263 // as opposed to calling a function called async: `x = async();`
2264 if (Next && Next->is(TT_JsFatArrow))
2267 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2268 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2270 if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
2272 if (Right.is(tok::star) &&
2273 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2275 if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2276 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2278 // JS methods can use some keywords as names (e.g. `delete()`).
2279 if (Right.is(tok::l_paren) && Line.MustBeDeclaration &&
2280 Left.Tok.getIdentifierInfo())
2282 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2284 // "of" is only a keyword if it appears after another identifier
2285 // (e.g. as "const x of y" in a for loop).
2286 (Left.is(Keywords.kw_of) && Left.Previous &&
2287 Left.Previous->Tok.getIdentifierInfo())) &&
2288 (!Left.Previous || !Left.Previous->is(tok::period)))
2290 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2291 Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2293 if (Left.is(Keywords.kw_as) &&
2294 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2296 if (Left.is(tok::kw_default) && Left.Previous &&
2297 Left.Previous->is(tok::kw_export))
2299 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2301 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2303 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2305 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2306 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2308 if (Left.is(tok::ellipsis))
2310 if (Left.is(TT_TemplateCloser) &&
2311 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2312 Keywords.kw_implements, Keywords.kw_extends))
2313 // Type assertions ('<type>expr') are not followed by whitespace. Other
2314 // locations that should have whitespace following are identified by the
2315 // above set of follower tokens.
2317 if (Right.is(TT_JsNonNullAssertion))
2319 if (Left.is(TT_JsNonNullAssertion) && Right.is(Keywords.kw_as))
2320 return true; // "x! as string"
2321 } else if (Style.Language == FormatStyle::LK_Java) {
2322 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2324 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2325 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2326 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2327 tok::kw_protected) ||
2328 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2329 Keywords.kw_native)) &&
2330 Right.is(TT_TemplateOpener))
2333 if (Left.is(TT_ImplicitStringLiteral))
2334 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2335 if (Line.Type == LT_ObjCMethodDecl) {
2336 if (Left.is(TT_ObjCMethodSpecifier))
2338 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2339 // Don't space between ')' and <id>
2342 if (Line.Type == LT_ObjCProperty &&
2343 (Right.is(tok::equal) || Left.is(tok::equal)))
2346 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2347 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2349 if (Right.is(TT_OverloadedOperatorLParen))
2350 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2351 if (Left.is(tok::comma))
2353 if (Right.is(tok::comma))
2355 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2357 if (Right.is(tok::colon)) {
2358 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2359 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2361 if (Right.is(TT_ObjCMethodExpr))
2363 if (Left.is(tok::question))
2365 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2367 if (Right.is(TT_DictLiteral))
2368 return Style.SpacesInContainerLiterals;
2371 if (Left.is(TT_UnaryOperator))
2372 return Right.is(TT_BinaryOperator);
2374 // If the next token is a binary operator or a selector name, we have
2375 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2376 if (Left.is(TT_CastRParen))
2377 return Style.SpaceAfterCStyleCast ||
2378 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2380 if (Left.is(tok::greater) && Right.is(tok::greater))
2381 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2382 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2383 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2384 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2386 if (!Style.SpaceBeforeAssignmentOperators &&
2387 Right.getPrecedence() == prec::Assignment)
2389 if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
2390 // Generally don't remove existing spaces between an identifier and "::".
2391 // The identifier might actually be a macro name such as ALWAYS_INLINE. If
2392 // this turns out to be too lenient, add analysis of the identifier itself.
2393 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2394 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2395 return (Left.is(TT_TemplateOpener) &&
2396 Style.Standard == FormatStyle::LS_Cpp03) ||
2397 !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
2398 tok::kw___super, TT_TemplateCloser, TT_TemplateOpener));
2399 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2400 return Style.SpacesInAngles;
2401 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2402 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2403 !Right.is(tok::r_paren)))
2405 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2406 Right.isNot(TT_FunctionTypeLParen))
2407 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2408 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2409 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2411 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2412 Line.startsWith(tok::hash))
2414 if (Right.is(TT_TrailingUnaryOperator))
2416 if (Left.is(TT_RegexLiteral))
2418 return spaceRequiredBetween(Line, Left, Right);
2421 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2422 static bool isAllmanBrace(const FormatToken &Tok) {
2423 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2424 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2427 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2428 const FormatToken &Right) {
2429 const FormatToken &Left = *Right.Previous;
2430 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2433 if (Style.Language == FormatStyle::LK_JavaScript) {
2434 // FIXME: This might apply to other languages and token kinds.
2435 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2436 Left.Previous->is(tok::string_literal))
2438 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2439 Left.Previous && Left.Previous->is(tok::equal) &&
2440 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2442 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2444 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2445 // Object literals on the top level of a file are treated as "enum-style".
2446 // Each key/value pair is put on a separate line, instead of bin-packing.
2448 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2449 (Line.startsWith(tok::kw_enum) ||
2450 Line.startsWith(tok::kw_export, tok::kw_enum)))
2451 // JavaScript top-level enum key/value pairs are put on separate lines
2452 // instead of bin-packing.
2454 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2455 !Left.Children.empty())
2456 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2457 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2458 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2459 (Left.NestingLevel == 0 && Line.Level == 0 &&
2460 Style.AllowShortFunctionsOnASingleLine ==
2461 FormatStyle::SFS_Inline);
2462 } else if (Style.Language == FormatStyle::LK_Java) {
2463 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2464 Right.Next->is(tok::string_literal))
2466 } else if (Style.Language == FormatStyle::LK_Cpp ||
2467 Style.Language == FormatStyle::LK_ObjC ||
2468 Style.Language == FormatStyle::LK_Proto) {
2469 if (Left.isStringLiteral() && Right.isStringLiteral())
2473 // If the last token before a '}', ']', or ')' is a comma or a trailing
2474 // comment, the intention is to insert a line break after it in order to make
2475 // shuffling around entries easier.
2476 const FormatToken *BeforeClosingBrace = nullptr;
2477 if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
2478 (Style.Language == FormatStyle::LK_JavaScript &&
2479 Left.is(tok::l_paren))) &&
2480 Left.BlockKind != BK_Block && Left.MatchingParen)
2481 BeforeClosingBrace = Left.MatchingParen->Previous;
2482 else if (Right.MatchingParen &&
2483 (Right.MatchingParen->isOneOf(tok::l_brace,
2484 TT_ArrayInitializerLSquare) ||
2485 (Style.Language == FormatStyle::LK_JavaScript &&
2486 Right.MatchingParen->is(tok::l_paren))))
2487 BeforeClosingBrace = &Left;
2488 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2489 BeforeClosingBrace->isTrailingComment()))
2492 if (Right.is(tok::comment))
2493 return Left.BlockKind != BK_BracedInit &&
2494 Left.isNot(TT_CtorInitializerColon) &&
2495 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2496 if (Left.isTrailingComment())
2498 if (Right.Previous->IsUnterminatedLiteral)
2500 if (Right.is(tok::lessless) && Right.Next &&
2501 Right.Previous->is(tok::string_literal) &&
2502 Right.Next->is(tok::string_literal))
2504 if (Right.Previous->ClosesTemplateDeclaration &&
2505 Right.Previous->MatchingParen &&
2506 Right.Previous->MatchingParen->NestingLevel == 0 &&
2507 Style.AlwaysBreakTemplateDeclarations)
2509 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2510 Style.BreakConstructorInitializersBeforeComma &&
2511 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2513 // Break only if we have multiple inheritance.
2514 if (Style.BreakBeforeInheritanceComma &&
2515 Right.is(TT_InheritanceComma))
2517 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2518 // Raw string literals are special wrt. line breaks. The author has made a
2519 // deliberate choice and might have aligned the contents of the string
2520 // literal accordingly. Thus, we try keep existing line breaks.
2521 return Right.NewlinesBefore > 0;
2522 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2523 Style.Language == FormatStyle::LK_Proto)
2524 // Don't put enums onto single lines in protocol buffers.
2526 if (Right.is(TT_InlineASMBrace))
2527 return Right.HasUnescapedNewline;
2528 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2529 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2530 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2531 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2532 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2535 if ((Style.Language == FormatStyle::LK_Java ||
2536 Style.Language == FormatStyle::LK_JavaScript) &&
2537 Left.is(TT_LeadingJavaAnnotation) &&
2538 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2539 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2545 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2546 const FormatToken &Right) {
2547 const FormatToken &Left = *Right.Previous;
2549 // Language-specific stuff.
2550 if (Style.Language == FormatStyle::LK_Java) {
2551 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2552 Keywords.kw_implements))
2554 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2555 Keywords.kw_implements))
2557 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2558 const FormatToken *NonComment = Right.getPreviousNonComment();
2560 NonComment->isOneOf(
2561 tok::kw_return, tok::kw_continue, tok::kw_break, tok::kw_throw,
2562 Keywords.kw_interface, Keywords.kw_type, tok::kw_static,
2563 tok::kw_public, tok::kw_private, tok::kw_protected,
2564 Keywords.kw_abstract, Keywords.kw_get, Keywords.kw_set))
2565 return false; // Otherwise a semicolon is inserted.
2566 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2568 if (Left.is(TT_JsTypeColon))
2570 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2572 if (Left.is(Keywords.kw_in))
2573 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
2574 if (Right.is(Keywords.kw_in))
2575 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
2576 if (Right.is(Keywords.kw_as))
2577 return false; // must not break before as in 'x as type' casts
2578 if (Left.is(Keywords.kw_as))
2580 if (Left.is(TT_JsNonNullAssertion))
2582 if (Left.is(Keywords.kw_declare) &&
2583 Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
2584 Keywords.kw_function, tok::kw_class, tok::kw_enum,
2585 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
2586 Keywords.kw_let, tok::kw_const))
2587 // See grammar for 'declare' statements at:
2588 // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
2590 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
2591 Right.isOneOf(tok::identifier, tok::string_literal))
2592 return false; // must not break in "module foo { ...}"
2593 if (Right.is(TT_TemplateString) && Right.closesScope())
2595 if (Left.is(TT_TemplateString) && Left.opensScope())
2599 if (Left.is(tok::at))
2601 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2603 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2604 return !Right.is(tok::l_paren);
2605 if (Right.is(TT_PointerOrReference))
2606 return Line.IsMultiVariableDeclStmt ||
2607 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2608 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2609 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2610 Right.is(tok::kw_operator))
2612 if (Left.is(TT_PointerOrReference))
2614 if (Right.isTrailingComment())
2615 // We rely on MustBreakBefore being set correctly here as we should not
2616 // change the "binding" behavior of a comment.
2617 // The first comment in a braced lists is always interpreted as belonging to
2618 // the first list element. Otherwise, it should be placed outside of the
2620 return Left.BlockKind == BK_BracedInit;
2621 if (Left.is(tok::question) && Right.is(tok::colon))
2623 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2624 return Style.BreakBeforeTernaryOperators;
2625 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2626 return !Style.BreakBeforeTernaryOperators;
2627 if (Right.is(TT_InheritanceColon))
2629 if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
2630 Left.isNot(TT_SelectorName))
2632 if (Right.is(tok::colon) &&
2633 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2635 if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr))
2637 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2638 Right.Next->is(TT_ObjCMethodExpr)))
2639 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2640 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2642 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2644 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2645 TT_OverloadedOperator))
2647 if (Left.is(TT_RangeBasedForLoopColon))
2649 if (Right.is(TT_RangeBasedForLoopColon))
2651 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
2653 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2654 Left.is(tok::kw_operator))
2656 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2657 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2659 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2661 if (Left.is(tok::l_paren) && Left.Previous &&
2662 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2664 if (Right.is(TT_ImplicitStringLiteral))
2667 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2669 if (Right.is(tok::r_square) && Right.MatchingParen &&
2670 Right.MatchingParen->is(TT_LambdaLSquare))
2673 // We only break before r_brace if there was a corresponding break before
2674 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2675 if (Right.is(tok::r_brace))
2676 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2678 // Allow breaking after a trailing annotation, e.g. after a method
2680 if (Left.is(TT_TrailingAnnotation))
2681 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2682 tok::less, tok::coloncolon);
2684 if (Right.is(tok::kw___attribute))
2687 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2690 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2693 if (Left.is(TT_CtorInitializerComma) &&
2694 Style.BreakConstructorInitializersBeforeComma)
2696 if (Right.is(TT_CtorInitializerComma) &&
2697 Style.BreakConstructorInitializersBeforeComma)
2699 if (Left.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
2701 if (Right.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
2703 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2704 (Left.is(tok::less) && Right.is(tok::less)))
2706 if (Right.is(TT_BinaryOperator) &&
2707 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2708 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2709 Right.getPrecedence() != prec::Assignment))
2711 if (Left.is(TT_ArrayInitializerLSquare))
2713 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2715 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2716 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2717 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2718 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2719 Left.getPrecedence() == prec::Assignment))
2721 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2722 tok::kw_class, tok::kw_struct, tok::comment) ||
2723 Right.isMemberAccess() ||
2724 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2725 tok::colon, tok::l_square, tok::at) ||
2726 (Left.is(tok::r_paren) &&
2727 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2728 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
2729 (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
2732 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2733 llvm::errs() << "AnnotatedTokens:\n";
2734 const FormatToken *Tok = Line.First;
2736 llvm::errs() << " M=" << Tok->MustBreakBefore
2737 << " C=" << Tok->CanBreakBefore
2738 << " T=" << getTokenTypeName(Tok->Type)
2739 << " S=" << Tok->SpacesRequiredBefore
2740 << " B=" << Tok->BlockParameterCount
2741 << " BK=" << Tok->BlockKind
2742 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2743 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2745 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2746 llvm::errs() << Tok->FakeLParens[i] << "/";
2747 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
2748 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
2750 assert(Tok == Line.Last);
2753 llvm::errs() << "----\n";
2756 } // namespace format
2757 } // namespace clang