]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Format/TokenAnnotator.cpp
Merge ^/head r293016 through r293035.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Format / TokenAnnotator.cpp
1 //===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements a token annotator, i.e. creates
12 /// \c AnnotatedTokens out of \c FormatTokens with required extra information.
13 ///
14 //===----------------------------------------------------------------------===//
15
16 #include "TokenAnnotator.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/Support/Debug.h"
20
21 #define DEBUG_TYPE "format-token-annotator"
22
23 namespace clang {
24 namespace format {
25
26 namespace {
27
28 /// \brief A parser that gathers additional information about tokens.
29 ///
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 {
34 public:
35   AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
36                    const AdditionalKeywords &Keywords)
37       : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
38         Keywords(Keywords) {
39     Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
40     resetTokenMetadata(CurrentToken);
41   }
42
43 private:
44   bool parseAngle() {
45     if (!CurrentToken)
46       return false;
47     FormatToken *Left = CurrentToken->Previous;
48     Left->ParentBracket = Contexts.back().ContextKind;
49     ScopedContextCreator ContextCreator(*this, tok::less, 10);
50
51     // If this angle is in the context of an expression, we need to be more
52     // hesitant to detect it as opening template parameters.
53     bool InExprContext = Contexts.back().IsExpression;
54
55     Contexts.back().IsExpression = false;
56     // If there's a template keyword before the opening angle bracket, this is a
57     // template parameter, not an argument.
58     Contexts.back().InTemplateArgument =
59         Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
60
61     if (Style.Language == FormatStyle::LK_Java &&
62         CurrentToken->is(tok::question))
63       next();
64
65     while (CurrentToken) {
66       if (CurrentToken->is(tok::greater)) {
67         Left->MatchingParen = CurrentToken;
68         CurrentToken->MatchingParen = Left;
69         CurrentToken->Type = TT_TemplateCloser;
70         next();
71         return true;
72       }
73       if (CurrentToken->is(tok::question) &&
74           Style.Language == FormatStyle::LK_Java) {
75         next();
76         continue;
77       }
78       if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
79           (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext))
80         return false;
81       // If a && or || is found and interpreted as a binary operator, this set
82       // of angles is likely part of something like "a < b && c > d". If the
83       // angles are inside an expression, the ||/&& might also be a binary
84       // operator that was misinterpreted because we are parsing template
85       // parameters.
86       // FIXME: This is getting out of hand, write a decent parser.
87       if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
88           CurrentToken->Previous->is(TT_BinaryOperator) &&
89           Contexts[Contexts.size() - 2].IsExpression &&
90           !Line.startsWith(tok::kw_template))
91         return false;
92       updateParameterCount(Left, CurrentToken);
93       if (!consumeToken())
94         return false;
95     }
96     return false;
97   }
98
99   bool parseParens(bool LookForDecls = false) {
100     if (!CurrentToken)
101       return false;
102     FormatToken *Left = CurrentToken->Previous;
103     Left->ParentBracket = Contexts.back().ContextKind;
104     ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
105
106     // FIXME: This is a bit of a hack. Do better.
107     Contexts.back().ColonIsForRangeExpr =
108         Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
109
110     bool StartsObjCMethodExpr = false;
111     if (CurrentToken->is(tok::caret)) {
112       // (^ can start a block type.
113       Left->Type = TT_ObjCBlockLParen;
114     } else if (FormatToken *MaybeSel = Left->Previous) {
115       // @selector( starts a selector.
116       if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
117           MaybeSel->Previous->is(tok::at)) {
118         StartsObjCMethodExpr = true;
119       }
120     }
121
122     if (Left->Previous &&
123         (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
124                                  tok::kw_if, tok::kw_while, tok::l_paren,
125                                  tok::comma) ||
126          Left->Previous->is(TT_BinaryOperator))) {
127       // static_assert, if and while usually contain expressions.
128       Contexts.back().IsExpression = true;
129     } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
130                Left->Previous->MatchingParen &&
131                Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
132       // This is a parameter list of a lambda expression.
133       Contexts.back().IsExpression = false;
134     } else if (Line.InPPDirective &&
135                (!Left->Previous ||
136                 !Left->Previous->isOneOf(tok::identifier,
137                                          TT_OverloadedOperator))) {
138       Contexts.back().IsExpression = true;
139     } else if (Contexts[Contexts.size() - 2].CaretFound) {
140       // This is the parameter list of an ObjC block.
141       Contexts.back().IsExpression = false;
142     } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
143       Left->Type = TT_AttributeParen;
144     } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
145       // The first argument to a foreach macro is a declaration.
146       Contexts.back().IsForEachMacro = true;
147       Contexts.back().IsExpression = false;
148     } else if (Left->Previous && Left->Previous->MatchingParen &&
149                Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
150       Contexts.back().IsExpression = false;
151     } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
152       bool IsForOrCatch =
153           Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
154       Contexts.back().IsExpression = !IsForOrCatch;
155     }
156
157     if (StartsObjCMethodExpr) {
158       Contexts.back().ColonIsObjCMethodExpr = true;
159       Left->Type = TT_ObjCMethodExpr;
160     }
161
162     bool MightBeFunctionType = CurrentToken->isOneOf(tok::star, tok::amp) &&
163                                !Contexts[Contexts.size() - 2].IsExpression;
164     bool HasMultipleLines = false;
165     bool HasMultipleParametersOnALine = false;
166     bool MightBeObjCForRangeLoop =
167         Left->Previous && Left->Previous->is(tok::kw_for);
168     while (CurrentToken) {
169       // LookForDecls is set when "if (" has been seen. Check for
170       // 'identifier' '*' 'identifier' followed by not '=' -- this
171       // '*' has to be a binary operator but determineStarAmpUsage() will
172       // categorize it as an unary operator, so set the right type here.
173       if (LookForDecls && CurrentToken->Next) {
174         FormatToken *Prev = CurrentToken->getPreviousNonComment();
175         if (Prev) {
176           FormatToken *PrevPrev = Prev->getPreviousNonComment();
177           FormatToken *Next = CurrentToken->Next;
178           if (PrevPrev && PrevPrev->is(tok::identifier) &&
179               Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
180               CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
181             Prev->Type = TT_BinaryOperator;
182             LookForDecls = false;
183           }
184         }
185       }
186
187       if (CurrentToken->Previous->is(TT_PointerOrReference) &&
188           CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
189                                                     tok::coloncolon))
190         MightBeFunctionType = true;
191       if (CurrentToken->Previous->is(TT_BinaryOperator))
192         Contexts.back().IsExpression = true;
193       if (CurrentToken->is(tok::r_paren)) {
194         if (MightBeFunctionType && CurrentToken->Next &&
195             (CurrentToken->Next->is(tok::l_paren) ||
196              (CurrentToken->Next->is(tok::l_square) &&
197               Line.MustBeDeclaration)))
198           Left->Type = TT_FunctionTypeLParen;
199         Left->MatchingParen = CurrentToken;
200         CurrentToken->MatchingParen = Left;
201
202         if (StartsObjCMethodExpr) {
203           CurrentToken->Type = TT_ObjCMethodExpr;
204           if (Contexts.back().FirstObjCSelectorName) {
205             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
206                 Contexts.back().LongestObjCSelectorName;
207           }
208         }
209
210         if (Left->is(TT_AttributeParen))
211           CurrentToken->Type = TT_AttributeParen;
212         if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
213           CurrentToken->Type = TT_JavaAnnotation;
214         if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
215           CurrentToken->Type = TT_LeadingJavaAnnotation;
216
217         if (!HasMultipleLines)
218           Left->PackingKind = PPK_Inconclusive;
219         else if (HasMultipleParametersOnALine)
220           Left->PackingKind = PPK_BinPacked;
221         else
222           Left->PackingKind = PPK_OnePerLine;
223
224         next();
225         return true;
226       }
227       if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
228         return false;
229
230       if (CurrentToken->is(tok::l_brace))
231         Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
232       if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
233           !CurrentToken->Next->HasUnescapedNewline &&
234           !CurrentToken->Next->isTrailingComment())
235         HasMultipleParametersOnALine = true;
236       if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
237           CurrentToken->isSimpleTypeSpecifier())
238         Contexts.back().IsExpression = false;
239       if (CurrentToken->isOneOf(tok::semi, tok::colon))
240         MightBeObjCForRangeLoop = false;
241       if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
242         CurrentToken->Type = TT_ObjCForIn;
243       // When we discover a 'new', we set CanBeExpression to 'false' in order to
244       // parse the type correctly. Reset that after a comma.
245       if (CurrentToken->is(tok::comma))
246         Contexts.back().CanBeExpression = true;
247
248       FormatToken *Tok = CurrentToken;
249       if (!consumeToken())
250         return false;
251       updateParameterCount(Left, Tok);
252       if (CurrentToken && CurrentToken->HasUnescapedNewline)
253         HasMultipleLines = true;
254     }
255     return false;
256   }
257
258   bool parseSquare() {
259     if (!CurrentToken)
260       return false;
261
262     // A '[' could be an index subscript (after an identifier or after
263     // ')' or ']'), it could be the start of an Objective-C method
264     // expression, or it could the start of an Objective-C array literal.
265     FormatToken *Left = CurrentToken->Previous;
266     Left->ParentBracket = Contexts.back().ContextKind;
267     FormatToken *Parent = Left->getPreviousNonComment();
268     bool StartsObjCMethodExpr =
269         Style.Language == FormatStyle::LK_Cpp &&
270         Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
271         CurrentToken->isNot(tok::l_brace) &&
272         (!Parent ||
273          Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
274                          tok::kw_return, tok::kw_throw) ||
275          Parent->isUnaryOperator() ||
276          Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
277          getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
278     bool ColonFound = false;
279
280     unsigned BindingIncrease = 1;
281     if (Left->is(TT_Unknown)) {
282       if (StartsObjCMethodExpr) {
283         Left->Type = TT_ObjCMethodExpr;
284       } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
285                  Contexts.back().ContextKind == tok::l_brace &&
286                  Parent->isOneOf(tok::l_brace, tok::comma)) {
287         Left->Type = TT_JsComputedPropertyName;
288       } else if (Parent &&
289                  Parent->isOneOf(tok::at, tok::equal, tok::comma, tok::l_paren,
290                                  tok::l_square, tok::question, tok::colon,
291                                  tok::kw_return)) {
292         Left->Type = TT_ArrayInitializerLSquare;
293       } else {
294         BindingIncrease = 10;
295         Left->Type = TT_ArraySubscriptLSquare;
296       }
297     }
298
299     ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
300     Contexts.back().IsExpression = true;
301     Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
302
303     while (CurrentToken) {
304       if (CurrentToken->is(tok::r_square)) {
305         if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
306             Left->is(TT_ObjCMethodExpr)) {
307           // An ObjC method call is rarely followed by an open parenthesis.
308           // FIXME: Do we incorrectly label ":" with this?
309           StartsObjCMethodExpr = false;
310           Left->Type = TT_Unknown;
311         }
312         if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
313           CurrentToken->Type = TT_ObjCMethodExpr;
314           // determineStarAmpUsage() thinks that '*' '[' is allocating an
315           // array of pointers, but if '[' starts a selector then '*' is a
316           // binary operator.
317           if (Parent && Parent->is(TT_PointerOrReference))
318             Parent->Type = TT_BinaryOperator;
319         }
320         Left->MatchingParen = CurrentToken;
321         CurrentToken->MatchingParen = Left;
322         if (Contexts.back().FirstObjCSelectorName) {
323           Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
324               Contexts.back().LongestObjCSelectorName;
325           if (Left->BlockParameterCount > 1)
326             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
327         }
328         next();
329         return true;
330       }
331       if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
332         return false;
333       if (CurrentToken->is(tok::colon)) {
334         if (Left->is(TT_ArraySubscriptLSquare)) {
335           Left->Type = TT_ObjCMethodExpr;
336           StartsObjCMethodExpr = true;
337           Contexts.back().ColonIsObjCMethodExpr = true;
338           if (Parent && Parent->is(tok::r_paren))
339             Parent->Type = TT_CastRParen;
340         }
341         ColonFound = true;
342       }
343       if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
344           !ColonFound)
345         Left->Type = TT_ArrayInitializerLSquare;
346       FormatToken *Tok = CurrentToken;
347       if (!consumeToken())
348         return false;
349       updateParameterCount(Left, Tok);
350     }
351     return false;
352   }
353
354   bool parseBrace() {
355     if (CurrentToken) {
356       FormatToken *Left = CurrentToken->Previous;
357       Left->ParentBracket = Contexts.back().ContextKind;
358
359       if (Contexts.back().CaretFound)
360         Left->Type = TT_ObjCBlockLBrace;
361       Contexts.back().CaretFound = false;
362
363       ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
364       Contexts.back().ColonIsDictLiteral = true;
365       if (Left->BlockKind == BK_BracedInit)
366         Contexts.back().IsExpression = true;
367
368       while (CurrentToken) {
369         if (CurrentToken->is(tok::r_brace)) {
370           Left->MatchingParen = CurrentToken;
371           CurrentToken->MatchingParen = Left;
372           next();
373           return true;
374         }
375         if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
376           return false;
377         updateParameterCount(Left, CurrentToken);
378         if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
379           FormatToken *Previous = CurrentToken->getPreviousNonComment();
380           if (((CurrentToken->is(tok::colon) &&
381                 (!Contexts.back().ColonIsDictLiteral ||
382                  Style.Language != FormatStyle::LK_Cpp)) ||
383                Style.Language == FormatStyle::LK_Proto) &&
384               Previous->Tok.getIdentifierInfo())
385             Previous->Type = TT_SelectorName;
386           if (CurrentToken->is(tok::colon) ||
387               Style.Language == FormatStyle::LK_JavaScript)
388             Left->Type = TT_DictLiteral;
389         }
390         if (!consumeToken())
391           return false;
392       }
393     }
394     return true;
395   }
396
397   void updateParameterCount(FormatToken *Left, FormatToken *Current) {
398     if (Current->is(tok::l_brace) && !Current->is(TT_DictLiteral))
399       ++Left->BlockParameterCount;
400     if (Current->is(tok::comma)) {
401       ++Left->ParameterCount;
402       if (!Left->Role)
403         Left->Role.reset(new CommaSeparatedList(Style));
404       Left->Role->CommaFound(Current);
405     } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
406       Left->ParameterCount = 1;
407     }
408   }
409
410   bool parseConditional() {
411     while (CurrentToken) {
412       if (CurrentToken->is(tok::colon)) {
413         CurrentToken->Type = TT_ConditionalExpr;
414         next();
415         return true;
416       }
417       if (!consumeToken())
418         return false;
419     }
420     return false;
421   }
422
423   bool parseTemplateDeclaration() {
424     if (CurrentToken && CurrentToken->is(tok::less)) {
425       CurrentToken->Type = TT_TemplateOpener;
426       next();
427       if (!parseAngle())
428         return false;
429       if (CurrentToken)
430         CurrentToken->Previous->ClosesTemplateDeclaration = true;
431       return true;
432     }
433     return false;
434   }
435
436   bool consumeToken() {
437     FormatToken *Tok = CurrentToken;
438     next();
439     switch (Tok->Tok.getKind()) {
440     case tok::plus:
441     case tok::minus:
442       if (!Tok->Previous && Line.MustBeDeclaration)
443         Tok->Type = TT_ObjCMethodSpecifier;
444       break;
445     case tok::colon:
446       if (!Tok->Previous)
447         return false;
448       // Colons from ?: are handled in parseConditional().
449       if (Style.Language == FormatStyle::LK_JavaScript) {
450         if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
451             (Contexts.size() == 1 &&               // switch/case labels
452              !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
453             Contexts.back().ContextKind == tok::l_paren ||  // function params
454             Contexts.back().ContextKind == tok::l_square || // array type
455             (Contexts.size() == 1 &&
456              Line.MustBeDeclaration)) { // method/property declaration
457           Tok->Type = TT_JsTypeColon;
458           break;
459         }
460       }
461       if (Contexts.back().ColonIsDictLiteral) {
462         Tok->Type = TT_DictLiteral;
463       } else if (Contexts.back().ColonIsObjCMethodExpr ||
464                  Line.startsWith(TT_ObjCMethodSpecifier)) {
465         Tok->Type = TT_ObjCMethodExpr;
466         Tok->Previous->Type = TT_SelectorName;
467         if (Tok->Previous->ColumnWidth >
468             Contexts.back().LongestObjCSelectorName) {
469           Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
470         }
471         if (!Contexts.back().FirstObjCSelectorName)
472           Contexts.back().FirstObjCSelectorName = Tok->Previous;
473       } else if (Contexts.back().ColonIsForRangeExpr) {
474         Tok->Type = TT_RangeBasedForLoopColon;
475       } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
476         Tok->Type = TT_BitFieldColon;
477       } else if (Contexts.size() == 1 &&
478                  !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
479         if (Tok->Previous->is(tok::r_paren))
480           Tok->Type = TT_CtorInitializerColon;
481         else
482           Tok->Type = TT_InheritanceColon;
483       } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
484                  Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
485         // This handles a special macro in ObjC code where selectors including
486         // the colon are passed as macro arguments.
487         Tok->Type = TT_ObjCMethodExpr;
488       } else if (Contexts.back().ContextKind == tok::l_paren) {
489         Tok->Type = TT_InlineASMColon;
490       }
491       break;
492     case tok::kw_if:
493     case tok::kw_while:
494       if (CurrentToken && CurrentToken->is(tok::l_paren)) {
495         next();
496         if (!parseParens(/*LookForDecls=*/true))
497           return false;
498       }
499       break;
500     case tok::kw_for:
501       Contexts.back().ColonIsForRangeExpr = true;
502       next();
503       if (!parseParens())
504         return false;
505       break;
506     case tok::l_paren:
507       // When faced with 'operator()()', the kw_operator handler incorrectly
508       // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
509       // the first two parens OverloadedOperators and the second l_paren an
510       // OverloadedOperatorLParen.
511       if (Tok->Previous &&
512           Tok->Previous->is(tok::r_paren) &&
513           Tok->Previous->MatchingParen &&
514           Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
515         Tok->Previous->Type = TT_OverloadedOperator;
516         Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
517         Tok->Type = TT_OverloadedOperatorLParen;
518       }
519
520       if (!parseParens())
521         return false;
522       if (Line.MustBeDeclaration && Contexts.size() == 1 &&
523           !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
524           (!Tok->Previous ||
525            !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
526                                    TT_LeadingJavaAnnotation)))
527         Line.MightBeFunctionDecl = true;
528       break;
529     case tok::l_square:
530       if (!parseSquare())
531         return false;
532       break;
533     case tok::l_brace:
534       if (!parseBrace())
535         return false;
536       break;
537     case tok::less:
538       if (!NonTemplateLess.count(Tok) &&
539           (!Tok->Previous ||
540            (!Tok->Previous->Tok.isLiteral() &&
541             !(Tok->Previous->is(tok::r_paren) && Contexts.size() > 1))) &&
542           parseAngle()) {
543         Tok->Type = TT_TemplateOpener;
544       } else {
545         Tok->Type = TT_BinaryOperator;
546         NonTemplateLess.insert(Tok);
547         CurrentToken = Tok;
548         next();
549       }
550       break;
551     case tok::r_paren:
552     case tok::r_square:
553       return false;
554     case tok::r_brace:
555       // Lines can start with '}'.
556       if (Tok->Previous)
557         return false;
558       break;
559     case tok::greater:
560       Tok->Type = TT_BinaryOperator;
561       break;
562     case tok::kw_operator:
563       while (CurrentToken &&
564              !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
565         if (CurrentToken->isOneOf(tok::star, tok::amp))
566           CurrentToken->Type = TT_PointerOrReference;
567         consumeToken();
568         if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
569           CurrentToken->Previous->Type = TT_OverloadedOperator;
570       }
571       if (CurrentToken) {
572         CurrentToken->Type = TT_OverloadedOperatorLParen;
573         if (CurrentToken->Previous->is(TT_BinaryOperator))
574           CurrentToken->Previous->Type = TT_OverloadedOperator;
575       }
576       break;
577     case tok::question:
578       if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
579           Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
580                              tok::r_brace)) {
581         // Question marks before semicolons, colons, etc. indicate optional
582         // types (fields, parameters), e.g.
583         //   function(x?: string, y?) {...}
584         //   class X { y?; }
585         Tok->Type = TT_JsTypeOptionalQuestion;
586         break;
587       }
588       // Declarations cannot be conditional expressions, this can only be part
589       // of a type declaration.
590       if (Line.MustBeDeclaration &&
591           Style.Language == FormatStyle::LK_JavaScript)
592         break;
593       parseConditional();
594       break;
595     case tok::kw_template:
596       parseTemplateDeclaration();
597       break;
598     case tok::comma:
599       if (Contexts.back().InCtorInitializer)
600         Tok->Type = TT_CtorInitializerComma;
601       else if (Contexts.back().FirstStartOfName &&
602                (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
603         Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
604         Line.IsMultiVariableDeclStmt = true;
605       }
606       if (Contexts.back().IsForEachMacro)
607         Contexts.back().IsExpression = true;
608       break;
609     default:
610       break;
611     }
612     return true;
613   }
614
615   void parseIncludeDirective() {
616     if (CurrentToken && CurrentToken->is(tok::less)) {
617       next();
618       while (CurrentToken) {
619         if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
620           CurrentToken->Type = TT_ImplicitStringLiteral;
621         next();
622       }
623     }
624   }
625
626   void parseWarningOrError() {
627     next();
628     // We still want to format the whitespace left of the first token of the
629     // warning or error.
630     next();
631     while (CurrentToken) {
632       CurrentToken->Type = TT_ImplicitStringLiteral;
633       next();
634     }
635   }
636
637   void parsePragma() {
638     next(); // Consume "pragma".
639     if (CurrentToken &&
640         CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
641       bool IsMark = CurrentToken->is(Keywords.kw_mark);
642       next(); // Consume "mark".
643       next(); // Consume first token (so we fix leading whitespace).
644       while (CurrentToken) {
645         if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
646           CurrentToken->Type = TT_ImplicitStringLiteral;
647         next();
648       }
649     }
650   }
651
652   LineType parsePreprocessorDirective() {
653     LineType Type = LT_PreprocessorDirective;
654     next();
655     if (!CurrentToken)
656       return Type;
657     if (CurrentToken->Tok.is(tok::numeric_constant)) {
658       CurrentToken->SpacesRequiredBefore = 1;
659       return Type;
660     }
661     // Hashes in the middle of a line can lead to any strange token
662     // sequence.
663     if (!CurrentToken->Tok.getIdentifierInfo())
664       return Type;
665     switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
666     case tok::pp_include:
667     case tok::pp_include_next:
668     case tok::pp_import:
669       next();
670       parseIncludeDirective();
671       Type = LT_ImportStatement;
672       break;
673     case tok::pp_error:
674     case tok::pp_warning:
675       parseWarningOrError();
676       break;
677     case tok::pp_pragma:
678       parsePragma();
679       break;
680     case tok::pp_if:
681     case tok::pp_elif:
682       Contexts.back().IsExpression = true;
683       parseLine();
684       break;
685     default:
686       break;
687     }
688     while (CurrentToken)
689       next();
690     return Type;
691   }
692
693 public:
694   LineType parseLine() {
695     NonTemplateLess.clear();
696     if (CurrentToken->is(tok::hash))
697       return parsePreprocessorDirective();
698
699     // Directly allow to 'import <string-literal>' to support protocol buffer
700     // definitions (code.google.com/p/protobuf) or missing "#" (either way we
701     // should not break the line).
702     IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
703     if ((Style.Language == FormatStyle::LK_Java &&
704          CurrentToken->is(Keywords.kw_package)) ||
705         (Info && Info->getPPKeywordID() == tok::pp_import &&
706          CurrentToken->Next &&
707          CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
708                                      tok::kw_static))) {
709       next();
710       parseIncludeDirective();
711       return LT_ImportStatement;
712     }
713
714     // If this line starts and ends in '<' and '>', respectively, it is likely
715     // part of "#define <a/b.h>".
716     if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
717       parseIncludeDirective();
718       return LT_ImportStatement;
719     }
720
721     // In .proto files, top-level options are very similar to import statements
722     // and should not be line-wrapped.
723     if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
724         CurrentToken->is(Keywords.kw_option)) {
725       next();
726       if (CurrentToken && CurrentToken->is(tok::identifier))
727         return LT_ImportStatement;
728     }
729
730     bool KeywordVirtualFound = false;
731     bool ImportStatement = false;
732     while (CurrentToken) {
733       if (CurrentToken->is(tok::kw_virtual))
734         KeywordVirtualFound = true;
735       if (isImportStatement(*CurrentToken))
736         ImportStatement = true;
737       if (!consumeToken())
738         return LT_Invalid;
739     }
740     if (KeywordVirtualFound)
741       return LT_VirtualFunctionDecl;
742     if (ImportStatement)
743       return LT_ImportStatement;
744
745     if (Line.startsWith(TT_ObjCMethodSpecifier)) {
746       if (Contexts.back().FirstObjCSelectorName)
747         Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
748             Contexts.back().LongestObjCSelectorName;
749       return LT_ObjCMethodDecl;
750     }
751
752     return LT_Other;
753   }
754
755 private:
756   bool isImportStatement(const FormatToken &Tok) {
757     // FIXME: Closure-library specific stuff should not be hard-coded but be
758     // configurable.
759     return Style.Language == FormatStyle::LK_JavaScript &&
760            Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
761            Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
762                               Tok.Next->Next->TokenText == "provide" ||
763                               Tok.Next->Next->TokenText == "require" ||
764                               Tok.Next->Next->TokenText == "setTestOnly") &&
765            Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
766   }
767
768   void resetTokenMetadata(FormatToken *Token) {
769     if (!Token)
770       return;
771
772     // Reset token type in case we have already looked at it and then
773     // recovered from an error (e.g. failure to find the matching >).
774     if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
775                                TT_FunctionLBrace, TT_ImplicitStringLiteral,
776                                TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
777                                TT_RegexLiteral))
778       CurrentToken->Type = TT_Unknown;
779     CurrentToken->Role.reset();
780     CurrentToken->MatchingParen = nullptr;
781     CurrentToken->FakeLParens.clear();
782     CurrentToken->FakeRParens = 0;
783   }
784
785   void next() {
786     if (CurrentToken) {
787       CurrentToken->NestingLevel = Contexts.size() - 1;
788       CurrentToken->BindingStrength = Contexts.back().BindingStrength;
789       modifyContext(*CurrentToken);
790       determineTokenType(*CurrentToken);
791       CurrentToken = CurrentToken->Next;
792     }
793
794     resetTokenMetadata(CurrentToken);
795   }
796
797   /// \brief A struct to hold information valid in a specific context, e.g.
798   /// a pair of parenthesis.
799   struct Context {
800     Context(tok::TokenKind ContextKind, unsigned BindingStrength,
801             bool IsExpression)
802         : ContextKind(ContextKind), BindingStrength(BindingStrength),
803           IsExpression(IsExpression) {}
804
805     tok::TokenKind ContextKind;
806     unsigned BindingStrength;
807     bool IsExpression;
808     unsigned LongestObjCSelectorName = 0;
809     bool ColonIsForRangeExpr = false;
810     bool ColonIsDictLiteral = false;
811     bool ColonIsObjCMethodExpr = false;
812     FormatToken *FirstObjCSelectorName = nullptr;
813     FormatToken *FirstStartOfName = nullptr;
814     bool CanBeExpression = true;
815     bool InTemplateArgument = false;
816     bool InCtorInitializer = false;
817     bool CaretFound = false;
818     bool IsForEachMacro = false;
819   };
820
821   /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
822   /// of each instance.
823   struct ScopedContextCreator {
824     AnnotatingParser &P;
825
826     ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
827                          unsigned Increase)
828         : P(P) {
829       P.Contexts.push_back(Context(ContextKind,
830                                    P.Contexts.back().BindingStrength + Increase,
831                                    P.Contexts.back().IsExpression));
832     }
833
834     ~ScopedContextCreator() { P.Contexts.pop_back(); }
835   };
836
837   void modifyContext(const FormatToken &Current) {
838     if (Current.getPrecedence() == prec::Assignment &&
839         !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
840         (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
841       Contexts.back().IsExpression = true;
842       if (!Line.startsWith(TT_UnaryOperator)) {
843         for (FormatToken *Previous = Current.Previous;
844              Previous && Previous->Previous &&
845              !Previous->Previous->isOneOf(tok::comma, tok::semi);
846              Previous = Previous->Previous) {
847           if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
848             Previous = Previous->MatchingParen;
849             if (!Previous)
850               break;
851           }
852           if (Previous->opensScope())
853             break;
854           if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
855               Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
856               Previous->Previous && Previous->Previous->isNot(tok::equal))
857             Previous->Type = TT_PointerOrReference;
858         }
859       }
860     } else if (Current.is(tok::lessless) &&
861                (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
862       Contexts.back().IsExpression = true;
863     } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
864       Contexts.back().IsExpression = true;
865     } else if (Current.is(TT_TrailingReturnArrow)) {
866       Contexts.back().IsExpression = false;
867     } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
868       Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
869     } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
870       for (FormatToken *Previous = Current.Previous;
871            Previous && Previous->isOneOf(tok::star, tok::amp);
872            Previous = Previous->Previous)
873         Previous->Type = TT_PointerOrReference;
874       if (Line.MustBeDeclaration)
875         Contexts.back().IsExpression = Contexts.front().InCtorInitializer;
876     } else if (Current.Previous &&
877                Current.Previous->is(TT_CtorInitializerColon)) {
878       Contexts.back().IsExpression = true;
879       Contexts.back().InCtorInitializer = true;
880     } else if (Current.is(tok::kw_new)) {
881       Contexts.back().CanBeExpression = false;
882     } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
883       // This should be the condition or increment in a for-loop.
884       Contexts.back().IsExpression = true;
885     }
886   }
887
888   void determineTokenType(FormatToken &Current) {
889     if (!Current.is(TT_Unknown))
890       // The token type is already known.
891       return;
892
893     // Line.MightBeFunctionDecl can only be true after the parentheses of a
894     // function declaration have been found. In this case, 'Current' is a
895     // trailing token of this declaration and thus cannot be a name.
896     if (Current.is(Keywords.kw_instanceof)) {
897       Current.Type = TT_BinaryOperator;
898     } else if (isStartOfName(Current) &&
899                (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
900       Contexts.back().FirstStartOfName = &Current;
901       Current.Type = TT_StartOfName;
902     } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
903       AutoFound = true;
904     } else if (Current.is(tok::arrow) &&
905                Style.Language == FormatStyle::LK_Java) {
906       Current.Type = TT_LambdaArrow;
907     } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
908                Current.NestingLevel == 0) {
909       Current.Type = TT_TrailingReturnArrow;
910     } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
911       Current.Type =
912           determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
913                                              Contexts.back().IsExpression,
914                                 Contexts.back().InTemplateArgument);
915     } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
916       Current.Type = determinePlusMinusCaretUsage(Current);
917       if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
918         Contexts.back().CaretFound = true;
919     } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
920       Current.Type = determineIncrementUsage(Current);
921     } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
922       Current.Type = TT_UnaryOperator;
923     } else if (Current.is(tok::question)) {
924       if (Style.Language == FormatStyle::LK_JavaScript &&
925           Line.MustBeDeclaration) {
926         // In JavaScript, `interface X { foo?(): bar; }` is an optional method
927         // on the interface, not a ternary expression.
928         Current.Type = TT_JsTypeOptionalQuestion;
929       } else {
930         Current.Type = TT_ConditionalExpr;
931       }
932     } else if (Current.isBinaryOperator() &&
933                (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
934       Current.Type = TT_BinaryOperator;
935     } else if (Current.is(tok::comment)) {
936       if (Current.TokenText.startswith("/*")) {
937         if (Current.TokenText.endswith("*/"))
938           Current.Type = TT_BlockComment;
939         else
940           // The lexer has for some reason determined a comment here. But we
941           // cannot really handle it, if it isn't properly terminated.
942           Current.Tok.setKind(tok::unknown);
943       } else {
944         Current.Type = TT_LineComment;
945       }
946     } else if (Current.is(tok::r_paren)) {
947       if (rParenEndsCast(Current))
948         Current.Type = TT_CastRParen;
949       if (Current.MatchingParen && Current.Next &&
950           !Current.Next->isBinaryOperator() &&
951           !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace))
952         if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
953           if (BeforeParen->is(tok::identifier) &&
954               BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
955               (!BeforeParen->Previous ||
956                BeforeParen->Previous->ClosesTemplateDeclaration))
957             Current.Type = TT_FunctionAnnotationRParen;
958     } else if (Current.is(tok::at) && Current.Next) {
959       if (Current.Next->isStringLiteral()) {
960         Current.Type = TT_ObjCStringLiteral;
961       } else {
962         switch (Current.Next->Tok.getObjCKeywordID()) {
963         case tok::objc_interface:
964         case tok::objc_implementation:
965         case tok::objc_protocol:
966           Current.Type = TT_ObjCDecl;
967           break;
968         case tok::objc_property:
969           Current.Type = TT_ObjCProperty;
970           break;
971         default:
972           break;
973         }
974       }
975     } else if (Current.is(tok::period)) {
976       FormatToken *PreviousNoComment = Current.getPreviousNonComment();
977       if (PreviousNoComment &&
978           PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
979         Current.Type = TT_DesignatedInitializerPeriod;
980       else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
981                Current.Previous->isOneOf(TT_JavaAnnotation,
982                                          TT_LeadingJavaAnnotation)) {
983         Current.Type = Current.Previous->Type;
984       }
985     } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
986                Current.Previous &&
987                !Current.Previous->isOneOf(tok::equal, tok::at) &&
988                Line.MightBeFunctionDecl && Contexts.size() == 1) {
989       // Line.MightBeFunctionDecl can only be true after the parentheses of a
990       // function declaration have been found.
991       Current.Type = TT_TrailingAnnotation;
992     } else if ((Style.Language == FormatStyle::LK_Java ||
993                 Style.Language == FormatStyle::LK_JavaScript) &&
994                Current.Previous) {
995       if (Current.Previous->is(tok::at) &&
996           Current.isNot(Keywords.kw_interface)) {
997         const FormatToken &AtToken = *Current.Previous;
998         const FormatToken *Previous = AtToken.getPreviousNonComment();
999         if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1000           Current.Type = TT_LeadingJavaAnnotation;
1001         else
1002           Current.Type = TT_JavaAnnotation;
1003       } else if (Current.Previous->is(tok::period) &&
1004                  Current.Previous->isOneOf(TT_JavaAnnotation,
1005                                            TT_LeadingJavaAnnotation)) {
1006         Current.Type = Current.Previous->Type;
1007       }
1008     }
1009   }
1010
1011   /// \brief Take a guess at whether \p Tok starts a name of a function or
1012   /// variable declaration.
1013   ///
1014   /// This is a heuristic based on whether \p Tok is an identifier following
1015   /// something that is likely a type.
1016   bool isStartOfName(const FormatToken &Tok) {
1017     if (Tok.isNot(tok::identifier) || !Tok.Previous)
1018       return false;
1019
1020     if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
1021       return false;
1022
1023     // Skip "const" as it does not have an influence on whether this is a name.
1024     FormatToken *PreviousNotConst = Tok.Previous;
1025     while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1026       PreviousNotConst = PreviousNotConst->Previous;
1027
1028     if (!PreviousNotConst)
1029       return false;
1030
1031     bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1032                        PreviousNotConst->Previous &&
1033                        PreviousNotConst->Previous->is(tok::hash);
1034
1035     if (PreviousNotConst->is(TT_TemplateCloser))
1036       return PreviousNotConst && PreviousNotConst->MatchingParen &&
1037              PreviousNotConst->MatchingParen->Previous &&
1038              PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1039              PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1040
1041     if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1042         PreviousNotConst->MatchingParen->Previous &&
1043         PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1044       return true;
1045
1046     return (!IsPPKeyword &&
1047             PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1048            PreviousNotConst->is(TT_PointerOrReference) ||
1049            PreviousNotConst->isSimpleTypeSpecifier();
1050   }
1051
1052   /// \brief Determine whether ')' is ending a cast.
1053   bool rParenEndsCast(const FormatToken &Tok) {
1054     // C-style casts are only used in C++ and Java.
1055     if (Style.Language != FormatStyle::LK_Cpp &&
1056         Style.Language != FormatStyle::LK_Java)
1057       return false;
1058
1059     // Empty parens aren't casts and there are no casts at the end of the line.
1060     if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1061       return false;
1062
1063     FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1064     if (LeftOfParens) {
1065       // If there is an opening parenthesis left of the current parentheses,
1066       // look past it as these might be chained casts.
1067       if (LeftOfParens->is(tok::r_paren)) {
1068         if (!LeftOfParens->MatchingParen ||
1069             !LeftOfParens->MatchingParen->Previous)
1070           return false;
1071         LeftOfParens = LeftOfParens->MatchingParen->Previous;
1072       }
1073
1074       // If there is an identifier (or with a few exceptions a keyword) right
1075       // before the parentheses, this is unlikely to be a cast.
1076       if (LeftOfParens->Tok.getIdentifierInfo() &&
1077           !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1078                                  tok::kw_delete))
1079         return false;
1080
1081       // Certain other tokens right before the parentheses are also signals that
1082       // this cannot be a cast.
1083       if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1084                                 TT_TemplateCloser))
1085         return false;
1086     }
1087
1088     if (Tok.Next->is(tok::question))
1089       return false;
1090
1091     // As Java has no function types, a "(" after the ")" likely means that this
1092     // is a cast.
1093     if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1094       return true;
1095
1096     // If a (non-string) literal follows, this is likely a cast.
1097     if (Tok.Next->isNot(tok::string_literal) &&
1098         (Tok.Next->Tok.isLiteral() ||
1099          Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1100       return true;
1101
1102     // Heuristically try to determine whether the parentheses contain a type.
1103     bool ParensAreType =
1104         !Tok.Previous ||
1105         Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1106         Tok.Previous->isSimpleTypeSpecifier();
1107     bool ParensCouldEndDecl =
1108         Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1109     if (ParensAreType && !ParensCouldEndDecl)
1110       return true;
1111
1112     // At this point, we heuristically assume that there are no casts at the
1113     // start of the line. We assume that we have found most cases where there
1114     // are by the logic above, e.g. "(void)x;".
1115     if (!LeftOfParens)
1116       return false;
1117
1118     // If the following token is an identifier, this is a cast. All cases where
1119     // this can be something else are handled above.
1120     if (Tok.Next->is(tok::identifier))
1121       return true;
1122
1123     if (!Tok.Next->Next)
1124       return false;
1125
1126     // If the next token after the parenthesis is a unary operator, assume
1127     // that this is cast, unless there are unexpected tokens inside the
1128     // parenthesis.
1129     bool NextIsUnary =
1130         Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1131     if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1132         !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1133       return false;
1134     // Search for unexpected tokens.
1135     for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1136          Prev = Prev->Previous) {
1137       if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1138         return false;
1139     }
1140     return true;
1141   }
1142
1143   /// \brief Return the type of the given token assuming it is * or &.
1144   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1145                                   bool InTemplateArgument) {
1146     if (Style.Language == FormatStyle::LK_JavaScript)
1147       return TT_BinaryOperator;
1148
1149     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1150     if (!PrevToken)
1151       return TT_UnaryOperator;
1152
1153     const FormatToken *NextToken = Tok.getNextNonComment();
1154     if (!NextToken ||
1155         NextToken->isOneOf(tok::arrow, Keywords.kw_final,
1156                            Keywords.kw_override) ||
1157         (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1158       return TT_PointerOrReference;
1159
1160     if (PrevToken->is(tok::coloncolon))
1161       return TT_PointerOrReference;
1162
1163     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1164                            tok::comma, tok::semi, tok::kw_return, tok::colon,
1165                            tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1166         PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1167                            TT_UnaryOperator, TT_CastRParen))
1168       return TT_UnaryOperator;
1169
1170     if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1171       return TT_PointerOrReference;
1172     if (NextToken->is(tok::kw_operator) && !IsExpression)
1173       return TT_PointerOrReference;
1174     if (NextToken->isOneOf(tok::comma, tok::semi))
1175       return TT_PointerOrReference;
1176
1177     if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1178         PrevToken->MatchingParen->Previous &&
1179         PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1180                                                     tok::kw_decltype))
1181       return TT_PointerOrReference;
1182
1183     if (PrevToken->Tok.isLiteral() ||
1184         PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1185                            tok::kw_false, tok::r_brace) ||
1186         NextToken->Tok.isLiteral() ||
1187         NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1188         NextToken->isUnaryOperator() ||
1189         // If we know we're in a template argument, there are no named
1190         // declarations. Thus, having an identifier on the right-hand side
1191         // indicates a binary operator.
1192         (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1193       return TT_BinaryOperator;
1194
1195     // "&&(" is quite unlikely to be two successive unary "&".
1196     if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1197       return TT_BinaryOperator;
1198
1199     // This catches some cases where evaluation order is used as control flow:
1200     //   aaa && aaa->f();
1201     const FormatToken *NextNextToken = NextToken->getNextNonComment();
1202     if (NextNextToken && NextNextToken->is(tok::arrow))
1203       return TT_BinaryOperator;
1204
1205     // It is very unlikely that we are going to find a pointer or reference type
1206     // definition on the RHS of an assignment.
1207     if (IsExpression && !Contexts.back().CaretFound)
1208       return TT_BinaryOperator;
1209
1210     return TT_PointerOrReference;
1211   }
1212
1213   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1214     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1215     if (!PrevToken || PrevToken->is(TT_CastRParen))
1216       return TT_UnaryOperator;
1217
1218     // Use heuristics to recognize unary operators.
1219     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1220                            tok::question, tok::colon, tok::kw_return,
1221                            tok::kw_case, tok::at, tok::l_brace))
1222       return TT_UnaryOperator;
1223
1224     // There can't be two consecutive binary operators.
1225     if (PrevToken->is(TT_BinaryOperator))
1226       return TT_UnaryOperator;
1227
1228     // Fall back to marking the token as binary operator.
1229     return TT_BinaryOperator;
1230   }
1231
1232   /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1233   TokenType determineIncrementUsage(const FormatToken &Tok) {
1234     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1235     if (!PrevToken || PrevToken->is(TT_CastRParen))
1236       return TT_UnaryOperator;
1237     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1238       return TT_TrailingUnaryOperator;
1239
1240     return TT_UnaryOperator;
1241   }
1242
1243   SmallVector<Context, 8> Contexts;
1244
1245   const FormatStyle &Style;
1246   AnnotatedLine &Line;
1247   FormatToken *CurrentToken;
1248   bool AutoFound;
1249   const AdditionalKeywords &Keywords;
1250
1251   // Set of "<" tokens that do not open a template parameter list. If parseAngle
1252   // determines that a specific token can't be a template opener, it will make
1253   // same decision irrespective of the decisions for tokens leading up to it.
1254   // Store this information to prevent this from causing exponential runtime.
1255   llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1256 };
1257
1258 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1259 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1260
1261 /// \brief Parses binary expressions by inserting fake parenthesis based on
1262 /// operator precedence.
1263 class ExpressionParser {
1264 public:
1265   ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1266                    AnnotatedLine &Line)
1267       : Style(Style), Keywords(Keywords), Current(Line.First) {}
1268
1269   /// \brief Parse expressions with the given operatore precedence.
1270   void parse(int Precedence = 0) {
1271     // Skip 'return' and ObjC selector colons as they are not part of a binary
1272     // expression.
1273     while (Current && (Current->is(tok::kw_return) ||
1274                        (Current->is(tok::colon) &&
1275                         Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1276       next();
1277
1278     if (!Current || Precedence > PrecedenceArrowAndPeriod)
1279       return;
1280
1281     // Conditional expressions need to be parsed separately for proper nesting.
1282     if (Precedence == prec::Conditional) {
1283       parseConditionalExpr();
1284       return;
1285     }
1286
1287     // Parse unary operators, which all have a higher precedence than binary
1288     // operators.
1289     if (Precedence == PrecedenceUnaryOperator) {
1290       parseUnaryOperator();
1291       return;
1292     }
1293
1294     FormatToken *Start = Current;
1295     FormatToken *LatestOperator = nullptr;
1296     unsigned OperatorIndex = 0;
1297
1298     while (Current) {
1299       // Consume operators with higher precedence.
1300       parse(Precedence + 1);
1301
1302       int CurrentPrecedence = getCurrentPrecedence();
1303
1304       if (Current && Current->is(TT_SelectorName) &&
1305           Precedence == CurrentPrecedence) {
1306         if (LatestOperator)
1307           addFakeParenthesis(Start, prec::Level(Precedence));
1308         Start = Current;
1309       }
1310
1311       // At the end of the line or when an operator with higher precedence is
1312       // found, insert fake parenthesis and return.
1313       if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1314           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1315           (CurrentPrecedence == prec::Conditional &&
1316            Precedence == prec::Assignment && Current->is(tok::colon))) {
1317         break;
1318       }
1319
1320       // Consume scopes: (), [], <> and {}
1321       if (Current->opensScope()) {
1322         while (Current && !Current->closesScope()) {
1323           next();
1324           parse();
1325         }
1326         next();
1327       } else {
1328         // Operator found.
1329         if (CurrentPrecedence == Precedence) {
1330           LatestOperator = Current;
1331           Current->OperatorIndex = OperatorIndex;
1332           ++OperatorIndex;
1333         }
1334         next(/*SkipPastLeadingComments=*/Precedence > 0);
1335       }
1336     }
1337
1338     if (LatestOperator && (Current || Precedence > 0)) {
1339       LatestOperator->LastOperator = true;
1340       if (Precedence == PrecedenceArrowAndPeriod) {
1341         // Call expressions don't have a binary operator precedence.
1342         addFakeParenthesis(Start, prec::Unknown);
1343       } else {
1344         addFakeParenthesis(Start, prec::Level(Precedence));
1345       }
1346     }
1347   }
1348
1349 private:
1350   /// \brief Gets the precedence (+1) of the given token for binary operators
1351   /// and other tokens that we treat like binary operators.
1352   int getCurrentPrecedence() {
1353     if (Current) {
1354       const FormatToken *NextNonComment = Current->getNextNonComment();
1355       if (Current->is(TT_ConditionalExpr))
1356         return prec::Conditional;
1357       if (NextNonComment && NextNonComment->is(tok::colon) &&
1358           NextNonComment->is(TT_DictLiteral))
1359         return prec::Comma;
1360       if (Current->is(TT_LambdaArrow))
1361         return prec::Comma;
1362       if (Current->is(TT_JsFatArrow))
1363         return prec::Assignment;
1364       if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
1365                            TT_JsComputedPropertyName) ||
1366           (Current->is(tok::comment) && NextNonComment &&
1367            NextNonComment->is(TT_SelectorName)))
1368         return 0;
1369       if (Current->is(TT_RangeBasedForLoopColon))
1370         return prec::Comma;
1371       if ((Style.Language == FormatStyle::LK_Java ||
1372            Style.Language == FormatStyle::LK_JavaScript) &&
1373           Current->is(Keywords.kw_instanceof))
1374         return prec::Relational;
1375       if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1376         return Current->getPrecedence();
1377       if (Current->isOneOf(tok::period, tok::arrow))
1378         return PrecedenceArrowAndPeriod;
1379       if (Style.Language == FormatStyle::LK_Java &&
1380           Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1381                            Keywords.kw_throws))
1382         return 0;
1383     }
1384     return -1;
1385   }
1386
1387   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1388     Start->FakeLParens.push_back(Precedence);
1389     if (Precedence > prec::Unknown)
1390       Start->StartsBinaryExpression = true;
1391     if (Current) {
1392       FormatToken *Previous = Current->Previous;
1393       while (Previous->is(tok::comment) && Previous->Previous)
1394         Previous = Previous->Previous;
1395       ++Previous->FakeRParens;
1396       if (Precedence > prec::Unknown)
1397         Previous->EndsBinaryExpression = true;
1398     }
1399   }
1400
1401   /// \brief Parse unary operator expressions and surround them with fake
1402   /// parentheses if appropriate.
1403   void parseUnaryOperator() {
1404     if (!Current || Current->isNot(TT_UnaryOperator)) {
1405       parse(PrecedenceArrowAndPeriod);
1406       return;
1407     }
1408
1409     FormatToken *Start = Current;
1410     next();
1411     parseUnaryOperator();
1412
1413     // The actual precedence doesn't matter.
1414     addFakeParenthesis(Start, prec::Unknown);
1415   }
1416
1417   void parseConditionalExpr() {
1418     while (Current && Current->isTrailingComment()) {
1419       next();
1420     }
1421     FormatToken *Start = Current;
1422     parse(prec::LogicalOr);
1423     if (!Current || !Current->is(tok::question))
1424       return;
1425     next();
1426     parse(prec::Assignment);
1427     if (!Current || Current->isNot(TT_ConditionalExpr))
1428       return;
1429     next();
1430     parse(prec::Assignment);
1431     addFakeParenthesis(Start, prec::Conditional);
1432   }
1433
1434   void next(bool SkipPastLeadingComments = true) {
1435     if (Current)
1436       Current = Current->Next;
1437     while (Current &&
1438            (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1439            Current->isTrailingComment())
1440       Current = Current->Next;
1441   }
1442
1443   const FormatStyle &Style;
1444   const AdditionalKeywords &Keywords;
1445   FormatToken *Current;
1446 };
1447
1448 } // end anonymous namespace
1449
1450 void TokenAnnotator::setCommentLineLevels(
1451     SmallVectorImpl<AnnotatedLine *> &Lines) {
1452   const AnnotatedLine *NextNonCommentLine = nullptr;
1453   for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1454                                                           E = Lines.rend();
1455        I != E; ++I) {
1456     if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1457         (*I)->First->Next == nullptr)
1458       (*I)->Level = NextNonCommentLine->Level;
1459     else
1460       NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1461
1462     setCommentLineLevels((*I)->Children);
1463   }
1464 }
1465
1466 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1467   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1468                                                   E = Line.Children.end();
1469        I != E; ++I) {
1470     annotate(**I);
1471   }
1472   AnnotatingParser Parser(Style, Line, Keywords);
1473   Line.Type = Parser.parseLine();
1474   if (Line.Type == LT_Invalid)
1475     return;
1476
1477   ExpressionParser ExprParser(Style, Keywords, Line);
1478   ExprParser.parse();
1479
1480   if (Line.startsWith(TT_ObjCMethodSpecifier))
1481     Line.Type = LT_ObjCMethodDecl;
1482   else if (Line.startsWith(TT_ObjCDecl))
1483     Line.Type = LT_ObjCDecl;
1484   else if (Line.startsWith(TT_ObjCProperty))
1485     Line.Type = LT_ObjCProperty;
1486
1487   Line.First->SpacesRequiredBefore = 1;
1488   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1489 }
1490
1491 // This function heuristically determines whether 'Current' starts the name of a
1492 // function declaration.
1493 static bool isFunctionDeclarationName(const FormatToken &Current) {
1494   auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1495     for (; Next; Next = Next->Next) {
1496       if (Next->is(TT_OverloadedOperatorLParen))
1497         return Next;
1498       if (Next->is(TT_OverloadedOperator))
1499         continue;
1500       if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1501         // For 'new[]' and 'delete[]'.
1502         if (Next->Next && Next->Next->is(tok::l_square) &&
1503             Next->Next->Next && Next->Next->Next->is(tok::r_square))
1504           Next = Next->Next->Next;
1505         continue;
1506       }
1507
1508       break;
1509     }
1510     return nullptr;
1511   };
1512
1513   const FormatToken *Next = Current.Next;
1514   if (Current.is(tok::kw_operator)) {
1515     if (Current.Previous && Current.Previous->is(tok::coloncolon))
1516       return false;
1517     Next = skipOperatorName(Next);
1518   } else {
1519     if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1520       return false;
1521     for (; Next; Next = Next->Next) {
1522       if (Next->is(TT_TemplateOpener)) {
1523         Next = Next->MatchingParen;
1524       } else if (Next->is(tok::coloncolon)) {
1525         Next = Next->Next;
1526         if (!Next)
1527           return false;
1528         if (Next->is(tok::kw_operator)) {
1529           Next = skipOperatorName(Next->Next);
1530           break;
1531         }
1532         if (!Next->is(tok::identifier))
1533           return false;
1534       } else if (Next->is(tok::l_paren)) {
1535         break;
1536       } else {
1537         return false;
1538       }
1539     }
1540   }
1541
1542   if (!Next || !Next->is(tok::l_paren))
1543     return false;
1544   if (Next->Next == Next->MatchingParen)
1545     return true;
1546   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1547        Tok = Tok->Next) {
1548     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1549         Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
1550       return true;
1551     if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1552         Tok->Tok.isLiteral())
1553       return false;
1554   }
1555   return false;
1556 }
1557
1558 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1559   assert(Line.MightBeFunctionDecl);
1560
1561   if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1562        Style.AlwaysBreakAfterReturnType ==
1563            FormatStyle::RTBS_TopLevelDefinitions) &&
1564       Line.Level > 0)
1565     return false;
1566
1567   switch (Style.AlwaysBreakAfterReturnType) {
1568   case FormatStyle::RTBS_None:
1569     return false;
1570   case FormatStyle::RTBS_All:
1571   case FormatStyle::RTBS_TopLevel:
1572     return true;
1573   case FormatStyle::RTBS_AllDefinitions:
1574   case FormatStyle::RTBS_TopLevelDefinitions:
1575     return Line.mightBeFunctionDefinition();
1576   }
1577
1578   return false;
1579 }
1580
1581 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1582   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1583                                                   E = Line.Children.end();
1584        I != E; ++I) {
1585     calculateFormattingInformation(**I);
1586   }
1587
1588   Line.First->TotalLength =
1589       Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1590   if (!Line.First->Next)
1591     return;
1592   FormatToken *Current = Line.First->Next;
1593   bool InFunctionDecl = Line.MightBeFunctionDecl;
1594   while (Current) {
1595     if (isFunctionDeclarationName(*Current))
1596       Current->Type = TT_FunctionDeclarationName;
1597     if (Current->is(TT_LineComment)) {
1598       if (Current->Previous->BlockKind == BK_BracedInit &&
1599           Current->Previous->opensScope())
1600         Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1601       else
1602         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1603
1604       // If we find a trailing comment, iterate backwards to determine whether
1605       // it seems to relate to a specific parameter. If so, break before that
1606       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1607       // to the previous line in:
1608       //   SomeFunction(a,
1609       //                b, // comment
1610       //                c);
1611       if (!Current->HasUnescapedNewline) {
1612         for (FormatToken *Parameter = Current->Previous; Parameter;
1613              Parameter = Parameter->Previous) {
1614           if (Parameter->isOneOf(tok::comment, tok::r_brace))
1615             break;
1616           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1617             if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1618                 Parameter->HasUnescapedNewline)
1619               Parameter->MustBreakBefore = true;
1620             break;
1621           }
1622         }
1623       }
1624     } else if (Current->SpacesRequiredBefore == 0 &&
1625                spaceRequiredBefore(Line, *Current)) {
1626       Current->SpacesRequiredBefore = 1;
1627     }
1628
1629     Current->MustBreakBefore =
1630         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1631
1632     if (!Current->MustBreakBefore && InFunctionDecl &&
1633         Current->is(TT_FunctionDeclarationName))
1634       Current->MustBreakBefore = mustBreakForReturnType(Line);
1635
1636     Current->CanBreakBefore =
1637         Current->MustBreakBefore || canBreakBefore(Line, *Current);
1638     unsigned ChildSize = 0;
1639     if (Current->Previous->Children.size() == 1) {
1640       FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1641       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1642                                                   : LastOfChild.TotalLength + 1;
1643     }
1644     const FormatToken *Prev = Current->Previous;
1645     if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1646         (Prev->Children.size() == 1 &&
1647          Prev->Children[0]->First->MustBreakBefore) ||
1648         Current->IsMultiline)
1649       Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1650     else
1651       Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1652                              ChildSize + Current->SpacesRequiredBefore;
1653
1654     if (Current->is(TT_CtorInitializerColon))
1655       InFunctionDecl = false;
1656
1657     // FIXME: Only calculate this if CanBreakBefore is true once static
1658     // initializers etc. are sorted out.
1659     // FIXME: Move magic numbers to a better place.
1660     Current->SplitPenalty = 20 * Current->BindingStrength +
1661                             splitPenalty(Line, *Current, InFunctionDecl);
1662
1663     Current = Current->Next;
1664   }
1665
1666   calculateUnbreakableTailLengths(Line);
1667   for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1668     if (Current->Role)
1669       Current->Role->precomputeFormattingInfos(Current);
1670   }
1671
1672   DEBUG({ printDebugInfo(Line); });
1673 }
1674
1675 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1676   unsigned UnbreakableTailLength = 0;
1677   FormatToken *Current = Line.Last;
1678   while (Current) {
1679     Current->UnbreakableTailLength = UnbreakableTailLength;
1680     if (Current->CanBreakBefore ||
1681         Current->isOneOf(tok::comment, tok::string_literal)) {
1682       UnbreakableTailLength = 0;
1683     } else {
1684       UnbreakableTailLength +=
1685           Current->ColumnWidth + Current->SpacesRequiredBefore;
1686     }
1687     Current = Current->Previous;
1688   }
1689 }
1690
1691 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1692                                       const FormatToken &Tok,
1693                                       bool InFunctionDecl) {
1694   const FormatToken &Left = *Tok.Previous;
1695   const FormatToken &Right = Tok;
1696
1697   if (Left.is(tok::semi))
1698     return 0;
1699
1700   if (Style.Language == FormatStyle::LK_Java) {
1701     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1702       return 1;
1703     if (Right.is(Keywords.kw_implements))
1704       return 2;
1705     if (Left.is(tok::comma) && Left.NestingLevel == 0)
1706       return 3;
1707   } else if (Style.Language == FormatStyle::LK_JavaScript) {
1708     if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1709       return 100;
1710     if (Left.is(TT_JsTypeColon))
1711       return 100;
1712   }
1713
1714   if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1715                               Right.Next->is(TT_DictLiteral)))
1716     return 1;
1717   if (Right.is(tok::l_square)) {
1718     if (Style.Language == FormatStyle::LK_Proto || Left.is(tok::r_square))
1719       return 1;
1720     // Slightly prefer formatting local lambda definitions like functions.
1721     if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1722       return 50;
1723     if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1724                        TT_ArrayInitializerLSquare))
1725       return 500;
1726   }
1727
1728   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1729       Right.is(tok::kw_operator)) {
1730     if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1731       return 3;
1732     if (Left.is(TT_StartOfName))
1733       return 110;
1734     if (InFunctionDecl && Right.NestingLevel == 0)
1735       return Style.PenaltyReturnTypeOnItsOwnLine;
1736     return 200;
1737   }
1738   if (Right.is(TT_PointerOrReference))
1739     return 190;
1740   if (Right.is(TT_LambdaArrow))
1741     return 110;
1742   if (Left.is(tok::equal) && Right.is(tok::l_brace))
1743     return 150;
1744   if (Left.is(TT_CastRParen))
1745     return 100;
1746   if (Left.is(tok::coloncolon) ||
1747       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1748     return 500;
1749   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1750     return 5000;
1751
1752   if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1753     return 2;
1754
1755   if (Right.isMemberAccess()) {
1756     // Breaking before the "./->" of a chained call/member access is reasonably
1757     // cheap, as formatting those with one call per line is generally
1758     // desirable. In particular, it should be cheaper to break before the call
1759     // than it is to break inside a call's parameters, which could lead to weird
1760     // "hanging" indents. The exception is the very last "./->" to support this
1761     // frequent pattern:
1762     //
1763     //   aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
1764     //       dddddddd);
1765     //
1766     // which might otherwise be blown up onto many lines. Here, clang-format
1767     // won't produce "hanging" indents anyway as there is no other trailing
1768     // call.
1769     return Right.LastOperator ? 150 : 40;
1770   }
1771
1772   if (Right.is(TT_TrailingAnnotation) &&
1773       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1774     // Moving trailing annotations to the next line is fine for ObjC method
1775     // declarations.
1776     if (Line.startsWith(TT_ObjCMethodSpecifier))
1777       return 10;
1778     // Generally, breaking before a trailing annotation is bad unless it is
1779     // function-like. It seems to be especially preferable to keep standard
1780     // annotations (i.e. "const", "final" and "override") on the same line.
1781     // Use a slightly higher penalty after ")" so that annotations like
1782     // "const override" are kept together.
1783     bool is_short_annotation = Right.TokenText.size() < 10;
1784     return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1785   }
1786
1787   // In for-loops, prefer breaking at ',' and ';'.
1788   if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1789     return 4;
1790
1791   // In Objective-C method expressions, prefer breaking before "param:" over
1792   // breaking after it.
1793   if (Right.is(TT_SelectorName))
1794     return 0;
1795   if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1796     return Line.MightBeFunctionDecl ? 50 : 500;
1797
1798   if (Left.is(tok::l_paren) && InFunctionDecl &&
1799       Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1800     return 100;
1801   if (Left.is(tok::l_paren) && Left.Previous &&
1802       Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
1803     return 1000;
1804   if (Left.is(tok::equal) && InFunctionDecl)
1805     return 110;
1806   if (Right.is(tok::r_brace))
1807     return 1;
1808   if (Left.is(TT_TemplateOpener))
1809     return 100;
1810   if (Left.opensScope()) {
1811     if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
1812       return 0;
1813     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1814                                    : 19;
1815   }
1816   if (Left.is(TT_JavaAnnotation))
1817     return 50;
1818
1819   if (Right.is(tok::lessless)) {
1820     if (Left.is(tok::string_literal) &&
1821         (!Right.LastOperator || Right.OperatorIndex != 1)) {
1822       StringRef Content = Left.TokenText;
1823       if (Content.startswith("\""))
1824         Content = Content.drop_front(1);
1825       if (Content.endswith("\""))
1826         Content = Content.drop_back(1);
1827       Content = Content.trim();
1828       if (Content.size() > 1 &&
1829           (Content.back() == ':' || Content.back() == '='))
1830         return 25;
1831     }
1832     return 1; // Breaking at a << is really cheap.
1833   }
1834   if (Left.is(TT_ConditionalExpr))
1835     return prec::Conditional;
1836   prec::Level Level = Left.getPrecedence();
1837   if (Level != prec::Unknown)
1838     return Level;
1839   Level = Right.getPrecedence();
1840   if (Level != prec::Unknown)
1841     return Level;
1842
1843   return 3;
1844 }
1845
1846 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1847                                           const FormatToken &Left,
1848                                           const FormatToken &Right) {
1849   if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1850     return true;
1851   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1852       Left.Tok.getObjCKeywordID() == tok::objc_property)
1853     return true;
1854   if (Right.is(tok::hashhash))
1855     return Left.is(tok::hash);
1856   if (Left.isOneOf(tok::hashhash, tok::hash))
1857     return Right.is(tok::hash);
1858   if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1859     return Style.SpaceInEmptyParentheses;
1860   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1861     return (Right.is(TT_CastRParen) ||
1862             (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1863                ? Style.SpacesInCStyleCastParentheses
1864                : Style.SpacesInParentheses;
1865   if (Right.isOneOf(tok::semi, tok::comma))
1866     return false;
1867   if (Right.is(tok::less) &&
1868       (Left.is(tok::kw_template) ||
1869        (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1870     return true;
1871   if (Left.isOneOf(tok::exclaim, tok::tilde))
1872     return false;
1873   if (Left.is(tok::at) &&
1874       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1875                     tok::numeric_constant, tok::l_paren, tok::l_brace,
1876                     tok::kw_true, tok::kw_false))
1877     return false;
1878   if (Left.is(tok::coloncolon))
1879     return false;
1880   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1881     return false;
1882   if (Right.is(tok::ellipsis))
1883     return Left.Tok.isLiteral();
1884   if (Left.is(tok::l_square) && Right.is(tok::amp))
1885     return false;
1886   if (Right.is(TT_PointerOrReference))
1887     return (Left.is(tok::r_paren) && Left.MatchingParen &&
1888             (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
1889              (Left.MatchingParen->Previous &&
1890               Left.MatchingParen->Previous->is(TT_FunctionDeclarationName)))) ||
1891            (Left.Tok.isLiteral() ||
1892             (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1893              (Style.PointerAlignment != FormatStyle::PAS_Left ||
1894               Line.IsMultiVariableDeclStmt)));
1895   if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
1896       (!Left.is(TT_PointerOrReference) ||
1897        (Style.PointerAlignment != FormatStyle::PAS_Right &&
1898         !Line.IsMultiVariableDeclStmt)))
1899     return true;
1900   if (Left.is(TT_PointerOrReference))
1901     return Right.Tok.isLiteral() ||
1902            Right.isOneOf(TT_BlockComment, Keywords.kw_final,
1903                          Keywords.kw_override) ||
1904            (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
1905            (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
1906                            tok::l_paren) &&
1907             (Style.PointerAlignment != FormatStyle::PAS_Right &&
1908              !Line.IsMultiVariableDeclStmt) &&
1909             Left.Previous &&
1910             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1911   if (Right.is(tok::star) && Left.is(tok::l_paren))
1912     return false;
1913   if (Left.is(tok::l_square))
1914     return (Left.is(TT_ArrayInitializerLSquare) &&
1915             Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
1916            (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
1917             Right.isNot(tok::r_square));
1918   if (Right.is(tok::r_square))
1919     return Right.MatchingParen &&
1920            ((Style.SpacesInContainerLiterals &&
1921              Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
1922             (Style.SpacesInSquareBrackets &&
1923              Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
1924   if (Right.is(tok::l_square) &&
1925       !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
1926       !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
1927     return false;
1928   if (Left.is(tok::colon))
1929     return !Left.is(TT_ObjCMethodExpr);
1930   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1931     return !Left.Children.empty(); // No spaces in "{}".
1932   if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1933       (Right.is(tok::r_brace) && Right.MatchingParen &&
1934        Right.MatchingParen->BlockKind != BK_Block))
1935     return !Style.Cpp11BracedListStyle;
1936   if (Left.is(TT_BlockComment))
1937     return !Left.TokenText.endswith("=*/");
1938   if (Right.is(tok::l_paren)) {
1939     if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
1940       return true;
1941     return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
1942            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1943             (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
1944                           tok::kw_switch, tok::kw_case, TT_ForEachMacro,
1945                           TT_ObjCForIn) ||
1946              (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
1947                            tok::kw_new, tok::kw_delete) &&
1948               (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
1949            (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1950             (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
1951              Left.is(tok::r_paren)) &&
1952             Line.Type != LT_PreprocessorDirective);
1953   }
1954   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1955     return false;
1956   if (Right.is(TT_UnaryOperator))
1957     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1958            (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
1959   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1960                     tok::r_paren) ||
1961        Left.isSimpleTypeSpecifier()) &&
1962       Right.is(tok::l_brace) && Right.getNextNonComment() &&
1963       Right.BlockKind != BK_Block)
1964     return false;
1965   if (Left.is(tok::period) || Right.is(tok::period))
1966     return false;
1967   if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1968     return false;
1969   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
1970       Left.MatchingParen->Previous &&
1971       Left.MatchingParen->Previous->is(tok::period))
1972     // A.<B>DoSomething();
1973     return false;
1974   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
1975     return false;
1976   return true;
1977 }
1978
1979 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1980                                          const FormatToken &Right) {
1981   const FormatToken &Left = *Right.Previous;
1982   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
1983     return true; // Never ever merge two identifiers.
1984   if (Style.Language == FormatStyle::LK_Cpp) {
1985     if (Left.is(tok::kw_operator))
1986       return Right.is(tok::coloncolon);
1987   } else if (Style.Language == FormatStyle::LK_Proto) {
1988     if (Right.is(tok::period) &&
1989         Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
1990                      Keywords.kw_repeated, Keywords.kw_extend))
1991       return true;
1992     if (Right.is(tok::l_paren) &&
1993         Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
1994       return true;
1995   } else if (Style.Language == FormatStyle::LK_JavaScript) {
1996     if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, TT_JsFatArrow,
1997                      Keywords.kw_in))
1998       return true;
1999     if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2000       return true;
2001     if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2002       return false;
2003     if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2004         Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2005       return false;
2006     if (Left.is(tok::ellipsis))
2007       return false;
2008     if (Left.is(TT_TemplateCloser) &&
2009         !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2010                        Keywords.kw_implements, Keywords.kw_extends))
2011       // Type assertions ('<type>expr') are not followed by whitespace. Other
2012       // locations that should have whitespace following are identified by the
2013       // above set of follower tokens.
2014       return false;
2015   } else if (Style.Language == FormatStyle::LK_Java) {
2016     if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2017       return true;
2018     if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2019       return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2020     if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2021                       tok::kw_protected) ||
2022          Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2023                       Keywords.kw_native)) &&
2024         Right.is(TT_TemplateOpener))
2025       return true;
2026   }
2027   if (Left.is(TT_ImplicitStringLiteral))
2028     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2029   if (Line.Type == LT_ObjCMethodDecl) {
2030     if (Left.is(TT_ObjCMethodSpecifier))
2031       return true;
2032     if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2033       // Don't space between ')' and <id>
2034       return false;
2035   }
2036   if (Line.Type == LT_ObjCProperty &&
2037       (Right.is(tok::equal) || Left.is(tok::equal)))
2038     return false;
2039
2040   if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2041       Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2042     return true;
2043   if (Left.is(tok::comma))
2044     return true;
2045   if (Right.is(tok::comma))
2046     return false;
2047   if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2048     return true;
2049   if (Right.is(TT_OverloadedOperatorLParen))
2050     return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2051   if (Right.is(tok::colon)) {
2052     if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2053         !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2054       return false;
2055     if (Right.is(TT_ObjCMethodExpr))
2056       return false;
2057     if (Left.is(tok::question))
2058       return false;
2059     if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2060       return false;
2061     if (Right.is(TT_DictLiteral))
2062       return Style.SpacesInContainerLiterals;
2063     return true;
2064   }
2065   if (Left.is(TT_UnaryOperator))
2066     return Right.is(TT_BinaryOperator);
2067
2068   // If the next token is a binary operator or a selector name, we have
2069   // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2070   if (Left.is(TT_CastRParen))
2071     return Style.SpaceAfterCStyleCast ||
2072            Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2073
2074   if (Left.is(tok::greater) && Right.is(tok::greater))
2075     return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2076            (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2077   if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2078       Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2079     return false;
2080   if (!Style.SpaceBeforeAssignmentOperators &&
2081       Right.getPrecedence() == prec::Assignment)
2082     return false;
2083   if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
2084     return (Left.is(TT_TemplateOpener) &&
2085             Style.Standard == FormatStyle::LS_Cpp03) ||
2086            !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
2087              Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
2088   if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2089     return Style.SpacesInAngles;
2090   if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2091       (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2092        !Right.is(tok::r_paren)))
2093     return true;
2094   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2095       Right.isNot(TT_FunctionTypeLParen))
2096     return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2097   if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2098       Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2099     return false;
2100   if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2101       Line.startsWith(tok::hash))
2102     return true;
2103   if (Right.is(TT_TrailingUnaryOperator))
2104     return false;
2105   if (Left.is(TT_RegexLiteral))
2106     return false;
2107   return spaceRequiredBetween(Line, Left, Right);
2108 }
2109
2110 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2111 static bool isAllmanBrace(const FormatToken &Tok) {
2112   return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2113          !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2114 }
2115
2116 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2117                                      const FormatToken &Right) {
2118   const FormatToken &Left = *Right.Previous;
2119   if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2120     return true;
2121
2122   if (Style.Language == FormatStyle::LK_JavaScript) {
2123     // FIXME: This might apply to other languages and token kinds.
2124     if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
2125         Left.Previous->is(tok::char_constant))
2126       return true;
2127     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2128         Left.Previous && Left.Previous->is(tok::equal) &&
2129         Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2130                             tok::kw_const) &&
2131         // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2132         // above.
2133         !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2134       // Object literals on the top level of a file are treated as "enum-style".
2135       // Each key/value pair is put on a separate line, instead of bin-packing.
2136       return true;
2137     if (Left.is(tok::l_brace) && Line.Level == 0 &&
2138         (Line.startsWith(tok::kw_enum) ||
2139          Line.startsWith(tok::kw_export, tok::kw_enum)))
2140       // JavaScript top-level enum key/value pairs are put on separate lines
2141       // instead of bin-packing.
2142       return true;
2143     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2144         !Left.Children.empty())
2145       // Support AllowShortFunctionsOnASingleLine for JavaScript.
2146       return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2147              Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2148              (Left.NestingLevel == 0 && Line.Level == 0 &&
2149               Style.AllowShortFunctionsOnASingleLine ==
2150                   FormatStyle::SFS_Inline);
2151   } else if (Style.Language == FormatStyle::LK_Java) {
2152     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2153         Right.Next->is(tok::string_literal))
2154       return true;
2155   }
2156
2157   // If the last token before a '}' is a comma or a trailing comment, the
2158   // intention is to insert a line break after it in order to make shuffling
2159   // around entries easier.
2160   const FormatToken *BeforeClosingBrace = nullptr;
2161   if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2162       Left.BlockKind != BK_Block && Left.MatchingParen)
2163     BeforeClosingBrace = Left.MatchingParen->Previous;
2164   else if (Right.MatchingParen &&
2165            Right.MatchingParen->isOneOf(tok::l_brace,
2166                                         TT_ArrayInitializerLSquare))
2167     BeforeClosingBrace = &Left;
2168   if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2169                              BeforeClosingBrace->isTrailingComment()))
2170     return true;
2171
2172   if (Right.is(tok::comment))
2173     return Left.BlockKind != BK_BracedInit &&
2174            Left.isNot(TT_CtorInitializerColon) &&
2175            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2176   if (Left.isTrailingComment())
2177     return true;
2178   if (Left.isStringLiteral() &&
2179       (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2180     return true;
2181   if (Right.Previous->IsUnterminatedLiteral)
2182     return true;
2183   if (Right.is(tok::lessless) && Right.Next &&
2184       Right.Previous->is(tok::string_literal) &&
2185       Right.Next->is(tok::string_literal))
2186     return true;
2187   if (Right.Previous->ClosesTemplateDeclaration &&
2188       Right.Previous->MatchingParen &&
2189       Right.Previous->MatchingParen->NestingLevel == 0 &&
2190       Style.AlwaysBreakTemplateDeclarations)
2191     return true;
2192   if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2193       Style.BreakConstructorInitializersBeforeComma &&
2194       !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2195     return true;
2196   if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2197     // Raw string literals are special wrt. line breaks. The author has made a
2198     // deliberate choice and might have aligned the contents of the string
2199     // literal accordingly. Thus, we try keep existing line breaks.
2200     return Right.NewlinesBefore > 0;
2201   if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2202       Style.Language == FormatStyle::LK_Proto)
2203     // Don't put enums onto single lines in protocol buffers.
2204     return true;
2205   if (Right.is(TT_InlineASMBrace))
2206     return Right.HasUnescapedNewline;
2207   if (isAllmanBrace(Left) || isAllmanBrace(Right))
2208     return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2209            (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2210            (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2211   if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2212       Right.is(TT_SelectorName))
2213     return true;
2214   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2215     return true;
2216
2217   if ((Style.Language == FormatStyle::LK_Java ||
2218        Style.Language == FormatStyle::LK_JavaScript) &&
2219       Left.is(TT_LeadingJavaAnnotation) &&
2220       Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2221       (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2222     return true;
2223
2224   return false;
2225 }
2226
2227 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2228                                     const FormatToken &Right) {
2229   const FormatToken &Left = *Right.Previous;
2230
2231   // Language-specific stuff.
2232   if (Style.Language == FormatStyle::LK_Java) {
2233     if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2234                      Keywords.kw_implements))
2235       return false;
2236     if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2237                       Keywords.kw_implements))
2238       return true;
2239   } else if (Style.Language == FormatStyle::LK_JavaScript) {
2240     if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2241       return false;
2242     if (Left.is(TT_JsTypeColon))
2243       return true;
2244     if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2245       return false;
2246   }
2247
2248   if (Left.is(tok::at))
2249     return false;
2250   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2251     return false;
2252   if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2253     return !Right.is(tok::l_paren);
2254   if (Right.is(TT_PointerOrReference))
2255     return Line.IsMultiVariableDeclStmt ||
2256            (Style.PointerAlignment == FormatStyle::PAS_Right &&
2257             (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2258   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2259       Right.is(tok::kw_operator))
2260     return true;
2261   if (Left.is(TT_PointerOrReference))
2262     return false;
2263   if (Right.isTrailingComment())
2264     // We rely on MustBreakBefore being set correctly here as we should not
2265     // change the "binding" behavior of a comment.
2266     // The first comment in a braced lists is always interpreted as belonging to
2267     // the first list element. Otherwise, it should be placed outside of the
2268     // list.
2269     return Left.BlockKind == BK_BracedInit;
2270   if (Left.is(tok::question) && Right.is(tok::colon))
2271     return false;
2272   if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2273     return Style.BreakBeforeTernaryOperators;
2274   if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2275     return !Style.BreakBeforeTernaryOperators;
2276   if (Right.is(TT_InheritanceColon))
2277     return true;
2278   if (Right.is(tok::colon) &&
2279       !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2280     return false;
2281   if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2282     return true;
2283   if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2284                                     Right.Next->is(TT_ObjCMethodExpr)))
2285     return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2286   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2287     return true;
2288   if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2289     return true;
2290   if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2291                     TT_OverloadedOperator))
2292     return false;
2293   if (Left.is(TT_RangeBasedForLoopColon))
2294     return true;
2295   if (Right.is(TT_RangeBasedForLoopColon))
2296     return false;
2297   if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2298       Left.is(tok::kw_operator))
2299     return false;
2300   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2301       Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2302     return false;
2303   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2304     return false;
2305   if (Left.is(tok::l_paren) && Left.Previous &&
2306       (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2307     return false;
2308   if (Right.is(TT_ImplicitStringLiteral))
2309     return false;
2310
2311   if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2312     return false;
2313   if (Right.is(tok::r_square) && Right.MatchingParen &&
2314       Right.MatchingParen->is(TT_LambdaLSquare))
2315     return false;
2316
2317   // We only break before r_brace if there was a corresponding break before
2318   // the l_brace, which is tracked by BreakBeforeClosingBrace.
2319   if (Right.is(tok::r_brace))
2320     return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2321
2322   // Allow breaking after a trailing annotation, e.g. after a method
2323   // declaration.
2324   if (Left.is(TT_TrailingAnnotation))
2325     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2326                           tok::less, tok::coloncolon);
2327
2328   if (Right.is(tok::kw___attribute))
2329     return true;
2330
2331   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2332     return true;
2333
2334   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2335     return true;
2336
2337   if (Left.is(TT_CtorInitializerComma) &&
2338       Style.BreakConstructorInitializersBeforeComma)
2339     return false;
2340   if (Right.is(TT_CtorInitializerComma) &&
2341       Style.BreakConstructorInitializersBeforeComma)
2342     return true;
2343   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2344       (Left.is(tok::less) && Right.is(tok::less)))
2345     return false;
2346   if (Right.is(TT_BinaryOperator) &&
2347       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2348       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2349        Right.getPrecedence() != prec::Assignment))
2350     return true;
2351   if (Left.is(TT_ArrayInitializerLSquare))
2352     return true;
2353   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2354     return true;
2355   if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2356       !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2357       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2358       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2359        Left.getPrecedence() == prec::Assignment))
2360     return true;
2361   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2362                       tok::kw_class, tok::kw_struct) ||
2363          Right.isMemberAccess() ||
2364          Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2365                        tok::colon, tok::l_square, tok::at) ||
2366          (Left.is(tok::r_paren) &&
2367           Right.isOneOf(tok::identifier, tok::kw_const)) ||
2368          (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2369 }
2370
2371 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2372   llvm::errs() << "AnnotatedTokens:\n";
2373   const FormatToken *Tok = Line.First;
2374   while (Tok) {
2375     llvm::errs() << " M=" << Tok->MustBreakBefore
2376                  << " C=" << Tok->CanBreakBefore
2377                  << " T=" << getTokenTypeName(Tok->Type)
2378                  << " S=" << Tok->SpacesRequiredBefore
2379                  << " B=" << Tok->BlockParameterCount
2380                  << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2381                  << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2382                  << " FakeLParens=";
2383     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2384       llvm::errs() << Tok->FakeLParens[i] << "/";
2385     llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2386     if (!Tok->Next)
2387       assert(Tok == Line.Last);
2388     Tok = Tok->Next;
2389   }
2390   llvm::errs() << "----\n";
2391 }
2392
2393 } // namespace format
2394 } // namespace clang