clang  6.0.0svn
TokenAnnotator.cpp
Go to the documentation of this file.
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"
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 || !CurrentToken->Previous)
46  return false;
47  if (NonTemplateLess.count(CurrentToken->Previous))
48  return false;
49 
50  const FormatToken &Previous = *CurrentToken->Previous; // The '<'.
51  if (Previous.Previous) {
52  if (Previous.Previous->Tok.isLiteral())
53  return false;
54  if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
55  (!Previous.Previous->MatchingParen ||
56  !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
57  return false;
58  }
59 
60  FormatToken *Left = CurrentToken->Previous;
61  Left->ParentBracket = Contexts.back().ContextKind;
62  ScopedContextCreator ContextCreator(*this, tok::less, 12);
63 
64  // If this angle is in the context of an expression, we need to be more
65  // hesitant to detect it as opening template parameters.
66  bool InExprContext = Contexts.back().IsExpression;
67 
68  Contexts.back().IsExpression = false;
69  // If there's a template keyword before the opening angle bracket, this is a
70  // template parameter, not an argument.
71  Contexts.back().InTemplateArgument =
72  Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
73 
74  if (Style.Language == FormatStyle::LK_Java &&
75  CurrentToken->is(tok::question))
76  next();
77 
78  while (CurrentToken) {
79  if (CurrentToken->is(tok::greater)) {
80  Left->MatchingParen = CurrentToken;
81  CurrentToken->MatchingParen = Left;
82  CurrentToken->Type = TT_TemplateCloser;
83  next();
84  return true;
85  }
86  if (CurrentToken->is(tok::question) &&
87  Style.Language == FormatStyle::LK_Java) {
88  next();
89  continue;
90  }
91  if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
92  (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
93  Style.Language != FormatStyle::LK_Proto &&
94  Style.Language != FormatStyle::LK_TextProto))
95  return false;
96  // If a && or || is found and interpreted as a binary operator, this set
97  // of angles is likely part of something like "a < b && c > d". If the
98  // angles are inside an expression, the ||/&& might also be a binary
99  // operator that was misinterpreted because we are parsing template
100  // parameters.
101  // FIXME: This is getting out of hand, write a decent parser.
102  if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
103  CurrentToken->Previous->is(TT_BinaryOperator) &&
104  Contexts[Contexts.size() - 2].IsExpression &&
105  !Line.startsWith(tok::kw_template))
106  return false;
107  updateParameterCount(Left, CurrentToken);
108  if (Style.Language == FormatStyle::LK_Proto) {
109  if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
110  if (CurrentToken->is(tok::colon) ||
111  (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
112  Previous->isNot(tok::colon)))
113  Previous->Type = TT_SelectorName;
114  }
115  }
116  if (!consumeToken())
117  return false;
118  }
119  return false;
120  }
121 
122  bool parseParens(bool LookForDecls = false) {
123  if (!CurrentToken)
124  return false;
125  FormatToken *Left = CurrentToken->Previous;
126  Left->ParentBracket = Contexts.back().ContextKind;
127  ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
128 
129  // FIXME: This is a bit of a hack. Do better.
130  Contexts.back().ColonIsForRangeExpr =
131  Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
132 
133  bool StartsObjCMethodExpr = false;
134  if (CurrentToken->is(tok::caret)) {
135  // (^ can start a block type.
136  Left->Type = TT_ObjCBlockLParen;
137  } else if (FormatToken *MaybeSel = Left->Previous) {
138  // @selector( starts a selector.
139  if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
140  MaybeSel->Previous->is(tok::at)) {
141  StartsObjCMethodExpr = true;
142  }
143  }
144 
145  if (Left->is(TT_OverloadedOperatorLParen)) {
146  Contexts.back().IsExpression = false;
147  } else if (Style.Language == FormatStyle::LK_JavaScript &&
148  (Line.startsWith(Keywords.kw_type, tok::identifier) ||
149  Line.startsWith(tok::kw_export, Keywords.kw_type,
150  tok::identifier))) {
151  // type X = (...);
152  // export type X = (...);
153  Contexts.back().IsExpression = false;
154  } else if (Left->Previous &&
155  (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
156  tok::kw_if, tok::kw_while, tok::l_paren,
157  tok::comma) ||
158  Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
159  Left->Previous->is(TT_BinaryOperator))) {
160  // static_assert, if and while usually contain expressions.
161  Contexts.back().IsExpression = true;
162  } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
163  (Left->Previous->is(Keywords.kw_function) ||
164  (Left->Previous->endsSequence(tok::identifier,
165  Keywords.kw_function)))) {
166  // function(...) or function f(...)
167  Contexts.back().IsExpression = false;
168  } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
169  Left->Previous->is(TT_JsTypeColon)) {
170  // let x: (SomeType);
171  Contexts.back().IsExpression = false;
172  } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
173  Left->Previous->MatchingParen &&
174  Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
175  // This is a parameter list of a lambda expression.
176  Contexts.back().IsExpression = false;
177  } else if (Line.InPPDirective &&
178  (!Left->Previous || !Left->Previous->is(tok::identifier))) {
179  Contexts.back().IsExpression = true;
180  } else if (Contexts[Contexts.size() - 2].CaretFound) {
181  // This is the parameter list of an ObjC block.
182  Contexts.back().IsExpression = false;
183  } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
184  Left->Type = TT_AttributeParen;
185  } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
186  // The first argument to a foreach macro is a declaration.
187  Contexts.back().IsForEachMacro = true;
188  Contexts.back().IsExpression = false;
189  } else if (Left->Previous && Left->Previous->MatchingParen &&
190  Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
191  Contexts.back().IsExpression = false;
192  } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
193  bool IsForOrCatch =
194  Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
195  Contexts.back().IsExpression = !IsForOrCatch;
196  }
197 
198  if (StartsObjCMethodExpr) {
199  Contexts.back().ColonIsObjCMethodExpr = true;
200  Left->Type = TT_ObjCMethodExpr;
201  }
202 
203  bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
204  bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
205  bool HasMultipleLines = false;
206  bool HasMultipleParametersOnALine = false;
207  bool MightBeObjCForRangeLoop =
208  Left->Previous && Left->Previous->is(tok::kw_for);
209  while (CurrentToken) {
210  // LookForDecls is set when "if (" has been seen. Check for
211  // 'identifier' '*' 'identifier' followed by not '=' -- this
212  // '*' has to be a binary operator but determineStarAmpUsage() will
213  // categorize it as an unary operator, so set the right type here.
214  if (LookForDecls && CurrentToken->Next) {
215  FormatToken *Prev = CurrentToken->getPreviousNonComment();
216  if (Prev) {
217  FormatToken *PrevPrev = Prev->getPreviousNonComment();
218  FormatToken *Next = CurrentToken->Next;
219  if (PrevPrev && PrevPrev->is(tok::identifier) &&
220  Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
221  CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
222  Prev->Type = TT_BinaryOperator;
223  LookForDecls = false;
224  }
225  }
226  }
227 
228  if (CurrentToken->Previous->is(TT_PointerOrReference) &&
229  CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
230  tok::coloncolon))
231  ProbablyFunctionType = true;
232  if (CurrentToken->is(tok::comma))
233  MightBeFunctionType = false;
234  if (CurrentToken->Previous->is(TT_BinaryOperator))
235  Contexts.back().IsExpression = true;
236  if (CurrentToken->is(tok::r_paren)) {
237  if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
238  (CurrentToken->Next->is(tok::l_paren) ||
239  (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
240  Left->Type = TT_FunctionTypeLParen;
241  Left->MatchingParen = CurrentToken;
242  CurrentToken->MatchingParen = Left;
243 
244  if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
245  Left->Previous && Left->Previous->is(tok::l_paren)) {
246  // Detect the case where macros are used to generate lambdas or
247  // function bodies, e.g.:
248  // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
249  for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
250  if (Tok->is(TT_BinaryOperator) &&
251  Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
252  Tok->Type = TT_PointerOrReference;
253  }
254  }
255 
256  if (StartsObjCMethodExpr) {
257  CurrentToken->Type = TT_ObjCMethodExpr;
258  if (Contexts.back().FirstObjCSelectorName) {
259  Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
260  Contexts.back().LongestObjCSelectorName;
261  }
262  }
263 
264  if (Left->is(TT_AttributeParen))
265  CurrentToken->Type = TT_AttributeParen;
266  if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
267  CurrentToken->Type = TT_JavaAnnotation;
268  if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
269  CurrentToken->Type = TT_LeadingJavaAnnotation;
270 
271  if (!HasMultipleLines)
272  Left->PackingKind = PPK_Inconclusive;
273  else if (HasMultipleParametersOnALine)
274  Left->PackingKind = PPK_BinPacked;
275  else
276  Left->PackingKind = PPK_OnePerLine;
277 
278  next();
279  return true;
280  }
281  if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
282  return false;
283 
284  if (CurrentToken->is(tok::l_brace))
285  Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
286  if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
287  !CurrentToken->Next->HasUnescapedNewline &&
288  !CurrentToken->Next->isTrailingComment())
289  HasMultipleParametersOnALine = true;
290  if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
291  CurrentToken->Previous->isSimpleTypeSpecifier()) &&
292  !CurrentToken->is(tok::l_brace))
293  Contexts.back().IsExpression = false;
294  if (CurrentToken->isOneOf(tok::semi, tok::colon))
295  MightBeObjCForRangeLoop = false;
296  if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
297  CurrentToken->Type = TT_ObjCForIn;
298  // When we discover a 'new', we set CanBeExpression to 'false' in order to
299  // parse the type correctly. Reset that after a comma.
300  if (CurrentToken->is(tok::comma))
301  Contexts.back().CanBeExpression = true;
302 
303  FormatToken *Tok = CurrentToken;
304  if (!consumeToken())
305  return false;
306  updateParameterCount(Left, Tok);
307  if (CurrentToken && CurrentToken->HasUnescapedNewline)
308  HasMultipleLines = true;
309  }
310  return false;
311  }
312 
313  bool parseSquare() {
314  if (!CurrentToken)
315  return false;
316 
317  // A '[' could be an index subscript (after an identifier or after
318  // ')' or ']'), it could be the start of an Objective-C method
319  // expression, or it could the start of an Objective-C array literal.
320  FormatToken *Left = CurrentToken->Previous;
321  Left->ParentBracket = Contexts.back().ContextKind;
322  FormatToken *Parent = Left->getPreviousNonComment();
323 
324  // Cases where '>' is followed by '['.
325  // In C++, this can happen either in array of templates (foo<int>[10])
326  // or when array is a nested template type (unique_ptr<type1<type2>[]>).
327  bool CppArrayTemplates =
328  Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
329  (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
330  Contexts.back().InTemplateArgument);
331 
332  bool StartsObjCMethodExpr =
333  !CppArrayTemplates && Style.isCpp() &&
334  Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
335  CurrentToken->isNot(tok::l_brace) &&
336  (!Parent ||
337  Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
338  tok::kw_return, tok::kw_throw) ||
339  Parent->isUnaryOperator() ||
340  Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
341  getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
342  bool ColonFound = false;
343 
344  unsigned BindingIncrease = 1;
345  if (Left->isCppStructuredBinding(Style)) {
346  Left->Type = TT_StructuredBindingLSquare;
347  } else if (Left->is(TT_Unknown)) {
348  if (StartsObjCMethodExpr) {
349  Left->Type = TT_ObjCMethodExpr;
350  } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
351  Contexts.back().ContextKind == tok::l_brace &&
352  Parent->isOneOf(tok::l_brace, tok::comma)) {
353  Left->Type = TT_JsComputedPropertyName;
354  } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
355  Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
356  Left->Type = TT_DesignatedInitializerLSquare;
357  } else if (CurrentToken->is(tok::r_square) && Parent &&
358  Parent->is(TT_TemplateCloser)) {
359  Left->Type = TT_ArraySubscriptLSquare;
360  } else if (Style.Language == FormatStyle::LK_Proto ||
361  (!CppArrayTemplates && Parent &&
362  Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
363  tok::comma, tok::l_paren, tok::l_square,
364  tok::question, tok::colon, tok::kw_return,
365  // Should only be relevant to JavaScript:
366  tok::kw_default))) {
367  Left->Type = TT_ArrayInitializerLSquare;
368  } else {
369  BindingIncrease = 10;
370  Left->Type = TT_ArraySubscriptLSquare;
371  }
372  }
373 
374  ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
375  Contexts.back().IsExpression = true;
376  if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
377  Parent->is(TT_JsTypeColon))
378  Contexts.back().IsExpression = false;
379 
380  Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
381 
382  while (CurrentToken) {
383  if (CurrentToken->is(tok::r_square)) {
384  if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
385  Left->is(TT_ObjCMethodExpr)) {
386  // An ObjC method call is rarely followed by an open parenthesis.
387  // FIXME: Do we incorrectly label ":" with this?
388  StartsObjCMethodExpr = false;
389  Left->Type = TT_Unknown;
390  }
391  if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
392  CurrentToken->Type = TT_ObjCMethodExpr;
393  // determineStarAmpUsage() thinks that '*' '[' is allocating an
394  // array of pointers, but if '[' starts a selector then '*' is a
395  // binary operator.
396  if (Parent && Parent->is(TT_PointerOrReference))
397  Parent->Type = TT_BinaryOperator;
398  }
399  Left->MatchingParen = CurrentToken;
400  CurrentToken->MatchingParen = Left;
401  if (Contexts.back().FirstObjCSelectorName) {
402  Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
403  Contexts.back().LongestObjCSelectorName;
404  if (Left->BlockParameterCount > 1)
405  Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
406  }
407  next();
408  return true;
409  }
410  if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
411  return false;
412  if (CurrentToken->is(tok::colon)) {
413  if (Left->isOneOf(TT_ArraySubscriptLSquare,
414  TT_DesignatedInitializerLSquare)) {
415  Left->Type = TT_ObjCMethodExpr;
416  StartsObjCMethodExpr = true;
417  Contexts.back().ColonIsObjCMethodExpr = true;
418  if (Parent && Parent->is(tok::r_paren))
419  Parent->Type = TT_CastRParen;
420  }
421  ColonFound = true;
422  }
423  if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
424  !ColonFound)
425  Left->Type = TT_ArrayInitializerLSquare;
426  FormatToken *Tok = CurrentToken;
427  if (!consumeToken())
428  return false;
429  updateParameterCount(Left, Tok);
430  }
431  return false;
432  }
433 
434  bool parseBrace() {
435  if (CurrentToken) {
436  FormatToken *Left = CurrentToken->Previous;
437  Left->ParentBracket = Contexts.back().ContextKind;
438 
439  if (Contexts.back().CaretFound)
440  Left->Type = TT_ObjCBlockLBrace;
441  Contexts.back().CaretFound = false;
442 
443  ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
444  Contexts.back().ColonIsDictLiteral = true;
445  if (Left->BlockKind == BK_BracedInit)
446  Contexts.back().IsExpression = true;
447  if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
448  Left->Previous->is(TT_JsTypeColon))
449  Contexts.back().IsExpression = false;
450 
451  while (CurrentToken) {
452  if (CurrentToken->is(tok::r_brace)) {
453  Left->MatchingParen = CurrentToken;
454  CurrentToken->MatchingParen = Left;
455  next();
456  return true;
457  }
458  if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
459  return false;
460  updateParameterCount(Left, CurrentToken);
461  if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
462  FormatToken *Previous = CurrentToken->getPreviousNonComment();
463  if (Previous->is(TT_JsTypeOptionalQuestion))
464  Previous = Previous->getPreviousNonComment();
465  if (((CurrentToken->is(tok::colon) &&
466  (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
467  Style.Language == FormatStyle::LK_Proto ||
468  Style.Language == FormatStyle::LK_TextProto) &&
469  (Previous->Tok.getIdentifierInfo() ||
470  Previous->is(tok::string_literal)))
471  Previous->Type = TT_SelectorName;
472  if (CurrentToken->is(tok::colon) ||
473  Style.Language == FormatStyle::LK_JavaScript)
474  Left->Type = TT_DictLiteral;
475  }
476  if (CurrentToken->is(tok::comma) &&
477  Style.Language == FormatStyle::LK_JavaScript)
478  Left->Type = TT_DictLiteral;
479  if (!consumeToken())
480  return false;
481  }
482  }
483  return true;
484  }
485 
486  void updateParameterCount(FormatToken *Left, FormatToken *Current) {
487  if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
488  ++Left->BlockParameterCount;
489  if (Current->is(tok::comma)) {
490  ++Left->ParameterCount;
491  if (!Left->Role)
492  Left->Role.reset(new CommaSeparatedList(Style));
493  Left->Role->CommaFound(Current);
494  } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
495  Left->ParameterCount = 1;
496  }
497  }
498 
499  bool parseConditional() {
500  while (CurrentToken) {
501  if (CurrentToken->is(tok::colon)) {
502  CurrentToken->Type = TT_ConditionalExpr;
503  next();
504  return true;
505  }
506  if (!consumeToken())
507  return false;
508  }
509  return false;
510  }
511 
512  bool parseTemplateDeclaration() {
513  if (CurrentToken && CurrentToken->is(tok::less)) {
514  CurrentToken->Type = TT_TemplateOpener;
515  next();
516  if (!parseAngle())
517  return false;
518  if (CurrentToken)
519  CurrentToken->Previous->ClosesTemplateDeclaration = true;
520  return true;
521  }
522  return false;
523  }
524 
525  bool consumeToken() {
526  FormatToken *Tok = CurrentToken;
527  next();
528  switch (Tok->Tok.getKind()) {
529  case tok::plus:
530  case tok::minus:
531  if (!Tok->Previous && Line.MustBeDeclaration)
532  Tok->Type = TT_ObjCMethodSpecifier;
533  break;
534  case tok::colon:
535  if (!Tok->Previous)
536  return false;
537  // Colons from ?: are handled in parseConditional().
538  if (Style.Language == FormatStyle::LK_JavaScript) {
539  if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
540  (Contexts.size() == 1 && // switch/case labels
541  !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
542  Contexts.back().ContextKind == tok::l_paren || // function params
543  Contexts.back().ContextKind == tok::l_square || // array type
544  (!Contexts.back().IsExpression &&
545  Contexts.back().ContextKind == tok::l_brace) || // object type
546  (Contexts.size() == 1 &&
547  Line.MustBeDeclaration)) { // method/property declaration
548  Contexts.back().IsExpression = false;
549  Tok->Type = TT_JsTypeColon;
550  break;
551  }
552  }
553  if (Contexts.back().ColonIsDictLiteral ||
554  Style.Language == FormatStyle::LK_Proto ||
555  Style.Language == FormatStyle::LK_TextProto) {
556  Tok->Type = TT_DictLiteral;
557  if (Style.Language == FormatStyle::LK_TextProto) {
558  if (FormatToken *Previous = Tok->getPreviousNonComment())
559  Previous->Type = TT_SelectorName;
560  }
561  } else if (Contexts.back().ColonIsObjCMethodExpr ||
562  Line.startsWith(TT_ObjCMethodSpecifier)) {
563  Tok->Type = TT_ObjCMethodExpr;
564  const FormatToken *BeforePrevious = Tok->Previous->Previous;
565  if (!BeforePrevious ||
566  !(BeforePrevious->is(TT_CastRParen) ||
567  (BeforePrevious->is(TT_ObjCMethodExpr) &&
568  BeforePrevious->is(tok::colon))) ||
569  BeforePrevious->is(tok::r_square) ||
570  Contexts.back().LongestObjCSelectorName == 0) {
571  Tok->Previous->Type = TT_SelectorName;
572  if (Tok->Previous->ColumnWidth >
573  Contexts.back().LongestObjCSelectorName)
574  Contexts.back().LongestObjCSelectorName =
575  Tok->Previous->ColumnWidth;
576  if (!Contexts.back().FirstObjCSelectorName)
577  Contexts.back().FirstObjCSelectorName = Tok->Previous;
578  }
579  } else if (Contexts.back().ColonIsForRangeExpr) {
580  Tok->Type = TT_RangeBasedForLoopColon;
581  } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
582  Tok->Type = TT_BitFieldColon;
583  } else if (Contexts.size() == 1 &&
584  !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
585  if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
586  tok::kw_noexcept))
587  Tok->Type = TT_CtorInitializerColon;
588  else
589  Tok->Type = TT_InheritanceColon;
590  } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
591  Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
592  // This handles a special macro in ObjC code where selectors including
593  // the colon are passed as macro arguments.
594  Tok->Type = TT_ObjCMethodExpr;
595  } else if (Contexts.back().ContextKind == tok::l_paren) {
596  Tok->Type = TT_InlineASMColon;
597  }
598  break;
599  case tok::pipe:
600  case tok::amp:
601  // | and & in declarations/type expressions represent union and
602  // intersection types, respectively.
603  if (Style.Language == FormatStyle::LK_JavaScript &&
604  !Contexts.back().IsExpression)
605  Tok->Type = TT_JsTypeOperator;
606  break;
607  case tok::kw_if:
608  case tok::kw_while:
609  if (Tok->is(tok::kw_if) && CurrentToken &&
610  CurrentToken->is(tok::kw_constexpr))
611  next();
612  if (CurrentToken && CurrentToken->is(tok::l_paren)) {
613  next();
614  if (!parseParens(/*LookForDecls=*/true))
615  return false;
616  }
617  break;
618  case tok::kw_for:
619  if (Style.Language == FormatStyle::LK_JavaScript) {
620  if (Tok->Previous && Tok->Previous->is(tok::period))
621  break;
622  // JS' for await ( ...
623  if (CurrentToken && CurrentToken->is(Keywords.kw_await))
624  next();
625  }
626  Contexts.back().ColonIsForRangeExpr = true;
627  next();
628  if (!parseParens())
629  return false;
630  break;
631  case tok::l_paren:
632  // When faced with 'operator()()', the kw_operator handler incorrectly
633  // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
634  // the first two parens OverloadedOperators and the second l_paren an
635  // OverloadedOperatorLParen.
636  if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
637  Tok->Previous->MatchingParen &&
638  Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
639  Tok->Previous->Type = TT_OverloadedOperator;
640  Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
641  Tok->Type = TT_OverloadedOperatorLParen;
642  }
643 
644  if (!parseParens())
645  return false;
646  if (Line.MustBeDeclaration && Contexts.size() == 1 &&
647  !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
648  (!Tok->Previous ||
649  !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
650  TT_LeadingJavaAnnotation)))
651  Line.MightBeFunctionDecl = true;
652  break;
653  case tok::l_square:
654  if (!parseSquare())
655  return false;
656  break;
657  case tok::l_brace:
658  if (Style.Language == FormatStyle::LK_TextProto) {
659  FormatToken *Previous = Tok->getPreviousNonComment();
660  if (Previous && Previous->Type != TT_DictLiteral)
661  Previous->Type = TT_SelectorName;
662  }
663  if (!parseBrace())
664  return false;
665  break;
666  case tok::less:
667  if (parseAngle()) {
668  Tok->Type = TT_TemplateOpener;
669  if (Style.Language == FormatStyle::LK_TextProto) {
670  FormatToken *Previous = Tok->getPreviousNonComment();
671  if (Previous && Previous->Type != TT_DictLiteral)
672  Previous->Type = TT_SelectorName;
673  }
674  } else {
675  Tok->Type = TT_BinaryOperator;
676  NonTemplateLess.insert(Tok);
677  CurrentToken = Tok;
678  next();
679  }
680  break;
681  case tok::r_paren:
682  case tok::r_square:
683  return false;
684  case tok::r_brace:
685  // Lines can start with '}'.
686  if (Tok->Previous)
687  return false;
688  break;
689  case tok::greater:
690  Tok->Type = TT_BinaryOperator;
691  break;
692  case tok::kw_operator:
693  while (CurrentToken &&
694  !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
695  if (CurrentToken->isOneOf(tok::star, tok::amp))
696  CurrentToken->Type = TT_PointerOrReference;
697  consumeToken();
698  if (CurrentToken &&
699  CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma))
700  CurrentToken->Previous->Type = TT_OverloadedOperator;
701  }
702  if (CurrentToken) {
703  CurrentToken->Type = TT_OverloadedOperatorLParen;
704  if (CurrentToken->Previous->is(TT_BinaryOperator))
705  CurrentToken->Previous->Type = TT_OverloadedOperator;
706  }
707  break;
708  case tok::question:
709  if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
710  Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
711  tok::r_brace)) {
712  // Question marks before semicolons, colons, etc. indicate optional
713  // types (fields, parameters), e.g.
714  // function(x?: string, y?) {...}
715  // class X { y?; }
716  Tok->Type = TT_JsTypeOptionalQuestion;
717  break;
718  }
719  // Declarations cannot be conditional expressions, this can only be part
720  // of a type declaration.
721  if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
722  Style.Language == FormatStyle::LK_JavaScript)
723  break;
724  parseConditional();
725  break;
726  case tok::kw_template:
727  parseTemplateDeclaration();
728  break;
729  case tok::comma:
730  if (Contexts.back().InCtorInitializer)
731  Tok->Type = TT_CtorInitializerComma;
732  else if (Contexts.back().InInheritanceList)
733  Tok->Type = TT_InheritanceComma;
734  else if (Contexts.back().FirstStartOfName &&
735  (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
736  Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
737  Line.IsMultiVariableDeclStmt = true;
738  }
739  if (Contexts.back().IsForEachMacro)
740  Contexts.back().IsExpression = true;
741  break;
742  case tok::identifier:
743  if (Tok->isOneOf(Keywords.kw___has_include,
744  Keywords.kw___has_include_next)) {
745  parseHasInclude();
746  }
747  break;
748  default:
749  break;
750  }
751  return true;
752  }
753 
754  void parseIncludeDirective() {
755  if (CurrentToken && CurrentToken->is(tok::less)) {
756  next();
757  while (CurrentToken) {
758  // Mark tokens up to the trailing line comments as implicit string
759  // literals.
760  if (CurrentToken->isNot(tok::comment) &&
761  !CurrentToken->TokenText.startswith("//"))
762  CurrentToken->Type = TT_ImplicitStringLiteral;
763  next();
764  }
765  }
766  }
767 
768  void parseWarningOrError() {
769  next();
770  // We still want to format the whitespace left of the first token of the
771  // warning or error.
772  next();
773  while (CurrentToken) {
774  CurrentToken->Type = TT_ImplicitStringLiteral;
775  next();
776  }
777  }
778 
779  void parsePragma() {
780  next(); // Consume "pragma".
781  if (CurrentToken &&
782  CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
783  bool IsMark = CurrentToken->is(Keywords.kw_mark);
784  next(); // Consume "mark".
785  next(); // Consume first token (so we fix leading whitespace).
786  while (CurrentToken) {
787  if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
788  CurrentToken->Type = TT_ImplicitStringLiteral;
789  next();
790  }
791  }
792  }
793 
794  void parseHasInclude() {
795  if (!CurrentToken || !CurrentToken->is(tok::l_paren))
796  return;
797  next(); // '('
798  parseIncludeDirective();
799  next(); // ')'
800  }
801 
802  LineType parsePreprocessorDirective() {
803  bool IsFirstToken = CurrentToken->IsFirst;
805  next();
806  if (!CurrentToken)
807  return Type;
808 
809  if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
810  // JavaScript files can contain shebang lines of the form:
811  // #!/usr/bin/env node
812  // Treat these like C++ #include directives.
813  while (CurrentToken) {
814  // Tokens cannot be comments here.
815  CurrentToken->Type = TT_ImplicitStringLiteral;
816  next();
817  }
818  return LT_ImportStatement;
819  }
820 
821  if (CurrentToken->Tok.is(tok::numeric_constant)) {
822  CurrentToken->SpacesRequiredBefore = 1;
823  return Type;
824  }
825  // Hashes in the middle of a line can lead to any strange token
826  // sequence.
827  if (!CurrentToken->Tok.getIdentifierInfo())
828  return Type;
829  switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
830  case tok::pp_include:
831  case tok::pp_include_next:
832  case tok::pp_import:
833  next();
834  parseIncludeDirective();
835  Type = LT_ImportStatement;
836  break;
837  case tok::pp_error:
838  case tok::pp_warning:
839  parseWarningOrError();
840  break;
841  case tok::pp_pragma:
842  parsePragma();
843  break;
844  case tok::pp_if:
845  case tok::pp_elif:
846  Contexts.back().IsExpression = true;
847  parseLine();
848  break;
849  default:
850  break;
851  }
852  while (CurrentToken) {
853  FormatToken *Tok = CurrentToken;
854  next();
855  if (Tok->is(tok::l_paren))
856  parseParens();
857  else if (Tok->isOneOf(Keywords.kw___has_include,
858  Keywords.kw___has_include_next))
859  parseHasInclude();
860  }
861  return Type;
862  }
863 
864 public:
865  LineType parseLine() {
866  NonTemplateLess.clear();
867  if (CurrentToken->is(tok::hash))
868  return parsePreprocessorDirective();
869 
870  // Directly allow to 'import <string-literal>' to support protocol buffer
871  // definitions (code.google.com/p/protobuf) or missing "#" (either way we
872  // should not break the line).
873  IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
874  if ((Style.Language == FormatStyle::LK_Java &&
875  CurrentToken->is(Keywords.kw_package)) ||
876  (Info && Info->getPPKeywordID() == tok::pp_import &&
877  CurrentToken->Next &&
878  CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
879  tok::kw_static))) {
880  next();
881  parseIncludeDirective();
882  return LT_ImportStatement;
883  }
884 
885  // If this line starts and ends in '<' and '>', respectively, it is likely
886  // part of "#define <a/b.h>".
887  if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
888  parseIncludeDirective();
889  return LT_ImportStatement;
890  }
891 
892  // In .proto files, top-level options are very similar to import statements
893  // and should not be line-wrapped.
894  if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
895  CurrentToken->is(Keywords.kw_option)) {
896  next();
897  if (CurrentToken && CurrentToken->is(tok::identifier))
898  return LT_ImportStatement;
899  }
900 
901  bool KeywordVirtualFound = false;
902  bool ImportStatement = false;
903 
904  // import {...} from '...';
905  if (Style.Language == FormatStyle::LK_JavaScript &&
906  CurrentToken->is(Keywords.kw_import))
907  ImportStatement = true;
908 
909  while (CurrentToken) {
910  if (CurrentToken->is(tok::kw_virtual))
911  KeywordVirtualFound = true;
912  if (Style.Language == FormatStyle::LK_JavaScript) {
913  // export {...} from '...';
914  // An export followed by "from 'some string';" is a re-export from
915  // another module identified by a URI and is treated as a
916  // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
917  // Just "export {...};" or "export class ..." should not be treated as
918  // an import in this sense.
919  if (Line.First->is(tok::kw_export) &&
920  CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
921  CurrentToken->Next->isStringLiteral())
922  ImportStatement = true;
923  if (isClosureImportStatement(*CurrentToken))
924  ImportStatement = true;
925  }
926  if (!consumeToken())
927  return LT_Invalid;
928  }
929  if (KeywordVirtualFound)
930  return LT_VirtualFunctionDecl;
931  if (ImportStatement)
932  return LT_ImportStatement;
933 
934  if (Line.startsWith(TT_ObjCMethodSpecifier)) {
935  if (Contexts.back().FirstObjCSelectorName)
936  Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
937  Contexts.back().LongestObjCSelectorName;
938  return LT_ObjCMethodDecl;
939  }
940 
941  return LT_Other;
942  }
943 
944 private:
945  bool isClosureImportStatement(const FormatToken &Tok) {
946  // FIXME: Closure-library specific stuff should not be hard-coded but be
947  // configurable.
948  return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
949  Tok.Next->Next &&
950  (Tok.Next->Next->TokenText == "module" ||
951  Tok.Next->Next->TokenText == "provide" ||
952  Tok.Next->Next->TokenText == "require" ||
953  Tok.Next->Next->TokenText == "forwardDeclare") &&
954  Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
955  }
956 
957  void resetTokenMetadata(FormatToken *Token) {
958  if (!Token)
959  return;
960 
961  // Reset token type in case we have already looked at it and then
962  // recovered from an error (e.g. failure to find the matching >).
963  if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
964  TT_FunctionLBrace, TT_ImplicitStringLiteral,
965  TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
966  TT_OverloadedOperator, TT_RegexLiteral,
967  TT_TemplateString, TT_ObjCStringLiteral))
968  CurrentToken->Type = TT_Unknown;
969  CurrentToken->Role.reset();
970  CurrentToken->MatchingParen = nullptr;
971  CurrentToken->FakeLParens.clear();
972  CurrentToken->FakeRParens = 0;
973  }
974 
975  void next() {
976  if (CurrentToken) {
977  CurrentToken->NestingLevel = Contexts.size() - 1;
978  CurrentToken->BindingStrength = Contexts.back().BindingStrength;
979  modifyContext(*CurrentToken);
980  determineTokenType(*CurrentToken);
981  CurrentToken = CurrentToken->Next;
982  }
983 
984  resetTokenMetadata(CurrentToken);
985  }
986 
987  /// \brief A struct to hold information valid in a specific context, e.g.
988  /// a pair of parenthesis.
989  struct Context {
990  Context(tok::TokenKind ContextKind, unsigned BindingStrength,
991  bool IsExpression)
992  : ContextKind(ContextKind), BindingStrength(BindingStrength),
993  IsExpression(IsExpression) {}
994 
996  unsigned BindingStrength;
999  bool ColonIsForRangeExpr = false;
1000  bool ColonIsDictLiteral = false;
1002  FormatToken *FirstObjCSelectorName = nullptr;
1003  FormatToken *FirstStartOfName = nullptr;
1004  bool CanBeExpression = true;
1005  bool InTemplateArgument = false;
1006  bool InCtorInitializer = false;
1007  bool InInheritanceList = false;
1008  bool CaretFound = false;
1009  bool IsForEachMacro = false;
1010  };
1011 
1012  /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
1013  /// of each instance.
1014  struct ScopedContextCreator {
1015  AnnotatingParser &P;
1016 
1017  ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
1018  unsigned Increase)
1019  : P(P) {
1020  P.Contexts.push_back(Context(ContextKind,
1021  P.Contexts.back().BindingStrength + Increase,
1022  P.Contexts.back().IsExpression));
1023  }
1024 
1025  ~ScopedContextCreator() { P.Contexts.pop_back(); }
1026  };
1027 
1028  void modifyContext(const FormatToken &Current) {
1029  if (Current.getPrecedence() == prec::Assignment &&
1030  !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
1031  // Type aliases use `type X = ...;` in TypeScript and can be exported
1032  // using `export type ...`.
1033  !(Style.Language == FormatStyle::LK_JavaScript &&
1034  (Line.startsWith(Keywords.kw_type, tok::identifier) ||
1035  Line.startsWith(tok::kw_export, Keywords.kw_type,
1036  tok::identifier))) &&
1037  (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
1038  Contexts.back().IsExpression = true;
1039  if (!Line.startsWith(TT_UnaryOperator)) {
1040  for (FormatToken *Previous = Current.Previous;
1041  Previous && Previous->Previous &&
1042  !Previous->Previous->isOneOf(tok::comma, tok::semi);
1043  Previous = Previous->Previous) {
1044  if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
1045  Previous = Previous->MatchingParen;
1046  if (!Previous)
1047  break;
1048  }
1049  if (Previous->opensScope())
1050  break;
1051  if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
1052  Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
1053  Previous->Previous && Previous->Previous->isNot(tok::equal))
1054  Previous->Type = TT_PointerOrReference;
1055  }
1056  }
1057  } else if (Current.is(tok::lessless) &&
1058  (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1059  Contexts.back().IsExpression = true;
1060  } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1061  Contexts.back().IsExpression = true;
1062  } else if (Current.is(TT_TrailingReturnArrow)) {
1063  Contexts.back().IsExpression = false;
1064  } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1065  Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1066  } else if (Current.Previous &&
1067  Current.Previous->is(TT_CtorInitializerColon)) {
1068  Contexts.back().IsExpression = true;
1069  Contexts.back().InCtorInitializer = true;
1070  } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
1071  Contexts.back().InInheritanceList = true;
1072  } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1073  for (FormatToken *Previous = Current.Previous;
1074  Previous && Previous->isOneOf(tok::star, tok::amp);
1075  Previous = Previous->Previous)
1076  Previous->Type = TT_PointerOrReference;
1077  if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1078  Contexts.back().IsExpression = false;
1079  } else if (Current.is(tok::kw_new)) {
1080  Contexts.back().CanBeExpression = false;
1081  } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
1082  // This should be the condition or increment in a for-loop.
1083  Contexts.back().IsExpression = true;
1084  }
1085  }
1086 
1087  void determineTokenType(FormatToken &Current) {
1088  if (!Current.is(TT_Unknown))
1089  // The token type is already known.
1090  return;
1091 
1092  if (Style.Language == FormatStyle::LK_JavaScript) {
1093  if (Current.is(tok::exclaim)) {
1094  if (Current.Previous &&
1095  (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
1096  tok::r_paren, tok::r_square,
1097  tok::r_brace) ||
1098  Current.Previous->Tok.isLiteral())) {
1099  Current.Type = TT_JsNonNullAssertion;
1100  return;
1101  }
1102  if (Current.Next &&
1103  Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1104  Current.Type = TT_JsNonNullAssertion;
1105  return;
1106  }
1107  }
1108  }
1109 
1110  // Line.MightBeFunctionDecl can only be true after the parentheses of a
1111  // function declaration have been found. In this case, 'Current' is a
1112  // trailing token of this declaration and thus cannot be a name.
1113  if (Current.is(Keywords.kw_instanceof)) {
1114  Current.Type = TT_BinaryOperator;
1115  } else if (isStartOfName(Current) &&
1116  (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1117  Contexts.back().FirstStartOfName = &Current;
1118  Current.Type = TT_StartOfName;
1119  } else if (Current.is(tok::semi)) {
1120  // Reset FirstStartOfName after finding a semicolon so that a for loop
1121  // with multiple increment statements is not confused with a for loop
1122  // having multiple variable declarations.
1123  Contexts.back().FirstStartOfName = nullptr;
1124  } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1125  AutoFound = true;
1126  } else if (Current.is(tok::arrow) &&
1127  Style.Language == FormatStyle::LK_Java) {
1128  Current.Type = TT_LambdaArrow;
1129  } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1130  Current.NestingLevel == 0) {
1131  Current.Type = TT_TrailingReturnArrow;
1132  } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1133  Current.Type = determineStarAmpUsage(Current,
1134  Contexts.back().CanBeExpression &&
1135  Contexts.back().IsExpression,
1136  Contexts.back().InTemplateArgument);
1137  } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1138  Current.Type = determinePlusMinusCaretUsage(Current);
1139  if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1140  Contexts.back().CaretFound = true;
1141  } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1142  Current.Type = determineIncrementUsage(Current);
1143  } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1144  Current.Type = TT_UnaryOperator;
1145  } else if (Current.is(tok::question)) {
1146  if (Style.Language == FormatStyle::LK_JavaScript &&
1147  Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1148  // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1149  // on the interface, not a ternary expression.
1150  Current.Type = TT_JsTypeOptionalQuestion;
1151  } else {
1152  Current.Type = TT_ConditionalExpr;
1153  }
1154  } else if (Current.isBinaryOperator() &&
1155  (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
1156  Current.Type = TT_BinaryOperator;
1157  } else if (Current.is(tok::comment)) {
1158  if (Current.TokenText.startswith("/*")) {
1159  if (Current.TokenText.endswith("*/"))
1160  Current.Type = TT_BlockComment;
1161  else
1162  // The lexer has for some reason determined a comment here. But we
1163  // cannot really handle it, if it isn't properly terminated.
1164  Current.Tok.setKind(tok::unknown);
1165  } else {
1166  Current.Type = TT_LineComment;
1167  }
1168  } else if (Current.is(tok::r_paren)) {
1169  if (rParenEndsCast(Current))
1170  Current.Type = TT_CastRParen;
1171  if (Current.MatchingParen && Current.Next &&
1172  !Current.Next->isBinaryOperator() &&
1173  !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1174  tok::comma, tok::period, tok::arrow,
1175  tok::coloncolon))
1176  if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1177  // Make sure this isn't the return type of an Obj-C block declaration
1178  if (AfterParen->Tok.isNot(tok::caret)) {
1179  if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1180  if (BeforeParen->is(tok::identifier) &&
1181  BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1182  (!BeforeParen->Previous ||
1183  BeforeParen->Previous->ClosesTemplateDeclaration))
1184  Current.Type = TT_FunctionAnnotationRParen;
1185  }
1186  }
1187  } else if (Current.is(tok::at) && Current.Next &&
1188  Style.Language != FormatStyle::LK_JavaScript &&
1189  Style.Language != FormatStyle::LK_Java) {
1190  // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1191  // marks declarations and properties that need special formatting.
1192  switch (Current.Next->Tok.getObjCKeywordID()) {
1193  case tok::objc_interface:
1194  case tok::objc_implementation:
1195  case tok::objc_protocol:
1196  Current.Type = TT_ObjCDecl;
1197  break;
1198  case tok::objc_property:
1199  Current.Type = TT_ObjCProperty;
1200  break;
1201  default:
1202  break;
1203  }
1204  } else if (Current.is(tok::period)) {
1205  FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1206  if (PreviousNoComment &&
1207  PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1208  Current.Type = TT_DesignatedInitializerPeriod;
1209  else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1210  Current.Previous->isOneOf(TT_JavaAnnotation,
1211  TT_LeadingJavaAnnotation)) {
1212  Current.Type = Current.Previous->Type;
1213  }
1214  } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1215  Current.Previous &&
1216  !Current.Previous->isOneOf(tok::equal, tok::at) &&
1217  Line.MightBeFunctionDecl && Contexts.size() == 1) {
1218  // Line.MightBeFunctionDecl can only be true after the parentheses of a
1219  // function declaration have been found.
1220  Current.Type = TT_TrailingAnnotation;
1221  } else if ((Style.Language == FormatStyle::LK_Java ||
1222  Style.Language == FormatStyle::LK_JavaScript) &&
1223  Current.Previous) {
1224  if (Current.Previous->is(tok::at) &&
1225  Current.isNot(Keywords.kw_interface)) {
1226  const FormatToken &AtToken = *Current.Previous;
1227  const FormatToken *Previous = AtToken.getPreviousNonComment();
1228  if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1229  Current.Type = TT_LeadingJavaAnnotation;
1230  else
1231  Current.Type = TT_JavaAnnotation;
1232  } else if (Current.Previous->is(tok::period) &&
1233  Current.Previous->isOneOf(TT_JavaAnnotation,
1234  TT_LeadingJavaAnnotation)) {
1235  Current.Type = Current.Previous->Type;
1236  }
1237  }
1238  }
1239 
1240  /// \brief Take a guess at whether \p Tok starts a name of a function or
1241  /// variable declaration.
1242  ///
1243  /// This is a heuristic based on whether \p Tok is an identifier following
1244  /// something that is likely a type.
1245  bool isStartOfName(const FormatToken &Tok) {
1246  if (Tok.isNot(tok::identifier) || !Tok.Previous)
1247  return false;
1248 
1249  if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1250  Keywords.kw_as))
1251  return false;
1252  if (Style.Language == FormatStyle::LK_JavaScript &&
1253  Tok.Previous->is(Keywords.kw_in))
1254  return false;
1255 
1256  // Skip "const" as it does not have an influence on whether this is a name.
1257  FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1258  while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1259  PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1260 
1261  if (!PreviousNotConst)
1262  return false;
1263 
1264  bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1265  PreviousNotConst->Previous &&
1266  PreviousNotConst->Previous->is(tok::hash);
1267 
1268  if (PreviousNotConst->is(TT_TemplateCloser))
1269  return PreviousNotConst && PreviousNotConst->MatchingParen &&
1270  PreviousNotConst->MatchingParen->Previous &&
1271  PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1272  PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1273 
1274  if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1275  PreviousNotConst->MatchingParen->Previous &&
1276  PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1277  return true;
1278 
1279  return (!IsPPKeyword &&
1280  PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1281  PreviousNotConst->is(TT_PointerOrReference) ||
1282  PreviousNotConst->isSimpleTypeSpecifier();
1283  }
1284 
1285  /// \brief Determine whether ')' is ending a cast.
1286  bool rParenEndsCast(const FormatToken &Tok) {
1287  // C-style casts are only used in C++ and Java.
1288  if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
1289  return false;
1290 
1291  // Empty parens aren't casts and there are no casts at the end of the line.
1292  if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1293  return false;
1294 
1295  FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1296  if (LeftOfParens) {
1297  // If there is a closing parenthesis left of the current parentheses,
1298  // look past it as these might be chained casts.
1299  if (LeftOfParens->is(tok::r_paren)) {
1300  if (!LeftOfParens->MatchingParen ||
1301  !LeftOfParens->MatchingParen->Previous)
1302  return false;
1303  LeftOfParens = LeftOfParens->MatchingParen->Previous;
1304  }
1305 
1306  // If there is an identifier (or with a few exceptions a keyword) right
1307  // before the parentheses, this is unlikely to be a cast.
1308  if (LeftOfParens->Tok.getIdentifierInfo() &&
1309  !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1310  tok::kw_delete))
1311  return false;
1312 
1313  // Certain other tokens right before the parentheses are also signals that
1314  // this cannot be a cast.
1315  if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1316  TT_TemplateCloser, tok::ellipsis))
1317  return false;
1318  }
1319 
1320  if (Tok.Next->is(tok::question))
1321  return false;
1322 
1323  // As Java has no function types, a "(" after the ")" likely means that this
1324  // is a cast.
1325  if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1326  return true;
1327 
1328  // If a (non-string) literal follows, this is likely a cast.
1329  if (Tok.Next->isNot(tok::string_literal) &&
1330  (Tok.Next->Tok.isLiteral() ||
1331  Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1332  return true;
1333 
1334  // Heuristically try to determine whether the parentheses contain a type.
1335  bool ParensAreType =
1336  !Tok.Previous ||
1337  Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1338  Tok.Previous->isSimpleTypeSpecifier();
1339  bool ParensCouldEndDecl =
1340  Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1341  if (ParensAreType && !ParensCouldEndDecl)
1342  return true;
1343 
1344  // At this point, we heuristically assume that there are no casts at the
1345  // start of the line. We assume that we have found most cases where there
1346  // are by the logic above, e.g. "(void)x;".
1347  if (!LeftOfParens)
1348  return false;
1349 
1350  // Certain token types inside the parentheses mean that this can't be a
1351  // cast.
1352  for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1353  Token = Token->Next)
1354  if (Token->is(TT_BinaryOperator))
1355  return false;
1356 
1357  // If the following token is an identifier or 'this', this is a cast. All
1358  // cases where this can be something else are handled above.
1359  if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1360  return true;
1361 
1362  if (!Tok.Next->Next)
1363  return false;
1364 
1365  // If the next token after the parenthesis is a unary operator, assume
1366  // that this is cast, unless there are unexpected tokens inside the
1367  // parenthesis.
1368  bool NextIsUnary =
1369  Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1370  if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1371  !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1372  return false;
1373  // Search for unexpected tokens.
1374  for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1375  Prev = Prev->Previous) {
1376  if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1377  return false;
1378  }
1379  return true;
1380  }
1381 
1382  /// \brief Return the type of the given token assuming it is * or &.
1383  TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1384  bool InTemplateArgument) {
1385  if (Style.Language == FormatStyle::LK_JavaScript)
1386  return TT_BinaryOperator;
1387 
1388  const FormatToken *PrevToken = Tok.getPreviousNonComment();
1389  if (!PrevToken)
1390  return TT_UnaryOperator;
1391 
1392  const FormatToken *NextToken = Tok.getNextNonComment();
1393  if (!NextToken ||
1394  NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
1395  (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1396  return TT_PointerOrReference;
1397 
1398  if (PrevToken->is(tok::coloncolon))
1399  return TT_PointerOrReference;
1400 
1401  if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1402  tok::comma, tok::semi, tok::kw_return, tok::colon,
1403  tok::equal, tok::kw_delete, tok::kw_sizeof,
1404  tok::kw_throw) ||
1405  PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1406  TT_UnaryOperator, TT_CastRParen))
1407  return TT_UnaryOperator;
1408 
1409  if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1410  return TT_PointerOrReference;
1411  if (NextToken->is(tok::kw_operator) && !IsExpression)
1412  return TT_PointerOrReference;
1413  if (NextToken->isOneOf(tok::comma, tok::semi))
1414  return TT_PointerOrReference;
1415 
1416  if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
1417  FormatToken *TokenBeforeMatchingParen =
1418  PrevToken->MatchingParen->getPreviousNonComment();
1419  if (TokenBeforeMatchingParen &&
1420  TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
1421  return TT_PointerOrReference;
1422  }
1423 
1424  if (PrevToken->Tok.isLiteral() ||
1425  PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1426  tok::kw_false, tok::r_brace) ||
1427  NextToken->Tok.isLiteral() ||
1428  NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1429  NextToken->isUnaryOperator() ||
1430  // If we know we're in a template argument, there are no named
1431  // declarations. Thus, having an identifier on the right-hand side
1432  // indicates a binary operator.
1433  (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1434  return TT_BinaryOperator;
1435 
1436  // "&&(" is quite unlikely to be two successive unary "&".
1437  if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1438  return TT_BinaryOperator;
1439 
1440  // This catches some cases where evaluation order is used as control flow:
1441  // aaa && aaa->f();
1442  const FormatToken *NextNextToken = NextToken->getNextNonComment();
1443  if (NextNextToken && NextNextToken->is(tok::arrow))
1444  return TT_BinaryOperator;
1445 
1446  // It is very unlikely that we are going to find a pointer or reference type
1447  // definition on the RHS of an assignment.
1448  if (IsExpression && !Contexts.back().CaretFound)
1449  return TT_BinaryOperator;
1450 
1451  return TT_PointerOrReference;
1452  }
1453 
1454  TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1455  const FormatToken *PrevToken = Tok.getPreviousNonComment();
1456  if (!PrevToken)
1457  return TT_UnaryOperator;
1458 
1459  if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
1460  !PrevToken->is(tok::exclaim))
1461  // There aren't any trailing unary operators except for TypeScript's
1462  // non-null operator (!). Thus, this must be squence of leading operators.
1463  return TT_UnaryOperator;
1464 
1465  // Use heuristics to recognize unary operators.
1466  if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1467  tok::question, tok::colon, tok::kw_return,
1468  tok::kw_case, tok::at, tok::l_brace))
1469  return TT_UnaryOperator;
1470 
1471  // There can't be two consecutive binary operators.
1472  if (PrevToken->is(TT_BinaryOperator))
1473  return TT_UnaryOperator;
1474 
1475  // Fall back to marking the token as binary operator.
1476  return TT_BinaryOperator;
1477  }
1478 
1479  /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1480  TokenType determineIncrementUsage(const FormatToken &Tok) {
1481  const FormatToken *PrevToken = Tok.getPreviousNonComment();
1482  if (!PrevToken || PrevToken->is(TT_CastRParen))
1483  return TT_UnaryOperator;
1484  if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1485  return TT_TrailingUnaryOperator;
1486 
1487  return TT_UnaryOperator;
1488  }
1489 
1490  SmallVector<Context, 8> Contexts;
1491 
1492  const FormatStyle &Style;
1493  AnnotatedLine &Line;
1494  FormatToken *CurrentToken;
1495  bool AutoFound;
1496  const AdditionalKeywords &Keywords;
1497 
1498  // Set of "<" tokens that do not open a template parameter list. If parseAngle
1499  // determines that a specific token can't be a template opener, it will make
1500  // same decision irrespective of the decisions for tokens leading up to it.
1501  // Store this information to prevent this from causing exponential runtime.
1502  llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1503 };
1504 
1505 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1506 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1507 
1508 /// \brief Parses binary expressions by inserting fake parenthesis based on
1509 /// operator precedence.
1510 class ExpressionParser {
1511 public:
1512  ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1513  AnnotatedLine &Line)
1514  : Style(Style), Keywords(Keywords), Current(Line.First) {}
1515 
1516  /// \brief Parse expressions with the given operatore precedence.
1517  void parse(int Precedence = 0) {
1518  // Skip 'return' and ObjC selector colons as they are not part of a binary
1519  // expression.
1520  while (Current && (Current->is(tok::kw_return) ||
1521  (Current->is(tok::colon) &&
1522  Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1523  next();
1524 
1525  if (!Current || Precedence > PrecedenceArrowAndPeriod)
1526  return;
1527 
1528  // Conditional expressions need to be parsed separately for proper nesting.
1529  if (Precedence == prec::Conditional) {
1530  parseConditionalExpr();
1531  return;
1532  }
1533 
1534  // Parse unary operators, which all have a higher precedence than binary
1535  // operators.
1536  if (Precedence == PrecedenceUnaryOperator) {
1537  parseUnaryOperator();
1538  return;
1539  }
1540 
1541  FormatToken *Start = Current;
1542  FormatToken *LatestOperator = nullptr;
1543  unsigned OperatorIndex = 0;
1544 
1545  while (Current) {
1546  // Consume operators with higher precedence.
1547  parse(Precedence + 1);
1548 
1549  int CurrentPrecedence = getCurrentPrecedence();
1550 
1551  if (Current && Current->is(TT_SelectorName) &&
1552  Precedence == CurrentPrecedence) {
1553  if (LatestOperator)
1554  addFakeParenthesis(Start, prec::Level(Precedence));
1555  Start = Current;
1556  }
1557 
1558  // At the end of the line or when an operator with higher precedence is
1559  // found, insert fake parenthesis and return.
1560  if (!Current ||
1561  (Current->closesScope() &&
1562  (Current->MatchingParen || Current->is(TT_TemplateString))) ||
1563  (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1564  (CurrentPrecedence == prec::Conditional &&
1565  Precedence == prec::Assignment && Current->is(tok::colon))) {
1566  break;
1567  }
1568 
1569  // Consume scopes: (), [], <> and {}
1570  if (Current->opensScope()) {
1571  // In fragment of a JavaScript template string can look like '}..${' and
1572  // thus close a scope and open a new one at the same time.
1573  while (Current && (!Current->closesScope() || Current->opensScope())) {
1574  next();
1575  parse();
1576  }
1577  next();
1578  } else {
1579  // Operator found.
1580  if (CurrentPrecedence == Precedence) {
1581  if (LatestOperator)
1582  LatestOperator->NextOperator = Current;
1583  LatestOperator = Current;
1584  Current->OperatorIndex = OperatorIndex;
1585  ++OperatorIndex;
1586  }
1587  next(/*SkipPastLeadingComments=*/Precedence > 0);
1588  }
1589  }
1590 
1591  if (LatestOperator && (Current || Precedence > 0)) {
1592  // LatestOperator->LastOperator = true;
1593  if (Precedence == PrecedenceArrowAndPeriod) {
1594  // Call expressions don't have a binary operator precedence.
1595  addFakeParenthesis(Start, prec::Unknown);
1596  } else {
1597  addFakeParenthesis(Start, prec::Level(Precedence));
1598  }
1599  }
1600  }
1601 
1602 private:
1603  /// \brief Gets the precedence (+1) of the given token for binary operators
1604  /// and other tokens that we treat like binary operators.
1605  int getCurrentPrecedence() {
1606  if (Current) {
1607  const FormatToken *NextNonComment = Current->getNextNonComment();
1608  if (Current->is(TT_ConditionalExpr))
1609  return prec::Conditional;
1610  if (NextNonComment && Current->is(TT_SelectorName) &&
1611  (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
1612  ((Style.Language == FormatStyle::LK_Proto ||
1613  Style.Language == FormatStyle::LK_TextProto) &&
1614  NextNonComment->is(tok::less))))
1615  return prec::Assignment;
1616  if (Current->is(TT_JsComputedPropertyName))
1617  return prec::Assignment;
1618  if (Current->is(TT_LambdaArrow))
1619  return prec::Comma;
1620  if (Current->is(TT_JsFatArrow))
1621  return prec::Assignment;
1622  if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
1623  (Current->is(tok::comment) && NextNonComment &&
1624  NextNonComment->is(TT_SelectorName)))
1625  return 0;
1626  if (Current->is(TT_RangeBasedForLoopColon))
1627  return prec::Comma;
1628  if ((Style.Language == FormatStyle::LK_Java ||
1629  Style.Language == FormatStyle::LK_JavaScript) &&
1630  Current->is(Keywords.kw_instanceof))
1631  return prec::Relational;
1632  if (Style.Language == FormatStyle::LK_JavaScript &&
1633  Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
1634  return prec::Relational;
1635  if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1636  return Current->getPrecedence();
1637  if (Current->isOneOf(tok::period, tok::arrow))
1638  return PrecedenceArrowAndPeriod;
1639  if ((Style.Language == FormatStyle::LK_Java ||
1640  Style.Language == FormatStyle::LK_JavaScript) &&
1641  Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1642  Keywords.kw_throws))
1643  return 0;
1644  }
1645  return -1;
1646  }
1647 
1648  void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1649  Start->FakeLParens.push_back(Precedence);
1650  if (Precedence > prec::Unknown)
1651  Start->StartsBinaryExpression = true;
1652  if (Current) {
1653  FormatToken *Previous = Current->Previous;
1654  while (Previous->is(tok::comment) && Previous->Previous)
1655  Previous = Previous->Previous;
1656  ++Previous->FakeRParens;
1657  if (Precedence > prec::Unknown)
1658  Previous->EndsBinaryExpression = true;
1659  }
1660  }
1661 
1662  /// \brief Parse unary operator expressions and surround them with fake
1663  /// parentheses if appropriate.
1664  void parseUnaryOperator() {
1665  if (!Current || Current->isNot(TT_UnaryOperator)) {
1666  parse(PrecedenceArrowAndPeriod);
1667  return;
1668  }
1669 
1670  FormatToken *Start = Current;
1671  next();
1672  parseUnaryOperator();
1673 
1674  // The actual precedence doesn't matter.
1675  addFakeParenthesis(Start, prec::Unknown);
1676  }
1677 
1678  void parseConditionalExpr() {
1679  while (Current && Current->isTrailingComment()) {
1680  next();
1681  }
1682  FormatToken *Start = Current;
1683  parse(prec::LogicalOr);
1684  if (!Current || !Current->is(tok::question))
1685  return;
1686  next();
1687  parse(prec::Assignment);
1688  if (!Current || Current->isNot(TT_ConditionalExpr))
1689  return;
1690  next();
1691  parse(prec::Assignment);
1692  addFakeParenthesis(Start, prec::Conditional);
1693  }
1694 
1695  void next(bool SkipPastLeadingComments = true) {
1696  if (Current)
1697  Current = Current->Next;
1698  while (Current &&
1699  (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1700  Current->isTrailingComment())
1701  Current = Current->Next;
1702  }
1703 
1704  const FormatStyle &Style;
1705  const AdditionalKeywords &Keywords;
1706  FormatToken *Current;
1707 };
1708 
1709 } // end anonymous namespace
1710 
1713  const AnnotatedLine *NextNonCommentLine = nullptr;
1715  E = Lines.rend();
1716  I != E; ++I) {
1717  bool CommentLine = true;
1718  for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
1719  if (!Tok->is(tok::comment)) {
1720  CommentLine = false;
1721  break;
1722  }
1723  }
1724 
1725  if (NextNonCommentLine && CommentLine) {
1726  // If the comment is currently aligned with the line immediately following
1727  // it, that's probably intentional and we should keep it.
1728  bool AlignedWithNextLine =
1729  NextNonCommentLine->First->NewlinesBefore <= 1 &&
1730  NextNonCommentLine->First->OriginalColumn ==
1731  (*I)->First->OriginalColumn;
1732  if (AlignedWithNextLine)
1733  (*I)->Level = NextNonCommentLine->Level;
1734  } else {
1735  NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1736  }
1737 
1738  setCommentLineLevels((*I)->Children);
1739  }
1740 }
1741 
1742 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
1743  unsigned Result = 0;
1744  for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
1745  Result = std::max(Result, Tok->NestingLevel);
1746  return Result;
1747 }
1748 
1751  E = Line.Children.end();
1752  I != E; ++I) {
1753  annotate(**I);
1754  }
1755  AnnotatingParser Parser(Style, Line, Keywords);
1756  Line.Type = Parser.parseLine();
1757 
1758  // With very deep nesting, ExpressionParser uses lots of stack and the
1759  // formatting algorithm is very slow. We're not going to do a good job here
1760  // anyway - it's probably generated code being formatted by mistake.
1761  // Just skip the whole line.
1762  if (maxNestingDepth(Line) > 50)
1763  Line.Type = LT_Invalid;
1764 
1765  if (Line.Type == LT_Invalid)
1766  return;
1767 
1768  ExpressionParser ExprParser(Style, Keywords, Line);
1769  ExprParser.parse();
1770 
1771  if (Line.startsWith(TT_ObjCMethodSpecifier))
1772  Line.Type = LT_ObjCMethodDecl;
1773  else if (Line.startsWith(TT_ObjCDecl))
1774  Line.Type = LT_ObjCDecl;
1775  else if (Line.startsWith(TT_ObjCProperty))
1776  Line.Type = LT_ObjCProperty;
1777 
1778  Line.First->SpacesRequiredBefore = 1;
1779  Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1780 }
1781 
1782 // This function heuristically determines whether 'Current' starts the name of a
1783 // function declaration.
1784 static bool isFunctionDeclarationName(const FormatToken &Current,
1785  const AnnotatedLine &Line) {
1786  auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
1787  for (; Next; Next = Next->Next) {
1788  if (Next->is(TT_OverloadedOperatorLParen))
1789  return Next;
1790  if (Next->is(TT_OverloadedOperator))
1791  continue;
1792  if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1793  // For 'new[]' and 'delete[]'.
1794  if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
1795  Next->Next->Next->is(tok::r_square))
1796  Next = Next->Next->Next;
1797  continue;
1798  }
1799 
1800  break;
1801  }
1802  return nullptr;
1803  };
1804 
1805  // Find parentheses of parameter list.
1806  const FormatToken *Next = Current.Next;
1807  if (Current.is(tok::kw_operator)) {
1808  if (Current.Previous && Current.Previous->is(tok::coloncolon))
1809  return false;
1810  Next = skipOperatorName(Next);
1811  } else {
1812  if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1813  return false;
1814  for (; Next; Next = Next->Next) {
1815  if (Next->is(TT_TemplateOpener)) {
1816  Next = Next->MatchingParen;
1817  } else if (Next->is(tok::coloncolon)) {
1818  Next = Next->Next;
1819  if (!Next)
1820  return false;
1821  if (Next->is(tok::kw_operator)) {
1822  Next = skipOperatorName(Next->Next);
1823  break;
1824  }
1825  if (!Next->is(tok::identifier))
1826  return false;
1827  } else if (Next->is(tok::l_paren)) {
1828  break;
1829  } else {
1830  return false;
1831  }
1832  }
1833  }
1834 
1835  // Check whether parameter list can belong to a function declaration.
1836  if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
1837  return false;
1838  // If the lines ends with "{", this is likely an function definition.
1839  if (Line.Last->is(tok::l_brace))
1840  return true;
1841  if (Next->Next == Next->MatchingParen)
1842  return true; // Empty parentheses.
1843  // If there is an &/&& after the r_paren, this is likely a function.
1844  if (Next->MatchingParen->Next &&
1845  Next->MatchingParen->Next->is(TT_PointerOrReference))
1846  return true;
1847  for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1848  Tok = Tok->Next) {
1849  if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
1850  Tok = Tok->MatchingParen;
1851  continue;
1852  }
1853  if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1854  Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
1855  return true;
1856  if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1857  Tok->Tok.isLiteral())
1858  return false;
1859  }
1860  return false;
1861 }
1862 
1863 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1864  assert(Line.MightBeFunctionDecl);
1865 
1869  Line.Level > 0)
1870  return false;
1871 
1874  return false;
1875  case FormatStyle::RTBS_All:
1877  return true;
1880  return Line.mightBeFunctionDefinition();
1881  }
1882 
1883  return false;
1884 }
1885 
1888  E = Line.Children.end();
1889  I != E; ++I) {
1890  calculateFormattingInformation(**I);
1891  }
1892 
1893  Line.First->TotalLength =
1895  FormatToken *Current = Line.First->Next;
1896  bool InFunctionDecl = Line.MightBeFunctionDecl;
1897  while (Current) {
1898  if (isFunctionDeclarationName(*Current, Line))
1899  Current->Type = TT_FunctionDeclarationName;
1900  if (Current->is(TT_LineComment)) {
1901  if (Current->Previous->BlockKind == BK_BracedInit &&
1902  Current->Previous->opensScope())
1903  Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1904  else
1906 
1907  // If we find a trailing comment, iterate backwards to determine whether
1908  // it seems to relate to a specific parameter. If so, break before that
1909  // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1910  // to the previous line in:
1911  // SomeFunction(a,
1912  // b, // comment
1913  // c);
1914  if (!Current->HasUnescapedNewline) {
1915  for (FormatToken *Parameter = Current->Previous; Parameter;
1916  Parameter = Parameter->Previous) {
1917  if (Parameter->isOneOf(tok::comment, tok::r_brace))
1918  break;
1919  if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1920  if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1921  Parameter->HasUnescapedNewline)
1922  Parameter->MustBreakBefore = true;
1923  break;
1924  }
1925  }
1926  }
1927  } else if (Current->SpacesRequiredBefore == 0 &&
1928  spaceRequiredBefore(Line, *Current)) {
1929  Current->SpacesRequiredBefore = 1;
1930  }
1931 
1932  Current->MustBreakBefore =
1933  Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1934 
1935  if (!Current->MustBreakBefore && InFunctionDecl &&
1936  Current->is(TT_FunctionDeclarationName))
1937  Current->MustBreakBefore = mustBreakForReturnType(Line);
1938 
1939  Current->CanBreakBefore =
1940  Current->MustBreakBefore || canBreakBefore(Line, *Current);
1941  unsigned ChildSize = 0;
1942  if (Current->Previous->Children.size() == 1) {
1943  FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1944  ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1945  : LastOfChild.TotalLength + 1;
1946  }
1947  const FormatToken *Prev = Current->Previous;
1948  if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1949  (Prev->Children.size() == 1 &&
1950  Prev->Children[0]->First->MustBreakBefore) ||
1951  Current->IsMultiline)
1952  Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1953  else
1954  Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1955  ChildSize + Current->SpacesRequiredBefore;
1956 
1957  if (Current->is(TT_CtorInitializerColon))
1958  InFunctionDecl = false;
1959 
1960  // FIXME: Only calculate this if CanBreakBefore is true once static
1961  // initializers etc. are sorted out.
1962  // FIXME: Move magic numbers to a better place.
1963  Current->SplitPenalty = 20 * Current->BindingStrength +
1964  splitPenalty(Line, *Current, InFunctionDecl);
1965 
1966  Current = Current->Next;
1967  }
1968 
1969  calculateUnbreakableTailLengths(Line);
1970  unsigned IndentLevel = Line.Level;
1971  for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1972  if (Current->Role)
1973  Current->Role->precomputeFormattingInfos(Current);
1974  if (Current->MatchingParen &&
1976  assert(IndentLevel > 0);
1977  --IndentLevel;
1978  }
1979  Current->IndentLevel = IndentLevel;
1980  if (Current->opensBlockOrBlockTypeList(Style))
1981  ++IndentLevel;
1982  }
1983 
1984  DEBUG({ printDebugInfo(Line); });
1985 }
1986 
1987 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1988  unsigned UnbreakableTailLength = 0;
1989  FormatToken *Current = Line.Last;
1990  while (Current) {
1991  Current->UnbreakableTailLength = UnbreakableTailLength;
1992  if (Current->CanBreakBefore ||
1993  Current->isOneOf(tok::comment, tok::string_literal)) {
1994  UnbreakableTailLength = 0;
1995  } else {
1996  UnbreakableTailLength +=
1997  Current->ColumnWidth + Current->SpacesRequiredBefore;
1998  }
1999  Current = Current->Previous;
2000  }
2001 }
2002 
2003 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2004  const FormatToken &Tok,
2005  bool InFunctionDecl) {
2006  const FormatToken &Left = *Tok.Previous;
2007  const FormatToken &Right = Tok;
2008 
2009  if (Left.is(tok::semi))
2010  return 0;
2011 
2013  if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2014  return 1;
2015  if (Right.is(Keywords.kw_implements))
2016  return 2;
2017  if (Left.is(tok::comma) && Left.NestingLevel == 0)
2018  return 3;
2019  } else if (Style.Language == FormatStyle::LK_JavaScript) {
2020  if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2021  return 100;
2022  if (Left.is(TT_JsTypeColon))
2023  return 35;
2024  if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2025  (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2026  return 100;
2027  // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2028  if (Left.opensScope() && Right.closesScope())
2029  return 200;
2030  }
2031 
2032  if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2033  return 1;
2034  if (Right.is(tok::l_square)) {
2036  return 1;
2037  if (Left.is(tok::r_square))
2038  return 200;
2039  // Slightly prefer formatting local lambda definitions like functions.
2040  if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2041  return 35;
2042  if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2043  TT_ArrayInitializerLSquare,
2044  TT_DesignatedInitializerLSquare))
2045  return 500;
2046  }
2047 
2048  if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2049  Right.is(tok::kw_operator)) {
2050  if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2051  return 3;
2052  if (Left.is(TT_StartOfName))
2053  return 110;
2054  if (InFunctionDecl && Right.NestingLevel == 0)
2056  return 200;
2057  }
2058  if (Right.is(TT_PointerOrReference))
2059  return 190;
2060  if (Right.is(TT_LambdaArrow))
2061  return 110;
2062  if (Left.is(tok::equal) && Right.is(tok::l_brace))
2063  return 160;
2064  if (Left.is(TT_CastRParen))
2065  return 100;
2066  if (Left.is(tok::coloncolon) ||
2067  (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2068  return 500;
2069  if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2070  return 5000;
2071  if (Left.is(tok::comment))
2072  return 1000;
2073 
2074  if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2075  TT_CtorInitializerColon))
2076  return 2;
2077 
2078  if (Right.isMemberAccess()) {
2079  // Breaking before the "./->" of a chained call/member access is reasonably
2080  // cheap, as formatting those with one call per line is generally
2081  // desirable. In particular, it should be cheaper to break before the call
2082  // than it is to break inside a call's parameters, which could lead to weird
2083  // "hanging" indents. The exception is the very last "./->" to support this
2084  // frequent pattern:
2085  //
2086  // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2087  // dddddddd);
2088  //
2089  // which might otherwise be blown up onto many lines. Here, clang-format
2090  // won't produce "hanging" indents anyway as there is no other trailing
2091  // call.
2092  //
2093  // Also apply higher penalty is not a call as that might lead to a wrapping
2094  // like:
2095  //
2096  // aaaaaaa
2097  // .aaaaaaaaa.bbbbbbbb(cccccccc);
2098  return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2099  ? 150
2100  : 35;
2101  }
2102 
2103  if (Right.is(TT_TrailingAnnotation) &&
2104  (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2105  // Moving trailing annotations to the next line is fine for ObjC method
2106  // declarations.
2107  if (Line.startsWith(TT_ObjCMethodSpecifier))
2108  return 10;
2109  // Generally, breaking before a trailing annotation is bad unless it is
2110  // function-like. It seems to be especially preferable to keep standard
2111  // annotations (i.e. "const", "final" and "override") on the same line.
2112  // Use a slightly higher penalty after ")" so that annotations like
2113  // "const override" are kept together.
2114  bool is_short_annotation = Right.TokenText.size() < 10;
2115  return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2116  }
2117 
2118  // In for-loops, prefer breaking at ',' and ';'.
2119  if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2120  return 4;
2121 
2122  // In Objective-C method expressions, prefer breaking before "param:" over
2123  // breaking after it.
2124  if (Right.is(TT_SelectorName))
2125  return 0;
2126  if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2127  return Line.MightBeFunctionDecl ? 50 : 500;
2128 
2129  if (Left.is(tok::l_paren) && InFunctionDecl &&
2131  return 100;
2132  if (Left.is(tok::l_paren) && Left.Previous &&
2133  (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
2134  Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
2135  return 1000;
2136  if (Left.is(tok::equal) && InFunctionDecl)
2137  return 110;
2138  if (Right.is(tok::r_brace))
2139  return 1;
2140  if (Left.is(TT_TemplateOpener))
2141  return 100;
2142  if (Left.opensScope()) {
2144  return 0;
2146  : 19;
2147  }
2148  if (Left.is(TT_JavaAnnotation))
2149  return 50;
2150 
2151  if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2152  Left.Previous->isLabelString() &&
2153  (Left.NextOperator || Left.OperatorIndex != 0))
2154  return 45;
2155  if (Right.is(tok::plus) && Left.isLabelString() &&
2156  (Right.NextOperator || Right.OperatorIndex != 0))
2157  return 25;
2158  if (Left.is(tok::comma))
2159  return 1;
2160  if (Right.is(tok::lessless) && Left.isLabelString() &&
2161  (Right.NextOperator || Right.OperatorIndex != 1))
2162  return 25;
2163  if (Right.is(tok::lessless)) {
2164  // Breaking at a << is really cheap.
2165  if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2166  // Slightly prefer to break before the first one in log-like statements.
2167  return 2;
2168  return 1;
2169  }
2170  if (Left.is(TT_ConditionalExpr))
2171  return prec::Conditional;
2172  prec::Level Level = Left.getPrecedence();
2173  if (Level == prec::Unknown)
2174  Level = Right.getPrecedence();
2175  if (Level == prec::Assignment)
2177  if (Level != prec::Unknown)
2178  return Level;
2179 
2180  return 3;
2181 }
2182 
2183 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2184  const FormatToken &Left,
2185  const FormatToken &Right) {
2186  if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2187  return true;
2188  if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2189  return true;
2191  Left.Tok.getObjCKeywordID() == tok::objc_property)
2192  return true;
2193  if (Right.is(tok::hashhash))
2194  return Left.is(tok::hash);
2195  if (Left.isOneOf(tok::hashhash, tok::hash))
2196  return Right.is(tok::hash);
2197  if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2199  if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2200  return (Right.is(TT_CastRParen) ||
2201  (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2204  if (Right.isOneOf(tok::semi, tok::comma))
2205  return false;
2206  if (Right.is(tok::less) && Line.Type == LT_ObjCDecl &&
2208  return true;
2209  if (Right.is(tok::less) && Left.is(tok::kw_template))
2211  if (Left.isOneOf(tok::exclaim, tok::tilde))
2212  return false;
2213  if (Left.is(tok::at) &&
2214  Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2215  tok::numeric_constant, tok::l_paren, tok::l_brace,
2216  tok::kw_true, tok::kw_false))
2217  return false;
2218  if (Left.is(tok::colon))
2219  return !Left.is(TT_ObjCMethodExpr);
2220  if (Left.is(tok::coloncolon))
2221  return false;
2222  if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
2223  return false;
2224  if (Right.is(tok::ellipsis))
2225  return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2226  Left.Previous->is(tok::kw_case));
2227  if (Left.is(tok::l_square) && Right.is(tok::amp))
2228  return false;
2229  if (Right.is(TT_PointerOrReference)) {
2230  if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
2231  if (!Left.MatchingParen)
2232  return true;
2233  FormatToken *TokenBeforeMatchingParen =
2235  if (!TokenBeforeMatchingParen ||
2236  !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
2237  return true;
2238  }
2239  return (Left.Tok.isLiteral() ||
2240  (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2242  (Line.IsMultiVariableDeclStmt &&
2243  (Left.NestingLevel == 0 ||
2244  (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2245  }
2246  if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2247  (!Left.is(TT_PointerOrReference) ||
2249  !Line.IsMultiVariableDeclStmt)))
2250  return true;
2251  if (Left.is(TT_PointerOrReference))
2252  return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2253  (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2254  !Right.is(TT_StartOfName)) ||
2255  (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2256  (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2257  tok::l_paren) &&
2259  !Line.IsMultiVariableDeclStmt) &&
2260  Left.Previous &&
2261  !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2262  if (Right.is(tok::star) && Left.is(tok::l_paren))
2263  return false;
2264  if (Left.is(tok::l_square))
2265  return (Left.is(TT_ArrayInitializerLSquare) &&
2266  Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
2267  (Left.isOneOf(TT_ArraySubscriptLSquare,
2268  TT_StructuredBindingLSquare) &&
2269  Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
2270  if (Right.is(tok::r_square))
2271  return Right.MatchingParen &&
2273  Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
2275  Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
2276  TT_StructuredBindingLSquare)));
2277  if (Right.is(tok::l_square) &&
2278  !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2279  TT_DesignatedInitializerLSquare,
2280  TT_StructuredBindingLSquare) &&
2281  !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2282  return false;
2283  if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2284  return !Left.Children.empty(); // No spaces in "{}".
2285  if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2286  (Right.is(tok::r_brace) && Right.MatchingParen &&
2287  Right.MatchingParen->BlockKind != BK_Block))
2288  return !Style.Cpp11BracedListStyle;
2289  if (Left.is(TT_BlockComment))
2290  return !Left.TokenText.endswith("=*/");
2291  if (Right.is(tok::l_paren)) {
2292  if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
2293  return true;
2294  return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2296  (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2297  tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2298  TT_ObjCForIn) ||
2299  Left.endsSequence(tok::kw_constexpr, tok::kw_if) ||
2300  (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2301  tok::kw_new, tok::kw_delete) &&
2302  (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2304  (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2305  Left.is(tok::r_paren)) &&
2306  Line.Type != LT_PreprocessorDirective);
2307  }
2308  if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2309  return false;
2310  if (Right.is(TT_UnaryOperator))
2311  return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2312  (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2313  if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2314  tok::r_paren) ||
2315  Left.isSimpleTypeSpecifier()) &&
2316  Right.is(tok::l_brace) && Right.getNextNonComment() &&
2317  Right.BlockKind != BK_Block)
2318  return false;
2319  if (Left.is(tok::period) || Right.is(tok::period))
2320  return false;
2321  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2322  return false;
2323  if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2324  Left.MatchingParen->Previous &&
2325  Left.MatchingParen->Previous->is(tok::period))
2326  // A.<B<C<...>>>DoSomething();
2327  return false;
2328  if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2329  return false;
2330  return true;
2331 }
2332 
2333 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2334  const FormatToken &Right) {
2335  const FormatToken &Left = *Right.Previous;
2336  if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2337  return true; // Never ever merge two identifiers.
2338  if (Style.isCpp()) {
2339  if (Left.is(tok::kw_operator))
2340  return Right.is(tok::coloncolon);
2341  } else if (Style.Language == FormatStyle::LK_Proto ||
2343  if (Right.is(tok::period) &&
2344  Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2345  Keywords.kw_repeated, Keywords.kw_extend))
2346  return true;
2347  if (Right.is(tok::l_paren) &&
2348  Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2349  return true;
2350  if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
2351  return true;
2352  } else if (Style.Language == FormatStyle::LK_JavaScript) {
2353  if (Left.is(TT_JsFatArrow))
2354  return true;
2355  // for await ( ...
2356  if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
2357  Left.Previous->is(tok::kw_for))
2358  return true;
2359  if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
2360  Right.MatchingParen) {
2361  const FormatToken *Next = Right.MatchingParen->getNextNonComment();
2362  // An async arrow function, for example: `x = async () => foo();`,
2363  // as opposed to calling a function called async: `x = async();`
2364  if (Next && Next->is(TT_JsFatArrow))
2365  return true;
2366  }
2367  if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2368  (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2369  return false;
2370  // In tagged template literals ("html`bar baz`"), there is no space between
2371  // the tag identifier and the template string. getIdentifierInfo makes sure
2372  // that the identifier is not a pseudo keyword like `yield`, either.
2373  if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
2374  Right.is(TT_TemplateString))
2375  return false;
2376  if (Right.is(tok::star) &&
2377  Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2378  return false;
2379  if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2380  Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
2381  Keywords.kw_extends, Keywords.kw_implements))
2382  return true;
2383  if (Right.is(tok::l_paren)) {
2384  // JS methods can use some keywords as names (e.g. `delete()`).
2385  if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
2386  return false;
2387  // Valid JS method names can include keywords, e.g. `foo.delete()` or
2388  // `bar.instanceof()`. Recognize call positions by preceding period.
2389  if (Left.Previous && Left.Previous->is(tok::period) &&
2390  Left.Tok.getIdentifierInfo())
2391  return false;
2392  // Additional unary JavaScript operators that need a space after.
2393  if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
2394  tok::kw_void))
2395  return true;
2396  }
2397  if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2398  tok::kw_const) ||
2399  // "of" is only a keyword if it appears after another identifier
2400  // (e.g. as "const x of y" in a for loop).
2401  (Left.is(Keywords.kw_of) && Left.Previous &&
2402  Left.Previous->Tok.getIdentifierInfo())) &&
2403  (!Left.Previous || !Left.Previous->is(tok::period)))
2404  return true;
2405  if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2406  Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2407  return false;
2408  if (Left.is(Keywords.kw_as) &&
2409  Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2410  return true;
2411  if (Left.is(tok::kw_default) && Left.Previous &&
2412  Left.Previous->is(tok::kw_export))
2413  return true;
2414  if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2415  return true;
2416  if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2417  return false;
2418  if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2419  return false;
2420  if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2421  Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2422  return false;
2423  if (Left.is(tok::ellipsis))
2424  return false;
2425  if (Left.is(TT_TemplateCloser) &&
2426  !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2427  Keywords.kw_implements, Keywords.kw_extends))
2428  // Type assertions ('<type>expr') are not followed by whitespace. Other
2429  // locations that should have whitespace following are identified by the
2430  // above set of follower tokens.
2431  return false;
2432  if (Right.is(TT_JsNonNullAssertion))
2433  return false;
2434  if (Left.is(TT_JsNonNullAssertion) && Right.is(Keywords.kw_as))
2435  return true; // "x! as string"
2436  } else if (Style.Language == FormatStyle::LK_Java) {
2437  if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2438  return true;
2439  if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2441  if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2442  tok::kw_protected) ||
2443  Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2444  Keywords.kw_native)) &&
2445  Right.is(TT_TemplateOpener))
2446  return true;
2447  }
2448  if (Left.is(TT_ImplicitStringLiteral))
2449  return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2450  if (Line.Type == LT_ObjCMethodDecl) {
2451  if (Left.is(TT_ObjCMethodSpecifier))
2452  return true;
2453  if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2454  // Don't space between ')' and <id>
2455  return false;
2456  }
2457  if (Line.Type == LT_ObjCProperty &&
2458  (Right.is(tok::equal) || Left.is(tok::equal)))
2459  return false;
2460 
2461  if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2462  Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2463  return true;
2464  if (Right.is(TT_OverloadedOperatorLParen))
2466  if (Left.is(tok::comma))
2467  return true;
2468  if (Right.is(tok::comma))
2469  return false;
2470  if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2471  return true;
2472  if (Right.is(tok::colon)) {
2473  if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2474  !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2475  return false;
2476  if (Right.is(TT_ObjCMethodExpr))
2477  return false;
2478  if (Left.is(tok::question))
2479  return false;
2480  if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2481  return false;
2482  if (Right.is(TT_DictLiteral))
2484  return true;
2485  }
2486  if (Left.is(TT_UnaryOperator))
2487  return Right.is(TT_BinaryOperator);
2488 
2489  // If the next token is a binary operator or a selector name, we have
2490  // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2491  if (Left.is(TT_CastRParen))
2492  return Style.SpaceAfterCStyleCast ||
2493  Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2494 
2495  if (Left.is(tok::greater) && Right.is(tok::greater))
2496  return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2498  if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
2499  Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2500  (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
2501  return false;
2503  Right.getPrecedence() == prec::Assignment)
2504  return false;
2505  if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
2506  // Generally don't remove existing spaces between an identifier and "::".
2507  // The identifier might actually be a macro name such as ALWAYS_INLINE. If
2508  // this turns out to be too lenient, add analysis of the identifier itself.
2509  return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2510  if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2511  return (Left.is(TT_TemplateOpener) &&
2513  !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
2514  tok::kw___super, TT_TemplateCloser,
2515  TT_TemplateOpener));
2516  if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2517  return Style.SpacesInAngles;
2518  // Space before TT_StructuredBindingLSquare.
2519  if (Right.is(TT_StructuredBindingLSquare))
2520  return !Left.isOneOf(tok::amp, tok::ampamp) ||
2522  // Space before & or && following a TT_StructuredBindingLSquare.
2523  if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
2524  Right.isOneOf(tok::amp, tok::ampamp))
2526  if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2527  (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2528  !Right.is(tok::r_paren)))
2529  return true;
2530  if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2531  Right.isNot(TT_FunctionTypeLParen))
2533  if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2534  Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2535  return false;
2536  if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2537  Line.startsWith(tok::hash))
2538  return true;
2539  if (Right.is(TT_TrailingUnaryOperator))
2540  return false;
2541  if (Left.is(TT_RegexLiteral))
2542  return false;
2543  return spaceRequiredBetween(Line, Left, Right);
2544 }
2545 
2546 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2547 static bool isAllmanBrace(const FormatToken &Tok) {
2548  return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2549  !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2550 }
2551 
2552 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2553  const FormatToken &Right) {
2554  const FormatToken &Left = *Right.Previous;
2555  if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2556  return true;
2557 
2559  // FIXME: This might apply to other languages and token kinds.
2560  if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2561  Left.Previous->is(tok::string_literal))
2562  return true;
2563  if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2564  Left.Previous && Left.Previous->is(tok::equal) &&
2565  Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2566  tok::kw_const) &&
2567  // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2568  // above.
2569  !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2570  // Object literals on the top level of a file are treated as "enum-style".
2571  // Each key/value pair is put on a separate line, instead of bin-packing.
2572  return true;
2573  if (Left.is(tok::l_brace) && Line.Level == 0 &&
2574  (Line.startsWith(tok::kw_enum) ||
2575  Line.startsWith(tok::kw_const, tok::kw_enum) ||
2576  Line.startsWith(tok::kw_export, tok::kw_enum) ||
2577  Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
2578  // JavaScript top-level enum key/value pairs are put on separate lines
2579  // instead of bin-packing.
2580  return true;
2581  if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2582  !Left.Children.empty())
2583  // Support AllowShortFunctionsOnASingleLine for JavaScript.
2586  (Left.NestingLevel == 0 && Line.Level == 0 &&
2589  } else if (Style.Language == FormatStyle::LK_Java) {
2590  if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2591  Right.Next->is(tok::string_literal))
2592  return true;
2593  } else if (Style.Language == FormatStyle::LK_Cpp ||
2596  if (Left.isStringLiteral() && Right.isStringLiteral())
2597  return true;
2598  }
2599 
2600  // If the last token before a '}', ']', or ')' is a comma or a trailing
2601  // comment, the intention is to insert a line break after it in order to make
2602  // shuffling around entries easier. Import statements, especially in
2603  // JavaScript, can be an exception to this rule.
2605  const FormatToken *BeforeClosingBrace = nullptr;
2606  if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
2608  Left.is(tok::l_paren))) &&
2609  Left.BlockKind != BK_Block && Left.MatchingParen)
2610  BeforeClosingBrace = Left.MatchingParen->Previous;
2611  else if (Right.MatchingParen &&
2612  (Right.MatchingParen->isOneOf(tok::l_brace,
2613  TT_ArrayInitializerLSquare) ||
2615  Right.MatchingParen->is(tok::l_paren))))
2616  BeforeClosingBrace = &Left;
2617  if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2618  BeforeClosingBrace->isTrailingComment()))
2619  return true;
2620  }
2621 
2622  if (Right.is(tok::comment))
2623  return Left.BlockKind != BK_BracedInit &&
2624  Left.isNot(TT_CtorInitializerColon) &&
2625  (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2626  if (Left.isTrailingComment())
2627  return true;
2628  if (Right.Previous->IsUnterminatedLiteral)
2629  return true;
2630  if (Right.is(tok::lessless) && Right.Next &&
2631  Right.Previous->is(tok::string_literal) &&
2632  Right.Next->is(tok::string_literal))
2633  return true;
2634  if (Right.Previous->ClosesTemplateDeclaration &&
2635  Right.Previous->MatchingParen &&
2636  Right.Previous->MatchingParen->NestingLevel == 0 &&
2638  return true;
2639  if (Right.is(TT_CtorInitializerComma) &&
2642  return true;
2643  if (Right.is(TT_CtorInitializerColon) &&
2646  return true;
2647  // Break only if we have multiple inheritance.
2648  if (Style.BreakBeforeInheritanceComma && Right.is(TT_InheritanceComma))
2649  return true;
2650  if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2651  // Raw string literals are special wrt. line breaks. The author has made a
2652  // deliberate choice and might have aligned the contents of the string
2653  // literal accordingly. Thus, we try keep existing line breaks.
2654  return Right.NewlinesBefore > 0;
2655  if ((Right.Previous->is(tok::l_brace) ||
2656  (Right.Previous->is(tok::less) && Right.Previous->Previous &&
2657  Right.Previous->Previous->is(tok::equal))) &&
2658  Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
2659  // Don't put enums or option definitions onto single lines in protocol
2660  // buffers.
2661  return true;
2662  }
2663  if (Right.is(TT_InlineASMBrace))
2664  return Right.HasUnescapedNewline;
2665  if (isAllmanBrace(Left) || isAllmanBrace(Right))
2666  return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2667  (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
2669  (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2670  (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2671  if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2672  return true;
2673 
2676  Left.is(TT_LeadingJavaAnnotation) &&
2677  Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2678  (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2679  return true;
2680 
2681  return false;
2682 }
2683 
2684 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2685  const FormatToken &Right) {
2686  const FormatToken &Left = *Right.Previous;
2687 
2688  // Language-specific stuff.
2690  if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2691  Keywords.kw_implements))
2692  return false;
2693  if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2694  Keywords.kw_implements))
2695  return true;
2696  } else if (Style.Language == FormatStyle::LK_JavaScript) {
2697  const FormatToken *NonComment = Right.getPreviousNonComment();
2698  if (NonComment &&
2699  NonComment->isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
2700  tok::kw_throw, Keywords.kw_interface,
2701  Keywords.kw_type, tok::kw_static, tok::kw_public,
2702  tok::kw_private, tok::kw_protected,
2703  Keywords.kw_readonly, Keywords.kw_abstract,
2704  Keywords.kw_get, Keywords.kw_set))
2705  return false; // Otherwise automatic semicolon insertion would trigger.
2706  if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2707  return false;
2708  if (Left.is(TT_JsTypeColon))
2709  return true;
2710  if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2711  return false;
2712  if (Left.is(Keywords.kw_in))
2714  if (Right.is(Keywords.kw_in))
2716  if (Right.is(Keywords.kw_as))
2717  return false; // must not break before as in 'x as type' casts
2718  if (Left.is(Keywords.kw_as))
2719  return true;
2720  if (Left.is(TT_JsNonNullAssertion))
2721  return true;
2722  if (Left.is(Keywords.kw_declare) &&
2723  Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
2724  Keywords.kw_function, tok::kw_class, tok::kw_enum,
2725  Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
2726  Keywords.kw_let, tok::kw_const))
2727  // See grammar for 'declare' statements at:
2728  // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
2729  return false;
2730  if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
2731  Right.isOneOf(tok::identifier, tok::string_literal))
2732  return false; // must not break in "module foo { ...}"
2733  if (Right.is(TT_TemplateString) && Right.closesScope())
2734  return false;
2735  if (Left.is(TT_TemplateString) && Left.opensScope())
2736  return true;
2737  }
2738 
2739  if (Left.is(tok::at))
2740  return false;
2741  if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2742  return false;
2743  if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2744  return !Right.is(tok::l_paren);
2745  if (Right.is(TT_PointerOrReference))
2746  return Line.IsMultiVariableDeclStmt ||
2748  (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2749  if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2750  Right.is(tok::kw_operator))
2751  return true;
2752  if (Left.is(TT_PointerOrReference))
2753  return false;
2754  if (Right.isTrailingComment())
2755  // We rely on MustBreakBefore being set correctly here as we should not
2756  // change the "binding" behavior of a comment.
2757  // The first comment in a braced lists is always interpreted as belonging to
2758  // the first list element. Otherwise, it should be placed outside of the
2759  // list.
2760  return Left.BlockKind == BK_BracedInit ||
2761  (Left.is(TT_CtorInitializerColon) &&
2763  if (Left.is(tok::question) && Right.is(tok::colon))
2764  return false;
2765  if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2767  if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2769  if (Right.is(TT_InheritanceColon))
2770  return true;
2771  if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
2772  Left.isNot(TT_SelectorName))
2773  return true;
2774  if (Right.is(tok::colon) &&
2775  !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2776  return false;
2777  if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr))
2778  return true;
2779  if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2780  Right.Next->is(TT_ObjCMethodExpr)))
2781  return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2782  if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2783  return true;
2784  if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2785  return true;
2786  if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2787  TT_OverloadedOperator))
2788  return false;
2789  if (Left.is(TT_RangeBasedForLoopColon))
2790  return true;
2791  if (Right.is(TT_RangeBasedForLoopColon))
2792  return false;
2793  if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
2794  return true;
2795  if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2796  Left.is(tok::kw_operator))
2797  return false;
2798  if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2799  Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2800  return false;
2801  if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2802  return false;
2803  if (Left.is(tok::l_paren) && Left.Previous &&
2804  (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2805  return false;
2806  if (Right.is(TT_ImplicitStringLiteral))
2807  return false;
2808 
2809  if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2810  return false;
2811  if (Right.is(tok::r_square) && Right.MatchingParen &&
2812  Right.MatchingParen->is(TT_LambdaLSquare))
2813  return false;
2814 
2815  // We only break before r_brace if there was a corresponding break before
2816  // the l_brace, which is tracked by BreakBeforeClosingBrace.
2817  if (Right.is(tok::r_brace))
2818  return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2819 
2820  // Allow breaking after a trailing annotation, e.g. after a method
2821  // declaration.
2822  if (Left.is(TT_TrailingAnnotation))
2823  return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2824  tok::less, tok::coloncolon);
2825 
2826  if (Right.is(tok::kw___attribute))
2827  return true;
2828 
2829  if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2830  return true;
2831 
2832  if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2833  return true;
2834 
2835  if (Left.is(TT_CtorInitializerColon))
2837  if (Right.is(TT_CtorInitializerColon))
2839  if (Left.is(TT_CtorInitializerComma) &&
2841  return false;
2842  if (Right.is(TT_CtorInitializerComma) &&
2844  return true;
2845  if (Left.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
2846  return false;
2847  if (Right.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
2848  return true;
2849  if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2850  (Left.is(tok::less) && Right.is(tok::less)))
2851  return false;
2852  if (Right.is(TT_BinaryOperator) &&
2855  Right.getPrecedence() != prec::Assignment))
2856  return true;
2857  if (Left.is(TT_ArrayInitializerLSquare))
2858  return true;
2859  if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2860  return true;
2861  if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2862  !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2865  Left.getPrecedence() == prec::Assignment))
2866  return true;
2867  return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2868  tok::kw_class, tok::kw_struct, tok::comment) ||
2869  Right.isMemberAccess() ||
2870  Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2871  tok::colon, tok::l_square, tok::at) ||
2872  (Left.is(tok::r_paren) &&
2873  Right.isOneOf(tok::identifier, tok::kw_const)) ||
2874  (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
2875  (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
2876 }
2877 
2878 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2879  llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
2880  const FormatToken *Tok = Line.First;
2881  while (Tok) {
2882  llvm::errs() << " M=" << Tok->MustBreakBefore
2883  << " C=" << Tok->CanBreakBefore
2884  << " T=" << getTokenTypeName(Tok->Type)
2885  << " S=" << Tok->SpacesRequiredBefore
2886  << " B=" << Tok->BlockParameterCount
2887  << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
2888  << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
2889  << " PPK=" << Tok->PackingKind << " FakeLParens=";
2890  for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2891  llvm::errs() << Tok->FakeLParens[i] << "/";
2892  llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
2893  llvm::errs() << " Text='" << Tok->TokenText << "'\n";
2894  if (!Tok->Next)
2895  assert(Tok == Line.Last);
2896  Tok = Tok->Next;
2897  }
2898  llvm::errs() << "----\n";
2899 }
2900 
2901 } // namespace format
2902 } // namespace clang
Always break after the return type of top-level definitions.
Definition: Format.h:328
bool endsSequence(A K1, Ts... Tokens) const
true if this token ends a sequence with the given tokens in order, following the Previous pointers...
Definition: FormatToken.h:325
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
unsigned NestingLevel
The nesting level of this token, i.e.
Definition: FormatToken.h:228
unsigned PenaltyBreakBeforeFirstCallParameter
The penalty for breaking a function call after call(.
Definition: Format.h:1290
Token Tok
The Token.
Definition: FormatToken.h:124
Should be used for Protocol Buffers (https://developers.google.com/protocol-buffers/).
Definition: Format.h:1175
Defines the SourceManager interface.
std::unique_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token&#39;s formatting...
Definition: FormatToken.h:204
Break constructor initializers before the colon and commas, and align the commas with the colon...
Definition: Format.h:810
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
Definition: FormatToken.h:215
static LLVM_ATTRIBUTE_UNUSED void printDebugInfo(const UnwrappedLine &Line, StringRef Prefix="")
bool isMemberAccess() const
Returns true if this is a "." or "->" accessing a member.
Definition: FormatToken.h:367
bool isFunctionLikeKeyword() const
Returns true if this is a keyword that can be used like a function call (e.g.
Definition: FormatToken.h:401
const FormatToken * getNextNonComment() const
Returns the next token ignoring comments.
Definition: FormatToken.h:456
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
bool SpaceAfterTemplateKeyword
If true, a space will be inserted after the &#39;template&#39; keyword.
Definition: Format.h:1372
PointerAlignmentStyle PointerAlignment
Pointer and reference alignment style.
Definition: Format.h:1328
Align pointer to the left.
Definition: Format.h:1314
Should be used for C, C++.
Definition: Format.h:1166
bool IsMultiline
Whether the token text contains newlines (escaped or not).
Definition: FormatToken.h:153
bool AfterEnum
Wrap enum definitions.
Definition: Format.h:621
unsigned TotalLength
The total length of the unwrapped line up to and including this token.
Definition: FormatToken.h:211
bool isBinaryOperator() const
Definition: FormatToken.h:389
unsigned NewlinesBefore
The number of newlines immediately before the Token.
Definition: FormatToken.h:130
FormatToken * Next
The next token in the unwrapped line.
Definition: FormatToken.h:283
Break after operators.
Definition: Format.h:406
bool isLiteral() const
Return true if this is a "literal", like a numeric constant, string, etc.
Definition: Token.h:113
bool CanBeExpression
tok::TokenKind ContextKind
unsigned UnbreakableTailLength
The length of following tokens until the next natural split point, or the next token that can be brok...
Definition: FormatToken.h:219
bool closesScope() const
Returns whether Tok is )]} or a template closing >.
Definition: FormatToken.h:359
bool JavaScriptWrapImports
Whether to wrap JavaScript import/export statements.
Definition: Format.h:1145
Always break after the return type.
Definition: Format.h:288
unsigned SplitPenalty
Penalty for inserting a line break before this token.
Definition: FormatToken.h:234
bool ColonIsForRangeExpr
prec::Level getPrecedence() const
Definition: FormatToken.h:443
unsigned ParameterCount
Number of parameters, if this is "(", "[" or "<".
Definition: FormatToken.h:192
unsigned FakeRParens
Insert this many fake ) after this token for correct indentation.
Definition: FormatToken.h:250
bool SpaceInEmptyParentheses
If true, spaces may be inserted into ().
Definition: Format.h:1430
bool CanBreakBefore
true if it is allowed to break before this token.
Definition: FormatToken.h:182
Should be used for Java.
Definition: Format.h:1168
FormatToken * Previous
The previous token in the unwrapped line.
Definition: FormatToken.h:280
Always break after the return type of function definitions.
Definition: Format.h:316
Only merge functions defined inside a class.
Definition: Format.h:207
This file implements a token annotator, i.e.
bool BreakAfterJavaFieldAnnotations
Break after each annotation on a field in Java files.
Definition: Format.h:830
bool ConstructorInitializerAllOnOneLineOrOnePerLine
If the constructor initializers don&#39;t fit on a line, put each initializer on its own line...
Definition: Format.h:901
unsigned OperatorIndex
Is this is an operator (or "."/"->") in a sequence of operators with the same precedence, contains the 0-based operator index.
Definition: FormatToken.h:260
unsigned SpacesRequiredBefore
The number of spaces that should be inserted before this token.
Definition: FormatToken.h:179
bool isNot(T Kind) const
Definition: FormatToken.h:313
bool SpacesInParentheses
If true, spaces will be inserted after ( and before ).
Definition: Format.h:1478
const FormatToken & Tok
ReturnTypeBreakingStyle AlwaysBreakAfterReturnType
The function declaration return type breaking style to use.
Definition: Format.h:336
unsigned BlockParameterCount
Number of parameters that are nested blocks, if this is "(", "[" or "<".
Definition: FormatToken.h:196
bool InInheritanceList
bool SpaceBeforeAssignmentOperators
If false, spaces will be removed before assignment operators.
Definition: Format.h:1380
SpaceBeforeParensOptions SpaceBeforeParens
Defines in which cases to put a space before opening parentheses.
Definition: Format.h:1418
unsigned PenaltyBreakAssignment
The penalty for breaking around an assignment operator.
Definition: Format.h:1287
const char * getName() const
Definition: Token.h:166
Always put a space before opening parentheses, except when it&#39;s prohibited by the syntax rules (in fu...
Definition: Format.h:1414
bool mightBeFunctionDefinition() const
true if this line looks like a function definition instead of a function declaration.
unsigned ColumnLimit
The column limit.
Definition: Format.h:840
Never merge functions into a single line.
Definition: Format.h:193
FormatToken * getPreviousNonComment() const
Returns the previous token ignoring comments.
Definition: FormatToken.h:448
AnnotatingParser & P
BracketAlignmentStyle AlignAfterOpenBracket
If true, horizontally aligns arguments after an open bracket.
Definition: Format.h:77
NodeId Parent
Definition: ASTDiff.cpp:192
bool isLabelString() const
Returns true if this is a string literal that&#39;s like a label, e.g.
Definition: FormatToken.h:421
bool isOneOf(A K1, B K2) const
Definition: FormatToken.h:306
Break after return type automatically.
Definition: Format.h:272
Only merge empty functions.
Definition: Format.h:215
Should be used for JavaScript.
Definition: Format.h:1170
const AnnotatedLine * Line
StateNode * Previous
SmallVector< AnnotatedLine *, 0 > Children
ParameterPackingKind PackingKind
If this is an opening parenthesis, how are the parameters packed?
Definition: FormatToken.h:207
bool SpacesInContainerLiterals
If true, spaces are inserted inside container literals (e.g.
Definition: Format.h:1464
BraceWrappingFlags BraceWrapping
Control of individual brace wrapping cases.
Definition: Format.h:778
bool SpacesInAngles
If true, spaces will be inserted after < and before > in template argument lists. ...
Definition: Format.h:1455
A wrapper around a Token storing information about the whitespace characters preceding it...
Definition: FormatToken.h:120
void setCommentLineLevels(SmallVectorImpl< AnnotatedLine *> &Lines)
Adapts the indent levels of comment lines to the indent of the subsequent line.
static unsigned maxNestingDepth(const AnnotatedLine &Line)
FormatToken * FirstStartOfName
SourceLocation getEnd() const
bool isTrailingComment() const
Definition: FormatToken.h:394
void annotate(AnnotatedLine &Line)
Don&#39;t align, instead use ContinuationIndentWidth, e.g.
Definition: Format.h:63
const char * getTokenTypeName(TokenType Type)
Determines the name of a token type.
Definition: FormatToken.cpp:25
static bool isAllmanBrace(const FormatToken &Tok)
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:297
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177
Break constructor initializers after the colon and commas.
Definition: Format.h:817
bool BreakBeforeTernaryOperators
If true, ternary operators will be placed after line breaks.
Definition: Format.h:792
SourceRange WhitespaceRange
The range of the whitespace immediately preceding the Token.
Definition: FormatToken.h:137
bool AlwaysBreakTemplateDeclarations
If true, always break after the template<...> of a template declaration.
Definition: Format.h:359
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
bool SpacesInCStyleCastParentheses
If true, spaces may be inserted into C style casts.
Definition: Format.h:1471
bool IsUnterminatedLiteral
Set to true if this token is an unterminated literal.
Definition: FormatToken.h:171
bool startsWith(Ts... Tokens) const
true if this line starts with the given tokens in order, ignoring comments.
bool SpacesInSquareBrackets
If true, spaces will be inserted after [ and before ].
Definition: Format.h:1487
StringRef TokenText
The raw text of the token.
Definition: FormatToken.h:168
SmallVector< prec::Level, 4 > FakeLParens
Stores the number of required fake parentheses and the corresponding operator precedence.
Definition: FormatToken.h:248
tok::ObjCKeywordKind getObjCKeywordID() const
Return the ObjC keyword kind.
Definition: Lexer.cpp:55
bool isSimpleTypeSpecifier() const
Determine whether the token is a simple-type-specifier.
Definition: FormatToken.cpp:40
Never put a space before opening parentheses.
Definition: Format.h:1392
unsigned PenaltyReturnTypeOnItsOwnLine
Penalty for putting the return type of a function onto its own line.
Definition: Format.h:1306
unsigned IndentLevel
The indent level of this token. Copied from the surrounding line.
Definition: FormatToken.h:231
LanguageKind Language
Language, this format style is targeted at.
Definition: Format.h:1185
bool ColonIsObjCMethodExpr
Dataflow Directional Tag Classes.
ShortFunctionStyle AllowShortFunctionsOnASingleLine
Dependent on the value, int f() { return 0; } can be put on a single line.
Definition: Format.h:239
unsigned ColumnWidth
The width of the non-whitespace parts of the token (or its first line for multi-line tokens) in colum...
Definition: FormatToken.h:146
Use C++03-compatible syntax.
Definition: Format.h:1492
Always break after the return types of top-level functions.
Definition: Format.h:301
bool IsExpression
Use features of C++11, C++14 and C++1z (e.g.
Definition: Format.h:1495
bool Cpp11BracedListStyle
If true, format braced lists as best suited for C++11 braced lists.
Definition: Format.h:937
static bool isFunctionDeclarationName(const FormatToken &Current, const AnnotatedLine &Line)
bool AfterStruct
Wrap struct definitions.
Definition: Format.h:669
void calculateFormattingInformation(AnnotatedLine &Line)
bool SpaceAfterCStyleCast
If true, a space is inserted after C style casts.
Definition: Format.h:1365
bool BreakBeforeInheritanceComma
If true, in the class inheritance expression clang-format will break before : and ...
Definition: Format.h:860
Should be used for Objective-C, Objective-C++.
Definition: Format.h:1172
LanguageStandard Standard
Format compatible with this standard, e.g.
Definition: Format.h:1502
FormatToken * NextOperator
If this is an operator (or "."/"->") in a sequence of operators with the same precedence, points to the next operator.
Definition: FormatToken.h:264
BreakConstructorInitializersStyle BreakConstructorInitializers
The constructor initializers style to use.
Definition: Format.h:821
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
unsigned BindingStrength
bool ClosesTemplateDeclaration
true if this is the ">" of "template<..>".
Definition: FormatToken.h:185
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
Definition: FormatToken.h:277
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
Definition: FormatToken.h:287
FormatToken * FirstObjCSelectorName
bool InTemplateArgument
bool ColonIsDictLiteral
The parameter type of a method or function.
BinaryOperatorStyle BreakBeforeBinaryOperators
The way to wrap binary operators.
Definition: Format.h:434
bool opensBlockOrBlockTypeList(const FormatStyle &Style) const
Returns true if this tokens starts a block-type list, i.e.
Definition: FormatToken.h:465
Break before operators.
Definition: Format.h:430
bool ObjCSpaceBeforeProtocolList
Add a space in front of an Objective-C protocol list, i.e.
Definition: Format.h:1284
unsigned SpacesBeforeTrailingComments
The number of spaces before trailing line comments (// - comments).
Definition: Format.h:1446
bool opensScope() const
Returns whether Tok is ([{ or a template opening <.
Definition: FormatToken.h:352
bool AllowShortBlocksOnASingleLine
Allows contracting simple braced statements to a single line.
Definition: Format.h:174
unsigned LongestObjCSelectorName
bool MustBreakBefore
Whether there must be a line break before this token.
Definition: FormatToken.h:162
bool AfterClass
Wrap class definitions.
Definition: Format.h:591
Should be used for Protocol Buffer messages in text format (https://developers.google.com/protocol-buffers/).
Definition: Format.h:1180
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
Align pointer to the right.
Definition: Format.h:1319
unsigned BindingStrength
The binding strength of a token.
Definition: FormatToken.h:224
bool CaretFound
bool InCtorInitializer
bool isStringLiteral() const
Definition: FormatToken.h:329
SourceLocation getBegin() const
unsigned MaxEmptyLinesToKeep
The maximum number of consecutive empty lines to keep.
Definition: Format.h:1229
bool HasUnescapedNewline
Whether there is at least one unescaped newline before the Token.
Definition: FormatToken.h:134
BraceBlockKind BlockKind
Contains the kind of block if this token is a brace.
Definition: FormatToken.h:174
bool PartOfMultiVariableDeclStmt
Is this token part of a DeclStmt defining multiple variables?
Definition: FormatToken.h:269
bool IsForEachMacro
const FormatStyle & Style