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