head	1.1;
branch	1.1.1;
access;
symbols
	netbsd-11-0-RC4:1.1.1.13
	netbsd-11-0-RC3:1.1.1.13
	netbsd-11-0-RC2:1.1.1.13
	netbsd-11-0-RC1:1.1.1.13
	perseant-exfatfs-base-20250801:1.1.1.13
	netbsd-11:1.1.1.13.0.10
	netbsd-11-base:1.1.1.13
	netbsd-10-1-RELEASE:1.1.1.13
	perseant-exfatfs-base-20240630:1.1.1.13
	perseant-exfatfs:1.1.1.13.0.8
	perseant-exfatfs-base:1.1.1.13
	netbsd-8-3-RELEASE:1.1.1.10
	netbsd-9-4-RELEASE:1.1.1.12
	netbsd-10-0-RELEASE:1.1.1.13
	netbsd-10-0-RC6:1.1.1.13
	netbsd-10-0-RC5:1.1.1.13
	netbsd-10-0-RC4:1.1.1.13
	netbsd-10-0-RC3:1.1.1.13
	netbsd-10-0-RC2:1.1.1.13
	netbsd-10-0-RC1:1.1.1.13
	netbsd-10:1.1.1.13.0.6
	netbsd-10-base:1.1.1.13
	netbsd-9-3-RELEASE:1.1.1.12
	cjep_sun2x:1.1.1.13.0.4
	cjep_sun2x-base:1.1.1.13
	cjep_staticlib_x-base1:1.1.1.13
	netbsd-9-2-RELEASE:1.1.1.12
	cjep_staticlib_x:1.1.1.13.0.2
	cjep_staticlib_x-base:1.1.1.13
	netbsd-9-1-RELEASE:1.1.1.12
	phil-wifi-20200421:1.1.1.13
	phil-wifi-20200411:1.1.1.13
	phil-wifi-20200406:1.1.1.13
	netbsd-8-2-RELEASE:1.1.1.10
	netbsd-9-0-RELEASE:1.1.1.12
	netbsd-9-0-RC2:1.1.1.12
	netbsd-9-0-RC1:1.1.1.12
	netbsd-9:1.1.1.12.0.2
	netbsd-9-base:1.1.1.12
	phil-wifi-20190609:1.1.1.12
	netbsd-8-1-RELEASE:1.1.1.10
	netbsd-8-1-RC1:1.1.1.10
	pgoyette-compat-merge-20190127:1.1.1.11.2.1
	pgoyette-compat-20190127:1.1.1.12
	pgoyette-compat-20190118:1.1.1.12
	pgoyette-compat-1226:1.1.1.12
	pgoyette-compat-1126:1.1.1.12
	pgoyette-compat-1020:1.1.1.12
	pgoyette-compat-0930:1.1.1.12
	pgoyette-compat-0906:1.1.1.12
	netbsd-7-2-RELEASE:1.1.1.7.2.1
	pgoyette-compat-0728:1.1.1.12
	clang-337282:1.1.1.12
	netbsd-8-0-RELEASE:1.1.1.10
	phil-wifi:1.1.1.11.0.4
	phil-wifi-base:1.1.1.11
	pgoyette-compat-0625:1.1.1.11
	netbsd-8-0-RC2:1.1.1.10
	pgoyette-compat-0521:1.1.1.11
	pgoyette-compat-0502:1.1.1.11
	pgoyette-compat-0422:1.1.1.11
	netbsd-8-0-RC1:1.1.1.10
	pgoyette-compat-0415:1.1.1.11
	pgoyette-compat-0407:1.1.1.11
	pgoyette-compat-0330:1.1.1.11
	pgoyette-compat-0322:1.1.1.11
	pgoyette-compat-0315:1.1.1.11
	netbsd-7-1-2-RELEASE:1.1.1.7.2.1
	pgoyette-compat:1.1.1.11.0.2
	pgoyette-compat-base:1.1.1.11
	netbsd-7-1-1-RELEASE:1.1.1.7.2.1
	clang-319952:1.1.1.11
	matt-nb8-mediatek:1.1.1.10.0.10
	matt-nb8-mediatek-base:1.1.1.10
	clang-309604:1.1.1.11
	perseant-stdc-iso10646:1.1.1.10.0.8
	perseant-stdc-iso10646-base:1.1.1.10
	netbsd-8:1.1.1.10.0.6
	netbsd-8-base:1.1.1.10
	prg-localcount2-base3:1.1.1.10
	prg-localcount2-base2:1.1.1.10
	prg-localcount2-base1:1.1.1.10
	prg-localcount2:1.1.1.10.0.4
	prg-localcount2-base:1.1.1.10
	pgoyette-localcount-20170426:1.1.1.10
	bouyer-socketcan-base1:1.1.1.10
	pgoyette-localcount-20170320:1.1.1.10
	netbsd-7-1:1.1.1.7.2.1.0.6
	netbsd-7-1-RELEASE:1.1.1.7.2.1
	netbsd-7-1-RC2:1.1.1.7.2.1
	clang-294123:1.1.1.10
	netbsd-7-nhusb-base-20170116:1.1.1.7.2.1
	bouyer-socketcan:1.1.1.10.0.2
	bouyer-socketcan-base:1.1.1.10
	clang-291444:1.1.1.10
	pgoyette-localcount-20170107:1.1.1.9
	netbsd-7-1-RC1:1.1.1.7.2.1
	pgoyette-localcount-20161104:1.1.1.9
	netbsd-7-0-2-RELEASE:1.1.1.7.2.1
	localcount-20160914:1.1.1.9
	netbsd-7-nhusb:1.1.1.7.2.1.0.4
	netbsd-7-nhusb-base:1.1.1.7.2.1
	clang-280599:1.1.1.9
	pgoyette-localcount-20160806:1.1.1.9
	pgoyette-localcount-20160726:1.1.1.9
	pgoyette-localcount:1.1.1.9.0.2
	pgoyette-localcount-base:1.1.1.9
	netbsd-7-0-1-RELEASE:1.1.1.7.2.1
	clang-261930:1.1.1.9
	netbsd-7-0:1.1.1.7.2.1.0.2
	netbsd-7-0-RELEASE:1.1.1.7.2.1
	netbsd-7-0-RC3:1.1.1.7.2.1
	netbsd-7-0-RC2:1.1.1.7.2.1
	netbsd-7-0-RC1:1.1.1.7.2.1
	clang-237755:1.1.1.8
	clang-232565:1.1.1.8
	clang-227398:1.1.1.8
	tls-maxphys-base:1.1.1.7
	tls-maxphys:1.1.1.7.0.4
	netbsd-7:1.1.1.7.0.2
	netbsd-7-base:1.1.1.7
	clang-215315:1.1.1.7
	clang-209886:1.1.1.6
	yamt-pagecache:1.1.1.5.0.4
	yamt-pagecache-base9:1.1.1.5
	tls-earlyentropy:1.1.1.5.0.2
	tls-earlyentropy-base:1.1.1.6
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.1.1.5
	riastradh-drm2-base3:1.1.1.5
	clang-202566:1.1.1.5
	clang-201163:1.1.1.4
	clang-199312:1.1.1.3
	clang-198450:1.1.1.2
	clang-196603:1.1.1.1
	clang-195771:1.1.1.1
	LLVM:1.1.1;
locks; strict;
comment	@// @;


1.1
date	2013.11.28.14.14.52;	author joerg;	state Exp;
branches
	1.1.1.1;
next	;
commitid	ow8OybrawrB1f3fx;

1.1.1.1
date	2013.11.28.14.14.52;	author joerg;	state Exp;
branches;
next	1.1.1.2;
commitid	ow8OybrawrB1f3fx;

1.1.1.2
date	2014.01.05.15.39.25;	author joerg;	state Exp;
branches;
next	1.1.1.3;
commitid	wh3aCSIWykURqWjx;

1.1.1.3
date	2014.01.15.21.26.24;	author joerg;	state Exp;
branches;
next	1.1.1.4;
commitid	NQXlzzA0SPkc5glx;

1.1.1.4
date	2014.02.14.20.07.24;	author joerg;	state Exp;
branches;
next	1.1.1.5;
commitid	annVkZ1sc17rF6px;

1.1.1.5
date	2014.03.04.19.54.54;	author joerg;	state Exp;
branches
	1.1.1.5.2.1
	1.1.1.5.4.1;
next	1.1.1.6;
commitid	29z1hJonZISIXprx;

1.1.1.6
date	2014.05.30.18.14.41;	author joerg;	state Exp;
branches;
next	1.1.1.7;
commitid	8q0kdlBlCn09GACx;

1.1.1.7
date	2014.08.10.17.08.34;	author joerg;	state Exp;
branches
	1.1.1.7.2.1
	1.1.1.7.4.1;
next	1.1.1.8;
commitid	N85tXAN6Ex9VZPLx;

1.1.1.8
date	2015.01.29.19.57.30;	author joerg;	state Exp;
branches;
next	1.1.1.9;
commitid	mlISSizlPKvepX7y;

1.1.1.9
date	2016.02.27.22.12.04;	author joerg;	state Exp;
branches
	1.1.1.9.2.1;
next	1.1.1.10;
commitid	tIimz3oDlh1NpBWy;

1.1.1.10
date	2017.01.11.10.33.39;	author joerg;	state Exp;
branches;
next	1.1.1.11;
commitid	CNnUNfII1jgNmxBz;

1.1.1.11
date	2017.08.01.19.34.53;	author joerg;	state Exp;
branches
	1.1.1.11.2.1
	1.1.1.11.4.1;
next	1.1.1.12;
commitid	pMuDy65V0VicSx1A;

1.1.1.12
date	2018.07.17.18.30.58;	author joerg;	state Exp;
branches;
next	1.1.1.13;
commitid	wDzL46ALjrCZgwKA;

1.1.1.13
date	2019.11.13.22.19.23;	author joerg;	state dead;
branches;
next	;
commitid	QD8YATxuNG34YJKB;

1.1.1.5.2.1
date	2014.08.10.07.08.08;	author tls;	state Exp;
branches;
next	;
commitid	t01A1TLTYxkpGMLx;

1.1.1.5.4.1
date	2014.03.04.19.54.54;	author yamt;	state dead;
branches;
next	1.1.1.5.4.2;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.5.4.2
date	2014.05.22.16.18.27;	author yamt;	state Exp;
branches;
next	;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.7.2.1
date	2015.06.04.20.04.28;	author snj;	state Exp;
branches;
next	;
commitid	yRnjq9fueSo6n9oy;

1.1.1.7.4.1
date	2014.08.10.17.08.34;	author tls;	state dead;
branches;
next	1.1.1.7.4.2;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.7.4.2
date	2014.08.19.23.47.28;	author tls;	state Exp;
branches;
next	;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.9.2.1
date	2017.03.20.06.52.38;	author pgoyette;	state Exp;
branches;
next	;
commitid	jjw7cAwgyKq7RfKz;

1.1.1.11.2.1
date	2018.07.28.04.33.19;	author pgoyette;	state Exp;
branches;
next	;
commitid	1UP1xAIUxv1ZgRLA;

1.1.1.11.4.1
date	2019.06.10.21.45.23;	author christos;	state Exp;
branches;
next	1.1.1.11.4.2;
commitid	jtc8rnCzWiEEHGqB;

1.1.1.11.4.2
date	2020.04.13.07.46.33;	author martin;	state dead;
branches;
next	;
commitid	X01YhRUPVUDaec4C;


desc
@@


1.1
log
@Initial revision
@
text
@//===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a token annotator, i.e. creates
/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
///
//===----------------------------------------------------------------------===//

#include "TokenAnnotator.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/Debug.h"

namespace clang {
namespace format {

namespace {

/// \brief A parser that gathers additional information about tokens.
///
/// The \c TokenAnnotator tries to match parenthesis and square brakets and
/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
/// into template parameter lists.
class AnnotatingParser {
public:
  AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
                   IdentifierInfo &Ident_in)
      : Style(Style), Line(Line), CurrentToken(Line.First),
        KeywordVirtualFound(false), AutoFound(false), Ident_in(Ident_in) {
    Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
  }

private:
  bool parseAngle() {
    if (CurrentToken == NULL)
      return false;
    ScopedContextCreator ContextCreator(*this, tok::less, 10);
    FormatToken *Left = CurrentToken->Previous;
    Contexts.back().IsExpression = false;
    while (CurrentToken != NULL) {
      if (CurrentToken->is(tok::greater)) {
        Left->MatchingParen = CurrentToken;
        CurrentToken->MatchingParen = Left;
        CurrentToken->Type = TT_TemplateCloser;
        next();
        return true;
      }
      if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace,
                                tok::question, tok::colon))
        return false;
      // If a && or || is found and interpreted as a binary operator, this set
      // of angles is likely part of something like "a < b && c > d". If the
      // angles are inside an expression, the ||/&& might also be a binary
      // operator that was misinterpreted because we are parsing template
      // parameters.
      // FIXME: This is getting out of hand, write a decent parser.
      if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
          (CurrentToken->Previous->Type == TT_BinaryOperator ||
           Contexts[Contexts.size() - 2].IsExpression) &&
          Line.First->isNot(tok::kw_template))
        return false;
      updateParameterCount(Left, CurrentToken);
      if (!consumeToken())
        return false;
    }
    return false;
  }

  bool parseParens(bool LookForDecls = false) {
    if (CurrentToken == NULL)
      return false;
    ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);

    // FIXME: This is a bit of a hack. Do better.
    Contexts.back().ColonIsForRangeExpr =
        Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;

    bool StartsObjCMethodExpr = false;
    FormatToken *Left = CurrentToken->Previous;
    if (CurrentToken->is(tok::caret)) {
      // ^( starts a block.
      Left->Type = TT_ObjCBlockLParen;
    } else if (FormatToken *MaybeSel = Left->Previous) {
      // @@selector( starts a selector.
      if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
          MaybeSel->Previous->is(tok::at)) {
        StartsObjCMethodExpr = true;
      }
    }

    if (Left->Previous && Left->Previous->isOneOf(tok::kw_static_assert,
                                                  tok::kw_if, tok::kw_while)) {
      // static_assert, if and while usually contain expressions.
      Contexts.back().IsExpression = true;
    } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
               Left->Previous->MatchingParen &&
               Left->Previous->MatchingParen->Type == TT_LambdaLSquare) {
      // This is a parameter list of a lambda expression.
      Contexts.back().IsExpression = false;
    }

    if (StartsObjCMethodExpr) {
      Contexts.back().ColonIsObjCMethodExpr = true;
      Left->Type = TT_ObjCMethodExpr;
    }

    bool MightBeFunctionType = CurrentToken->is(tok::star);
    bool HasMultipleLines = false;
    bool HasMultipleParametersOnALine = false;
    while (CurrentToken != NULL) {
      // LookForDecls is set when "if (" has been seen. Check for
      // 'identifier' '*' 'identifier' followed by not '=' -- this
      // '*' has to be a binary operator but determineStarAmpUsage() will
      // categorize it as an unary operator, so set the right type here.
      if (LookForDecls && CurrentToken->Next) {
        FormatToken *Prev = CurrentToken->getPreviousNonComment();
        if (Prev) {
          FormatToken *PrevPrev = Prev->getPreviousNonComment();
          FormatToken *Next = CurrentToken->Next;
          if (PrevPrev && PrevPrev->is(tok::identifier) &&
              Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
              CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
            Prev->Type = TT_BinaryOperator;
            LookForDecls = false;
          }
        }
      }

      if (CurrentToken->Previous->Type == TT_PointerOrReference &&
          CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
                                                    tok::coloncolon))
        MightBeFunctionType = true;
      if (CurrentToken->is(tok::r_paren)) {
        if (MightBeFunctionType && CurrentToken->Next &&
            (CurrentToken->Next->is(tok::l_paren) ||
             (CurrentToken->Next->is(tok::l_square) &&
              !Contexts.back().IsExpression)))
          Left->Type = TT_FunctionTypeLParen;
        Left->MatchingParen = CurrentToken;
        CurrentToken->MatchingParen = Left;

        if (StartsObjCMethodExpr) {
          CurrentToken->Type = TT_ObjCMethodExpr;
          if (Contexts.back().FirstObjCSelectorName != NULL) {
            Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
                Contexts.back().LongestObjCSelectorName;
          }
        }

        if (!HasMultipleLines)
          Left->PackingKind = PPK_Inconclusive;
        else if (HasMultipleParametersOnALine)
          Left->PackingKind = PPK_BinPacked;
        else
          Left->PackingKind = PPK_OnePerLine;

        next();
        return true;
      }
      if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
        return false;
      updateParameterCount(Left, CurrentToken);
      if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
          !CurrentToken->Next->HasUnescapedNewline &&
          !CurrentToken->Next->isTrailingComment())
        HasMultipleParametersOnALine = true;
      if (!consumeToken())
        return false;
      if (CurrentToken && CurrentToken->HasUnescapedNewline)
        HasMultipleLines = true;
    }
    return false;
  }

  bool parseSquare() {
    if (!CurrentToken)
      return false;

    // A '[' could be an index subscript (after an identifier or after
    // ')' or ']'), it could be the start of an Objective-C method
    // expression, or it could the the start of an Objective-C array literal.
    FormatToken *Left = CurrentToken->Previous;
    FormatToken *Parent = Left->getPreviousNonComment();
    bool StartsObjCMethodExpr =
        Contexts.back().CanBeExpression && Left->Type != TT_LambdaLSquare &&
        (!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
                                    tok::kw_return, tok::kw_throw) ||
         Parent->isUnaryOperator() || Parent->Type == TT_ObjCForIn ||
         Parent->Type == TT_CastRParen ||
         getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
    ScopedContextCreator ContextCreator(*this, tok::l_square, 10);
    Contexts.back().IsExpression = true;
    bool ColonFound = false;

    if (StartsObjCMethodExpr) {
      Contexts.back().ColonIsObjCMethodExpr = true;
      Left->Type = TT_ObjCMethodExpr;
    } else if (Parent && Parent->is(tok::at)) {
      Left->Type = TT_ArrayInitializerLSquare;
    } else if (Left->Type == TT_Unknown) {
      Left->Type = TT_ArraySubscriptLSquare;
    }

    while (CurrentToken != NULL) {
      if (CurrentToken->is(tok::r_square)) {
        if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
            Left->Type == TT_ObjCMethodExpr) {
          // An ObjC method call is rarely followed by an open parenthesis.
          // FIXME: Do we incorrectly label ":" with this?
          StartsObjCMethodExpr = false;
          Left->Type = TT_Unknown;
        }
        if (StartsObjCMethodExpr) {
          CurrentToken->Type = TT_ObjCMethodExpr;
          // determineStarAmpUsage() thinks that '*' '[' is allocating an
          // array of pointers, but if '[' starts a selector then '*' is a
          // binary operator.
          if (Parent != NULL && Parent->Type == TT_PointerOrReference)
            Parent->Type = TT_BinaryOperator;
        }
        Left->MatchingParen = CurrentToken;
        CurrentToken->MatchingParen = Left;
        if (Contexts.back().FirstObjCSelectorName != NULL)
          Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
              Contexts.back().LongestObjCSelectorName;
        next();
        return true;
      }
      if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
        return false;
      if (CurrentToken->is(tok::colon))
        ColonFound = true;
      if (CurrentToken->is(tok::comma) &&
          (Left->Type == TT_ArraySubscriptLSquare ||
           (Left->Type == TT_ObjCMethodExpr && !ColonFound)))
        Left->Type = TT_ArrayInitializerLSquare;
      updateParameterCount(Left, CurrentToken);
      if (!consumeToken())
        return false;
    }
    return false;
  }

  bool parseBrace() {
    if (CurrentToken != NULL) {
      FormatToken *Left = CurrentToken->Previous;
      ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
      Contexts.back().ColonIsDictLiteral = true;

      while (CurrentToken != NULL) {
        if (CurrentToken->is(tok::r_brace)) {
          Left->MatchingParen = CurrentToken;
          CurrentToken->MatchingParen = Left;
          next();
          return true;
        }
        if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
          return false;
        updateParameterCount(Left, CurrentToken);
        if (CurrentToken->is(tok::colon))
          Left->Type = TT_DictLiteral;
        if (!consumeToken())
          return false;
      }
    }
    // No closing "}" found, this probably starts a definition.
    Line.StartsDefinition = true;
    return true;
  }

  void updateParameterCount(FormatToken *Left, FormatToken *Current) {
    if (Current->is(tok::comma)) {
      ++Left->ParameterCount;
      if (!Left->Role)
        Left->Role.reset(new CommaSeparatedList(Style));
      Left->Role->CommaFound(Current);
    } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
      Left->ParameterCount = 1;
    }
  }

  bool parseConditional() {
    while (CurrentToken != NULL) {
      if (CurrentToken->is(tok::colon)) {
        CurrentToken->Type = TT_ConditionalExpr;
        next();
        return true;
      }
      if (!consumeToken())
        return false;
    }
    return false;
  }

  bool parseTemplateDeclaration() {
    if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
      CurrentToken->Type = TT_TemplateOpener;
      next();
      if (!parseAngle())
        return false;
      if (CurrentToken != NULL)
        CurrentToken->Previous->ClosesTemplateDeclaration = true;
      return true;
    }
    return false;
  }

  bool consumeToken() {
    FormatToken *Tok = CurrentToken;
    next();
    switch (Tok->Tok.getKind()) {
    case tok::plus:
    case tok::minus:
      if (Tok->Previous == NULL && Line.MustBeDeclaration)
        Tok->Type = TT_ObjCMethodSpecifier;
      break;
    case tok::colon:
      if (Tok->Previous == NULL)
        return false;
      // Colons from ?: are handled in parseConditional().
      if (Tok->Previous->is(tok::r_paren) && Contexts.size() == 1) {
        Tok->Type = TT_CtorInitializerColon;
      } else if (Contexts.back().ColonIsDictLiteral) {
        Tok->Type = TT_DictLiteral;
      } else if (Contexts.back().ColonIsObjCMethodExpr ||
                 Line.First->Type == TT_ObjCMethodSpecifier) {
        Tok->Type = TT_ObjCMethodExpr;
        Tok->Previous->Type = TT_ObjCSelectorName;
        if (Tok->Previous->ColumnWidth >
            Contexts.back().LongestObjCSelectorName) {
          Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
        }
        if (Contexts.back().FirstObjCSelectorName == NULL)
          Contexts.back().FirstObjCSelectorName = Tok->Previous;
      } else if (Contexts.back().ColonIsForRangeExpr) {
        Tok->Type = TT_RangeBasedForLoopColon;
      } else if (CurrentToken != NULL &&
                 CurrentToken->is(tok::numeric_constant)) {
        Tok->Type = TT_BitFieldColon;
      } else if (Contexts.size() == 1 && Line.First->isNot(tok::kw_enum)) {
        Tok->Type = TT_InheritanceColon;
      } else if (Contexts.back().ContextKind == tok::l_paren) {
        Tok->Type = TT_InlineASMColon;
      }
      break;
    case tok::kw_if:
    case tok::kw_while:
      if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
        next();
        if (!parseParens(/*LookForDecls=*/true))
          return false;
      }
      break;
    case tok::kw_for:
      Contexts.back().ColonIsForRangeExpr = true;
      next();
      if (!parseParens())
        return false;
      break;
    case tok::l_paren:
      if (!parseParens())
        return false;
      if (Line.MustBeDeclaration && Contexts.size() == 1 &&
          !Contexts.back().IsExpression)
        Line.MightBeFunctionDecl = true;
      break;
    case tok::l_square:
      if (!parseSquare())
        return false;
      break;
    case tok::l_brace:
      if (!parseBrace())
        return false;
      break;
    case tok::less:
      if (Tok->Previous && !Tok->Previous->Tok.isLiteral() && parseAngle())
        Tok->Type = TT_TemplateOpener;
      else {
        Tok->Type = TT_BinaryOperator;
        CurrentToken = Tok;
        next();
      }
      break;
    case tok::r_paren:
    case tok::r_square:
      return false;
    case tok::r_brace:
      // Lines can start with '}'.
      if (Tok->Previous != NULL)
        return false;
      break;
    case tok::greater:
      Tok->Type = TT_BinaryOperator;
      break;
    case tok::kw_operator:
      while (CurrentToken &&
             !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
        if (CurrentToken->isOneOf(tok::star, tok::amp))
          CurrentToken->Type = TT_PointerOrReference;
        consumeToken();
        if (CurrentToken && CurrentToken->Previous->Type == TT_BinaryOperator)
          CurrentToken->Previous->Type = TT_OverloadedOperator;
      }
      if (CurrentToken) {
        CurrentToken->Type = TT_OverloadedOperatorLParen;
        if (CurrentToken->Previous->Type == TT_BinaryOperator)
          CurrentToken->Previous->Type = TT_OverloadedOperator;
      }
      break;
    case tok::question:
      parseConditional();
      break;
    case tok::kw_template:
      parseTemplateDeclaration();
      break;
    case tok::identifier:
      if (Line.First->is(tok::kw_for) &&
          Tok->Tok.getIdentifierInfo() == &Ident_in)
        Tok->Type = TT_ObjCForIn;
      break;
    case tok::comma:
      if (Contexts.back().FirstStartOfName)
        Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
      if (Contexts.back().InCtorInitializer)
        Tok->Type = TT_CtorInitializerComma;
      break;
    default:
      break;
    }
    return true;
  }

  void parseIncludeDirective() {
    next();
    if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
      next();
      while (CurrentToken != NULL) {
        if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
          CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
    } else {
      while (CurrentToken != NULL) {
        if (CurrentToken->is(tok::string_literal))
          // Mark these string literals as "implicit" literals, too, so that
          // they are not split or line-wrapped.
          CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
    }
  }

  void parseWarningOrError() {
    next();
    // We still want to format the whitespace left of the first token of the
    // warning or error.
    next();
    while (CurrentToken != NULL) {
      CurrentToken->Type = TT_ImplicitStringLiteral;
      next();
    }
  }

  void parsePreprocessorDirective() {
    next();
    if (CurrentToken == NULL)
      return;
    if (CurrentToken->Tok.is(tok::numeric_constant)) {
      CurrentToken->SpacesRequiredBefore = 1;
      return;
    }
    // Hashes in the middle of a line can lead to any strange token
    // sequence.
    if (CurrentToken->Tok.getIdentifierInfo() == NULL)
      return;
    switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
    case tok::pp_include:
    case tok::pp_import:
      parseIncludeDirective();
      break;
    case tok::pp_error:
    case tok::pp_warning:
      parseWarningOrError();
      break;
    case tok::pp_if:
    case tok::pp_elif:
      parseLine();
      break;
    default:
      break;
    }
    while (CurrentToken != NULL)
      next();
  }

public:
  LineType parseLine() {
    if (CurrentToken->is(tok::hash)) {
      parsePreprocessorDirective();
      return LT_PreprocessorDirective;
    }
    while (CurrentToken != NULL) {
      if (CurrentToken->is(tok::kw_virtual))
        KeywordVirtualFound = true;
      if (!consumeToken())
        return LT_Invalid;
    }
    if (KeywordVirtualFound)
      return LT_VirtualFunctionDecl;

    if (Line.First->Type == TT_ObjCMethodSpecifier) {
      if (Contexts.back().FirstObjCSelectorName != NULL)
        Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
            Contexts.back().LongestObjCSelectorName;
      return LT_ObjCMethodDecl;
    }

    return LT_Other;
  }

private:
  void next() {
    if (CurrentToken != NULL) {
      determineTokenType(*CurrentToken);
      CurrentToken->BindingStrength = Contexts.back().BindingStrength;
    }

    if (CurrentToken != NULL)
      CurrentToken = CurrentToken->Next;

    if (CurrentToken != NULL) {
      // Reset token type in case we have already looked at it and then
      // recovered from an error (e.g. failure to find the matching >).
      if (CurrentToken->Type != TT_LambdaLSquare &&
          CurrentToken->Type != TT_ImplicitStringLiteral)
        CurrentToken->Type = TT_Unknown;
      if (CurrentToken->Role)
        CurrentToken->Role.reset(NULL);
      CurrentToken->FakeLParens.clear();
      CurrentToken->FakeRParens = 0;
    }
  }

  /// \brief A struct to hold information valid in a specific context, e.g.
  /// a pair of parenthesis.
  struct Context {
    Context(tok::TokenKind ContextKind, unsigned BindingStrength,
            bool IsExpression)
        : ContextKind(ContextKind), BindingStrength(BindingStrength),
          LongestObjCSelectorName(0), ColonIsForRangeExpr(false),
          ColonIsDictLiteral(false), ColonIsObjCMethodExpr(false),
          FirstObjCSelectorName(NULL), FirstStartOfName(NULL),
          IsExpression(IsExpression), CanBeExpression(true),
          InCtorInitializer(false) {}

    tok::TokenKind ContextKind;
    unsigned BindingStrength;
    unsigned LongestObjCSelectorName;
    bool ColonIsForRangeExpr;
    bool ColonIsDictLiteral;
    bool ColonIsObjCMethodExpr;
    FormatToken *FirstObjCSelectorName;
    FormatToken *FirstStartOfName;
    bool IsExpression;
    bool CanBeExpression;
    bool InCtorInitializer;
  };

  /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
  /// of each instance.
  struct ScopedContextCreator {
    AnnotatingParser &P;

    ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
                         unsigned Increase)
        : P(P) {
      P.Contexts.push_back(Context(ContextKind,
                                   P.Contexts.back().BindingStrength + Increase,
                                   P.Contexts.back().IsExpression));
    }

    ~ScopedContextCreator() { P.Contexts.pop_back(); }
  };

  void determineTokenType(FormatToken &Current) {
    if (Current.getPrecedence() == prec::Assignment &&
        !Line.First->isOneOf(tok::kw_template, tok::kw_using) &&
        (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
      Contexts.back().IsExpression = true;
      for (FormatToken *Previous = Current.Previous;
           Previous && !Previous->isOneOf(tok::comma, tok::semi);
           Previous = Previous->Previous) {
        if (Previous->is(tok::r_square))
          Previous = Previous->MatchingParen;
        if (Previous->Type == TT_BinaryOperator &&
            Previous->isOneOf(tok::star, tok::amp)) {
          Previous->Type = TT_PointerOrReference;
        }
      }
    } else if (Current.isOneOf(tok::kw_return, tok::kw_throw) ||
               (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
                !Line.InPPDirective &&
                (!Current.Previous ||
                 !Current.Previous->isOneOf(tok::kw_for, tok::kw_catch)))) {
      Contexts.back().IsExpression = true;
    } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
      for (FormatToken *Previous = Current.Previous;
           Previous && Previous->isOneOf(tok::star, tok::amp);
           Previous = Previous->Previous)
        Previous->Type = TT_PointerOrReference;
    } else if (Current.Previous &&
               Current.Previous->Type == TT_CtorInitializerColon) {
      Contexts.back().IsExpression = true;
      Contexts.back().InCtorInitializer = true;
    } else if (Current.is(tok::kw_new)) {
      Contexts.back().CanBeExpression = false;
    } else if (Current.is(tok::semi) || Current.is(tok::exclaim)) {
      // This should be the condition or increment in a for-loop.
      Contexts.back().IsExpression = true;
    }

    if (Current.Type == TT_Unknown) {
      // Line.MightBeFunctionDecl can only be true after the parentheses of a
      // function declaration have been found. In this case, 'Current' is a
      // trailing token of this declaration and thus cannot be a name.
      if (isStartOfName(Current) && !Line.MightBeFunctionDecl) {
        Contexts.back().FirstStartOfName = &Current;
        Current.Type = TT_StartOfName;
      } else if (Current.is(tok::kw_auto)) {
        AutoFound = true;
      } else if (Current.is(tok::arrow) && AutoFound &&
                 Line.MustBeDeclaration) {
        Current.Type = TT_TrailingReturnArrow;
      } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
        Current.Type =
            determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
                                               Contexts.back().IsExpression);
      } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
        Current.Type = determinePlusMinusCaretUsage(Current);
      } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
        Current.Type = determineIncrementUsage(Current);
      } else if (Current.is(tok::exclaim)) {
        Current.Type = TT_UnaryOperator;
      } else if (Current.isBinaryOperator() &&
                 (!Current.Previous ||
                  Current.Previous->isNot(tok::l_square))) {
        Current.Type = TT_BinaryOperator;
      } else if (Current.is(tok::comment)) {
        if (Current.TokenText.startswith("//"))
          Current.Type = TT_LineComment;
        else
          Current.Type = TT_BlockComment;
      } else if (Current.is(tok::r_paren)) {
        FormatToken *LeftOfParens = NULL;
        if (Current.MatchingParen)
          LeftOfParens = Current.MatchingParen->getPreviousNonComment();
        bool IsCast = false;
        bool ParensAreEmpty = Current.Previous == Current.MatchingParen;
        bool ParensAreType = !Current.Previous ||
                             Current.Previous->Type == TT_PointerOrReference ||
                             Current.Previous->Type == TT_TemplateCloser ||
                             isSimpleTypeSpecifier(*Current.Previous);
        bool ParensCouldEndDecl =
            Current.Next &&
            Current.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
        bool IsSizeOfOrAlignOf =
            LeftOfParens &&
            LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
        if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
            (Contexts.back().IsExpression ||
             (Current.Next && Current.Next->isBinaryOperator())))
          IsCast = true;
        if (Current.Next && Current.Next->isNot(tok::string_literal) &&
            (Current.Next->Tok.isLiteral() ||
             Current.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
          IsCast = true;
        // If there is an identifier after the (), it is likely a cast, unless
        // there is also an identifier before the ().
        if (LeftOfParens && (LeftOfParens->Tok.getIdentifierInfo() == NULL ||
                             LeftOfParens->is(tok::kw_return)) &&
            LeftOfParens->Type != TT_OverloadedOperator &&
            LeftOfParens->Type != TT_TemplateCloser && Current.Next &&
            Current.Next->is(tok::identifier))
          IsCast = true;
        if (IsCast && !ParensAreEmpty)
          Current.Type = TT_CastRParen;
      } else if (Current.is(tok::at) && Current.Next) {
        switch (Current.Next->Tok.getObjCKeywordID()) {
        case tok::objc_interface:
        case tok::objc_implementation:
        case tok::objc_protocol:
          Current.Type = TT_ObjCDecl;
          break;
        case tok::objc_property:
          Current.Type = TT_ObjCProperty;
          break;
        default:
          break;
        }
      } else if (Current.is(tok::period)) {
        FormatToken *PreviousNoComment = Current.getPreviousNonComment();
        if (PreviousNoComment &&
            PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
          Current.Type = TT_DesignatedInitializerPeriod;
      }
    }
  }

  /// \brief Take a guess at whether \p Tok starts a name of a function or
  /// variable declaration.
  ///
  /// This is a heuristic based on whether \p Tok is an identifier following
  /// something that is likely a type.
  bool isStartOfName(const FormatToken &Tok) {
    if (Tok.isNot(tok::identifier) || Tok.Previous == NULL)
      return false;

    // Skip "const" as it does not have an influence on whether this is a name.
    FormatToken *PreviousNotConst = Tok.Previous;
    while (PreviousNotConst != NULL && PreviousNotConst->is(tok::kw_const))
      PreviousNotConst = PreviousNotConst->Previous;

    if (PreviousNotConst == NULL)
      return false;

    bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
                       PreviousNotConst->Previous &&
                       PreviousNotConst->Previous->is(tok::hash);

    if (PreviousNotConst->Type == TT_TemplateCloser)
      return PreviousNotConst && PreviousNotConst->MatchingParen &&
             PreviousNotConst->MatchingParen->Previous &&
             PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);

    return (!IsPPKeyword && PreviousNotConst->is(tok::identifier)) ||
           PreviousNotConst->Type == TT_PointerOrReference ||
           isSimpleTypeSpecifier(*PreviousNotConst);
  }

  /// \brief Return the type of the given token assuming it is * or &.
  TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression) {
    const FormatToken *PrevToken = Tok.getPreviousNonComment();
    if (PrevToken == NULL)
      return TT_UnaryOperator;

    const FormatToken *NextToken = Tok.getNextNonComment();
    if (NextToken == NULL)
      return TT_Unknown;

    if (PrevToken->is(tok::coloncolon) ||
        (PrevToken->is(tok::l_paren) && !IsExpression))
      return TT_PointerOrReference;

    if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
                           tok::comma, tok::semi, tok::kw_return, tok::colon,
                           tok::equal, tok::kw_delete, tok::kw_sizeof) ||
        PrevToken->Type == TT_BinaryOperator ||
        PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
      return TT_UnaryOperator;

    if (NextToken->is(tok::l_square))
      return TT_PointerOrReference;

    if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
        PrevToken->MatchingParen->Previous &&
        PrevToken->MatchingParen->Previous->is(tok::kw_typeof))
      return TT_PointerOrReference;

    if (PrevToken->Tok.isLiteral() ||
        PrevToken->isOneOf(tok::r_paren, tok::r_square) ||
        NextToken->Tok.isLiteral() || NextToken->isUnaryOperator())
      return TT_BinaryOperator;

    // It is very unlikely that we are going to find a pointer or reference type
    // definition on the RHS of an assignment.
    if (IsExpression)
      return TT_BinaryOperator;

    return TT_PointerOrReference;
  }

  TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
    const FormatToken *PrevToken = Tok.getPreviousNonComment();
    if (PrevToken == NULL || PrevToken->Type == TT_CastRParen)
      return TT_UnaryOperator;

    // Use heuristics to recognize unary operators.
    if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
                           tok::question, tok::colon, tok::kw_return,
                           tok::kw_case, tok::at, tok::l_brace))
      return TT_UnaryOperator;

    // There can't be two consecutive binary operators.
    if (PrevToken->Type == TT_BinaryOperator)
      return TT_UnaryOperator;

    // Fall back to marking the token as binary operator.
    return TT_BinaryOperator;
  }

  /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
  TokenType determineIncrementUsage(const FormatToken &Tok) {
    const FormatToken *PrevToken = Tok.getPreviousNonComment();
    if (PrevToken == NULL || PrevToken->Type == TT_CastRParen)
      return TT_UnaryOperator;
    if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
      return TT_TrailingUnaryOperator;

    return TT_UnaryOperator;
  }

  // FIXME: This is copy&pasted from Sema. Put it in a common place and remove
  // duplication.
  /// \brief Determine whether the token kind starts a simple-type-specifier.
  bool isSimpleTypeSpecifier(const FormatToken &Tok) const {
    switch (Tok.Tok.getKind()) {
    case tok::kw_short:
    case tok::kw_long:
    case tok::kw___int64:
    case tok::kw___int128:
    case tok::kw_signed:
    case tok::kw_unsigned:
    case tok::kw_void:
    case tok::kw_char:
    case tok::kw_int:
    case tok::kw_half:
    case tok::kw_float:
    case tok::kw_double:
    case tok::kw_wchar_t:
    case tok::kw_bool:
    case tok::kw___underlying_type:
    case tok::annot_typename:
    case tok::kw_char16_t:
    case tok::kw_char32_t:
    case tok::kw_typeof:
    case tok::kw_decltype:
      return true;
    default:
      return false;
    }
  }

  SmallVector<Context, 8> Contexts;

  const FormatStyle &Style;
  AnnotatedLine &Line;
  FormatToken *CurrentToken;
  bool KeywordVirtualFound;
  bool AutoFound;
  IdentifierInfo &Ident_in;
};

static int PrecedenceUnaryOperator = prec::PointerToMember + 1;
static int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;

/// \brief Parses binary expressions by inserting fake parenthesis based on
/// operator precedence.
class ExpressionParser {
public:
  ExpressionParser(AnnotatedLine &Line) : Current(Line.First) {
    // Skip leading "}", e.g. in "} else if (...) {".
    if (Current->is(tok::r_brace))
      next();
  }

  /// \brief Parse expressions with the given operatore precedence.
  void parse(int Precedence = 0) {
    // Skip 'return' and ObjC selector colons as they are not part of a binary
    // expression.
    while (Current &&
           (Current->is(tok::kw_return) ||
            (Current->is(tok::colon) && Current->Type == TT_ObjCMethodExpr)))
      next();

    if (Current == NULL || Precedence > PrecedenceArrowAndPeriod)
      return;

    // Conditional expressions need to be parsed separately for proper nesting.
    if (Precedence == prec::Conditional) {
      parseConditionalExpr();
      return;
    }

    // Parse unary operators, which all have a higher precedence than binary
    // operators.
    if (Precedence == PrecedenceUnaryOperator) {
      parseUnaryOperator();
      return;
    }

    FormatToken *Start = Current;
    FormatToken *LatestOperator = NULL;

    while (Current) {
      // Consume operators with higher precedence.
      parse(Precedence + 1);

      int CurrentPrecedence = getCurrentPrecedence();

      if (Current && Current->Type == TT_ObjCSelectorName &&
          Precedence == CurrentPrecedence)
        Start = Current;

      // At the end of the line or when an operator with higher precedence is
      // found, insert fake parenthesis and return.
      if (Current == NULL || Current->closesScope() ||
          (CurrentPrecedence != -1 && CurrentPrecedence < Precedence)) {
        if (LatestOperator) {
          if (Precedence == PrecedenceArrowAndPeriod) {
            LatestOperator->LastInChainOfCalls = true;
            // Call expressions don't have a binary operator precedence.
            addFakeParenthesis(Start, prec::Unknown);
          } else {
            addFakeParenthesis(Start, prec::Level(Precedence));
          }
        }
        return;
      }

      // Consume scopes: (), [], <> and {}
      if (Current->opensScope()) {
        while (Current && !Current->closesScope()) {
          next();
          parse();
        }
        next();
      } else {
        // Operator found.
        if (CurrentPrecedence == Precedence)
          LatestOperator = Current;

        next();
      }
    }
  }

private:
  /// \brief Gets the precedence (+1) of the given token for binary operators
  /// and other tokens that we treat like binary operators.
  int getCurrentPrecedence() {
    if (Current) {
      if (Current->Type == TT_ConditionalExpr)
        return prec::Conditional;
      else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon ||
               Current->Type == TT_ObjCSelectorName)
        return 0;
      else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
        return Current->getPrecedence();
      else if (Current->isOneOf(tok::period, tok::arrow))
        return PrecedenceArrowAndPeriod;
    }
    return -1;
  }

  void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
    Start->FakeLParens.push_back(Precedence);
    if (Precedence > prec::Unknown)
      Start->StartsBinaryExpression = true;
    if (Current) {
      ++Current->Previous->FakeRParens;
      if (Precedence > prec::Unknown)
        Current->Previous->EndsBinaryExpression = true;
    }
  }

  /// \brief Parse unary operator expressions and surround them with fake
  /// parentheses if appropriate.
  void parseUnaryOperator() {
    if (Current == NULL || Current->Type != TT_UnaryOperator) {
      parse(PrecedenceArrowAndPeriod);
      return;
    }

    FormatToken *Start = Current;
    next();
    parseUnaryOperator();

    // The actual precedence doesn't matter.
    addFakeParenthesis(Start, prec::Unknown);
  }

  void parseConditionalExpr() {
    FormatToken *Start = Current;
    parse(prec::LogicalOr);
    if (!Current || !Current->is(tok::question))
      return;
    next();
    parse(prec::LogicalOr);
    if (!Current || Current->Type != TT_ConditionalExpr)
      return;
    next();
    parseConditionalExpr();
    addFakeParenthesis(Start, prec::Conditional);
  }

  void next() {
    if (Current)
      Current = Current->Next;
    while (Current && Current->isTrailingComment())
      Current = Current->Next;
  }

  FormatToken *Current;
};

} // end anonymous namespace

void
TokenAnnotator::setCommentLineLevels(SmallVectorImpl<AnnotatedLine *> &Lines) {
  const AnnotatedLine *NextNonCommentLine = NULL;
  for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
                                                          E = Lines.rend();
       I != E; ++I) {
    if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
        (*I)->First->Next == NULL)
      (*I)->Level = NextNonCommentLine->Level;
    else
      NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : NULL;

    setCommentLineLevels((*I)->Children);
  }
}

void TokenAnnotator::annotate(AnnotatedLine &Line) {
  for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
                                                  E = Line.Children.end();
       I != E; ++I) {
    annotate(**I);
  }
  AnnotatingParser Parser(Style, Line, Ident_in);
  Line.Type = Parser.parseLine();
  if (Line.Type == LT_Invalid)
    return;

  ExpressionParser ExprParser(Line);
  ExprParser.parse();

  if (Line.First->Type == TT_ObjCMethodSpecifier)
    Line.Type = LT_ObjCMethodDecl;
  else if (Line.First->Type == TT_ObjCDecl)
    Line.Type = LT_ObjCDecl;
  else if (Line.First->Type == TT_ObjCProperty)
    Line.Type = LT_ObjCProperty;

  Line.First->SpacesRequiredBefore = 1;
  Line.First->CanBreakBefore = Line.First->MustBreakBefore;
}

void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
  Line.First->TotalLength =
      Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
  if (!Line.First->Next)
    return;
  FormatToken *Current = Line.First->Next;
  bool InFunctionDecl = Line.MightBeFunctionDecl;
  while (Current != NULL) {
    if (Current->Type == TT_LineComment)
      Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
    else if (Current->SpacesRequiredBefore == 0 &&
             spaceRequiredBefore(Line, *Current))
      Current->SpacesRequiredBefore = 1;

    Current->MustBreakBefore =
        Current->MustBreakBefore || mustBreakBefore(Line, *Current);

    Current->CanBreakBefore =
        Current->MustBreakBefore || canBreakBefore(Line, *Current);
    if (Current->MustBreakBefore || !Current->Children.empty() ||
        Current->IsMultiline)
      Current->TotalLength = Current->Previous->TotalLength + Style.ColumnLimit;
    else
      Current->TotalLength = Current->Previous->TotalLength +
                             Current->ColumnWidth +
                             Current->SpacesRequiredBefore;

    if (Current->Type == TT_CtorInitializerColon)
      InFunctionDecl = false;

    // FIXME: Only calculate this if CanBreakBefore is true once static
    // initializers etc. are sorted out.
    // FIXME: Move magic numbers to a better place.
    Current->SplitPenalty = 20 * Current->BindingStrength +
                            splitPenalty(Line, *Current, InFunctionDecl);

    Current = Current->Next;
  }

  calculateUnbreakableTailLengths(Line);
  for (Current = Line.First; Current != NULL; Current = Current->Next) {
    if (Current->Role)
      Current->Role->precomputeFormattingInfos(Current);
  }

  DEBUG({ printDebugInfo(Line); });

  for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
                                                  E = Line.Children.end();
       I != E; ++I) {
    calculateFormattingInformation(**I);
  }
}

void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
  unsigned UnbreakableTailLength = 0;
  FormatToken *Current = Line.Last;
  while (Current != NULL) {
    Current->UnbreakableTailLength = UnbreakableTailLength;
    if (Current->CanBreakBefore ||
        Current->isOneOf(tok::comment, tok::string_literal)) {
      UnbreakableTailLength = 0;
    } else {
      UnbreakableTailLength +=
          Current->ColumnWidth + Current->SpacesRequiredBefore;
    }
    Current = Current->Previous;
  }
}

unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
                                      const FormatToken &Tok,
                                      bool InFunctionDecl) {
  const FormatToken &Left = *Tok.Previous;
  const FormatToken &Right = Tok;

  if (Left.is(tok::semi))
    return 0;
  if (Left.is(tok::comma))
    return 1;
  if (Right.is(tok::l_square))
    return 150;

  if (Right.Type == TT_StartOfName || Right.is(tok::kw_operator)) {
    if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
      return 3;
    if (Left.Type == TT_StartOfName)
      return 20;
    if (InFunctionDecl && Right.BindingStrength == 1)
      // FIXME: Clean up hack of using BindingStrength to find top-level names.
      return Style.PenaltyReturnTypeOnItsOwnLine;
    return 200;
  }
  if (Left.is(tok::equal) && Right.is(tok::l_brace))
    return 150;
  if (Left.Type == TT_CastRParen)
    return 100;
  if (Left.is(tok::coloncolon))
    return 500;
  if (Left.isOneOf(tok::kw_class, tok::kw_struct))
    return 5000;

  if (Left.Type == TT_RangeBasedForLoopColon ||
      Left.Type == TT_InheritanceColon)
    return 2;

  if (Right.isMemberAccess()) {
    if (Left.isOneOf(tok::r_paren, tok::r_square) && Left.MatchingParen &&
        Left.MatchingParen->ParameterCount > 0)
      return 20; // Should be smaller than breaking at a nested comma.
    return 150;
  }

  // Breaking before a trailing 'const' or not-function-like annotation is bad.
  if (Left.is(tok::r_paren) && Line.Type != LT_ObjCProperty &&
      (Right.is(tok::kw_const) || (Right.is(tok::identifier) && Right.Next &&
                                   Right.Next->isNot(tok::l_paren))))
    return 100;

  // In for-loops, prefer breaking at ',' and ';'.
  if (Line.First->is(tok::kw_for) && Left.is(tok::equal))
    return 4;

  // In Objective-C method expressions, prefer breaking before "param:" over
  // breaking after it.
  if (Right.Type == TT_ObjCSelectorName)
    return 0;
  if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
    return 50;

  if (Left.is(tok::l_paren) && InFunctionDecl)
    return 100;
  if (Left.opensScope())
    return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
                                   : 19;

  if (Right.is(tok::lessless)) {
    if (Left.is(tok::string_literal)) {
      StringRef Content = Left.TokenText;
      if (Content.startswith("\""))
        Content = Content.drop_front(1);
      if (Content.endswith("\""))
        Content = Content.drop_back(1);
      Content = Content.trim();
      if (Content.size() > 1 &&
          (Content.back() == ':' || Content.back() == '='))
        return 25;
    }
    return 1; // Breaking at a << is really cheap.
  }
  if (Left.Type == TT_ConditionalExpr)
    return prec::Conditional;
  prec::Level Level = Left.getPrecedence();

  if (Level != prec::Unknown)
    return Level;

  return 3;
}

bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
                                          const FormatToken &Left,
                                          const FormatToken &Right) {
  if (Right.is(tok::hashhash))
    return Left.is(tok::hash);
  if (Left.isOneOf(tok::hashhash, tok::hash))
    return Right.is(tok::hash);
  if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
    return Style.SpaceInEmptyParentheses;
  if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
    return (Right.Type == TT_CastRParen ||
            (Left.MatchingParen && Left.MatchingParen->Type == TT_CastRParen))
               ? Style.SpacesInCStyleCastParentheses
               : Style.SpacesInParentheses;
  if (Style.SpacesInAngles &&
      ((Left.Type == TT_TemplateOpener) != (Right.Type == TT_TemplateCloser)))
    return true;
  if (Right.isOneOf(tok::semi, tok::comma))
    return false;
  if (Right.is(tok::less) &&
      (Left.is(tok::kw_template) ||
       (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
    return true;
  if (Left.is(tok::arrow) || Right.is(tok::arrow))
    return false;
  if (Left.isOneOf(tok::exclaim, tok::tilde))
    return false;
  if (Left.is(tok::at) &&
      Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
                    tok::numeric_constant, tok::l_paren, tok::l_brace,
                    tok::kw_true, tok::kw_false))
    return false;
  if (Left.is(tok::coloncolon))
    return false;
  if (Right.is(tok::coloncolon))
    return (Left.is(tok::less) && Style.Standard == FormatStyle::LS_Cpp03) ||
           !Left.isOneOf(tok::identifier, tok::greater, tok::l_paren,
                         tok::r_paren, tok::less);
  if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
    return false;
  if (Right.is(tok::ellipsis))
    return Left.Tok.isLiteral();
  if (Left.is(tok::l_square) && Right.is(tok::amp))
    return false;
  if (Right.Type == TT_PointerOrReference)
    return Left.Tok.isLiteral() ||
           ((Left.Type != TT_PointerOrReference) && Left.isNot(tok::l_paren) &&
            !Style.PointerBindsToType);
  if (Right.Type == TT_FunctionTypeLParen && Left.isNot(tok::l_paren) &&
      (Left.Type != TT_PointerOrReference || Style.PointerBindsToType))
    return true;
  if (Left.Type == TT_PointerOrReference)
    return Right.Tok.isLiteral() || Right.Type == TT_BlockComment ||
           ((Right.Type != TT_PointerOrReference) &&
            Right.isNot(tok::l_paren) && Style.PointerBindsToType &&
            Left.Previous &&
            !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
  if (Right.is(tok::star) && Left.is(tok::l_paren))
    return false;
  if (Left.is(tok::l_square))
    return Left.Type == TT_ArrayInitializerLSquare &&
           Right.isNot(tok::r_square);
  if (Right.is(tok::r_square))
    return Right.MatchingParen &&
           Right.MatchingParen->Type == TT_ArrayInitializerLSquare;
  if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr &&
      Right.Type != TT_LambdaLSquare && Left.isNot(tok::numeric_constant))
    return false;
  if (Left.is(tok::colon))
    return Left.Type != TT_ObjCMethodExpr;
  if (Right.is(tok::colon))
    return Right.Type != TT_ObjCMethodExpr && !Left.is(tok::question);
  if (Right.is(tok::l_paren)) {
    if (Left.is(tok::r_paren) && Left.MatchingParen &&
        Left.MatchingParen->Previous &&
        Left.MatchingParen->Previous->is(tok::kw___attribute))
      return true;
    return Line.Type == LT_ObjCDecl ||
           Left.isOneOf(tok::kw_return, tok::kw_new, tok::kw_delete,
                        tok::semi) ||
           (Style.SpaceAfterControlStatementKeyword &&
            Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
                         tok::kw_catch));
  }
  if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
    return false;
  if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
    return !Left.Children.empty(); // No spaces in "{}".
  if (Left.is(tok::l_brace) || Right.is(tok::r_brace))
    return !Style.Cpp11BracedListStyle;
  if (Right.Type == TT_UnaryOperator)
    return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
           (Left.isNot(tok::colon) || Left.Type != TT_ObjCMethodExpr);
  if (Left.isOneOf(tok::identifier, tok::greater, tok::r_square) &&
      Right.is(tok::l_brace) && Right.getNextNonComment() &&
      Right.BlockKind != BK_Block)
    return false;
  if (Left.is(tok::period) || Right.is(tok::period))
    return false;
  if (Left.Type == TT_BlockComment && Left.TokenText.endswith("=*/"))
    return false;
  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
    return false;
  return true;
}

bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
                                         const FormatToken &Tok) {
  if (Tok.Tok.getIdentifierInfo() && Tok.Previous->Tok.getIdentifierInfo())
    return true; // Never ever merge two identifiers.
  if (Tok.Previous->Type == TT_ImplicitStringLiteral)
    return Tok.WhitespaceRange.getBegin() != Tok.WhitespaceRange.getEnd();
  if (Line.Type == LT_ObjCMethodDecl) {
    if (Tok.Previous->Type == TT_ObjCMethodSpecifier)
      return true;
    if (Tok.Previous->is(tok::r_paren) && Tok.is(tok::identifier))
      // Don't space between ')' and <id>
      return false;
  }
  if (Line.Type == LT_ObjCProperty &&
      (Tok.is(tok::equal) || Tok.Previous->is(tok::equal)))
    return false;

  if (Tok.Type == TT_TrailingReturnArrow ||
      Tok.Previous->Type == TT_TrailingReturnArrow)
    return true;
  if (Tok.Previous->is(tok::comma))
    return true;
  if (Tok.is(tok::comma))
    return false;
  if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
    return true;
  if (Tok.Previous->Tok.is(tok::kw_operator))
    return Tok.is(tok::coloncolon);
  if (Tok.Type == TT_OverloadedOperatorLParen)
    return false;
  if (Tok.is(tok::colon))
    return !Line.First->isOneOf(tok::kw_case, tok::kw_default) &&
           Tok.getNextNonComment() != NULL && Tok.Type != TT_ObjCMethodExpr &&
           !Tok.Previous->is(tok::question);
  if (Tok.Previous->Type == TT_UnaryOperator ||
      Tok.Previous->Type == TT_CastRParen)
    return false;
  if (Tok.Previous->is(tok::greater) && Tok.is(tok::greater)) {
    return Tok.Type == TT_TemplateCloser &&
           Tok.Previous->Type == TT_TemplateCloser &&
           (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
  }
  if (Tok.isOneOf(tok::arrowstar, tok::periodstar) ||
      Tok.Previous->isOneOf(tok::arrowstar, tok::periodstar))
    return false;
  if (!Style.SpaceBeforeAssignmentOperators &&
      Tok.getPrecedence() == prec::Assignment)
    return false;
  if ((Tok.Type == TT_BinaryOperator && !Tok.Previous->is(tok::l_paren)) ||
      Tok.Previous->Type == TT_BinaryOperator)
    return true;
  if (Tok.Previous->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
    return false;
  if (Tok.is(tok::less) && Tok.Previous->isNot(tok::l_paren) &&
      Line.First->is(tok::hash))
    return true;
  if (Tok.Type == TT_TrailingUnaryOperator)
    return false;
  return spaceRequiredBetween(Line, *Tok.Previous, Tok);
}

bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
                                     const FormatToken &Right) {
  if (Right.is(tok::comment)) {
    return Right.NewlinesBefore > 0;
  } else if (Right.Previous->isTrailingComment() ||
             (Right.is(tok::string_literal) &&
              Right.Previous->is(tok::string_literal))) {
    return true;
  } else if (Right.Previous->IsUnterminatedLiteral) {
    return true;
  } else if (Right.is(tok::lessless) && Right.Next &&
             Right.Previous->is(tok::string_literal) &&
             Right.Next->is(tok::string_literal)) {
    return true;
  } else if (Right.Previous->ClosesTemplateDeclaration &&
             Right.Previous->MatchingParen &&
             Right.Previous->MatchingParen->BindingStrength == 1 &&
             Style.AlwaysBreakTemplateDeclarations) {
    // FIXME: Fix horrible hack of using BindingStrength to find top-level <>.
    return true;
  } else if (Right.Type == TT_CtorInitializerComma &&
             Style.BreakConstructorInitializersBeforeComma &&
             !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
    return true;
  } else if (Right.Previous->BlockKind == BK_Block &&
             Right.Previous->isNot(tok::r_brace) && Right.isNot(tok::r_brace)) {
    return true;
  } else if (Right.is(tok::l_brace) && (Right.BlockKind == BK_Block)) {
    return Style.BreakBeforeBraces == FormatStyle::BS_Allman;
  }
  return false;
}

bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
                                    const FormatToken &Right) {
  const FormatToken &Left = *Right.Previous;
  if (Right.Type == TT_StartOfName || Right.is(tok::kw_operator))
    return true;
  if (Right.isTrailingComment())
    // We rely on MustBreakBefore being set correctly here as we should not
    // change the "binding" behavior of a comment.
    return false;
  if (Left.is(tok::question) && Right.is(tok::colon))
    return false;
  if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
    return Style.BreakBeforeTernaryOperators;
  if (Left.Type == TT_ConditionalExpr || Left.is(tok::question))
    return !Style.BreakBeforeTernaryOperators;
  if (Right.is(tok::colon) &&
      (Right.Type == TT_DictLiteral || Right.Type == TT_ObjCMethodExpr))
    return false;
  if (Left.is(tok::colon) &&
      (Left.Type == TT_DictLiteral || Left.Type == TT_ObjCMethodExpr))
    return true;
  if (Right.Type == TT_ObjCSelectorName)
    return true;
  if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
    return true;
  if (Left.ClosesTemplateDeclaration)
    return true;
  if (Right.Type == TT_RangeBasedForLoopColon ||
      Right.Type == TT_OverloadedOperatorLParen ||
      Right.Type == TT_OverloadedOperator)
    return false;
  if (Left.Type == TT_RangeBasedForLoopColon)
    return true;
  if (Right.Type == TT_RangeBasedForLoopColon)
    return false;
  if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
      Left.Type == TT_UnaryOperator || Left.is(tok::kw_operator))
    return false;
  if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
    return false;
  if (Left.Previous) {
    if (Left.is(tok::l_paren) && Right.is(tok::l_paren) &&
        Left.Previous->is(tok::kw___attribute))
      return false;
    if (Left.is(tok::l_paren) && (Left.Previous->Type == TT_BinaryOperator ||
                                  Left.Previous->Type == TT_CastRParen))
      return false;
  }
  if (Right.Type == TT_ImplicitStringLiteral)
    return false;

  if (Right.is(tok::r_paren) || Right.Type == TT_TemplateCloser)
    return false;

  // We only break before r_brace if there was a corresponding break before
  // the l_brace, which is tracked by BreakBeforeClosingBrace.
  if (Right.is(tok::r_brace))
    return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;

  // Allow breaking after a trailing 'const', e.g. after a method declaration,
  // unless it is follow by ';', '{' or '='.
  if (Left.is(tok::kw_const) && Left.Previous != NULL &&
      Left.Previous->is(tok::r_paren))
    return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal);

  if (Right.is(tok::kw___attribute))
    return true;

  if (Left.is(tok::identifier) && Right.is(tok::string_literal))
    return true;

  if (Left.Type == TT_CtorInitializerComma &&
      Style.BreakConstructorInitializersBeforeComma)
    return false;
  if (Right.Type == TT_CtorInitializerComma &&
      Style.BreakConstructorInitializersBeforeComma)
    return true;
  if (Right.isBinaryOperator() && Style.BreakBeforeBinaryOperators)
    return true;
  if (Left.is(tok::greater) && Right.is(tok::greater) &&
      Left.Type != TT_TemplateCloser)
    return false;
  if (Left.Type == TT_ArrayInitializerLSquare)
    return true;
  return (Left.isBinaryOperator() && Left.isNot(tok::lessless) &&
          !Style.BreakBeforeBinaryOperators) ||
         Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
                      tok::kw_class, tok::kw_struct) ||
         Right.isOneOf(tok::lessless, tok::arrow, tok::period, tok::colon,
                       tok::l_square, tok::at) ||
         (Left.is(tok::r_paren) &&
          Right.isOneOf(tok::identifier, tok::kw_const, tok::kw___attribute)) ||
         (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
}

void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
  llvm::errs() << "AnnotatedTokens:\n";
  const FormatToken *Tok = Line.First;
  while (Tok) {
    llvm::errs() << " M=" << Tok->MustBreakBefore
                 << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
                 << " S=" << Tok->SpacesRequiredBefore
                 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
                 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
                 << " FakeLParens=";
    for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
      llvm::errs() << Tok->FakeLParens[i] << "/";
    llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
    if (Tok->Next == NULL)
      assert(Tok == Line.Last);
    Tok = Tok->Next;
  }
  llvm::errs() << "----\n";
}

} // namespace format
} // namespace clang
@


1.1.1.1
log
@Import Clang 3.4rc1 r195771.
@
text
@@


1.1.1.2
log
@Import clang 3.5svn r198450.
@
text
@d87 1
a87 1
      // (^ can start a block type.
a105 4
    } else if (Left->Previous && Left->Previous->is(tok::caret) &&
               Left->Previous->Type == TT_UnaryOperator) {
      // This is the parameter list of an ObjC block.
      Contexts.back().IsExpression = false;
d229 1
a229 1
        if (Contexts.back().FirstObjCSelectorName != NULL) {
a231 3
          if (Contexts.back().NumBlockParameters > 1)
            Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
        }
d370 1
a370 1
          !Contexts.back().IsExpression && Line.First->Type != TT_ObjCProperty)
a531 1
      CurrentToken->NestingLevel = Contexts.size() - 1;
a540 1
          CurrentToken->Type != TT_FunctionLBrace &&
d556 5
a560 5
          LongestObjCSelectorName(0), NumBlockParameters(0),
          ColonIsForRangeExpr(false), ColonIsDictLiteral(false),
          ColonIsObjCMethodExpr(false), FirstObjCSelectorName(NULL),
          FirstStartOfName(NULL), IsExpression(IsExpression),
          CanBeExpression(true), InCtorInitializer(false) {}
a564 1
    unsigned NumBlockParameters;
d606 5
a610 1
    } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
a611 9
    } else if (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
               !Line.InPPDirective) {
      bool ParametersOfFunctionType =
          Current.Previous && Current.Previous->is(tok::r_paren) &&
          Current.Previous->MatchingParen &&
          Current.Previous->MatchingParen->Type == TT_FunctionTypeLParen;
      bool IsForOrCatch = Current.Previous &&
                          Current.Previous->isOneOf(tok::kw_for, tok::kw_catch);
      Contexts.back().IsExpression = !ParametersOfFunctionType && !IsForOrCatch;
a645 2
        if (Current.Type == TT_UnaryOperator)
          ++Contexts.back().NumBlockParameters;
a710 5
      } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
                 Line.MightBeFunctionDecl && Contexts.size() == 1) {
        // Line.MightBeFunctionDecl can only be true after the parentheses of a
        // function declaration have been found.
        Current.Type = TT_TrailingAnnotation;
d907 1
a907 3
          Precedence == CurrentPrecedence) {
        if (LatestOperator)
          addFakeParenthesis(Start, prec::Level(Precedence));
a908 1
      }
d1063 4
a1066 7
    if (Current->Type == TT_LineComment) {
      if (Current->Previous->BlockKind == BK_BracedInit)
        Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
      else
        Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
    } else if (Current->SpacesRequiredBefore == 0 &&
             spaceRequiredBefore(Line, *Current)) {
a1067 1
    }
d1135 2
a1136 2
  if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr)
    return 250;
d1143 2
a1144 1
    if (InFunctionDecl && Right.NestingLevel == 0)
d1168 5
a1172 7
  if (Right.Type == TT_TrailingAnnotation && Right.Next &&
      Right.Next->isNot(tok::l_paren)) {
    // Breaking before a trailing annotation is bad unless it is function-like.
    // Use a slightly higher penalty after ")" so that annotations like
    // "const override" are kept together.
    return Left.is(tok::r_paren) ? 100 : 120;
  }
d1183 1
a1183 1
    return Line.MightBeFunctionDecl ? 50 : 500;
a1186 2
  if (Left.is(tok::equal) && InFunctionDecl)
    return 110;
d1295 1
a1295 1
           (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
d1297 1
a1297 4
                         tok::kw_catch)) ||
           (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
            Left.isOneOf(tok::identifier, tok::kw___attribute) &&
            Line.Type != LT_PreprocessorDirective);
a1304 2
  if (Left.Type == TT_BlockComment && Left.TokenText.endswith("=*/"))
    return false;
d1314 2
d1385 1
a1385 2
    return Right.Previous->BlockKind != BK_BracedInit &&
           Right.NewlinesBefore > 0;
d1387 2
a1388 1
             (Right.isStringLiteral() && Right.Previous->isStringLiteral())) {
d1398 1
a1398 1
             Right.Previous->MatchingParen->NestingLevel == 0 &&
d1400 1
d1402 1
a1402 2
  } else if ((Right.Type == TT_CtorInitializerComma ||
              Right.Type == TT_CtorInitializerColon) &&
d1410 1
a1410 8
    return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
           Style.BreakBeforeBraces == FormatStyle::BS_GNU;
  } else if (Right.is(tok::string_literal) &&
             Right.TokenText.startswith("R\"")) {
    // Raw string literals are special wrt. line breaks. The author has made a
    // deliberate choice and might have aligned the contents of the string
    // literal accordingly. Thus, we try keep existing line breaks.
    return Right.NewlinesBefore > 0;
a1417 2
  if (Left.is(tok::at))
    return false;
d1423 1
a1423 4
    // The first comment in a braced lists is always interpreted as belonging to
    // the first list element. Otherwise, it should be placed outside of the
    // list.
    return Left.BlockKind == BK_BracedInit;
d1492 1
a1492 1
  if (Right.Type == TT_BinaryOperator && Style.BreakBeforeBinaryOperators)
@


1.1.1.3
log
@Import Clang 3.5svn r199312
@
text
@a476 12
  void parsePragma() {
    next(); // Consume "pragma".
    if (CurrentToken && CurrentToken->TokenText == "mark") {
      next(); // Consume "mark".
      next(); // Consume first token (so we fix leading whitespace).
      while (CurrentToken != NULL) {
        CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
    }
  }

a497 3
    case tok::pp_pragma:
      parsePragma();
      break;
a704 1
            LeftOfParens->isNot(tok::at) &&
d1190 1
a1190 1
    if (Left.is(tok::r_paren) && Left.MatchingParen &&
d1281 1
a1281 1
  if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
d1338 1
a1338 3
  if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
      (Right.is(tok::r_brace) && Right.MatchingParen &&
       Right.MatchingParen->BlockKind != BK_Block))
a1420 1
           Right.Previous->Type != TT_CtorInitializerColon &&
d1441 3
@


1.1.1.4
log
@Import Clang 3.5svn r201163.
@
text
@a77 3
    bool AfterCaret = Contexts.back().CaretFound;
    Contexts.back().CaretFound = false;

d106 2
a107 1
    } else if (AfterCaret) {
a109 2
    } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
      Left->Type = TT_AttributeParen;
a159 3
        if (Left->Type == TT_AttributeParen)
          CurrentToken->Type = TT_AttributeParen;

a171 2
      else if (CurrentToken->is(tok::l_brace))
        Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
a246 1
          Style.Language != FormatStyle::LK_Proto &&
d273 1
a273 2
        if (CurrentToken->is(tok::colon) &&
            Style.Language != FormatStyle::LK_Proto)
a514 1
      Contexts.back().IsExpression = true;
a529 9

    // Directly allow to 'import <string-literal>' to support protocol buffer
    // definitions (code.google.com/p/protobuf) or missing "#" (either way we
    // should not break the line).
    IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
    if (Info && Info->getPPKeywordID() == tok::pp_import &&
        CurrentToken->Next && CurrentToken->Next->is(tok::string_literal))
      parseIncludeDirective();

d584 1
a584 1
          CanBeExpression(true), InCtorInitializer(false), CaretFound(false) {}
a597 1
    bool CaretFound;
d676 1
a676 1
        if (Current.Type == TT_UnaryOperator) {
a677 3
          if (Current.is(tok::caret))
            Contexts.back().CaretFound = true;
        }
d700 1
a700 1
                             Current.Previous->isSimpleTypeSpecifier();
d781 1
a781 1
           PreviousNotConst->isSimpleTypeSpecifier();
d856 30
a993 2
      else if (Current->Type == TT_RangeBasedForLoopColon)
        return prec::Comma;
d1180 3
a1182 6
  if (Right.is(tok::l_square)) {
    if (Style.Language == FormatStyle::LK_Proto)
      return 1;
    if (Right.Type != TT_ObjCMethodExpr)
      return 250;
  }
d1196 1
a1196 2
  if (Left.is(tok::coloncolon) ||
      (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
a1265 8
  if (Style.Language == FormatStyle::LK_Proto) {
    if (Right.is(tok::l_paren) &&
        (Left.TokenText == "returns" || Left.TokenText == "option"))
      return true;
  }
  if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
      Left.Tok.getObjCKeywordID() == tok::objc_property)
    return true;
d1324 1
a1324 1
           Style.SpacesInContainerLiterals && Right.isNot(tok::r_square);
d1326 1
a1326 1
    return Right.MatchingParen && Style.SpacesInContainerLiterals &&
d1333 2
d1336 3
a1338 1
    if (Left.is(tok::r_paren) && Left.Type == TT_AttributeParen)
d1407 1
a1407 2
           !Tok.Previous->is(tok::question) &&
           (Tok.Type != TT_DictLiteral || Style.SpacesInContainerLiterals);
d1410 1
a1410 1
    return Tok.Type == TT_BinaryOperator;
a1468 4
  } else if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
             Style.Language == FormatStyle::LK_Proto) {
    // Don't enums onto single lines in protocol buffers.
    return true;
d1518 8
a1525 6
  if (Left.is(tok::l_paren) && Left.Type == TT_AttributeParen)
    return false;
  if (Left.is(tok::l_paren) && Left.Previous &&
      (Left.Previous->Type == TT_BinaryOperator ||
       Left.Previous->Type == TT_CastRParen))
    return false;
d1569 1
a1569 1
          Right.isOneOf(tok::identifier, tok::kw_const)) ||
@


1.1.1.5
log
@Import Clang 3.5svn r202566.
@
text
@d1215 1
a1215 3
    // Generally, breaking before a trailing annotation is bad unless it is
    // function-like. It seems to be especially preferable to keep standard
    // annotations (i.e. "const", "final" and "override") on the same line.
d1218 1
a1218 5
    bool is_standard_annotation = Right.is(tok::kw_const) ||
                                  Right.TokenText == "override" ||
                                  Right.TokenText == "final";
    return (Left.is(tok::r_paren) ? 100 : 120) +
           (is_standard_annotation ? 50 : 0);
a1505 2
  if (Right.Type == TT_InheritanceColon)
    return true;
@


1.1.1.5.2.1
log
@Rebase.
@
text
@a19 2
#define DEBUG_TYPE "format-token-annotator"

a36 1
    resetTokenMetadata(CurrentToken);
d41 1
a41 1
    if (!CurrentToken)
d46 1
a46 6
    // If there's a template keyword before the opening angle bracket, this is a
    // template parameter, not an argument.
    Contexts.back().InTemplateArgument =
        Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);

    while (CurrentToken) {
d64 1
a64 5
          ((CurrentToken->Previous->Type == TT_BinaryOperator &&
            // Toplevel bool expressions do not make lots of sense;
            // If we're on the top level, it contains only the base context and
            // the context for the current opening angle bracket.
            Contexts.size() > 2) ||
d76 1
a76 1
    if (!CurrentToken)
d78 3
d100 2
a101 4
    if (Left->Previous &&
        (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_if,
                                 tok::kw_while, tok::l_paren, tok::comma) ||
         Left->Previous->Type == TT_BinaryOperator)) {
a103 5
    } else if (Line.InPPDirective &&
               (!Left->Previous ||
                (Left->Previous->isNot(tok::identifier) &&
                 Left->Previous->Type != TT_OverloadedOperator))) {
      Contexts.back().IsExpression = true;
d109 1
a109 1
    } else if (Contexts[Contexts.size() - 2].CaretFound) {
a113 4
    } else if (Left->Previous && Left->Previous->IsForEachMacro) {
      // The first argument to a foreach macro is a declaration.
      Contexts.back().IsForEachMacro = true;
      Contexts.back().IsExpression = false;
d124 1
a124 1
    while (CurrentToken) {
d158 1
a158 1
          if (Contexts.back().FirstObjCSelectorName) {
a185 3
      if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
          CurrentToken->isSimpleTypeSpecifier())
        Contexts.back().IsExpression = false;
a204 1
        CurrentToken->isNot(tok::l_brace) &&
d223 1
a223 1
    while (CurrentToken) {
d232 1
a232 1
        if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
d237 1
a237 1
          if (Parent && Parent->Type == TT_PointerOrReference)
d242 1
a242 1
        if (Contexts.back().FirstObjCSelectorName) {
d268 1
a268 1
    if (CurrentToken) {
a269 5

      if (Contexts.back().CaretFound)
        Left->Type = TT_ObjCBlockLBrace;
      Contexts.back().CaretFound = false;

a271 2
      if (Left->BlockKind == BK_BracedInit)
        Contexts.back().IsExpression = true;
d273 1
a273 1
      while (CurrentToken) {
d307 1
a307 1
    while (CurrentToken) {
d320 1
a320 1
    if (CurrentToken && CurrentToken->is(tok::less)) {
d325 1
a325 1
      if (CurrentToken)
d338 1
a338 1
      if (!Tok->Previous && Line.MustBeDeclaration)
d342 1
a342 1
      if (!Tok->Previous)
d345 1
a345 2
      if (Tok->Previous->is(tok::r_paren) && Contexts.size() == 1 &&
          Line.First->isNot(tok::kw_case)) {
d357 1
a357 1
        if (!Contexts.back().FirstObjCSelectorName)
d361 2
a362 1
      } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
d364 1
a364 2
      } else if (Contexts.size() == 1 &&
                 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
d372 1
a372 1
      if (CurrentToken && CurrentToken->is(tok::l_paren)) {
d388 1
a388 3
          !Contexts.back().IsExpression &&
          Line.First->Type != TT_ObjCProperty &&
          (!Tok->Previous || Tok->Previous->isNot(tok::kw_decltype)))
d413 1
a413 1
      if (Tok->Previous)
a449 2
      if (Contexts.back().IsForEachMacro)
        Contexts.back().IsExpression = true;
d459 1
a459 1
    if (CurrentToken && CurrentToken->is(tok::less)) {
d461 1
a461 1
      while (CurrentToken) {
d467 1
a467 1
      while (CurrentToken) {
d482 1
a482 1
    while (CurrentToken) {
d493 1
a493 1
      while (CurrentToken) {
d502 1
a502 1
    if (!CurrentToken)
d510 1
a510 1
    if (!CurrentToken->Tok.getIdentifierInfo())
d532 1
a532 1
    while (CurrentToken)
d551 1
a551 1
    while (CurrentToken) {
d561 1
a561 1
      if (Contexts.back().FirstObjCSelectorName)
a570 18
  void resetTokenMetadata(FormatToken *Token) {
    if (!Token)
      return;

    // Reset token type in case we have already looked at it and then
    // recovered from an error (e.g. failure to find the matching >).
    if (CurrentToken->Type != TT_LambdaLSquare &&
        CurrentToken->Type != TT_FunctionLBrace &&
        CurrentToken->Type != TT_ImplicitStringLiteral &&
        CurrentToken->Type != TT_RegexLiteral &&
        CurrentToken->Type != TT_TrailingReturnArrow)
      CurrentToken->Type = TT_Unknown;
    if (CurrentToken->Role)
      CurrentToken->Role.reset(nullptr);
    CurrentToken->FakeLParens.clear();
    CurrentToken->FakeRParens = 0;
  }

d572 1
a572 1
    if (CurrentToken) {
d576 3
d580 12
a592 2

    resetTokenMetadata(CurrentToken);
d603 3
a605 4
          ColonIsObjCMethodExpr(false), FirstObjCSelectorName(nullptr),
          FirstStartOfName(nullptr), IsExpression(IsExpression),
          CanBeExpression(true), InTemplateArgument(false),
          InCtorInitializer(false), CaretFound(false), IsForEachMacro(false) {}
a617 1
    bool InTemplateArgument;
a619 1
    bool IsForEachMacro;
d646 1
a646 1
        if (Previous->isOneOf(tok::r_square, tok::r_paren))
d656 1
a656 3
               !Line.InPPDirective &&
               (!Current.Previous ||
                Current.Previous->isNot(tok::kw_decltype))) {
d695 1
a695 2
                                               Contexts.back().IsExpression,
                                  Contexts.back().InTemplateArgument);
d698 1
a698 1
        if (Current.Type == TT_UnaryOperator && Current.is(tok::caret)) {
d700 2
a701 1
          Contexts.back().CaretFound = true;
a706 2
      } else if (Current.is(tok::question)) {
        Current.Type = TT_ConditionalExpr;
d717 33
a749 1
        if (rParenEndsCast(Current))
a769 1
                 Current.Previous && Current.Previous->isNot(tok::equal) &&
d784 1
a784 1
    if (Tok.isNot(tok::identifier) || !Tok.Previous)
d789 1
a789 1
    while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
d792 1
a792 1
    if (!PreviousNotConst)
a803 5
    if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
        PreviousNotConst->MatchingParen->Previous &&
        PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
      return true;

a808 56
  /// \brief Determine whether ')' is ending a cast.
  bool rParenEndsCast(const FormatToken &Tok) {
    FormatToken *LeftOfParens = NULL;
    if (Tok.MatchingParen)
      LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
    bool IsCast = false;
    bool ParensAreEmpty = Tok.Previous == Tok.MatchingParen;
    bool ParensAreType = !Tok.Previous ||
                         Tok.Previous->Type == TT_PointerOrReference ||
                         Tok.Previous->Type == TT_TemplateCloser ||
                         Tok.Previous->isSimpleTypeSpecifier();
    bool ParensCouldEndDecl =
        Tok.Next && Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
    bool IsSizeOfOrAlignOf =
        LeftOfParens && LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
    if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
        ((Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression) ||
         (Tok.Next && Tok.Next->isBinaryOperator())))
      IsCast = true;
    else if (Tok.Next && Tok.Next->isNot(tok::string_literal) &&
             (Tok.Next->Tok.isLiteral() ||
              Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
      IsCast = true;
    // If there is an identifier after the (), it is likely a cast, unless
    // there is also an identifier before the ().
    else if (LeftOfParens && (LeftOfParens->Tok.getIdentifierInfo() == NULL ||
                              LeftOfParens->is(tok::kw_return)) &&
             LeftOfParens->Type != TT_OverloadedOperator &&
             LeftOfParens->isNot(tok::at) &&
             LeftOfParens->Type != TT_TemplateCloser && Tok.Next) {
      if (Tok.Next->isOneOf(tok::identifier, tok::numeric_constant)) {
        IsCast = true;
      } else {
        // Use heuristics to recognize c style casting.
        FormatToken *Prev = Tok.Previous;
        if (Prev && Prev->isOneOf(tok::amp, tok::star))
          Prev = Prev->Previous;

        if (Prev && Tok.Next && Tok.Next->Next) {
          bool NextIsUnary = Tok.Next->isUnaryOperator() ||
                             Tok.Next->isOneOf(tok::amp, tok::star);
          IsCast = NextIsUnary && Tok.Next->Next->isOneOf(
                                      tok::identifier, tok::numeric_constant);
        }

        for (; Prev != Tok.MatchingParen; Prev = Prev->Previous) {
          if (!Prev || !Prev->isOneOf(tok::kw_const, tok::identifier)) {
            IsCast = false;
            break;
          }
        }
      }
    }
    return IsCast && !ParensAreEmpty;
  }

d810 1
a810 2
  TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
                                  bool InTemplateArgument) {
d812 1
a812 1
    if (!PrevToken)
d816 1
a816 1
    if (!NextToken)
a826 1
        PrevToken->Type == TT_ConditionalExpr ||
d830 1
a830 1
    if (NextToken->is(tok::l_square) && NextToken->Type != TT_LambdaLSquare)
d839 2
a840 9
        PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
                           tok::kw_false) ||
        NextToken->Tok.isLiteral() ||
        NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
        NextToken->isUnaryOperator() ||
        // If we know we're in a template argument, there are no named
        // declarations. Thus, having an identifier on the right-hand side
        // indicates a binary operator.
        (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
d853 1
a853 1
    if (!PrevToken || PrevToken->Type == TT_CastRParen)
d873 1
a873 1
    if (!PrevToken || PrevToken->Type == TT_CastRParen)
d881 1
d914 1
a914 1
    if (!Current || Precedence > PrecedenceArrowAndPeriod)
d931 1
a931 2
    FormatToken *LatestOperator = nullptr;
    unsigned OperatorIndex = 0;
d948 1
a948 1
      if (!Current || Current->closesScope() ||
a950 1
          LatestOperator->LastOperator = true;
d952 1
d971 1
a971 1
        if (CurrentPrecedence == Precedence) {
a972 3
          Current->OperatorIndex = OperatorIndex;
          ++OperatorIndex;
        }
d1013 1
a1013 1
    if (!Current || Current->Type != TT_UnaryOperator) {
d1054 1
a1054 1
  const AnnotatedLine *NextNonCommentLine = nullptr;
d1059 1
a1059 1
        (*I)->First->Next == nullptr)
d1062 1
a1062 1
      NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
a1093 6
  for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
                                                  E = Line.Children.end();
       I != E; ++I) {
    calculateFormattingInformation(**I);
  }

d1100 1
a1100 1
  while (Current) {
d1102 1
a1102 2
      if (Current->Previous->BlockKind == BK_BracedInit &&
          Current->Previous->opensScope())
a1105 21

      // If we find a trailing comment, iterate backwards to determine whether
      // it seems to relate to a specific parameter. If so, break before that
      // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
      // to the previous line in:
      //   SomeFunction(a,
      //                b, // comment
      //                c);
      if (!Current->HasUnescapedNewline) {
        for (FormatToken *Parameter = Current->Previous; Parameter;
             Parameter = Parameter->Previous) {
          if (Parameter->isOneOf(tok::comment, tok::r_brace))
            break;
          if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
            if (Parameter->Previous->Type != TT_CtorInitializerComma &&
                Parameter->HasUnescapedNewline)
              Parameter->MustBreakBefore = true;
            break;
          }
        }
      }
d1107 1
a1107 1
               spaceRequiredBefore(Line, *Current)) {
d1116 1
a1116 7
    unsigned ChildSize = 0;
    if (Current->Previous->Children.size() == 1) {
      FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
      ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
                                                  : LastOfChild.TotalLength + 1;
    }
    if (Current->MustBreakBefore || Current->Previous->Children.size() > 1 ||
d1121 1
a1121 1
                             Current->ColumnWidth + ChildSize +
d1137 1
a1137 1
  for (Current = Line.First; Current != nullptr; Current = Current->Next) {
d1143 6
d1154 1
a1154 1
  while (Current) {
d1175 1
a1175 2
  if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
                              Right.Next->Type == TT_DictLiteral))
d1220 5
a1224 2
    bool is_short_annotation = Right.TokenText.size() < 10;
    return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
a1276 3
  } else if (Style.Language == FormatStyle::LK_JavaScript) {
    if (Left.TokenText == "var")
      return true;
a1277 2
  if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
    return true;
d1344 1
a1344 2
      Right.Type != TT_LambdaLSquare && Left.isNot(tok::numeric_constant) &&
      Left.Type != TT_DictLiteral)
a1347 2
  if (Left.Type == TT_BlockComment)
    return !Left.TokenText.endswith("=*/");
d1352 2
a1353 1
           Left.isOneOf(tok::kw_new, tok::kw_delete, tok::semi) ||
d1355 2
a1356 3
            (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
                          tok::kw_switch, tok::kw_catch, tok::kw_case) ||
             Left.IsForEachMacro)) ||
d1369 2
d1374 1
a1374 2
  if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square) ||
       Left.isSimpleTypeSpecifier()) &&
d1417 1
a1417 1
           Tok.getNextNonComment() && Tok.Type != TT_ObjCMethodExpr &&
d1435 1
a1435 2
      Tok.Previous->Type == TT_BinaryOperator ||
      Tok.Previous->Type == TT_ConditionalExpr)
a1443 2
  if (Tok.Previous->Type == TT_RegexLiteral)
    return false;
a1448 1
  const FormatToken &Left = *Right.Previous;
d1452 1
a1452 1
           (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
d1472 1
a1472 2
  } else if (Right.is(tok::l_brace) && Right.BlockKind == BK_Block &&
             Right.Type != TT_ObjCBlockLBrace && Right.Type != TT_DictLiteral) {
a1485 20

  // If the last token before a '}' is a comma or a comment, the intention is to
  // insert a line break after it in order to make shuffling around entries
  // easier.
  const FormatToken *BeforeClosingBrace = nullptr;
  if (Left.is(tok::l_brace) && Left.MatchingParen)
    BeforeClosingBrace = Left.MatchingParen->Previous;
  else if (Right.is(tok::r_brace))
    BeforeClosingBrace = Right.Previous;
  if (BeforeClosingBrace &&
      BeforeClosingBrace->isOneOf(tok::comma, tok::comment))
    return true;

  if (Style.Language == FormatStyle::LK_JavaScript) {
    // FIXME: This might apply to other languages and token kinds.
    if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
        Left.Previous->is(tok::char_constant))
      return true;
  }

a1493 2
  if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
    return false;
d1509 3
a1513 3
  if (Right.is(tok::colon) && (Right.Type != TT_CtorInitializerColon &&
                               Right.Type != TT_InlineASMColon))
    return false;
d1540 1
a1540 1
       Left.Previous->Type == TT_CastRParen || Left.Previous->is(tok::kw_if)))
d1553 5
a1557 5
  // Allow breaking after a trailing annotation, e.g. after a method
  // declaration.
  if (Left.Type == TT_TrailingAnnotation)
    return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
                          tok::less, tok::coloncolon);
a1564 4
  if (Right.is(tok::identifier) && Right.Next &&
      Right.Next->Type == TT_DictLiteral)
    return true;

d1571 2
a1575 2
  if (Right.Type == TT_BinaryOperator && Style.BreakBeforeBinaryOperators)
    return true;
d1602 1
a1602 1
    if (!Tok->Next)
@


1.1.1.6
log
@Import Clang 3.5svn r209886.
@
text
@a19 2
#define DEBUG_TYPE "format-token-annotator"

a36 1
    resetTokenMetadata(CurrentToken);
d41 1
a41 1
    if (!CurrentToken)
d46 1
a46 6
    // If there's a template keyword before the opening angle bracket, this is a
    // template parameter, not an argument.
    Contexts.back().InTemplateArgument =
        Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);

    while (CurrentToken) {
d64 1
a64 5
          ((CurrentToken->Previous->Type == TT_BinaryOperator &&
            // Toplevel bool expressions do not make lots of sense;
            // If we're on the top level, it contains only the base context and
            // the context for the current opening angle bracket.
            Contexts.size() > 2) ||
d76 1
a76 1
    if (!CurrentToken)
d78 3
d100 2
a101 4
    if (Left->Previous &&
        (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_if,
                                 tok::kw_while, tok::l_paren, tok::comma) ||
         Left->Previous->Type == TT_BinaryOperator)) {
a103 5
    } else if (Line.InPPDirective &&
               (!Left->Previous ||
                (Left->Previous->isNot(tok::identifier) &&
                 Left->Previous->Type != TT_OverloadedOperator))) {
      Contexts.back().IsExpression = true;
d109 1
a109 1
    } else if (Contexts[Contexts.size() - 2].CaretFound) {
a113 4
    } else if (Left->Previous && Left->Previous->IsForEachMacro) {
      // The first argument to a foreach macro is a declaration.
      Contexts.back().IsForEachMacro = true;
      Contexts.back().IsExpression = false;
d124 1
a124 1
    while (CurrentToken) {
d158 1
a158 1
          if (Contexts.back().FirstObjCSelectorName) {
a185 3
      if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
          CurrentToken->isSimpleTypeSpecifier())
        Contexts.back().IsExpression = false;
a204 1
        CurrentToken->isNot(tok::l_brace) &&
d223 1
a223 1
    while (CurrentToken) {
d232 1
a232 1
        if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
d237 1
a237 1
          if (Parent && Parent->Type == TT_PointerOrReference)
d242 1
a242 1
        if (Contexts.back().FirstObjCSelectorName) {
d268 1
a268 1
    if (CurrentToken) {
a269 5

      if (Contexts.back().CaretFound)
        Left->Type = TT_ObjCBlockLBrace;
      Contexts.back().CaretFound = false;

a271 2
      if (Left->BlockKind == BK_BracedInit)
        Contexts.back().IsExpression = true;
d273 1
a273 1
      while (CurrentToken) {
d307 1
a307 1
    while (CurrentToken) {
d320 1
a320 1
    if (CurrentToken && CurrentToken->is(tok::less)) {
d325 1
a325 1
      if (CurrentToken)
d338 1
a338 1
      if (!Tok->Previous && Line.MustBeDeclaration)
d342 1
a342 1
      if (!Tok->Previous)
d345 1
a345 2
      if (Tok->Previous->is(tok::r_paren) && Contexts.size() == 1 &&
          Line.First->isNot(tok::kw_case)) {
d357 1
a357 1
        if (!Contexts.back().FirstObjCSelectorName)
d361 2
a362 1
      } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
d364 1
a364 2
      } else if (Contexts.size() == 1 &&
                 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
d372 1
a372 1
      if (CurrentToken && CurrentToken->is(tok::l_paren)) {
d388 1
a388 3
          !Contexts.back().IsExpression &&
          Line.First->Type != TT_ObjCProperty &&
          (!Tok->Previous || Tok->Previous->isNot(tok::kw_decltype)))
d413 1
a413 1
      if (Tok->Previous)
a449 2
      if (Contexts.back().IsForEachMacro)
        Contexts.back().IsExpression = true;
d459 1
a459 1
    if (CurrentToken && CurrentToken->is(tok::less)) {
d461 1
a461 1
      while (CurrentToken) {
d467 1
a467 1
      while (CurrentToken) {
d482 1
a482 1
    while (CurrentToken) {
d493 1
a493 1
      while (CurrentToken) {
d502 1
a502 1
    if (!CurrentToken)
d510 1
a510 1
    if (!CurrentToken->Tok.getIdentifierInfo())
d532 1
a532 1
    while (CurrentToken)
d551 1
a551 1
    while (CurrentToken) {
d561 1
a561 1
      if (Contexts.back().FirstObjCSelectorName)
a570 18
  void resetTokenMetadata(FormatToken *Token) {
    if (!Token)
      return;

    // Reset token type in case we have already looked at it and then
    // recovered from an error (e.g. failure to find the matching >).
    if (CurrentToken->Type != TT_LambdaLSquare &&
        CurrentToken->Type != TT_FunctionLBrace &&
        CurrentToken->Type != TT_ImplicitStringLiteral &&
        CurrentToken->Type != TT_RegexLiteral &&
        CurrentToken->Type != TT_TrailingReturnArrow)
      CurrentToken->Type = TT_Unknown;
    if (CurrentToken->Role)
      CurrentToken->Role.reset(nullptr);
    CurrentToken->FakeLParens.clear();
    CurrentToken->FakeRParens = 0;
  }

d572 1
a572 1
    if (CurrentToken) {
d576 3
d580 12
a592 2

    resetTokenMetadata(CurrentToken);
d603 3
a605 4
          ColonIsObjCMethodExpr(false), FirstObjCSelectorName(nullptr),
          FirstStartOfName(nullptr), IsExpression(IsExpression),
          CanBeExpression(true), InTemplateArgument(false),
          InCtorInitializer(false), CaretFound(false), IsForEachMacro(false) {}
a617 1
    bool InTemplateArgument;
a619 1
    bool IsForEachMacro;
d646 1
a646 1
        if (Previous->isOneOf(tok::r_square, tok::r_paren))
d656 1
a656 3
               !Line.InPPDirective &&
               (!Current.Previous ||
                Current.Previous->isNot(tok::kw_decltype))) {
d695 1
a695 2
                                               Contexts.back().IsExpression,
                                  Contexts.back().InTemplateArgument);
d698 1
a698 1
        if (Current.Type == TT_UnaryOperator && Current.is(tok::caret)) {
d700 2
a701 1
          Contexts.back().CaretFound = true;
a706 2
      } else if (Current.is(tok::question)) {
        Current.Type = TT_ConditionalExpr;
d717 33
a749 1
        if (rParenEndsCast(Current))
a769 1
                 Current.Previous && Current.Previous->isNot(tok::equal) &&
d784 1
a784 1
    if (Tok.isNot(tok::identifier) || !Tok.Previous)
d789 1
a789 1
    while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
d792 1
a792 1
    if (!PreviousNotConst)
a803 5
    if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
        PreviousNotConst->MatchingParen->Previous &&
        PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
      return true;

a808 56
  /// \brief Determine whether ')' is ending a cast.
  bool rParenEndsCast(const FormatToken &Tok) {
    FormatToken *LeftOfParens = NULL;
    if (Tok.MatchingParen)
      LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
    bool IsCast = false;
    bool ParensAreEmpty = Tok.Previous == Tok.MatchingParen;
    bool ParensAreType = !Tok.Previous ||
                         Tok.Previous->Type == TT_PointerOrReference ||
                         Tok.Previous->Type == TT_TemplateCloser ||
                         Tok.Previous->isSimpleTypeSpecifier();
    bool ParensCouldEndDecl =
        Tok.Next && Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
    bool IsSizeOfOrAlignOf =
        LeftOfParens && LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
    if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
        ((Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression) ||
         (Tok.Next && Tok.Next->isBinaryOperator())))
      IsCast = true;
    else if (Tok.Next && Tok.Next->isNot(tok::string_literal) &&
             (Tok.Next->Tok.isLiteral() ||
              Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
      IsCast = true;
    // If there is an identifier after the (), it is likely a cast, unless
    // there is also an identifier before the ().
    else if (LeftOfParens && (LeftOfParens->Tok.getIdentifierInfo() == NULL ||
                              LeftOfParens->is(tok::kw_return)) &&
             LeftOfParens->Type != TT_OverloadedOperator &&
             LeftOfParens->isNot(tok::at) &&
             LeftOfParens->Type != TT_TemplateCloser && Tok.Next) {
      if (Tok.Next->isOneOf(tok::identifier, tok::numeric_constant)) {
        IsCast = true;
      } else {
        // Use heuristics to recognize c style casting.
        FormatToken *Prev = Tok.Previous;
        if (Prev && Prev->isOneOf(tok::amp, tok::star))
          Prev = Prev->Previous;

        if (Prev && Tok.Next && Tok.Next->Next) {
          bool NextIsUnary = Tok.Next->isUnaryOperator() ||
                             Tok.Next->isOneOf(tok::amp, tok::star);
          IsCast = NextIsUnary && Tok.Next->Next->isOneOf(
                                      tok::identifier, tok::numeric_constant);
        }

        for (; Prev != Tok.MatchingParen; Prev = Prev->Previous) {
          if (!Prev || !Prev->isOneOf(tok::kw_const, tok::identifier)) {
            IsCast = false;
            break;
          }
        }
      }
    }
    return IsCast && !ParensAreEmpty;
  }

d810 1
a810 2
  TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
                                  bool InTemplateArgument) {
d812 1
a812 1
    if (!PrevToken)
d816 1
a816 1
    if (!NextToken)
a826 1
        PrevToken->Type == TT_ConditionalExpr ||
d830 1
a830 1
    if (NextToken->is(tok::l_square) && NextToken->Type != TT_LambdaLSquare)
d839 2
a840 9
        PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
                           tok::kw_false) ||
        NextToken->Tok.isLiteral() ||
        NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
        NextToken->isUnaryOperator() ||
        // If we know we're in a template argument, there are no named
        // declarations. Thus, having an identifier on the right-hand side
        // indicates a binary operator.
        (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
d853 1
a853 1
    if (!PrevToken || PrevToken->Type == TT_CastRParen)
d873 1
a873 1
    if (!PrevToken || PrevToken->Type == TT_CastRParen)
d881 1
d914 1
a914 1
    if (!Current || Precedence > PrecedenceArrowAndPeriod)
d931 1
a931 2
    FormatToken *LatestOperator = nullptr;
    unsigned OperatorIndex = 0;
d948 1
a948 1
      if (!Current || Current->closesScope() ||
a950 1
          LatestOperator->LastOperator = true;
d952 1
d971 1
a971 1
        if (CurrentPrecedence == Precedence) {
a972 3
          Current->OperatorIndex = OperatorIndex;
          ++OperatorIndex;
        }
d1013 1
a1013 1
    if (!Current || Current->Type != TT_UnaryOperator) {
d1054 1
a1054 1
  const AnnotatedLine *NextNonCommentLine = nullptr;
d1059 1
a1059 1
        (*I)->First->Next == nullptr)
d1062 1
a1062 1
      NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
a1093 6
  for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
                                                  E = Line.Children.end();
       I != E; ++I) {
    calculateFormattingInformation(**I);
  }

d1100 1
a1100 1
  while (Current) {
d1102 1
a1102 2
      if (Current->Previous->BlockKind == BK_BracedInit &&
          Current->Previous->opensScope())
a1105 21

      // If we find a trailing comment, iterate backwards to determine whether
      // it seems to relate to a specific parameter. If so, break before that
      // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
      // to the previous line in:
      //   SomeFunction(a,
      //                b, // comment
      //                c);
      if (!Current->HasUnescapedNewline) {
        for (FormatToken *Parameter = Current->Previous; Parameter;
             Parameter = Parameter->Previous) {
          if (Parameter->isOneOf(tok::comment, tok::r_brace))
            break;
          if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
            if (Parameter->Previous->Type != TT_CtorInitializerComma &&
                Parameter->HasUnescapedNewline)
              Parameter->MustBreakBefore = true;
            break;
          }
        }
      }
d1107 1
a1107 1
               spaceRequiredBefore(Line, *Current)) {
d1116 1
a1116 7
    unsigned ChildSize = 0;
    if (Current->Previous->Children.size() == 1) {
      FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
      ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
                                                  : LastOfChild.TotalLength + 1;
    }
    if (Current->MustBreakBefore || Current->Previous->Children.size() > 1 ||
d1121 1
a1121 1
                             Current->ColumnWidth + ChildSize +
d1137 1
a1137 1
  for (Current = Line.First; Current != nullptr; Current = Current->Next) {
d1143 6
d1154 1
a1154 1
  while (Current) {
d1175 1
a1175 2
  if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
                              Right.Next->Type == TT_DictLiteral))
d1220 5
a1224 2
    bool is_short_annotation = Right.TokenText.size() < 10;
    return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
a1276 3
  } else if (Style.Language == FormatStyle::LK_JavaScript) {
    if (Left.TokenText == "var")
      return true;
a1277 2
  if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
    return true;
d1344 1
a1344 2
      Right.Type != TT_LambdaLSquare && Left.isNot(tok::numeric_constant) &&
      Left.Type != TT_DictLiteral)
a1347 2
  if (Left.Type == TT_BlockComment)
    return !Left.TokenText.endswith("=*/");
d1352 2
a1353 1
           Left.isOneOf(tok::kw_new, tok::kw_delete, tok::semi) ||
d1355 2
a1356 3
            (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
                          tok::kw_switch, tok::kw_catch, tok::kw_case) ||
             Left.IsForEachMacro)) ||
d1369 2
d1374 1
a1374 2
  if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square) ||
       Left.isSimpleTypeSpecifier()) &&
d1417 1
a1417 1
           Tok.getNextNonComment() && Tok.Type != TT_ObjCMethodExpr &&
d1435 1
a1435 2
      Tok.Previous->Type == TT_BinaryOperator ||
      Tok.Previous->Type == TT_ConditionalExpr)
a1443 2
  if (Tok.Previous->Type == TT_RegexLiteral)
    return false;
a1448 1
  const FormatToken &Left = *Right.Previous;
d1452 1
a1452 1
           (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
d1472 1
a1472 2
  } else if (Right.is(tok::l_brace) && Right.BlockKind == BK_Block &&
             Right.Type != TT_ObjCBlockLBrace && Right.Type != TT_DictLiteral) {
a1485 20

  // If the last token before a '}' is a comma or a comment, the intention is to
  // insert a line break after it in order to make shuffling around entries
  // easier.
  const FormatToken *BeforeClosingBrace = nullptr;
  if (Left.is(tok::l_brace) && Left.MatchingParen)
    BeforeClosingBrace = Left.MatchingParen->Previous;
  else if (Right.is(tok::r_brace))
    BeforeClosingBrace = Right.Previous;
  if (BeforeClosingBrace &&
      BeforeClosingBrace->isOneOf(tok::comma, tok::comment))
    return true;

  if (Style.Language == FormatStyle::LK_JavaScript) {
    // FIXME: This might apply to other languages and token kinds.
    if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
        Left.Previous->is(tok::char_constant))
      return true;
  }

a1493 2
  if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
    return false;
d1509 3
a1513 3
  if (Right.is(tok::colon) && (Right.Type != TT_CtorInitializerColon &&
                               Right.Type != TT_InlineASMColon))
    return false;
d1540 1
a1540 1
       Left.Previous->Type == TT_CastRParen || Left.Previous->is(tok::kw_if)))
d1553 5
a1557 5
  // Allow breaking after a trailing annotation, e.g. after a method
  // declaration.
  if (Left.Type == TT_TrailingAnnotation)
    return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
                          tok::less, tok::coloncolon);
a1564 4
  if (Right.is(tok::identifier) && Right.Next &&
      Right.Next->Type == TT_DictLiteral)
    return true;

d1571 2
a1575 2
  if (Right.Type == TT_BinaryOperator && Style.BreakBeforeBinaryOperators)
    return true;
d1602 1
a1602 1
    if (!Tok->Next)
@


1.1.1.7
log
@Import clang 3.6svn r215315.
@
text
@d72 6
a77 2
          CurrentToken->Previous->Type == TT_BinaryOperator &&
          Contexts[Contexts.size() - 2].IsExpression &&
a166 2
      if (CurrentToken->Previous->Type == TT_BinaryOperator)
        Contexts.back().IsExpression = true;
d201 1
a208 1
      FormatToken *Tok = CurrentToken;
a210 1
      updateParameterCount(Left, Tok);
d269 1
a269 1
          if (Left->BlockParameterCount > 1)
d284 1
a284 1
      FormatToken* Tok = CurrentToken;
a286 1
      updateParameterCount(Left, Tok);
d314 2
a315 3
        if (CurrentToken->is(tok::colon)) {
          if (CurrentToken->getPreviousNonComment()->is(tok::identifier))
            CurrentToken->getPreviousNonComment()->Type = TT_SelectorName;
a316 1
        }
d321 2
a326 6
    if (Current->Type == TT_LambdaLSquare ||
        (Current->is(tok::caret) && Current->Type == TT_UnaryOperator) ||
        (Style.Language == FormatStyle::LK_JavaScript &&
         Current->TokenText == "function")) {
      ++Left->BlockParameterCount;
    }
d384 1
a384 1
        Tok->Previous->Type = TT_SelectorName;
d619 2
a620 1
    CurrentToken->Role.reset();
d642 6
a647 6
          LongestObjCSelectorName(0), ColonIsForRangeExpr(false),
          ColonIsDictLiteral(false), ColonIsObjCMethodExpr(false),
          FirstObjCSelectorName(nullptr), FirstStartOfName(nullptr),
          IsExpression(IsExpression), CanBeExpression(true),
          InTemplateArgument(false), InCtorInitializer(false),
          CaretFound(false), IsForEachMacro(false) {}
d652 1
d692 1
a692 2
        if ((Previous->Type == TT_BinaryOperator ||
             Previous->Type == TT_UnaryOperator) &&
d745 2
a746 1
        if (Current.Type == TT_UnaryOperator && Current.is(tok::caret))
d748 1
d751 1
a751 1
      } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
d833 1
a833 1
    FormatToken *LeftOfParens = nullptr;
a835 6
    if (LeftOfParens && LeftOfParens->is(tok::r_paren))
      return false;
    if (LeftOfParens && LeftOfParens->is(tok::r_square) &&
        LeftOfParens->MatchingParen &&
        LeftOfParens->MatchingParen->Type == TT_LambdaLSquare)
      return false;
d856 2
a857 3
    else if (LeftOfParens &&
             (LeftOfParens->Tok.getIdentifierInfo() == nullptr ||
              LeftOfParens->is(tok::kw_return)) &&
d895 1
a895 1
    if (!NextToken || NextToken->is(tok::l_brace))
a911 2
    if (NextToken->isOneOf(tok::kw_operator, tok::comma))
      return TT_PointerOrReference;
d915 1
a915 2
        PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
                                                    tok::kw_decltype))
a929 6
    // This catches some cases where evaluation order is used as control flow:
    //   aaa && aaa->f();
    const FormatToken *NextNextToken = NextToken->getNextNonComment();
    if (NextNextToken && NextNextToken->is(tok::arrow))
      return TT_BinaryOperator;

d997 1
a997 2
            (Current->is(tok::colon) && (Current->Type == TT_ObjCMethodExpr ||
                                         Current->Type == TT_DictLiteral))))
d1026 1
a1026 1
      if (Current && Current->Type == TT_SelectorName &&
d1077 1
a1077 1
               Current->Type == TT_SelectorName)
d1122 1
a1122 1
    parseConditionalExpr();
a1182 37
// This function heuristically determines whether 'Current' starts the name of a
// function declaration.
static bool isFunctionDeclarationName(const FormatToken &Current) {
  if (Current.Type != TT_StartOfName ||
      Current.NestingLevel != 0 ||
      Current.Previous->Type == TT_StartOfName)
    return false;
  const FormatToken *Next = Current.Next;
  for (; Next; Next = Next->Next) {
    if (Next->Type == TT_TemplateOpener) {
      Next = Next->MatchingParen;
    } else if (Next->is(tok::coloncolon)) {
      Next = Next->Next;
      if (!Next || !Next->is(tok::identifier))
        return false;
    } else if (Next->is(tok::l_paren)) {
      break;
    } else {
      return false;
    }
  }
  if (!Next)
    return false;
  assert(Next->is(tok::l_paren));
  if (Next->Next == Next->MatchingParen)
    return true;
  for (const FormatToken *Tok = Next->Next; Tok != Next->MatchingParen;
       Tok = Tok->Next) {
    if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
        Tok->Type == TT_PointerOrReference || Tok->Type == TT_StartOfName)
      return true;
    if (Tok->isOneOf(tok::l_brace, tok::string_literal) || Tok->Tok.isLiteral())
      return false;
  }
  return false;
}

a1196 2
    if (isFunctionDeclarationName(*Current))
      Current->Type = TT_FunctionDeclarationName;
a1231 5
    if (Style.AlwaysBreakAfterDefinitionReturnType &&
        InFunctionDecl && Current->Type == TT_FunctionDeclarationName &&
        Line.Last->is(tok::l_brace))  // Only for definitions.
      Current->MustBreakBefore = true;

d1299 2
a1300 2
    if (Right.Type != TT_ObjCMethodExpr && Right.Type != TT_LambdaLSquare)
      return 500;
d1302 1
a1302 2
  if (Right.Type == TT_StartOfName ||
      Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator)) {
d1332 2
a1333 2
  if (Right.Type == TT_TrailingAnnotation &&
      (!Right.Next || Right.Next->isNot(tok::l_paren))) {
d1349 1
a1349 1
  if (Right.Type == TT_SelectorName)
a1357 2
  if (Right.is(tok::r_brace))
    return 1;
a1389 4
    if (Right.is(tok::period) &&
        (Left.TokenText == "optional" || Left.TokenText == "required" ||
         Left.TokenText == "repeated"))
      return true;
d1419 1
a1419 1
      (Left.isOneOf(tok::kw_template, tok::r_paren) ||
d1446 1
a1446 1
            Style.PointerAlignment != FormatStyle::PAS_Left);
d1448 1
a1448 2
      (Left.Type != TT_PointerOrReference ||
       Style.PointerAlignment != FormatStyle::PAS_Right))
d1453 2
a1454 2
            Right.isNot(tok::l_paren) &&
            Style.PointerAlignment != FormatStyle::PAS_Right && Left.Previous &&
d1482 1
a1482 1
            (Left.is(tok::identifier) || Left.isFunctionLikeKeyword()) &&
d1496 1
a1496 2
  if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
                    tok::r_paren) ||
d1562 1
a1562 1
    return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
a1572 6
// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
static bool isAllmanBrace(const FormatToken &Tok) {
  return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
         Tok.Type != TT_ObjCBlockLBrace && Tok.Type != TT_DictLiteral;
}

a1575 2
  if (Right.NewlinesBefore > 1)
    return true;
d1599 4
a1612 6
  } else if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
    return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
           Style.BreakBeforeBraces == FormatStyle::BS_GNU;
  } else if (Style.Language == FormatStyle::LK_Proto &&
             Left.isNot(tok::l_brace) && Right.Type == TT_SelectorName) {
    return true;
d1644 1
a1644 2
  if (Right.Type == TT_StartOfName ||
      Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator))
d1667 1
a1667 1
  if (Right.Type == TT_SelectorName)
d1732 1
a1732 2
  return (Left.isBinaryOperator() &&
          !Left.isOneOf(tok::arrowstar, tok::lessless) &&
d1736 2
a1737 3
         Right.isMemberAccess() ||
         Right.isOneOf(tok::lessless, tok::colon, tok::l_square, tok::at,
                       tok::kw_typename) ||
a1749 1
                 << " B=" << Tok->BlockParameterCount
@


1.1.1.7.2.1
log
@Update LLVM to 3.6.1, requested by joerg in ticket 824.
@
text
@d35 3
a37 3
                   const AdditionalKeywords &Keywords)
      : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
        Keywords(Keywords) {
a53 4
    if (Style.Language == FormatStyle::LK_Java &&
        CurrentToken->is(tok::question))
      next();

a61 5
      if (CurrentToken->is(tok::question) &&
          Style.Language == FormatStyle::LK_Java) {
        next();
        continue;
      }
d63 1
a63 1
                                tok::colon, tok::question))
d72 1
a72 1
          CurrentToken->Previous->is(TT_BinaryOperator) &&
d108 1
a108 1
         Left->Previous->is(TT_BinaryOperator))) {
d113 2
a114 2
                !Left->Previous->isOneOf(tok::identifier,
                                         TT_OverloadedOperator))) {
d118 1
a118 1
               Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
a129 3
    } else if (Left->Previous && Left->Previous->MatchingParen &&
               Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
      Contexts.back().IsExpression = false;
d159 1
a159 1
      if (CurrentToken->Previous->is(TT_PointerOrReference) &&
d163 1
a163 1
      if (CurrentToken->Previous->is(TT_BinaryOperator))
d182 1
a182 1
        if (Left->is(TT_AttributeParen))
a183 4
        if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
          CurrentToken->Type = TT_JavaAnnotation;
        if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
          CurrentToken->Type = TT_LeadingJavaAnnotation;
d226 1
a226 1
        Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
d228 4
a231 5
        (!Parent ||
         Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
                         tok::kw_return, tok::kw_throw) ||
         Parent->isUnaryOperator() ||
         Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
d242 1
a242 1
    } else if (Left->is(TT_Unknown)) {
d249 1
a249 1
            Left->is(TT_ObjCMethodExpr)) {
d260 1
a260 1
          if (Parent && Parent->is(TT_PointerOrReference))
d276 1
a276 8
      if (CurrentToken->is(tok::colon)) {
        if (Left->is(TT_ArraySubscriptLSquare)) {
          Left->Type = TT_ObjCMethodExpr;
          StartsObjCMethodExpr = true;
          Contexts.back().ColonIsObjCMethodExpr = true;
          if (Parent && Parent->is(tok::r_paren))
            Parent->Type = TT_CastRParen;
        }
a277 1
      }
d280 2
a281 2
          (Left->is(TT_ArraySubscriptLSquare) ||
           (Left->is(TT_ObjCMethodExpr) && !ColonFound)))
d283 1
a283 1
      FormatToken *Tok = CurrentToken;
d314 4
a317 8
        if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
          FormatToken *Previous = CurrentToken->getPreviousNonComment();
          if ((CurrentToken->is(tok::colon) ||
               Style.Language == FormatStyle::LK_Proto) &&
              Previous->is(tok::identifier))
            Previous->Type = TT_SelectorName;
          if (CurrentToken->is(tok::colon))
            Left->Type = TT_DictLiteral;
d327 2
a328 2
    if (Current->is(TT_LambdaLSquare) ||
        (Current->is(tok::caret) && Current->is(TT_UnaryOperator)) ||
d330 1
a330 1
         Current->is(Keywords.kw_function))) {
d388 1
a388 1
                 Line.First->is(TT_ObjCMethodSpecifier)) {
a403 5
      } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
                 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
        // This handles a special macro in ObjC code where selectors including
        // the colon are passed as macro arguments.
        Tok->Type = TT_ObjCMethodExpr;
d426 3
a428 3
          !Contexts.back().IsExpression && Line.First->isNot(TT_ObjCProperty) &&
          (!Tok->Previous ||
           !Tok->Previous->isOneOf(tok::kw_decltype, TT_LeadingJavaAnnotation)))
d440 1
a440 4
      if ((!Tok->Previous ||
           (!Tok->Previous->Tok.isLiteral() &&
            !(Tok->Previous->is(tok::r_paren) && Contexts.size() > 1))) &&
          parseAngle()) {
d442 1
a442 1
      } else {
d465 1
a465 1
        if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
d470 1
a470 1
        if (CurrentToken->Previous->is(TT_BinaryOperator))
d481 2
a482 2
      if (Line.First->is(tok::kw_for) && Tok->is(Keywords.kw_in) &&
          Tok->Previous->isNot(tok::colon))
d500 1
d508 8
d542 1
a542 2
  LineType parsePreprocessorDirective() {
    LineType Type = LT_PreprocessorDirective;
d545 1
a545 1
      return Type;
d548 1
a548 1
      return Type;
d553 1
a553 1
      return Type;
a556 1
      next();
a557 1
      Type = LT_ImportStatement;
a575 1
    return Type;
d581 2
a582 1
      return parsePreprocessorDirective();
d589 2
a590 7
    if ((Style.Language == FormatStyle::LK_Java &&
         CurrentToken->is(Keywords.kw_package)) ||
        (Info && Info->getPPKeywordID() == tok::pp_import &&
         CurrentToken->Next &&
         CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
                                     tok::kw_static))) {
      next();
a591 2
      return LT_ImportStatement;
    }
a592 9
    // If this line starts and ends in '<' and '>', respectively, it is likely
    // part of "#define <a/b.h>".
    if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
      parseIncludeDirective();
      return LT_ImportStatement;
    }

    bool KeywordVirtualFound = false;
    bool ImportStatement = false;
a595 2
      if (IsImportStatement(*CurrentToken))
        ImportStatement = true;
a600 2
    if (ImportStatement)
      return LT_ImportStatement;
d602 1
a602 1
    if (Line.First->is(TT_ObjCMethodSpecifier)) {
a612 11
  bool IsImportStatement(const FormatToken &Tok) {
    // FIXME: Closure-library specific stuff should not be hard-coded but be
    // configurable.
    return Style.Language == FormatStyle::LK_JavaScript &&
           Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
           Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
                              Tok.Next->Next->TokenText == "require" ||
                              Tok.Next->Next->TokenText == "provide") &&
           Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
  }

d619 5
a623 3
    if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_FunctionLBrace,
                               TT_ImplicitStringLiteral, TT_RegexLiteral,
                               TT_TrailingReturnArrow))
d632 2
a634 3
      CurrentToken->BindingStrength = Contexts.back().BindingStrength;
      modifyContext(*CurrentToken);
      determineTokenType(*CurrentToken);
d686 1
a686 1
  void modifyContext(const FormatToken &Current) {
d688 1
a688 2
        !Line.First->isOneOf(tok::kw_template, tok::kw_using,
                             TT_UnaryOperator) &&
d694 1
a694 1
        if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
d696 4
a699 2
          if (!Previous)
            break;
a700 4
        if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
            Previous->isOneOf(tok::star, tok::amp) && Previous->Previous &&
            Previous->Previous->isNot(tok::equal))
          Previous->Type = TT_PointerOrReference;
a703 2
    } else if (Current.is(TT_TrailingReturnArrow)) {
      Contexts.back().IsExpression = false;
d711 1
a711 1
          Current.Previous->MatchingParen->is(TT_FunctionTypeLParen);
a719 2
      if (Line.MustBeDeclaration)
        Contexts.back().IsExpression = Contexts.front().InCtorInitializer;
d721 1
a721 1
               Current.Previous->is(TT_CtorInitializerColon)) {
a729 6
  }

  void determineTokenType(FormatToken &Current) {
    if (!Current.is(TT_Unknown))
      // The token type is already known.
      return;
d731 1
a731 70
    // Line.MightBeFunctionDecl can only be true after the parentheses of a
    // function declaration have been found. In this case, 'Current' is a
    // trailing token of this declaration and thus cannot be a name.
    if (Current.is(Keywords.kw_instanceof)) {
      Current.Type = TT_BinaryOperator;
    } else if (isStartOfName(Current) &&
               (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
      Contexts.back().FirstStartOfName = &Current;
      Current.Type = TT_StartOfName;
    } else if (Current.is(tok::kw_auto)) {
      AutoFound = true;
    } else if (Current.is(tok::arrow) &&
               Style.Language == FormatStyle::LK_Java) {
      Current.Type = TT_LambdaArrow;
    } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
               Current.NestingLevel == 0) {
      Current.Type = TT_TrailingReturnArrow;
    } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
      Current.Type =
          determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
                                             Contexts.back().IsExpression,
                                Contexts.back().InTemplateArgument);
    } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
      Current.Type = determinePlusMinusCaretUsage(Current);
      if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
        Contexts.back().CaretFound = true;
    } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
      Current.Type = determineIncrementUsage(Current);
    } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
      Current.Type = TT_UnaryOperator;
    } else if (Current.is(tok::question)) {
      Current.Type = TT_ConditionalExpr;
    } else if (Current.isBinaryOperator() &&
               (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
      Current.Type = TT_BinaryOperator;
    } else if (Current.is(tok::comment)) {
      if (Current.TokenText.startswith("//"))
        Current.Type = TT_LineComment;
      else
        Current.Type = TT_BlockComment;
    } else if (Current.is(tok::r_paren)) {
      if (rParenEndsCast(Current))
        Current.Type = TT_CastRParen;
    } else if (Current.is(tok::at) && Current.Next) {
      switch (Current.Next->Tok.getObjCKeywordID()) {
      case tok::objc_interface:
      case tok::objc_implementation:
      case tok::objc_protocol:
        Current.Type = TT_ObjCDecl;
        break;
      case tok::objc_property:
        Current.Type = TT_ObjCProperty;
        break;
      default:
        break;
      }
    } else if (Current.is(tok::period)) {
      FormatToken *PreviousNoComment = Current.getPreviousNonComment();
      if (PreviousNoComment &&
          PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
        Current.Type = TT_DesignatedInitializerPeriod;
      else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
               Current.Previous->isOneOf(TT_JavaAnnotation,
                                         TT_LeadingJavaAnnotation)) {
        Current.Type = Current.Previous->Type;
      }
    } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
               Current.Previous &&
               !Current.Previous->isOneOf(tok::equal, tok::at) &&
               Line.MightBeFunctionDecl && Contexts.size() == 1) {
d733 32
a764 9
      // function declaration have been found.
      Current.Type = TT_TrailingAnnotation;
    } else if (Style.Language == FormatStyle::LK_Java && Current.Previous) {
      if (Current.Previous->is(tok::at) &&
          Current.isNot(Keywords.kw_interface)) {
        const FormatToken &AtToken = *Current.Previous;
        const FormatToken *Previous = AtToken.getPreviousNonComment();
        if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
          Current.Type = TT_LeadingJavaAnnotation;
d766 28
a793 5
          Current.Type = TT_JavaAnnotation;
      } else if (Current.Previous->is(tok::period) &&
                 Current.Previous->isOneOf(TT_JavaAnnotation,
                                           TT_LeadingJavaAnnotation)) {
        Current.Type = Current.Previous->Type;
a806 3
    if (Tok.Previous->is(TT_LeadingJavaAnnotation))
        return false;

d819 1
a819 1
    if (PreviousNotConst->is(TT_TemplateCloser))
a821 1
             PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
d830 1
a830 1
           PreviousNotConst->is(TT_PointerOrReference) ||
d839 2
a840 3
    if (LeftOfParens && LeftOfParens->is(tok::r_paren) &&
        LeftOfParens->MatchingParen)
      LeftOfParens = LeftOfParens->MatchingParen->Previous;
d843 1
a843 1
        LeftOfParens->MatchingParen->is(TT_LambdaLSquare))
a844 9
    if (Tok.Next) {
      if (Tok.Next->is(tok::question))
        return false;
      if (Style.Language == FormatStyle::LK_JavaScript &&
          Tok.Next->is(Keywords.kw_in))
        return false;
      if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
        return true;
    }
d847 4
a850 4
    bool ParensAreType =
        !Tok.Previous ||
        Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
        Tok.Previous->isSimpleTypeSpecifier();
d865 1
a865 1
    else if (LeftOfParens && Tok.Next &&
d868 3
a870 2
             !LeftOfParens->isOneOf(TT_OverloadedOperator, tok::at,
                                    TT_TemplateCloser)) {
d882 2
a883 3
          IsCast =
              NextIsUnary && !Tok.Next->is(tok::plus) &&
              Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant);
a899 3
    if (Style.Language == FormatStyle::LK_JavaScript)
      return TT_BinaryOperator;

d905 1
a905 2
    if (!NextToken ||
        (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
d908 2
a909 1
    if (PrevToken->is(tok::coloncolon))
d915 3
a917 2
        PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
                           TT_UnaryOperator, TT_CastRParen))
d920 1
a920 1
    if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
d933 1
a933 1
                           tok::kw_false, tok::r_brace) ||
a942 4
    // "&&(" is quite unlikely to be two successive unary "&".
    if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
      return TT_BinaryOperator;

d951 1
a951 1
    if (IsExpression && !Contexts.back().CaretFound)
d959 1
a959 1
    if (!PrevToken || PrevToken->is(TT_CastRParen))
d969 1
a969 1
    if (PrevToken->is(TT_BinaryOperator))
d979 1
a979 1
    if (!PrevToken || PrevToken->is(TT_CastRParen))
d992 1
d994 1
a994 1
  const AdditionalKeywords &Keywords;
d1004 5
a1008 3
  ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
                   AnnotatedLine &Line)
      : Style(Style), Keywords(Keywords), Current(Line.First) {}
d1014 4
a1017 3
    while (Current && (Current->is(tok::kw_return) ||
                       (Current->is(tok::colon) &&
                        Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
d1046 1
a1046 1
      if (Current && Current->is(TT_SelectorName) &&
d1055 12
a1066 5
      if (!Current || (Current->closesScope() && Current->MatchingParen) ||
          (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
          (CurrentPrecedence == prec::Conditional &&
           Precedence == prec::Assignment && Current->is(tok::colon))) {
        break;
a1082 3
        next(/*SkipPastLeadingComments=*/Precedence > 0);
      }
    }
d1084 1
a1084 7
    if (LatestOperator && (Current || Precedence > 0)) {
      LatestOperator->LastOperator = true;
      if (Precedence == PrecedenceArrowAndPeriod) {
        // Call expressions don't have a binary operator precedence.
        addFakeParenthesis(Start, prec::Unknown);
      } else {
        addFakeParenthesis(Start, prec::Level(Precedence));
d1094 1
a1094 2
      const FormatToken *NextNonComment = Current->getNextNonComment();
      if (Current->is(TT_ConditionalExpr))
d1096 2
a1097 9
      else if (NextNonComment && NextNonComment->is(tok::colon) &&
               NextNonComment->is(TT_DictLiteral))
        return prec::Comma;
      else if (Current->is(TT_LambdaArrow))
        return prec::Comma;
      else if (Current->isOneOf(tok::semi, TT_InlineASMColon,
                                TT_SelectorName) ||
               (Current->is(tok::comment) && NextNonComment &&
                NextNonComment->is(TT_SelectorName)))
d1099 1
a1099 1
      else if (Current->is(TT_RangeBasedForLoopColon))
d1101 1
a1101 1
      else if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
a1104 4
      else if (Style.Language == FormatStyle::LK_Java &&
               Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
                                Keywords.kw_throws))
        return 0;
d1114 1
a1114 4
      FormatToken *Previous = Current->Previous;
      while (Previous->is(tok::comment) && Previous->Previous)
        Previous = Previous->Previous;
      ++Previous->FakeRParens;
d1116 1
a1116 1
        Previous->EndsBinaryExpression = true;
d1123 1
a1123 1
    if (!Current || Current->isNot(TT_UnaryOperator)) {
a1136 3
    while (Current && Current->isTrailingComment()) {
      next();
    }
d1142 2
a1143 2
    parse(prec::Assignment);
    if (!Current || Current->isNot(TT_ConditionalExpr))
d1146 1
a1146 1
    parse(prec::Assignment);
d1150 1
a1150 1
  void next(bool SkipPastLeadingComments = true) {
d1153 1
a1153 3
    while (Current &&
           (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
           Current->isTrailingComment())
a1156 2
  const FormatStyle &Style;
  const AdditionalKeywords &Keywords;
d1162 2
a1163 2
void TokenAnnotator::setCommentLineLevels(
    SmallVectorImpl<AnnotatedLine *> &Lines) {
d1184 1
a1184 1
  AnnotatingParser Parser(Style, Line, Keywords);
d1189 1
a1189 1
  ExpressionParser ExprParser(Style, Keywords, Line);
d1192 1
a1192 1
  if (Line.First->is(TT_ObjCMethodSpecifier))
d1194 1
a1194 1
  else if (Line.First->is(TT_ObjCDecl))
d1196 1
a1196 1
  else if (Line.First->is(TT_ObjCProperty))
d1206 3
a1208 1
  if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
d1212 1
a1212 1
    if (Next->is(TT_TemplateOpener)) {
d1232 1
a1232 1
        Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
d1256 1
a1256 1
    if (Current->is(TT_LineComment)) {
d1276 1
a1276 1
            if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
d1291 3
a1293 5
    if (Style.AlwaysBreakAfterDefinitionReturnType && InFunctionDecl &&
        Current->is(TT_FunctionDeclarationName) &&
        !Line.Last->isOneOf(tok::semi, tok::comment)) // Only for definitions.
      // FIXME: Line.Last points to other characters than tok::semi
      // and tok::lbrace.
d1304 1
a1304 4
    const FormatToken *Prev = Current->Previous;
    if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
        (Prev->Children.size() == 1 &&
         Prev->Children[0]->First->MustBreakBefore) ||
d1306 1
a1306 1
      Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
d1308 3
a1310 2
      Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
                             ChildSize + Current->SpacesRequiredBefore;
d1312 1
a1312 1
    if (Current->is(TT_CtorInitializerColon))
a1356 13

  if (Style.Language == FormatStyle::LK_Java) {
    if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
      return 1;
    if (Right.is(Keywords.kw_implements))
      return 2;
    if (Left.is(tok::comma) && Left.NestingLevel == 0)
      return 3;
  } else if (Style.Language == FormatStyle::LK_JavaScript) {
    if (Right.is(Keywords.kw_function))
      return 100;
  }

d1358 1
a1358 1
                              Right.Next->is(TT_DictLiteral)))
d1363 1
a1363 1
    if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare))
d1366 2
a1367 3

  if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
      Right.is(tok::kw_operator)) {
d1370 1
a1370 1
    if (Left.is(TT_StartOfName))
d1378 1
a1378 1
  if (Left.is(TT_CastRParen))
d1386 2
a1387 1
  if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
d1397 1
a1397 1
  if (Right.is(TT_TrailingAnnotation) &&
a1398 5
    // Moving trailing annotations to the next line is fine for ObjC method
    // declarations.
    if (Line.First->is(TT_ObjCMethodSpecifier))

      return 10;
d1414 1
a1414 1
  if (Right.is(TT_SelectorName))
d1416 1
a1416 1
  if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
d1419 1
a1419 1
  if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
d1425 1
a1425 5
  if (Left.is(TT_TemplateOpener))
    return 100;
  if (Left.opensScope()) {
    if (!Style.AlignAfterOpenBracket)
      return 0;
a1427 3
  }
  if (Left.is(TT_JavaAnnotation))
    return 50;
d1443 1
a1443 1
  if (Left.is(TT_ConditionalExpr))
d1456 12
d1480 2
a1481 2
    return (Right.is(TT_CastRParen) ||
            (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
d1484 3
d1493 2
d1504 4
d1514 1
a1514 1
  if (Right.is(TT_PointerOrReference))
d1516 1
a1516 1
           (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
d1518 2
a1519 2
  if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
      (!Left.is(TT_PointerOrReference) ||
d1522 4
a1525 3
  if (Left.is(TT_PointerOrReference))
    return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
           (!Right.isOneOf(TT_PointerOrReference, tok::l_paren) &&
d1531 2
a1532 4
    return (Left.is(TT_ArrayInitializerLSquare) &&
            Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
           (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
            Right.isNot(tok::r_square));
d1534 5
a1538 8
    return Right.MatchingParen &&
           ((Style.SpacesInContainerLiterals &&
             Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
            (Style.SpacesInSquareBrackets &&
             Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
  if (Right.is(tok::l_square) &&
      !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
      !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
d1541 2
a1542 8
    return !Left.is(TT_ObjCMethodExpr);
  if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
    return !Left.Children.empty(); // No spaces in "{}".
  if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
      (Right.is(tok::r_brace) && Right.MatchingParen &&
       Right.MatchingParen->BlockKind != BK_Block))
    return !Style.Cpp11BracedListStyle;
  if (Left.is(TT_BlockComment))
d1545 1
a1545 1
    if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
d1547 2
a1548 1
    return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
d1551 1
a1551 4
                          tok::kw_switch, tok::kw_case) ||
             (Left.isOneOf(tok::kw_try, tok::kw_catch, tok::kw_new,
                           tok::kw_delete) &&
              (!Left.Previous || Left.Previous->isNot(tok::period))) ||
d1559 7
a1565 1
  if (Right.is(TT_UnaryOperator))
d1567 1
a1567 1
           (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
a1577 7
  if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
      Left.MatchingParen->Previous &&
      Left.MatchingParen->Previous->is(tok::period))
    // A.<B>DoSomething();
    return false;
  if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
    return false;
d1582 2
a1583 28
                                         const FormatToken &Right) {
  const FormatToken &Left = *Right.Previous;
  if (Style.Language == FormatStyle::LK_Proto) {
    if (Right.is(tok::period) &&
        Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
                     Keywords.kw_repeated))
      return true;
    if (Right.is(tok::l_paren) &&
        Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
      return true;
  } else if (Style.Language == FormatStyle::LK_JavaScript) {
    if (Left.is(Keywords.kw_var))
      return true;
  } else if (Style.Language == FormatStyle::LK_Java) {
    if (Left.is(tok::r_square) && Right.is(tok::l_brace))
      return true;
    if (Left.is(TT_LambdaArrow) || Right.is(TT_LambdaArrow))
      return true;
    if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
      return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
    if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
                      tok::kw_protected) ||
         Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
                      Keywords.kw_native)) &&
        Right.is(TT_TemplateOpener))
      return true;
  }
  if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
d1585 2
a1586 2
  if (Left.is(TT_ImplicitStringLiteral))
    return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
d1588 1
a1588 1
    if (Left.is(TT_ObjCMethodSpecifier))
d1590 1
a1590 1
    if (Left.is(tok::r_paren) && Right.is(tok::identifier))
d1595 1
a1595 1
      (Right.is(tok::equal) || Left.is(tok::equal)))
d1598 2
a1599 1
  if (Right.is(TT_TrailingReturnArrow) || Left.is(TT_TrailingReturnArrow))
d1601 1
a1601 1
  if (Left.is(tok::comma))
d1603 1
a1603 1
  if (Right.is(tok::comma))
d1605 1
a1605 1
  if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
d1607 3
a1609 3
  if (Left.is(tok::kw_operator))
    return Right.is(tok::coloncolon);
  if (Right.is(TT_OverloadedOperatorLParen))
d1611 1
a1611 1
  if (Right.is(tok::colon))
d1613 9
a1621 10
           Right.getNextNonComment() && Right.isNot(TT_ObjCMethodExpr) &&
           !Left.is(tok::question) &&
           !(Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon)) &&
           (Right.isNot(TT_DictLiteral) || Style.SpacesInContainerLiterals);
  if (Left.is(TT_UnaryOperator))
    return Right.is(TT_BinaryOperator);
  if (Left.is(TT_CastRParen))
    return Style.SpaceAfterCStyleCast || Right.is(TT_BinaryOperator);
  if (Left.is(tok::greater) && Right.is(tok::greater)) {
    return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
d1624 2
a1625 2
  if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
      Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
d1628 1
a1628 1
      Right.getPrecedence() == prec::Assignment)
d1630 3
a1632 9
  if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
    return (Left.is(TT_TemplateOpener) &&
            Style.Standard == FormatStyle::LS_Cpp03) ||
           !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
             Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
  if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
    return Style.SpacesInAngles;
  if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
      Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr))
d1634 1
a1634 1
  if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren))
d1636 1
a1636 4
  if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
      Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
    return false;
  if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
d1639 1
a1639 1
  if (Right.is(TT_TrailingUnaryOperator))
d1641 1
a1641 1
  if (Left.is(TT_RegexLiteral))
d1643 1
a1643 1
  return spaceRequiredBetween(Line, Left, Right);
d1649 1
a1649 1
         !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
d1657 3
a1659 16

  // If the last token before a '}' is a comma or a trailing comment, the
  // intention is to insert a line break after it in order to make shuffling
  // around entries easier.
  const FormatToken *BeforeClosingBrace = nullptr;
  if (Left.is(tok::l_brace) && Left.BlockKind != BK_Block && Left.MatchingParen)
    BeforeClosingBrace = Left.MatchingParen->Previous;
  else if (Right.is(tok::r_brace) && Right.BlockKind != BK_Block)
    BeforeClosingBrace = &Left;
  if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
                             BeforeClosingBrace->isTrailingComment()))
    return true;

  if (Right.is(tok::comment))
    return Left.BlockKind != BK_BracedInit &&
           Left.isNot(TT_CtorInitializerColon) &&
d1661 2
a1662 4
  if (Right.Previous->isTrailingComment() ||
      (Right.isStringLiteral() && Right.Previous->isStringLiteral()))
    return true;
  if (Right.Previous->IsUnterminatedLiteral)
d1664 1
a1664 3
  if (Right.is(tok::lessless) && Right.Next &&
      Right.Previous->is(tok::string_literal) &&
      Right.Next->is(tok::string_literal))
d1666 13
a1678 4
  if (Right.Previous->ClosesTemplateDeclaration &&
      Right.Previous->MatchingParen &&
      Right.Previous->MatchingParen->NestingLevel == 0 &&
      Style.AlwaysBreakTemplateDeclarations)
d1680 2
a1681 5
  if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
      Style.BreakConstructorInitializersBeforeComma &&
      !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
    return true;
  if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
d1686 5
a1690 11
  if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
      Style.Language == FormatStyle::LK_Proto)
    // Don't put enums onto single lines in protocol buffers.
    return true;
  if (Style.Language == FormatStyle::LK_JavaScript && Right.is(tok::r_brace) &&
      Left.is(tok::l_brace) && !Left.Children.empty())
    // Support AllowShortFunctionsOnASingleLine for JavaScript.
    return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
           (Left.NestingLevel == 0 && Line.Level == 0 &&
            Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline);
  if (isAllmanBrace(Left) || isAllmanBrace(Right))
d1693 2
a1694 2
  if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
      Right.is(TT_SelectorName))
d1696 12
a1707 4
  if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
    return true;
  if (Right.is(tok::lessless) && Left.is(tok::identifier) &&
      Left.TokenText == "endl")
a1714 11
    if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) &&
        Left.NestingLevel == 0)
      return true;
  } else if (Style.Language == FormatStyle::LK_Java) {
    if (Left.is(TT_LeadingJavaAnnotation) &&
        Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
        Line.Last->is(tok::l_brace))
      return true;
    if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
        Right.Next->is(tok::string_literal))
      return true;
a1722 10

  if (Style.Language == FormatStyle::LK_Java) {
    if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
                     Keywords.kw_implements))
      return false;
    if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
                      Keywords.kw_implements))
      return true;
  }

d1727 2
a1728 4
  if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
    return !Right.is(tok::l_paren);
  if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
      Right.is(tok::kw_operator))
d1739 1
a1739 1
  if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
d1741 1
a1741 1
  if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
d1743 1
a1743 1
  if (Right.is(TT_InheritanceColon))
d1745 2
a1746 2
  if (Right.is(tok::colon) &&
      !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
d1748 2
a1749 1
  if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
d1751 1
a1751 1
  if (Right.is(TT_SelectorName))
d1757 3
a1759 2
  if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
                    TT_OverloadedOperator))
d1761 1
a1761 1
  if (Left.is(TT_RangeBasedForLoopColon))
d1763 1
a1763 1
  if (Right.is(TT_RangeBasedForLoopColon))
d1765 2
a1766 3
  if (Left.isOneOf(TT_PointerOrReference, TT_TemplateCloser,
                   TT_UnaryOperator) ||
      Left.is(tok::kw_operator))
d1770 1
a1770 1
  if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
d1773 2
a1774 2
      (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen) ||
       Left.Previous->is(tok::kw_if)))
d1776 1
a1776 1
  if (Right.is(TT_ImplicitStringLiteral))
d1779 1
a1779 1
  if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
d1789 1
a1789 1
  if (Left.is(TT_TrailingAnnotation))
d1799 2
a1800 1
  if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
d1803 1
a1803 1
  if (Left.is(TT_CtorInitializerComma) &&
d1806 1
a1806 1
  if (Right.is(TT_CtorInitializerComma) &&
d1810 1
a1810 1
      Left.isNot(TT_TemplateCloser))
d1812 1
a1812 8
  if (Right.is(TT_BinaryOperator) &&
      Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
      (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
       Right.getPrecedence() != prec::Assignment))
    return true;
  if (Left.is(TT_ArrayInitializerLSquare))
    return true;
  if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
d1814 1
a1814 4
  if (Left.isBinaryOperator() && !Left.isOneOf(tok::arrowstar, tok::lessless) &&
      Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
      (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
       Left.getPrecedence() == prec::Assignment))
d1816 4
a1819 1
  return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
d1821 3
a1823 2
         Right.isMemberAccess() || Right.is(TT_TrailingReturnArrow) ||
         Right.isOneOf(tok::lessless, tok::colon, tok::l_square, tok::at) ||
@


1.1.1.8
log
@Import Clang 3.6RC1 r227398.
@
text
@d35 3
a37 3
                   const AdditionalKeywords &Keywords)
      : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
        Keywords(Keywords) {
a53 4
    if (Style.Language == FormatStyle::LK_Java &&
        CurrentToken->is(tok::question))
      next();

a61 5
      if (CurrentToken->is(tok::question) &&
          Style.Language == FormatStyle::LK_Java) {
        next();
        continue;
      }
d63 1
a63 1
                                tok::colon, tok::question))
d72 1
a72 1
          CurrentToken->Previous->is(TT_BinaryOperator) &&
d108 1
a108 1
         Left->Previous->is(TT_BinaryOperator))) {
d113 2
a114 2
                !Left->Previous->isOneOf(tok::identifier,
                                         TT_OverloadedOperator))) {
d118 1
a118 1
               Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
a129 3
    } else if (Left->Previous && Left->Previous->MatchingParen &&
               Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
      Contexts.back().IsExpression = false;
d159 1
a159 1
      if (CurrentToken->Previous->is(TT_PointerOrReference) &&
d163 1
a163 1
      if (CurrentToken->Previous->is(TT_BinaryOperator))
d182 1
a182 1
        if (Left->is(TT_AttributeParen))
a183 4
        if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
          CurrentToken->Type = TT_JavaAnnotation;
        if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
          CurrentToken->Type = TT_LeadingJavaAnnotation;
d226 1
a226 1
        Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
d228 4
a231 5
        (!Parent ||
         Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
                         tok::kw_return, tok::kw_throw) ||
         Parent->isUnaryOperator() ||
         Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
d242 1
a242 1
    } else if (Left->is(TT_Unknown)) {
d249 1
a249 1
            Left->is(TT_ObjCMethodExpr)) {
d260 1
a260 1
          if (Parent && Parent->is(TT_PointerOrReference))
d276 1
a276 8
      if (CurrentToken->is(tok::colon)) {
        if (Left->is(TT_ArraySubscriptLSquare)) {
          Left->Type = TT_ObjCMethodExpr;
          StartsObjCMethodExpr = true;
          Contexts.back().ColonIsObjCMethodExpr = true;
          if (Parent && Parent->is(tok::r_paren))
            Parent->Type = TT_CastRParen;
        }
a277 1
      }
d280 2
a281 2
          (Left->is(TT_ArraySubscriptLSquare) ||
           (Left->is(TT_ObjCMethodExpr) && !ColonFound)))
d283 1
a283 1
      FormatToken *Tok = CurrentToken;
d314 4
a317 8
        if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
          FormatToken *Previous = CurrentToken->getPreviousNonComment();
          if ((CurrentToken->is(tok::colon) ||
               Style.Language == FormatStyle::LK_Proto) &&
              Previous->is(tok::identifier))
            Previous->Type = TT_SelectorName;
          if (CurrentToken->is(tok::colon))
            Left->Type = TT_DictLiteral;
d327 2
a328 2
    if (Current->is(TT_LambdaLSquare) ||
        (Current->is(tok::caret) && Current->is(TT_UnaryOperator)) ||
d330 1
a330 1
         Current->is(Keywords.kw_function))) {
d388 1
a388 1
                 Line.First->is(TT_ObjCMethodSpecifier)) {
a403 5
      } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
                 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
        // This handles a special macro in ObjC code where selectors including
        // the colon are passed as macro arguments.
        Tok->Type = TT_ObjCMethodExpr;
d426 3
a428 3
          !Contexts.back().IsExpression && Line.First->isNot(TT_ObjCProperty) &&
          (!Tok->Previous ||
           !Tok->Previous->isOneOf(tok::kw_decltype, TT_LeadingJavaAnnotation)))
d440 1
a440 4
      if ((!Tok->Previous ||
           (!Tok->Previous->Tok.isLiteral() &&
            !(Tok->Previous->is(tok::r_paren) && Contexts.size() > 1))) &&
          parseAngle()) {
d442 1
a442 1
      } else {
d465 1
a465 1
        if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
d470 1
a470 1
        if (CurrentToken->Previous->is(TT_BinaryOperator))
d481 2
a482 2
      if (Line.First->is(tok::kw_for) && Tok->is(Keywords.kw_in) &&
          Tok->Previous->isNot(tok::colon))
d500 1
d508 8
d542 1
a542 2
  LineType parsePreprocessorDirective() {
    LineType Type = LT_PreprocessorDirective;
d545 1
a545 1
      return Type;
d548 1
a548 1
      return Type;
d553 1
a553 1
      return Type;
a556 1
      next();
a557 1
      Type = LT_ImportStatement;
a575 1
    return Type;
d581 2
a582 1
      return parsePreprocessorDirective();
d589 2
a590 7
    if ((Style.Language == FormatStyle::LK_Java &&
         CurrentToken->is(Keywords.kw_package)) ||
        (Info && Info->getPPKeywordID() == tok::pp_import &&
         CurrentToken->Next &&
         CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
                                     tok::kw_static))) {
      next();
a591 2
      return LT_ImportStatement;
    }
a592 9
    // If this line starts and ends in '<' and '>', respectively, it is likely
    // part of "#define <a/b.h>".
    if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
      parseIncludeDirective();
      return LT_ImportStatement;
    }

    bool KeywordVirtualFound = false;
    bool ImportStatement = false;
a595 2
      if (IsImportStatement(*CurrentToken))
        ImportStatement = true;
a600 2
    if (ImportStatement)
      return LT_ImportStatement;
d602 1
a602 1
    if (Line.First->is(TT_ObjCMethodSpecifier)) {
a612 11
  bool IsImportStatement(const FormatToken &Tok) {
    // FIXME: Closure-library specific stuff should not be hard-coded but be
    // configurable.
    return Style.Language == FormatStyle::LK_JavaScript &&
           Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
           Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
                              Tok.Next->Next->TokenText == "require" ||
                              Tok.Next->Next->TokenText == "provide") &&
           Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
  }

d619 5
a623 3
    if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_FunctionLBrace,
                               TT_ImplicitStringLiteral, TT_RegexLiteral,
                               TT_TrailingReturnArrow))
d632 2
a634 3
      CurrentToken->BindingStrength = Contexts.back().BindingStrength;
      modifyContext(*CurrentToken);
      determineTokenType(*CurrentToken);
d686 1
a686 1
  void modifyContext(const FormatToken &Current) {
d688 1
a688 2
        !Line.First->isOneOf(tok::kw_template, tok::kw_using,
                             TT_UnaryOperator) &&
d694 1
a694 1
        if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
d696 4
a699 2
          if (!Previous)
            break;
a700 4
        if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
            Previous->isOneOf(tok::star, tok::amp) && Previous->Previous &&
            Previous->Previous->isNot(tok::equal))
          Previous->Type = TT_PointerOrReference;
a703 2
    } else if (Current.is(TT_TrailingReturnArrow)) {
      Contexts.back().IsExpression = false;
d711 1
a711 1
          Current.Previous->MatchingParen->is(TT_FunctionTypeLParen);
a719 2
      if (Line.MustBeDeclaration)
        Contexts.back().IsExpression = Contexts.front().InCtorInitializer;
d721 1
a721 1
               Current.Previous->is(TT_CtorInitializerColon)) {
a729 6
  }

  void determineTokenType(FormatToken &Current) {
    if (!Current.is(TT_Unknown))
      // The token type is already known.
      return;
d731 1
a731 70
    // Line.MightBeFunctionDecl can only be true after the parentheses of a
    // function declaration have been found. In this case, 'Current' is a
    // trailing token of this declaration and thus cannot be a name.
    if (Current.is(Keywords.kw_instanceof)) {
      Current.Type = TT_BinaryOperator;
    } else if (isStartOfName(Current) &&
               (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
      Contexts.back().FirstStartOfName = &Current;
      Current.Type = TT_StartOfName;
    } else if (Current.is(tok::kw_auto)) {
      AutoFound = true;
    } else if (Current.is(tok::arrow) &&
               Style.Language == FormatStyle::LK_Java) {
      Current.Type = TT_LambdaArrow;
    } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
               Current.NestingLevel == 0) {
      Current.Type = TT_TrailingReturnArrow;
    } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
      Current.Type =
          determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
                                             Contexts.back().IsExpression,
                                Contexts.back().InTemplateArgument);
    } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
      Current.Type = determinePlusMinusCaretUsage(Current);
      if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
        Contexts.back().CaretFound = true;
    } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
      Current.Type = determineIncrementUsage(Current);
    } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
      Current.Type = TT_UnaryOperator;
    } else if (Current.is(tok::question)) {
      Current.Type = TT_ConditionalExpr;
    } else if (Current.isBinaryOperator() &&
               (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
      Current.Type = TT_BinaryOperator;
    } else if (Current.is(tok::comment)) {
      if (Current.TokenText.startswith("//"))
        Current.Type = TT_LineComment;
      else
        Current.Type = TT_BlockComment;
    } else if (Current.is(tok::r_paren)) {
      if (rParenEndsCast(Current))
        Current.Type = TT_CastRParen;
    } else if (Current.is(tok::at) && Current.Next) {
      switch (Current.Next->Tok.getObjCKeywordID()) {
      case tok::objc_interface:
      case tok::objc_implementation:
      case tok::objc_protocol:
        Current.Type = TT_ObjCDecl;
        break;
      case tok::objc_property:
        Current.Type = TT_ObjCProperty;
        break;
      default:
        break;
      }
    } else if (Current.is(tok::period)) {
      FormatToken *PreviousNoComment = Current.getPreviousNonComment();
      if (PreviousNoComment &&
          PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
        Current.Type = TT_DesignatedInitializerPeriod;
      else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
               Current.Previous->isOneOf(TT_JavaAnnotation,
                                         TT_LeadingJavaAnnotation)) {
        Current.Type = Current.Previous->Type;
      }
    } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
               Current.Previous &&
               !Current.Previous->isOneOf(tok::equal, tok::at) &&
               Line.MightBeFunctionDecl && Contexts.size() == 1) {
d733 32
a764 9
      // function declaration have been found.
      Current.Type = TT_TrailingAnnotation;
    } else if (Style.Language == FormatStyle::LK_Java && Current.Previous) {
      if (Current.Previous->is(tok::at) &&
          Current.isNot(Keywords.kw_interface)) {
        const FormatToken &AtToken = *Current.Previous;
        const FormatToken *Previous = AtToken.getPreviousNonComment();
        if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
          Current.Type = TT_LeadingJavaAnnotation;
d766 28
a793 5
          Current.Type = TT_JavaAnnotation;
      } else if (Current.Previous->is(tok::period) &&
                 Current.Previous->isOneOf(TT_JavaAnnotation,
                                           TT_LeadingJavaAnnotation)) {
        Current.Type = Current.Previous->Type;
a806 3
    if (Tok.Previous->is(TT_LeadingJavaAnnotation))
        return false;

d819 1
a819 1
    if (PreviousNotConst->is(TT_TemplateCloser))
a821 1
             PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
d830 1
a830 1
           PreviousNotConst->is(TT_PointerOrReference) ||
d839 2
a840 3
    if (LeftOfParens && LeftOfParens->is(tok::r_paren) &&
        LeftOfParens->MatchingParen)
      LeftOfParens = LeftOfParens->MatchingParen->Previous;
d843 1
a843 1
        LeftOfParens->MatchingParen->is(TT_LambdaLSquare))
a844 9
    if (Tok.Next) {
      if (Tok.Next->is(tok::question))
        return false;
      if (Style.Language == FormatStyle::LK_JavaScript &&
          Tok.Next->is(Keywords.kw_in))
        return false;
      if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
        return true;
    }
d847 4
a850 4
    bool ParensAreType =
        !Tok.Previous ||
        Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
        Tok.Previous->isSimpleTypeSpecifier();
d865 1
a865 1
    else if (LeftOfParens && Tok.Next &&
d868 3
a870 2
             !LeftOfParens->isOneOf(TT_OverloadedOperator, tok::at,
                                    TT_TemplateCloser)) {
d882 2
a883 3
          IsCast =
              NextIsUnary && !Tok.Next->is(tok::plus) &&
              Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant);
a899 3
    if (Style.Language == FormatStyle::LK_JavaScript)
      return TT_BinaryOperator;

d905 1
a905 2
    if (!NextToken ||
        (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
d908 2
a909 1
    if (PrevToken->is(tok::coloncolon))
d915 3
a917 2
        PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
                           TT_UnaryOperator, TT_CastRParen))
d920 1
a920 1
    if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
d933 1
a933 1
                           tok::kw_false, tok::r_brace) ||
a942 4
    // "&&(" is quite unlikely to be two successive unary "&".
    if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
      return TT_BinaryOperator;

d951 1
a951 1
    if (IsExpression && !Contexts.back().CaretFound)
d959 1
a959 1
    if (!PrevToken || PrevToken->is(TT_CastRParen))
d969 1
a969 1
    if (PrevToken->is(TT_BinaryOperator))
d979 1
a979 1
    if (!PrevToken || PrevToken->is(TT_CastRParen))
d992 1
d994 1
a994 1
  const AdditionalKeywords &Keywords;
d1004 5
a1008 3
  ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
                   AnnotatedLine &Line)
      : Style(Style), Keywords(Keywords), Current(Line.First) {}
d1014 4
a1017 3
    while (Current && (Current->is(tok::kw_return) ||
                       (Current->is(tok::colon) &&
                        Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
d1046 1
a1046 1
      if (Current && Current->is(TT_SelectorName) &&
d1055 12
a1066 5
      if (!Current || (Current->closesScope() && Current->MatchingParen) ||
          (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
          (CurrentPrecedence == prec::Conditional &&
           Precedence == prec::Assignment && Current->is(tok::colon))) {
        break;
a1082 3
        next(/*SkipPastLeadingComments=*/Precedence > 0);
      }
    }
d1084 1
a1084 7
    if (LatestOperator && (Current || Precedence > 0)) {
      LatestOperator->LastOperator = true;
      if (Precedence == PrecedenceArrowAndPeriod) {
        // Call expressions don't have a binary operator precedence.
        addFakeParenthesis(Start, prec::Unknown);
      } else {
        addFakeParenthesis(Start, prec::Level(Precedence));
d1094 1
a1094 2
      const FormatToken *NextNonComment = Current->getNextNonComment();
      if (Current->is(TT_ConditionalExpr))
d1096 2
a1097 9
      else if (NextNonComment && NextNonComment->is(tok::colon) &&
               NextNonComment->is(TT_DictLiteral))
        return prec::Comma;
      else if (Current->is(TT_LambdaArrow))
        return prec::Comma;
      else if (Current->isOneOf(tok::semi, TT_InlineASMColon,
                                TT_SelectorName) ||
               (Current->is(tok::comment) && NextNonComment &&
                NextNonComment->is(TT_SelectorName)))
d1099 1
a1099 1
      else if (Current->is(TT_RangeBasedForLoopColon))
d1101 1
a1101 1
      else if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
a1104 4
      else if (Style.Language == FormatStyle::LK_Java &&
               Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
                                Keywords.kw_throws))
        return 0;
d1114 1
a1114 4
      FormatToken *Previous = Current->Previous;
      while (Previous->is(tok::comment) && Previous->Previous)
        Previous = Previous->Previous;
      ++Previous->FakeRParens;
d1116 1
a1116 1
        Previous->EndsBinaryExpression = true;
d1123 1
a1123 1
    if (!Current || Current->isNot(TT_UnaryOperator)) {
a1136 3
    while (Current && Current->isTrailingComment()) {
      next();
    }
d1142 2
a1143 2
    parse(prec::Assignment);
    if (!Current || Current->isNot(TT_ConditionalExpr))
d1146 1
a1146 1
    parse(prec::Assignment);
d1150 1
a1150 1
  void next(bool SkipPastLeadingComments = true) {
d1153 1
a1153 3
    while (Current &&
           (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
           Current->isTrailingComment())
a1156 2
  const FormatStyle &Style;
  const AdditionalKeywords &Keywords;
d1162 2
a1163 2
void TokenAnnotator::setCommentLineLevels(
    SmallVectorImpl<AnnotatedLine *> &Lines) {
d1184 1
a1184 1
  AnnotatingParser Parser(Style, Line, Keywords);
d1189 1
a1189 1
  ExpressionParser ExprParser(Style, Keywords, Line);
d1192 1
a1192 1
  if (Line.First->is(TT_ObjCMethodSpecifier))
d1194 1
a1194 1
  else if (Line.First->is(TT_ObjCDecl))
d1196 1
a1196 1
  else if (Line.First->is(TT_ObjCProperty))
d1206 3
a1208 1
  if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
d1212 1
a1212 1
    if (Next->is(TT_TemplateOpener)) {
d1232 1
a1232 1
        Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
d1256 1
a1256 1
    if (Current->is(TT_LineComment)) {
d1276 1
a1276 1
            if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
d1291 3
a1293 5
    if (Style.AlwaysBreakAfterDefinitionReturnType && InFunctionDecl &&
        Current->is(TT_FunctionDeclarationName) &&
        !Line.Last->isOneOf(tok::semi, tok::comment)) // Only for definitions.
      // FIXME: Line.Last points to other characters than tok::semi
      // and tok::lbrace.
d1304 1
a1304 4
    const FormatToken *Prev = Current->Previous;
    if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
        (Prev->Children.size() == 1 &&
         Prev->Children[0]->First->MustBreakBefore) ||
d1306 1
a1306 1
      Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
d1308 3
a1310 2
      Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
                             ChildSize + Current->SpacesRequiredBefore;
d1312 1
a1312 1
    if (Current->is(TT_CtorInitializerColon))
a1356 13

  if (Style.Language == FormatStyle::LK_Java) {
    if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
      return 1;
    if (Right.is(Keywords.kw_implements))
      return 2;
    if (Left.is(tok::comma) && Left.NestingLevel == 0)
      return 3;
  } else if (Style.Language == FormatStyle::LK_JavaScript) {
    if (Right.is(Keywords.kw_function))
      return 100;
  }

d1358 1
a1358 1
                              Right.Next->is(TT_DictLiteral)))
d1363 1
a1363 1
    if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare))
d1366 2
a1367 3

  if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
      Right.is(tok::kw_operator)) {
d1370 1
a1370 1
    if (Left.is(TT_StartOfName))
d1378 1
a1378 1
  if (Left.is(TT_CastRParen))
d1386 2
a1387 1
  if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
d1397 1
a1397 1
  if (Right.is(TT_TrailingAnnotation) &&
a1398 5
    // Moving trailing annotations to the next line is fine for ObjC method
    // declarations.
    if (Line.First->is(TT_ObjCMethodSpecifier))

      return 10;
d1414 1
a1414 1
  if (Right.is(TT_SelectorName))
d1416 1
a1416 1
  if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
d1419 1
a1419 1
  if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
d1425 1
a1425 5
  if (Left.is(TT_TemplateOpener))
    return 100;
  if (Left.opensScope()) {
    if (!Style.AlignAfterOpenBracket)
      return 0;
a1427 3
  }
  if (Left.is(TT_JavaAnnotation))
    return 50;
d1443 1
a1443 1
  if (Left.is(TT_ConditionalExpr))
d1456 12
d1480 2
a1481 2
    return (Right.is(TT_CastRParen) ||
            (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
d1484 3
d1493 2
d1504 4
d1514 1
a1514 1
  if (Right.is(TT_PointerOrReference))
d1516 1
a1516 1
           (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
d1518 2
a1519 2
  if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
      (!Left.is(TT_PointerOrReference) ||
d1522 4
a1525 3
  if (Left.is(TT_PointerOrReference))
    return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
           (!Right.isOneOf(TT_PointerOrReference, tok::l_paren) &&
d1531 2
a1532 4
    return (Left.is(TT_ArrayInitializerLSquare) &&
            Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
           (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
            Right.isNot(tok::r_square));
d1534 5
a1538 8
    return Right.MatchingParen &&
           ((Style.SpacesInContainerLiterals &&
             Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
            (Style.SpacesInSquareBrackets &&
             Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
  if (Right.is(tok::l_square) &&
      !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
      !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
d1541 2
a1542 8
    return !Left.is(TT_ObjCMethodExpr);
  if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
    return !Left.Children.empty(); // No spaces in "{}".
  if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
      (Right.is(tok::r_brace) && Right.MatchingParen &&
       Right.MatchingParen->BlockKind != BK_Block))
    return !Style.Cpp11BracedListStyle;
  if (Left.is(TT_BlockComment))
d1545 1
a1545 1
    if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
d1547 2
a1548 1
    return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
d1551 1
a1551 4
                          tok::kw_switch, tok::kw_case) ||
             (Left.isOneOf(tok::kw_try, tok::kw_catch, tok::kw_new,
                           tok::kw_delete) &&
              (!Left.Previous || Left.Previous->isNot(tok::period))) ||
d1559 7
a1565 1
  if (Right.is(TT_UnaryOperator))
d1567 1
a1567 1
           (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
a1577 7
  if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
      Left.MatchingParen->Previous &&
      Left.MatchingParen->Previous->is(tok::period))
    // A.<B>DoSomething();
    return false;
  if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
    return false;
d1582 2
a1583 28
                                         const FormatToken &Right) {
  const FormatToken &Left = *Right.Previous;
  if (Style.Language == FormatStyle::LK_Proto) {
    if (Right.is(tok::period) &&
        Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
                     Keywords.kw_repeated))
      return true;
    if (Right.is(tok::l_paren) &&
        Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
      return true;
  } else if (Style.Language == FormatStyle::LK_JavaScript) {
    if (Left.is(Keywords.kw_var))
      return true;
  } else if (Style.Language == FormatStyle::LK_Java) {
    if (Left.is(tok::r_square) && Right.is(tok::l_brace))
      return true;
    if (Left.is(TT_LambdaArrow) || Right.is(TT_LambdaArrow))
      return true;
    if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
      return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
    if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
                      tok::kw_protected) ||
         Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
                      Keywords.kw_native)) &&
        Right.is(TT_TemplateOpener))
      return true;
  }
  if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
d1585 2
a1586 2
  if (Left.is(TT_ImplicitStringLiteral))
    return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
d1588 1
a1588 1
    if (Left.is(TT_ObjCMethodSpecifier))
d1590 1
a1590 1
    if (Left.is(tok::r_paren) && Right.is(tok::identifier))
d1595 1
a1595 1
      (Right.is(tok::equal) || Left.is(tok::equal)))
d1598 2
a1599 1
  if (Right.is(TT_TrailingReturnArrow) || Left.is(TT_TrailingReturnArrow))
d1601 1
a1601 1
  if (Left.is(tok::comma))
d1603 1
a1603 1
  if (Right.is(tok::comma))
d1605 1
a1605 1
  if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
d1607 3
a1609 3
  if (Left.is(tok::kw_operator))
    return Right.is(tok::coloncolon);
  if (Right.is(TT_OverloadedOperatorLParen))
d1611 1
a1611 1
  if (Right.is(tok::colon))
d1613 9
a1621 10
           Right.getNextNonComment() && Right.isNot(TT_ObjCMethodExpr) &&
           !Left.is(tok::question) &&
           !(Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon)) &&
           (Right.isNot(TT_DictLiteral) || Style.SpacesInContainerLiterals);
  if (Left.is(TT_UnaryOperator))
    return Right.is(TT_BinaryOperator);
  if (Left.is(TT_CastRParen))
    return Style.SpaceAfterCStyleCast || Right.is(TT_BinaryOperator);
  if (Left.is(tok::greater) && Right.is(tok::greater)) {
    return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
d1624 2
a1625 2
  if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
      Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
d1628 1
a1628 1
      Right.getPrecedence() == prec::Assignment)
d1630 3
a1632 9
  if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
    return (Left.is(TT_TemplateOpener) &&
            Style.Standard == FormatStyle::LS_Cpp03) ||
           !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
             Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
  if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
    return Style.SpacesInAngles;
  if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
      Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr))
d1634 1
a1634 1
  if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren))
d1636 1
a1636 4
  if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
      Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
    return false;
  if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
d1639 1
a1639 1
  if (Right.is(TT_TrailingUnaryOperator))
d1641 1
a1641 1
  if (Left.is(TT_RegexLiteral))
d1643 1
a1643 1
  return spaceRequiredBetween(Line, Left, Right);
d1649 1
a1649 1
         !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
d1657 3
a1659 16

  // If the last token before a '}' is a comma or a trailing comment, the
  // intention is to insert a line break after it in order to make shuffling
  // around entries easier.
  const FormatToken *BeforeClosingBrace = nullptr;
  if (Left.is(tok::l_brace) && Left.BlockKind != BK_Block && Left.MatchingParen)
    BeforeClosingBrace = Left.MatchingParen->Previous;
  else if (Right.is(tok::r_brace) && Right.BlockKind != BK_Block)
    BeforeClosingBrace = &Left;
  if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
                             BeforeClosingBrace->isTrailingComment()))
    return true;

  if (Right.is(tok::comment))
    return Left.BlockKind != BK_BracedInit &&
           Left.isNot(TT_CtorInitializerColon) &&
d1661 2
a1662 4
  if (Right.Previous->isTrailingComment() ||
      (Right.isStringLiteral() && Right.Previous->isStringLiteral()))
    return true;
  if (Right.Previous->IsUnterminatedLiteral)
d1664 1
a1664 3
  if (Right.is(tok::lessless) && Right.Next &&
      Right.Previous->is(tok::string_literal) &&
      Right.Next->is(tok::string_literal))
d1666 13
a1678 4
  if (Right.Previous->ClosesTemplateDeclaration &&
      Right.Previous->MatchingParen &&
      Right.Previous->MatchingParen->NestingLevel == 0 &&
      Style.AlwaysBreakTemplateDeclarations)
d1680 2
a1681 5
  if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
      Style.BreakConstructorInitializersBeforeComma &&
      !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
    return true;
  if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
d1686 5
a1690 11
  if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
      Style.Language == FormatStyle::LK_Proto)
    // Don't put enums onto single lines in protocol buffers.
    return true;
  if (Style.Language == FormatStyle::LK_JavaScript && Right.is(tok::r_brace) &&
      Left.is(tok::l_brace) && !Left.Children.empty())
    // Support AllowShortFunctionsOnASingleLine for JavaScript.
    return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
           (Left.NestingLevel == 0 && Line.Level == 0 &&
            Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline);
  if (isAllmanBrace(Left) || isAllmanBrace(Right))
d1693 2
a1694 2
  if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
      Right.is(TT_SelectorName))
d1696 12
a1707 4
  if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
    return true;
  if (Right.is(tok::lessless) && Left.is(tok::identifier) &&
      Left.TokenText == "endl")
a1714 11
    if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) &&
        Left.NestingLevel == 0)
      return true;
  } else if (Style.Language == FormatStyle::LK_Java) {
    if (Left.is(TT_LeadingJavaAnnotation) &&
        Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
        Line.Last->is(tok::l_brace))
      return true;
    if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
        Right.Next->is(tok::string_literal))
      return true;
a1722 10

  if (Style.Language == FormatStyle::LK_Java) {
    if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
                     Keywords.kw_implements))
      return false;
    if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
                      Keywords.kw_implements))
      return true;
  }

d1727 2
a1728 4
  if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
    return !Right.is(tok::l_paren);
  if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
      Right.is(tok::kw_operator))
d1739 1
a1739 1
  if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
d1741 1
a1741 1
  if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
d1743 1
a1743 1
  if (Right.is(TT_InheritanceColon))
d1745 2
a1746 2
  if (Right.is(tok::colon) &&
      !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
d1748 2
a1749 1
  if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
d1751 1
a1751 1
  if (Right.is(TT_SelectorName))
d1757 3
a1759 2
  if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
                    TT_OverloadedOperator))
d1761 1
a1761 1
  if (Left.is(TT_RangeBasedForLoopColon))
d1763 1
a1763 1
  if (Right.is(TT_RangeBasedForLoopColon))
d1765 2
a1766 3
  if (Left.isOneOf(TT_PointerOrReference, TT_TemplateCloser,
                   TT_UnaryOperator) ||
      Left.is(tok::kw_operator))
d1770 1
a1770 1
  if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
d1773 2
a1774 2
      (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen) ||
       Left.Previous->is(tok::kw_if)))
d1776 1
a1776 1
  if (Right.is(TT_ImplicitStringLiteral))
d1779 1
a1779 1
  if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
d1789 1
a1789 1
  if (Left.is(TT_TrailingAnnotation))
d1799 2
a1800 1
  if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
d1803 1
a1803 1
  if (Left.is(TT_CtorInitializerComma) &&
d1806 1
a1806 1
  if (Right.is(TT_CtorInitializerComma) &&
d1810 1
a1810 1
      Left.isNot(TT_TemplateCloser))
d1812 1
a1812 8
  if (Right.is(TT_BinaryOperator) &&
      Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
      (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
       Right.getPrecedence() != prec::Assignment))
    return true;
  if (Left.is(TT_ArrayInitializerLSquare))
    return true;
  if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
d1814 1
a1814 4
  if (Left.isBinaryOperator() && !Left.isOneOf(tok::arrowstar, tok::lessless) &&
      Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
      (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
       Left.getPrecedence() == prec::Assignment))
d1816 4
a1819 1
  return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
d1821 3
a1823 2
         Right.isMemberAccess() || Right.is(TT_TrailingReturnArrow) ||
         Right.isOneOf(tok::lessless, tok::colon, tok::l_square, tok::at) ||
@


1.1.1.9
log
@Import Clang 3.8.0rc3 r261930.
@
text
@a17 1
#include "llvm/ADT/SmallPtrSet.h"
d46 1
a47 7
    Left->ParentBracket = Contexts.back().ContextKind;
    ScopedContextCreator ContextCreator(*this, tok::less, 10);

    // If this angle is in the context of an expression, we need to be more
    // hesitant to detect it as opening template parameters.
    bool InExprContext = Contexts.back().IsExpression;

d71 2
a72 2
      if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
          (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext))
d83 1
a83 1
          !Line.startsWith(tok::kw_template))
a94 2
    FormatToken *Left = CurrentToken->Previous;
    Left->ParentBracket = Contexts.back().ContextKind;
d102 1
d114 3
a116 6
    if (Left->is(TT_OverloadedOperatorLParen)) {
      Contexts.back().IsExpression = false;
    } else if (Left->Previous &&
        (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
                                 tok::kw_if, tok::kw_while, tok::l_paren,
                                 tok::comma) ||
d120 5
a129 3
    } else if (Line.InPPDirective &&
               (!Left->Previous || !Left->Previous->is(tok::identifier))) {
      Contexts.back().IsExpression = true;
d135 1
a135 1
    } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
a141 4
    } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
      bool IsForOrCatch =
          Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
      Contexts.back().IsExpression = !IsForOrCatch;
d149 1
a149 2
    bool MightBeFunctionType = CurrentToken->isOneOf(tok::star, tok::amp) &&
                               !Contexts[Contexts.size() - 2].IsExpression;
a151 2
    bool MightBeObjCForRangeLoop =
        Left->Previous && Left->Previous->is(tok::kw_for);
d181 1
a181 1
              Line.MustBeDeclaration)))
a185 12
        if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
            Left->Previous && Left->Previous->is(tok::l_paren)) {
          // Detect the case where macros are used to generate lambdas or
          // function bodies, e.g.:
          //   auto my_lambda = MARCO((Type *type, int i) { .. body .. });
          for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
            if (Tok->is(TT_BinaryOperator) &&
                Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
              Tok->Type = TT_PointerOrReference;
          }
        }

d213 1
a213 2

      if (CurrentToken->is(tok::l_brace))
a221 9
      if (CurrentToken->isOneOf(tok::semi, tok::colon))
        MightBeObjCForRangeLoop = false;
      if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
        CurrentToken->Type = TT_ObjCForIn;
      // When we discover a 'new', we set CanBeExpression to 'false' in order to
      // parse the type correctly. Reset that after a comma.
      if (CurrentToken->is(tok::comma))
        Contexts.back().CanBeExpression = true;

d238 1
a238 1
    // expression, or it could the start of an Objective-C array literal.
a239 1
    Left->ParentBracket = Contexts.back().ContextKind;
a241 1
        Style.Language == FormatStyle::LK_Cpp &&
d250 2
d254 7
a260 20
    unsigned BindingIncrease = 1;
    if (Left->is(TT_Unknown)) {
      if (StartsObjCMethodExpr) {
        Left->Type = TT_ObjCMethodExpr;
      } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
                 Contexts.back().ContextKind == tok::l_brace &&
                 Parent->isOneOf(tok::l_brace, tok::comma)) {
        Left->Type = TT_JsComputedPropertyName;
      } else if (Style.Language == FormatStyle::LK_Proto ||
                 (Parent &&
                  Parent->isOneOf(TT_BinaryOperator, tok::at, tok::comma,
                                  tok::l_paren, tok::l_square, tok::question,
                                  tok::colon, tok::kw_return,
                                  // Should only be relevant to JavaScript:
                                  tok::kw_default))) {
        Left->Type = TT_ArrayInitializerLSquare;
      } else {
        BindingIncrease = 10;
        Left->Type = TT_ArraySubscriptLSquare;
      }
a262 4
    ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
    Contexts.back().IsExpression = true;
    Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;

d303 4
a306 2
      if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
          !ColonFound)
a318 1
      Left->ParentBracket = Contexts.back().ContextKind;
d341 1
a341 3
          if (((CurrentToken->is(tok::colon) &&
                (!Contexts.back().ColonIsDictLiteral ||
                 Style.Language != FormatStyle::LK_Cpp)) ||
d343 1
a343 1
              Previous->Tok.getIdentifierInfo())
d345 1
a345 2
          if (CurrentToken->is(tok::colon) ||
              Style.Language == FormatStyle::LK_JavaScript)
d356 4
a359 1
    if (Current->is(tok::l_brace) && !Current->is(TT_DictLiteral))
d361 1
d411 4
a414 14
      if (Style.Language == FormatStyle::LK_JavaScript) {
        if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
            (Contexts.size() == 1 &&               // switch/case labels
             !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
            Contexts.back().ContextKind == tok::l_paren ||  // function params
            Contexts.back().ContextKind == tok::l_square || // array type
            (Contexts.size() == 1 &&
             Line.MustBeDeclaration)) { // method/property declaration
          Tok->Type = TT_JsTypeColon;
          break;
        }
      }
      if (Contexts.back().ColonIsDictLiteral ||
          Style.Language == FormatStyle::LK_Proto) {
d417 1
a417 1
                 Line.startsWith(TT_ObjCMethodSpecifier)) {
d421 1
a421 1
            Contexts.back().LongestObjCSelectorName)
d423 1
d432 1
a432 4
        if (Tok->Previous->is(tok::r_paren))
          Tok->Type = TT_CtorInitializerColon;
        else
          Tok->Type = TT_InheritanceColon;
a456 13
      // When faced with 'operator()()', the kw_operator handler incorrectly
      // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
      // the first two parens OverloadedOperators and the second l_paren an
      // OverloadedOperatorLParen.
      if (Tok->Previous &&
          Tok->Previous->is(tok::r_paren) &&
          Tok->Previous->MatchingParen &&
          Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
        Tok->Previous->Type = TT_OverloadedOperator;
        Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
        Tok->Type = TT_OverloadedOperatorLParen;
      }

d460 1
a460 1
          !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
d462 1
a462 2
           !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
                                   TT_LeadingJavaAnnotation)))
d474 1
a474 2
      if (!NonTemplateLess.count(Tok) &&
          (!Tok->Previous ||
a480 1
        NonTemplateLess.insert(Tok);
d502 1
a502 2
        if (CurrentToken &&
            CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma))
a511 15
      if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
          Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
                             tok::r_brace)) {
        // Question marks before semicolons, colons, etc. indicate optional
        // types (fields, parameters), e.g.
        //   function(x?: string, y?) {...}
        //   class X { y?; }
        Tok->Type = TT_JsTypeOptionalQuestion;
        break;
      }
      // Declarations cannot be conditional expressions, this can only be part
      // of a type declaration.
      if (Line.MustBeDeclaration &&
          Style.Language == FormatStyle::LK_JavaScript)
        break;
d517 5
d523 2
a526 5
      else if (Contexts.back().FirstStartOfName &&
               (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
        Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
        Line.IsMultiVariableDeclStmt = true;
      }
d560 1
a560 3
    if (CurrentToken &&
        CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
      bool IsMark = CurrentToken->is(Keywords.kw_mark);
d564 1
a564 2
        if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
          CurrentToken->Type = TT_ImplicitStringLiteral;
a584 1
    case tok::pp_include_next:
d612 1
a612 2
    NonTemplateLess.clear();
    if (CurrentToken->is(tok::hash))
d614 1
a637 9
    // In .proto files, top-level options are very similar to import statements
    // and should not be line-wrapped.
    if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
        CurrentToken->is(Keywords.kw_option)) {
      next();
      if (CurrentToken && CurrentToken->is(tok::identifier))
        return LT_ImportStatement;
    }

d643 1
a643 1
      if (isImportStatement(*CurrentToken))
d653 1
a653 1
    if (Line.startsWith(TT_ObjCMethodSpecifier)) {
d664 1
a664 1
  bool isImportStatement(const FormatToken &Tok) {
a669 1
                              Tok.Next->Next->TokenText == "provide" ||
d671 1
a671 1
                              Tok.Next->Next->TokenText == "setTestOnly") &&
d681 3
a683 4
    if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
                               TT_FunctionLBrace, TT_ImplicitStringLiteral,
                               TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
                               TT_RegexLiteral))
a685 1
    CurrentToken->MatchingParen = nullptr;
d708 6
a713 1
          IsExpression(IsExpression) {}
d717 6
d724 5
a728 11
    unsigned LongestObjCSelectorName = 0;
    bool ColonIsForRangeExpr = false;
    bool ColonIsDictLiteral = false;
    bool ColonIsObjCMethodExpr = false;
    FormatToken *FirstObjCSelectorName = nullptr;
    FormatToken *FirstStartOfName = nullptr;
    bool CanBeExpression = true;
    bool InTemplateArgument = false;
    bool InCtorInitializer = false;
    bool CaretFound = false;
    bool IsForEachMacro = false;
d749 2
a750 1
        !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
d753 6
a758 11
      if (!Line.startsWith(TT_UnaryOperator)) {
        for (FormatToken *Previous = Current.Previous;
             Previous && Previous->Previous &&
             !Previous->Previous->isOneOf(tok::comma, tok::semi);
             Previous = Previous->Previous) {
          if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
            Previous = Previous->MatchingParen;
            if (!Previous)
              break;
          }
          if (Previous->opensScope())
a759 4
          if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
              Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
              Previous->Previous && Previous->Previous->isNot(tok::equal))
            Previous->Type = TT_PointerOrReference;
d761 4
a765 3
    } else if (Current.is(tok::lessless) &&
               (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
      Contexts.back().IsExpression = true;
d770 11
a780 2
    } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
      Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
d794 1
a794 1
    } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
d814 1
a814 1
    } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
d836 1
a836 8
      if (Style.Language == FormatStyle::LK_JavaScript &&
          Line.MustBeDeclaration) {
        // In JavaScript, `interface X { foo?(): bar; }` is an optional method
        // on the interface, not a ternary expression.
        Current.Type = TT_JsTypeOptionalQuestion;
      } else {
        Current.Type = TT_ConditionalExpr;
      }
d841 1
a841 8
      if (Current.TokenText.startswith("/*")) {
        if (Current.TokenText.endswith("*/"))
          Current.Type = TT_BlockComment;
        else
          // The lexer has for some reason determined a comment here. But we
          // cannot really handle it, if it isn't properly terminated.
          Current.Tok.setKind(tok::unknown);
      } else {
d843 2
a844 1
      }
a847 9
      if (Current.MatchingParen && Current.Next &&
          !Current.Next->isBinaryOperator() &&
          !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace))
        if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
          if (BeforeParen->is(tok::identifier) &&
              BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
              (!BeforeParen->Previous ||
               BeforeParen->Previous->ClosesTemplateDeclaration))
            Current.Type = TT_FunctionAnnotationRParen;
d849 11
a859 15
      if (Current.Next->isStringLiteral()) {
        Current.Type = TT_ObjCStringLiteral;
      } else {
        switch (Current.Next->Tok.getObjCKeywordID()) {
        case tok::objc_interface:
        case tok::objc_implementation:
        case tok::objc_protocol:
          Current.Type = TT_ObjCDecl;
          break;
        case tok::objc_property:
          Current.Type = TT_ObjCProperty;
          break;
        default:
          break;
        }
d878 1
a878 3
    } else if ((Style.Language == FormatStyle::LK_Java ||
                Style.Language == FormatStyle::LK_JavaScript) &&
               Current.Previous) {
d904 2
a905 2
    if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
      return false;
d930 1
a930 2
    return (!IsPPKeyword &&
            PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
d937 9
a945 7
    // C-style casts are only used in C++ and Java.
    if (Style.Language != FormatStyle::LK_Cpp &&
        Style.Language != FormatStyle::LK_Java)
      return false;

    // Empty parens aren't casts and there are no casts at the end of the line.
    if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
d947 2
a948 17

    FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
    if (LeftOfParens) {
      // If there is an opening parenthesis left of the current parentheses,
      // look past it as these might be chained casts.
      if (LeftOfParens->is(tok::r_paren)) {
        if (!LeftOfParens->MatchingParen ||
            !LeftOfParens->MatchingParen->Previous)
          return false;
        LeftOfParens = LeftOfParens->MatchingParen->Previous;
      }

      // If there is an identifier (or with a few exceptions a keyword) right
      // before the parentheses, this is unlikely to be a cast.
      if (LeftOfParens->Tok.getIdentifierInfo() &&
          !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
                                 tok::kw_delete))
d950 2
a951 5

      // Certain other tokens right before the parentheses are also signals that
      // this cannot be a cast.
      if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
                                TT_TemplateCloser))
d953 2
d956 2
a957 16

    if (Tok.Next->is(tok::question))
      return false;

    // As Java has no function types, a "(" after the ")" likely means that this
    // is a cast.
    if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
      return true;

    // If a (non-string) literal follows, this is likely a cast.
    if (Tok.Next->isNot(tok::string_literal) &&
        (Tok.Next->Tok.isLiteral() ||
         Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
      return true;

    // Heuristically try to determine whether the parentheses contain a type.
d963 33
a995 3
        Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
    if (ParensAreType && !ParensCouldEndDecl)
      return true;
d997 7
a1003 27
    // At this point, we heuristically assume that there are no casts at the
    // start of the line. We assume that we have found most cases where there
    // are by the logic above, e.g. "(void)x;".
    if (!LeftOfParens)
      return false;

    // If the following token is an identifier, this is a cast. All cases where
    // this can be something else are handled above.
    if (Tok.Next->is(tok::identifier))
      return true;

    if (!Tok.Next->Next)
      return false;

    // If the next token after the parenthesis is a unary operator, assume
    // that this is cast, unless there are unexpected tokens inside the
    // parenthesis.
    bool NextIsUnary =
        Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
    if (!NextIsUnary || Tok.Next->is(tok::plus) ||
        !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
      return false;
    // Search for unexpected tokens.
    for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
         Prev = Prev->Previous) {
      if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
        return false;
d1005 1
a1005 1
    return true;
a1019 2
        NextToken->isOneOf(tok::arrow, Keywords.kw_final,
                           Keywords.kw_override) ||
d1021 1
a1021 1
      return TT_PointerOrReference;
d1035 1
a1035 3
    if (NextToken->is(tok::kw_operator) && !IsExpression)
      return TT_PointerOrReference;
    if (NextToken->isOneOf(tok::comma, tok::semi))
a1110 6

  // Set of "<" tokens that do not open a template parameter list. If parseAngle
  // determines that a specific token can't be a template opener, it will make
  // same decision irrespective of the decisions for tokens leading up to it.
  // Store this information to prevent this from causing exponential runtime.
  llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
d1113 2
a1114 2
static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
a1184 2
          if (LatestOperator)
            LatestOperator->NextOperator = Current;
d1194 1
a1194 1
      // LatestOperator->LastOperator = true;
d1212 2
a1213 2
      if (NextNonComment && NextNonComment->is(tok::colon) &&
          NextNonComment->is(TT_DictLiteral))
d1215 1
a1215 1
      if (Current->is(TT_LambdaArrow))
d1217 4
a1220 6
      if (Current->is(TT_JsFatArrow))
        return prec::Assignment;
      if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
                           TT_JsComputedPropertyName) ||
          (Current->is(tok::comment) && NextNonComment &&
           NextNonComment->is(TT_SelectorName)))
d1222 1
a1222 1
      if (Current->is(TT_RangeBasedForLoopColon))
d1224 1
a1224 5
      if ((Style.Language == FormatStyle::LK_Java ||
           Style.Language == FormatStyle::LK_JavaScript) &&
          Current->is(Keywords.kw_instanceof))
        return prec::Relational;
      if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
d1226 1
a1226 1
      if (Current->isOneOf(tok::period, tok::arrow))
d1228 3
a1230 3
      if (Style.Language == FormatStyle::LK_Java &&
          Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
                           Keywords.kw_throws))
d1329 1
a1329 1
  if (Line.startsWith(TT_ObjCMethodSpecifier))
d1331 1
a1331 1
  else if (Line.startsWith(TT_ObjCDecl))
d1333 1
a1333 1
  else if (Line.startsWith(TT_ObjCProperty))
d1343 11
a1353 14
  auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
    for (; Next; Next = Next->Next) {
      if (Next->is(TT_OverloadedOperatorLParen))
        return Next;
      if (Next->is(TT_OverloadedOperator))
        continue;
      if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
        // For 'new[]' and 'delete[]'.
        if (Next->Next && Next->Next->is(tok::l_square) &&
            Next->Next->Next && Next->Next->Next->is(tok::r_square))
          Next = Next->Next->Next;
        continue;
      }

d1355 1
a1355 11
    }
    return nullptr;
  };

  const FormatToken *Next = Current.Next;
  if (Current.is(tok::kw_operator)) {
    if (Current.Previous && Current.Previous->is(tok::coloncolon))
      return false;
    Next = skipOperatorName(Next);
  } else {
    if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
a1356 18
    for (; Next; Next = Next->Next) {
      if (Next->is(TT_TemplateOpener)) {
        Next = Next->MatchingParen;
      } else if (Next->is(tok::coloncolon)) {
        Next = Next->Next;
        if (!Next)
          return false;
        if (Next->is(tok::kw_operator)) {
          Next = skipOperatorName(Next->Next);
          break;
        }
        if (!Next->is(tok::identifier))
          return false;
      } else if (Next->is(tok::l_paren)) {
        break;
      } else {
        return false;
      }
d1359 1
a1359 2

  if (!Next || !Next->is(tok::l_paren))
d1361 1
d1364 1
a1364 1
  for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
d1369 1
a1369 2
    if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
        Tok->Tok.isLiteral())
a1374 23
bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
  assert(Line.MightBeFunctionDecl);

  if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
       Style.AlwaysBreakAfterReturnType ==
           FormatStyle::RTBS_TopLevelDefinitions) &&
      Line.Level > 0)
    return false;

  switch (Style.AlwaysBreakAfterReturnType) {
  case FormatStyle::RTBS_None:
    return false;
  case FormatStyle::RTBS_All:
  case FormatStyle::RTBS_TopLevel:
    return true;
  case FormatStyle::RTBS_AllDefinitions:
  case FormatStyle::RTBS_TopLevelDefinitions:
    return Line.mightBeFunctionDefinition();
  }

  return false;
}

d1426 6
a1431 3
    if (!Current->MustBreakBefore && InFunctionDecl &&
        Current->is(TT_FunctionDeclarationName))
      Current->MustBreakBefore = mustBreakForReturnType(Line);
d1505 1
a1505 1
    if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
a1506 2
    if (Left.is(TT_JsTypeColon))
      return 35;
d1515 1
a1515 7
    if (Left.is(tok::r_square))
      return 25;
    // Slightly prefer formatting local lambda definitions like functions.
    if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
      return 35;
    if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
                       TT_ArrayInitializerLSquare))
d1521 1
a1521 1
    if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
d1524 1
a1524 1
      return 110;
a1528 4
  if (Right.is(TT_PointerOrReference))
    return 190;
  if (Right.is(TT_LambdaArrow))
    return 110;
d1543 4
a1546 22
    // Breaking before the "./->" of a chained call/member access is reasonably
    // cheap, as formatting those with one call per line is generally
    // desirable. In particular, it should be cheaper to break before the call
    // than it is to break inside a call's parameters, which could lead to weird
    // "hanging" indents. The exception is the very last "./->" to support this
    // frequent pattern:
    //
    //   aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
    //       dddddddd);
    //
    // which might otherwise be blown up onto many lines. Here, clang-format
    // won't produce "hanging" indents anyway as there is no other trailing
    // call.
    //
    // Also apply higher penalty is not a call as that might lead to a wrapping
    // like:
    //
    //   aaaaaaa
    //       .aaaaaaaaa.bbbbbbbb(cccccccc);
    return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
               ? 150
               : 35;
d1553 2
a1554 1
    if (Line.startsWith(TT_ObjCMethodSpecifier))
d1566 1
a1566 1
  if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
d1576 1
a1576 2
  if (Left.is(tok::l_paren) && InFunctionDecl &&
      Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
a1577 3
  if (Left.is(tok::l_paren) && Left.Previous &&
      Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
    return 1000;
d1585 1
a1585 1
    if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
d1594 1
a1594 2
    if (Left.is(tok::string_literal) &&
        (Right.NextOperator || Right.OperatorIndex != 1)) {
d1610 1
a1610 3
  if (Level != prec::Unknown)
    return Level;
  Level = Right.getPrecedence();
d1639 1
a1639 1
      (Left.is(tok::kw_template) ||
a1648 2
  if (Left.is(tok::colon))
    return !Left.is(TT_ObjCMethodExpr);
d1658 3
a1660 8
    return (Left.is(tok::r_paren) && Left.MatchingParen &&
            (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
             (Left.MatchingParen->Previous &&
              Left.MatchingParen->Previous->is(TT_FunctionDeclarationName)))) ||
           (Left.Tok.isLiteral() ||
            (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
             (Style.PointerAlignment != FormatStyle::PAS_Left ||
              Line.IsMultiVariableDeclStmt)));
d1663 1
a1663 2
       (Style.PointerAlignment != FormatStyle::PAS_Right &&
        !Line.IsMultiVariableDeclStmt)))
d1666 3
a1668 9
    return Right.Tok.isLiteral() ||
           Right.isOneOf(TT_BlockComment, Keywords.kw_final,
                         Keywords.kw_override) ||
           (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
           (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
                           tok::l_paren) &&
            (Style.PointerAlignment != FormatStyle::PAS_Right &&
             !Line.IsMultiVariableDeclStmt) &&
            Left.Previous &&
d1687 2
d1702 6
a1707 6
            (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
                          tok::kw_switch, tok::kw_case, TT_ForEachMacro,
                          TT_ObjCForIn) ||
             (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
                           tok::kw_new, tok::kw_delete) &&
              (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
d1709 1
a1709 2
            (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
             Left.is(tok::r_paren)) &&
d1740 1
a1740 6
  if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
    return true; // Never ever merge two identifiers.
  if (Style.Language == FormatStyle::LK_Cpp) {
    if (Left.is(tok::kw_operator))
      return Right.is(tok::coloncolon);
  } else if (Style.Language == FormatStyle::LK_Proto) {
d1743 1
a1743 1
                     Keywords.kw_repeated, Keywords.kw_extend))
d1749 1
a1749 5
    if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, TT_JsFatArrow,
                     Keywords.kw_in))
      return true;
    if (Left.is(tok::kw_default) && Left.Previous &&
        Left.Previous->is(tok::kw_export))
a1750 16
    if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
      return true;
    if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
      return false;
    if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
        Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
      return false;
    if (Left.is(tok::ellipsis))
      return false;
    if (Left.is(TT_TemplateCloser) &&
        !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
                       Keywords.kw_implements, Keywords.kw_extends))
      // Type assertions ('<type>expr') are not followed by whitespace. Other
      // locations that should have whitespace following are identified by the
      // above set of follower tokens.
      return false;
d1754 2
d1765 2
d1780 1
a1780 2
  if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
      Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
a1781 2
  if (Right.is(TT_OverloadedOperatorLParen))
    return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
d1788 10
a1797 14
  if (Right.is(tok::colon)) {
    if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
        !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
      return false;
    if (Right.is(TT_ObjCMethodExpr))
      return false;
    if (Left.is(tok::question))
      return false;
    if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
      return false;
    if (Right.is(TT_DictLiteral))
      return Style.SpacesInContainerLiterals;
    return true;
  }
a1799 3

  // If the next token is a binary operator or a selector name, we have
  // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
d1801 2
a1802 4
    return Style.SpaceAfterCStyleCast ||
           Right.isOneOf(TT_BinaryOperator, TT_SelectorName);

  if (Left.is(tok::greater) && Right.is(tok::greater))
d1805 1
d1820 1
a1820 2
      (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
       !Right.is(tok::r_paren)))
d1822 1
a1822 2
  if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
      Right.isNot(TT_FunctionTypeLParen))
d1828 1
a1828 1
      Line.startsWith(tok::hash))
d1846 1
a1846 1
  if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
a1848 35
  if (Style.Language == FormatStyle::LK_JavaScript) {
    // FIXME: This might apply to other languages and token kinds.
    if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
        Left.Previous->is(tok::char_constant))
      return true;
    if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
        Left.Previous && Left.Previous->is(tok::equal) &&
        Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
                            tok::kw_const) &&
        // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
        // above.
        !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
      // Object literals on the top level of a file are treated as "enum-style".
      // Each key/value pair is put on a separate line, instead of bin-packing.
      return true;
    if (Left.is(tok::l_brace) && Line.Level == 0 &&
        (Line.startsWith(tok::kw_enum) ||
         Line.startsWith(tok::kw_export, tok::kw_enum)))
      // JavaScript top-level enum key/value pairs are put on separate lines
      // instead of bin-packing.
      return true;
    if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
        !Left.Children.empty())
      // Support AllowShortFunctionsOnASingleLine for JavaScript.
      return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
             Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
             (Left.NestingLevel == 0 && Line.Level == 0 &&
              Style.AllowShortFunctionsOnASingleLine ==
                  FormatStyle::SFS_Inline);
  } else if (Style.Language == FormatStyle::LK_Java) {
    if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
        Right.Next->is(tok::string_literal))
      return true;
  }

d1853 1
a1853 2
  if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
      Left.BlockKind != BK_Block && Left.MatchingParen)
d1855 1
a1855 3
  else if (Right.MatchingParen &&
           Right.MatchingParen->isOneOf(tok::l_brace,
                                        TT_ArrayInitializerLSquare))
d1865 2
a1866 4
  if (Left.isTrailingComment())
    return true;
  if (Left.isStringLiteral() &&
      (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
d1892 6
a1897 2
  if (Right.is(TT_InlineASMBrace))
    return Right.HasUnescapedNewline;
d1899 2
a1900 3
    return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
           (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
           (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
d1906 3
d1910 17
a1926 6
  if ((Style.Language == FormatStyle::LK_Java ||
       Style.Language == FormatStyle::LK_JavaScript) &&
      Left.is(TT_LeadingJavaAnnotation) &&
      Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
      (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
    return true;
a1934 1
  // Language-specific stuff.
a1941 7
  } else if (Style.Language == FormatStyle::LK_JavaScript) {
    if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
      return false;
    if (Left.is(TT_JsTypeColon))
      return true;
    if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
      return false;
a1949 4
  if (Right.is(TT_PointerOrReference))
    return Line.IsMultiVariableDeclStmt ||
           (Style.PointerAlignment == FormatStyle::PAS_Right &&
            (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
a1952 2
  if (Left.is(TT_PointerOrReference))
    return false;
d1973 2
a1974 3
  if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
                                    Right.Next->is(TT_ObjCMethodExpr)))
    return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
d1977 1
a1977 1
  if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
d1986 2
a1987 1
  if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
d1990 1
a1990 2
  if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
      Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
d1995 2
a1996 1
      (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
a2002 3
  if (Right.is(tok::r_square) && Right.MatchingParen &&
      Right.MatchingParen->is(TT_LambdaLSquare))
    return false;
d2030 2
a2031 2
  if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
      (Left.is(tok::less) && Right.is(tok::less)))
d2042 1
a2042 2
  if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
      !Left.isOneOf(tok::arrowstar, tok::lessless) &&
d2049 2
a2050 3
         Right.isMemberAccess() ||
         Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
                       tok::colon, tok::l_square, tok::at) ||
d2061 1
a2061 2
                 << " C=" << Tok->CanBreakBefore
                 << " T=" << getTokenTypeName(Tok->Type)
@


1.1.1.9.2.1
log
@Sync with HEAD
@
text
@d45 1
a45 3
    if (!CurrentToken || !CurrentToken->Previous)
      return false;
    if (NonTemplateLess.count(CurrentToken->Previous))
a46 11

    const FormatToken& Previous = *CurrentToken->Previous;
    if (Previous.Previous) {
      if (Previous.Previous->Tok.isLiteral())
        return false;
      if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
          (!Previous.Previous->MatchingParen ||
           !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
        return false;
    }

d49 1
a49 1
    ScopedContextCreator ContextCreator(*this, tok::less, 12);
a123 4
    } else if (Style.Language == FormatStyle::LK_JavaScript &&
               Line.startsWith(Keywords.kw_type, tok::identifier)) {
      // type X = (...);
      Contexts.back().IsExpression = false;
a130 10
    } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
               (Left->Previous->is(Keywords.kw_function) ||
                (Left->Previous->endsSequence(tok::identifier,
                                              Keywords.kw_function)))) {
      // function(...) or function f(...)
      Contexts.back().IsExpression = false;
    } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
               Left->Previous->is(TT_JsTypeColon)) {
      // let x: (SomeType);
      Contexts.back().IsExpression = false;
d162 2
a163 2
    bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
    bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
d190 1
a190 3
        ProbablyFunctionType = true;
      if (CurrentToken->is(tok::comma))
        MightBeFunctionType = false;
d194 1
a194 1
        if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
d196 2
a197 1
             (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
d248 2
a249 3
      if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
           CurrentToken->Previous->isSimpleTypeSpecifier()) &&
          !CurrentToken->is(tok::l_brace))
a279 10

    // Cases where '>' is followed by '['.
    // In C++, this can happen either in array of templates (foo<int>[10])
    // or when array is a nested template type (unique_ptr<type1<type2>[]>).
    bool CppArrayTemplates =
        Style.Language == FormatStyle::LK_Cpp && Parent &&
        Parent->is(TT_TemplateCloser) &&
        (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
         Contexts.back().InTemplateArgument);

d281 1
a281 2
        !CppArrayTemplates && (Style.Language == FormatStyle::LK_Cpp ||
                               Style.Language == FormatStyle::LK_ObjC) &&
d301 4
a304 4
                 (!CppArrayTemplates && Parent &&
                  Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
                                  tok::comma, tok::l_paren, tok::l_square,
                                  tok::question, tok::colon, tok::kw_return,
d397 1
a397 2
                 (Style.Language != FormatStyle::LK_Cpp &&
                  Style.Language != FormatStyle::LK_ObjC))) ||
d399 1
a399 2
              (Previous->Tok.getIdentifierInfo() ||
               Previous->is(tok::string_literal)))
a404 3
        if (CurrentToken->is(tok::comma) &&
            Style.Language == FormatStyle::LK_JavaScript)
          Left->Type = TT_DictLiteral;
d413 1
a413 1
    if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
d482 6
a487 15
        const FormatToken *BeforePrevious = Tok->Previous->Previous;
        if (!BeforePrevious ||
            !(BeforePrevious->is(TT_CastRParen) ||
              (BeforePrevious->is(TT_ObjCMethodExpr) &&
               BeforePrevious->is(tok::colon))) ||
            BeforePrevious->is(tok::r_square) ||
            Contexts.back().LongestObjCSelectorName == 0) {
          Tok->Previous->Type = TT_SelectorName;
          if (Tok->Previous->ColumnWidth >
              Contexts.back().LongestObjCSelectorName)
            Contexts.back().LongestObjCSelectorName =
                Tok->Previous->ColumnWidth;
          if (!Contexts.back().FirstObjCSelectorName)
            Contexts.back().FirstObjCSelectorName = Tok->Previous;
        }
d494 1
a494 2
        if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
                                                  tok::kw_noexcept))
a506 8
    case tok::pipe:
    case tok::amp:
      // | and & in declarations/type expressions represent union and
      // intersection types, respectively.
      if (Style.Language == FormatStyle::LK_JavaScript &&
          !Contexts.back().IsExpression)
        Tok->Type = TT_JsTypeOperator;
      break;
a515 3
      if (Style.Language == FormatStyle::LK_JavaScript && Tok->Previous &&
          Tok->Previous->is(tok::period))
        break;
d553 5
a557 1
      if (parseAngle()) {
d606 1
a606 1
      if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
a668 1
    bool IsFirstToken = CurrentToken->IsFirst;
a672 13

    if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
      // JavaScript files can contain shebang lines of the form:
      // #!/usr/bin/env node
      // Treat these like C++ #include directives.
      while (CurrentToken) {
        // Tokens cannot be comments here.
        CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
      return LT_ImportStatement;
    }

a747 6

    // import {...} from '...';
    if (Style.Language == FormatStyle::LK_JavaScript &&
        CurrentToken->is(Keywords.kw_import))
      ImportStatement = true;

d751 2
a752 14
      if (Style.Language == FormatStyle::LK_JavaScript) {
        // export {...} from '...';
        // An export followed by "from 'some string';" is a re-export from
        // another module identified by a URI and is treated as a
        // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
        // Just "export {...};" or "export class ..." should not be treated as
        // an import in this sense.
        if (Line.First->is(tok::kw_export) &&
            CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
            CurrentToken->Next->isStringLiteral())
          ImportStatement = true;
        if (isClosureImportStatement(*CurrentToken))
          ImportStatement = true;
      }
d772 1
a772 1
  bool isClosureImportStatement(const FormatToken &Tok) {
d775 2
a776 1
    return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
d780 1
a780 2
                              Tok.Next->Next->TokenText == "setTestOnly" ||
                              Tok.Next->Next->TokenText == "forwardDeclare") &&
d793 1
a793 2
                               TT_OverloadedOperator, TT_RegexLiteral,
                               TT_TemplateString))
a855 3
        // Type aliases use `type X = ...;` in TypeScript.
        !(Style.Language == FormatStyle::LK_JavaScript &&
          Line.startsWith(Keywords.kw_type, tok::identifier)) &&
a884 4
    } else if (Current.Previous &&
               Current.Previous->is(TT_CtorInitializerColon)) {
      Contexts.back().IsExpression = true;
      Contexts.back().InCtorInitializer = true;
d890 6
a895 2
      if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
        Contexts.back().IsExpression = false;
d941 1
a941 1
          Line.MustBeDeclaration && !Contexts.back().IsExpression) {
d967 7
a973 13
          !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
                                 tok::period, tok::arrow, tok::coloncolon))
        if (FormatToken *AfterParen = Current.MatchingParen->Next) {
          // Make sure this isn't the return type of an Obj-C block declaration
          if (AfterParen->Tok.isNot(tok::caret)) {
            if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
              if (BeforeParen->is(tok::identifier) &&
                  BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
                  (!BeforeParen->Previous ||
                   BeforeParen->Previous->ClosesTemplateDeclaration))
                Current.Type = TT_FunctionAnnotationRParen;
          }
        }
a1037 3
    if (Style.Language == FormatStyle::LK_JavaScript &&
        Tok.Previous->is(Keywords.kw_in))
      return false;
a1071 1
        Style.Language != FormatStyle::LK_ObjC &&
d1081 1
a1081 1
      // If there is a closing parenthesis left of the current parentheses,
d1100 1
a1100 1
                                TT_TemplateCloser, tok::ellipsis))
d1134 3
a1136 10
    // Certain token types inside the parentheses mean that this can't be a
    // cast.
    for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
         Token = Token->Next)
      if (Token->is(TT_BinaryOperator))
        return false;

    // If the following token is an identifier or 'this', this is a cast. All
    // cases where this can be something else are handled above.
    if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
d1170 3
a1172 1
    if (!NextToken || NextToken->isOneOf(tok::arrow, tok::equal) ||
d1231 1
a1231 7
    if (!PrevToken)
      return TT_UnaryOperator;

    if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
        !PrevToken->is(tok::exclaim))
      // There aren't any trailing unary operators except for TypeScript's
      // non-null operator (!). Thus, this must be squence of leading operators.
a1392 3
      if (Style.Language == FormatStyle::LK_JavaScript &&
          Current->is(Keywords.kw_in))
        return prec::Relational;
d1397 1
a1397 2
      if ((Style.Language == FormatStyle::LK_Java ||
           Style.Language == FormatStyle::LK_JavaScript) &&
a1483 7
static unsigned maxNestingDepth(const AnnotatedLine &Line) {
  unsigned Result = 0;
  for (const auto* Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
    Result = std::max(Result, Tok->NestingLevel);
  return Result;
}

a1491 8

  // With very deep nesting, ExpressionParser uses lots of stack and the
  // formatting algorithm is very slow. We're not going to do a good job here
  // anyway - it's probably generated code being formatted by mistake.
  // Just skip the whole line.
  if (maxNestingDepth(Line) > 50)
    Line.Type = LT_Invalid;

d1511 1
a1511 2
static bool isFunctionDeclarationName(const FormatToken &Current,
                                      const AnnotatedLine &Line) {
a1530 1
  // Find parentheses of parameter list.
d1560 1
a1560 2
  // Check whether parameter list can be long to a function declaration.
  if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
a1561 3
  // If the lines ends with "{", this is likely an function definition.
  if (Line.Last->is(tok::l_brace))
    return true;
a1562 4
    return true; // Empty parentheses.
  // If there is an &/&& after the r_paren, this is likely a function.
  if (Next->MatchingParen->Next &&
      Next->MatchingParen->Next->is(TT_PointerOrReference))
d1567 1
a1567 1
        Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
d1613 1
a1613 1
    if (isFunctionDeclarationName(*Current, Line))
a1729 3
    if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
        (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
      return 100;
d1732 2
a1733 1
  if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
d1739 1
a1739 1
      return 200;
a1770 2
  if (Left.is(tok::comment))
    return 1000;
a1846 12
  if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
      Left.Previous->isLabelString() &&
      (Left.NextOperator || Left.OperatorIndex != 0))
    return 45;
  if (Right.is(tok::plus) && Left.isLabelString() &&
      (Right.NextOperator || Right.OperatorIndex != 0))
    return 25;
  if (Left.is(tok::comma))
    return 1;
  if (Right.is(tok::lessless) && Left.isLabelString() &&
      (Right.NextOperator || Right.OperatorIndex != 1))
    return 25;
d1848 13
a1860 5
    // Breaking at a << is really cheap.
    if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
      // Slightly prefer to break before the first one in log-like statements.
      return 2;
    return 1;
d1896 2
a1897 1
      Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)
a1898 2
  if (Right.is(tok::less) && Left.is(tok::kw_template))
    return Style.SpaceAfterTemplateKeyword;
d1913 1
a1913 2
    return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
                                    Left.Previous->is(tok::kw_case));
d1917 5
a1921 3
    return (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) ||
           (Left.Tok.isLiteral() || (Left.is(tok::kw_const) && Left.Previous &&
                                     Left.Previous->is(tok::r_paren)) ||
d1924 1
a1924 3
              (Line.IsMultiVariableDeclStmt &&
               (Left.NestingLevel == 0 ||
                (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
d1931 3
a1933 3
    return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
           (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
            !Right.is(TT_StartOfName)) ||
d2024 2
a2025 26
    if (Left.is(TT_JsFatArrow))
      return true;
    if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
        (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
      return false;
    if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
      return false;
    if (Right.is(tok::star) &&
        Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
      return false;
    if (Right.isOneOf(tok::l_brace, tok::l_square) &&
        Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
      return true;
    // JS methods can use some keywords as names (e.g. `delete()`).
    if (Right.is(tok::l_paren) && Line.MustBeDeclaration &&
        Left.Tok.getIdentifierInfo())
      return false;
    if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
                     Keywords.kw_of, tok::kw_const) &&
        (!Left.Previous || !Left.Previous->is(tok::period)))
      return true;
    if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
        Left.Previous->is(tok::period) && Right.is(tok::l_paren))
      return false;
    if (Left.is(Keywords.kw_as) &&
        Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
a2033 2
    if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
      return false;
a2045 7
    // Postfix non-null assertion operator, as in `foo!.bar()`.
    if (Right.is(tok::exclaim) && (Left.isOneOf(tok::identifier, tok::r_paren,
                                                tok::r_square, tok::r_brace) ||
                                   Left.Tok.isLiteral()))
      return false;
    if (Left.is(tok::exclaim) && Right.is(Keywords.kw_as))
      return true; // "x! as string"
d2114 1
a2114 1
  if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
d2117 1
a2117 2
           !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren,
                          tok::l_square) ||
d2155 2
a2156 2
    if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
        Left.Previous->is(tok::string_literal))
d2242 3
a2270 7
    const FormatToken *NonComment = Right.getPreviousNonComment();
    if (Left.isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
                     tok::kw_throw) ||
        (NonComment &&
         NonComment->isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
                             tok::kw_throw)))
      return false; // Otherwise a semicolon is inserted.
a2276 18
    if (Left.is(Keywords.kw_in))
      return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
    if (Right.is(Keywords.kw_in))
      return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
    if (Right.is(Keywords.kw_as))
      return false; // must not break before as in 'x as type' casts
    if (Left.is(Keywords.kw_declare) &&
        Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
                      Keywords.kw_function, tok::kw_class, tok::kw_enum,
                      Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
                      Keywords.kw_let, tok::kw_const))
      // See grammar for 'declare' statements at:
      // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
      return false;
    if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
        Right.isOneOf(tok::identifier, tok::string_literal)) {
      return false; // must not break in "module foo { ...}"
    }
a2308 3
  if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
      Left.isNot(TT_SelectorName))
    return true;
d2312 1
a2312 1
  if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr))
a2327 2
  if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
    return true;
d2393 1
a2393 1
                      tok::kw_class, tok::kw_struct, tok::comment) ||
d2416 1
a2416 2
    llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
    llvm::errs() << " Text='" << Tok->TokenText << "'\n";
@


1.1.1.10
log
@Import Clang pre-4.0.0 r291444.
@
text
@d45 1
a45 3
    if (!CurrentToken || !CurrentToken->Previous)
      return false;
    if (NonTemplateLess.count(CurrentToken->Previous))
a46 11

    const FormatToken& Previous = *CurrentToken->Previous;
    if (Previous.Previous) {
      if (Previous.Previous->Tok.isLiteral())
        return false;
      if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
          (!Previous.Previous->MatchingParen ||
           !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
        return false;
    }

d49 1
a49 1
    ScopedContextCreator ContextCreator(*this, tok::less, 12);
a123 4
    } else if (Style.Language == FormatStyle::LK_JavaScript &&
               Line.startsWith(Keywords.kw_type, tok::identifier)) {
      // type X = (...);
      Contexts.back().IsExpression = false;
a130 10
    } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
               (Left->Previous->is(Keywords.kw_function) ||
                (Left->Previous->endsSequence(tok::identifier,
                                              Keywords.kw_function)))) {
      // function(...) or function f(...)
      Contexts.back().IsExpression = false;
    } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
               Left->Previous->is(TT_JsTypeColon)) {
      // let x: (SomeType);
      Contexts.back().IsExpression = false;
d162 2
a163 2
    bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
    bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
d190 1
a190 3
        ProbablyFunctionType = true;
      if (CurrentToken->is(tok::comma))
        MightBeFunctionType = false;
d194 1
a194 1
        if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
d196 2
a197 1
             (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
d248 2
a249 3
      if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
           CurrentToken->Previous->isSimpleTypeSpecifier()) &&
          !CurrentToken->is(tok::l_brace))
a279 10

    // Cases where '>' is followed by '['.
    // In C++, this can happen either in array of templates (foo<int>[10])
    // or when array is a nested template type (unique_ptr<type1<type2>[]>).
    bool CppArrayTemplates =
        Style.Language == FormatStyle::LK_Cpp && Parent &&
        Parent->is(TT_TemplateCloser) &&
        (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
         Contexts.back().InTemplateArgument);

d281 1
a281 2
        !CppArrayTemplates && (Style.Language == FormatStyle::LK_Cpp ||
                               Style.Language == FormatStyle::LK_ObjC) &&
d301 4
a304 4
                 (!CppArrayTemplates && Parent &&
                  Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
                                  tok::comma, tok::l_paren, tok::l_square,
                                  tok::question, tok::colon, tok::kw_return,
d397 1
a397 2
                 (Style.Language != FormatStyle::LK_Cpp &&
                  Style.Language != FormatStyle::LK_ObjC))) ||
d399 1
a399 2
              (Previous->Tok.getIdentifierInfo() ||
               Previous->is(tok::string_literal)))
a404 3
        if (CurrentToken->is(tok::comma) &&
            Style.Language == FormatStyle::LK_JavaScript)
          Left->Type = TT_DictLiteral;
d413 1
a413 1
    if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
d482 6
a487 15
        const FormatToken *BeforePrevious = Tok->Previous->Previous;
        if (!BeforePrevious ||
            !(BeforePrevious->is(TT_CastRParen) ||
              (BeforePrevious->is(TT_ObjCMethodExpr) &&
               BeforePrevious->is(tok::colon))) ||
            BeforePrevious->is(tok::r_square) ||
            Contexts.back().LongestObjCSelectorName == 0) {
          Tok->Previous->Type = TT_SelectorName;
          if (Tok->Previous->ColumnWidth >
              Contexts.back().LongestObjCSelectorName)
            Contexts.back().LongestObjCSelectorName =
                Tok->Previous->ColumnWidth;
          if (!Contexts.back().FirstObjCSelectorName)
            Contexts.back().FirstObjCSelectorName = Tok->Previous;
        }
d494 1
a494 2
        if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
                                                  tok::kw_noexcept))
a506 8
    case tok::pipe:
    case tok::amp:
      // | and & in declarations/type expressions represent union and
      // intersection types, respectively.
      if (Style.Language == FormatStyle::LK_JavaScript &&
          !Contexts.back().IsExpression)
        Tok->Type = TT_JsTypeOperator;
      break;
a515 3
      if (Style.Language == FormatStyle::LK_JavaScript && Tok->Previous &&
          Tok->Previous->is(tok::period))
        break;
d553 5
a557 1
      if (parseAngle()) {
d606 1
a606 1
      if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
a668 1
    bool IsFirstToken = CurrentToken->IsFirst;
a672 13

    if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
      // JavaScript files can contain shebang lines of the form:
      // #!/usr/bin/env node
      // Treat these like C++ #include directives.
      while (CurrentToken) {
        // Tokens cannot be comments here.
        CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
      return LT_ImportStatement;
    }

a747 6

    // import {...} from '...';
    if (Style.Language == FormatStyle::LK_JavaScript &&
        CurrentToken->is(Keywords.kw_import))
      ImportStatement = true;

d751 2
a752 14
      if (Style.Language == FormatStyle::LK_JavaScript) {
        // export {...} from '...';
        // An export followed by "from 'some string';" is a re-export from
        // another module identified by a URI and is treated as a
        // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
        // Just "export {...};" or "export class ..." should not be treated as
        // an import in this sense.
        if (Line.First->is(tok::kw_export) &&
            CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
            CurrentToken->Next->isStringLiteral())
          ImportStatement = true;
        if (isClosureImportStatement(*CurrentToken))
          ImportStatement = true;
      }
d772 1
a772 1
  bool isClosureImportStatement(const FormatToken &Tok) {
d775 2
a776 1
    return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
d780 1
a780 2
                              Tok.Next->Next->TokenText == "setTestOnly" ||
                              Tok.Next->Next->TokenText == "forwardDeclare") &&
d793 1
a793 2
                               TT_OverloadedOperator, TT_RegexLiteral,
                               TT_TemplateString))
a855 3
        // Type aliases use `type X = ...;` in TypeScript.
        !(Style.Language == FormatStyle::LK_JavaScript &&
          Line.startsWith(Keywords.kw_type, tok::identifier)) &&
a884 4
    } else if (Current.Previous &&
               Current.Previous->is(TT_CtorInitializerColon)) {
      Contexts.back().IsExpression = true;
      Contexts.back().InCtorInitializer = true;
d890 6
a895 2
      if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
        Contexts.back().IsExpression = false;
d941 1
a941 1
          Line.MustBeDeclaration && !Contexts.back().IsExpression) {
d967 7
a973 13
          !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
                                 tok::period, tok::arrow, tok::coloncolon))
        if (FormatToken *AfterParen = Current.MatchingParen->Next) {
          // Make sure this isn't the return type of an Obj-C block declaration
          if (AfterParen->Tok.isNot(tok::caret)) {
            if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
              if (BeforeParen->is(tok::identifier) &&
                  BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
                  (!BeforeParen->Previous ||
                   BeforeParen->Previous->ClosesTemplateDeclaration))
                Current.Type = TT_FunctionAnnotationRParen;
          }
        }
a1037 3
    if (Style.Language == FormatStyle::LK_JavaScript &&
        Tok.Previous->is(Keywords.kw_in))
      return false;
a1071 1
        Style.Language != FormatStyle::LK_ObjC &&
d1081 1
a1081 1
      // If there is a closing parenthesis left of the current parentheses,
d1100 1
a1100 1
                                TT_TemplateCloser, tok::ellipsis))
d1134 3
a1136 10
    // Certain token types inside the parentheses mean that this can't be a
    // cast.
    for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
         Token = Token->Next)
      if (Token->is(TT_BinaryOperator))
        return false;

    // If the following token is an identifier or 'this', this is a cast. All
    // cases where this can be something else are handled above.
    if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
d1170 3
a1172 1
    if (!NextToken || NextToken->isOneOf(tok::arrow, tok::equal) ||
d1231 1
a1231 7
    if (!PrevToken)
      return TT_UnaryOperator;

    if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
        !PrevToken->is(tok::exclaim))
      // There aren't any trailing unary operators except for TypeScript's
      // non-null operator (!). Thus, this must be squence of leading operators.
a1392 3
      if (Style.Language == FormatStyle::LK_JavaScript &&
          Current->is(Keywords.kw_in))
        return prec::Relational;
d1397 1
a1397 2
      if ((Style.Language == FormatStyle::LK_Java ||
           Style.Language == FormatStyle::LK_JavaScript) &&
a1483 7
static unsigned maxNestingDepth(const AnnotatedLine &Line) {
  unsigned Result = 0;
  for (const auto* Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
    Result = std::max(Result, Tok->NestingLevel);
  return Result;
}

a1491 8

  // With very deep nesting, ExpressionParser uses lots of stack and the
  // formatting algorithm is very slow. We're not going to do a good job here
  // anyway - it's probably generated code being formatted by mistake.
  // Just skip the whole line.
  if (maxNestingDepth(Line) > 50)
    Line.Type = LT_Invalid;

d1511 1
a1511 2
static bool isFunctionDeclarationName(const FormatToken &Current,
                                      const AnnotatedLine &Line) {
a1530 1
  // Find parentheses of parameter list.
d1560 1
a1560 2
  // Check whether parameter list can be long to a function declaration.
  if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
a1561 3
  // If the lines ends with "{", this is likely an function definition.
  if (Line.Last->is(tok::l_brace))
    return true;
a1562 4
    return true; // Empty parentheses.
  // If there is an &/&& after the r_paren, this is likely a function.
  if (Next->MatchingParen->Next &&
      Next->MatchingParen->Next->is(TT_PointerOrReference))
d1567 1
a1567 1
        Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
d1613 1
a1613 1
    if (isFunctionDeclarationName(*Current, Line))
a1729 3
    if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
        (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
      return 100;
d1732 2
a1733 1
  if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
d1739 1
a1739 1
      return 200;
a1770 2
  if (Left.is(tok::comment))
    return 1000;
a1846 12
  if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
      Left.Previous->isLabelString() &&
      (Left.NextOperator || Left.OperatorIndex != 0))
    return 45;
  if (Right.is(tok::plus) && Left.isLabelString() &&
      (Right.NextOperator || Right.OperatorIndex != 0))
    return 25;
  if (Left.is(tok::comma))
    return 1;
  if (Right.is(tok::lessless) && Left.isLabelString() &&
      (Right.NextOperator || Right.OperatorIndex != 1))
    return 25;
d1848 13
a1860 5
    // Breaking at a << is really cheap.
    if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
      // Slightly prefer to break before the first one in log-like statements.
      return 2;
    return 1;
d1896 2
a1897 1
      Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)
a1898 2
  if (Right.is(tok::less) && Left.is(tok::kw_template))
    return Style.SpaceAfterTemplateKeyword;
d1913 1
a1913 2
    return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
                                    Left.Previous->is(tok::kw_case));
d1917 5
a1921 3
    return (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) ||
           (Left.Tok.isLiteral() || (Left.is(tok::kw_const) && Left.Previous &&
                                     Left.Previous->is(tok::r_paren)) ||
d1924 1
a1924 3
              (Line.IsMultiVariableDeclStmt &&
               (Left.NestingLevel == 0 ||
                (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
d1931 3
a1933 3
    return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
           (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
            !Right.is(TT_StartOfName)) ||
d2024 2
a2025 26
    if (Left.is(TT_JsFatArrow))
      return true;
    if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
        (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
      return false;
    if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
      return false;
    if (Right.is(tok::star) &&
        Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
      return false;
    if (Right.isOneOf(tok::l_brace, tok::l_square) &&
        Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
      return true;
    // JS methods can use some keywords as names (e.g. `delete()`).
    if (Right.is(tok::l_paren) && Line.MustBeDeclaration &&
        Left.Tok.getIdentifierInfo())
      return false;
    if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
                     Keywords.kw_of, tok::kw_const) &&
        (!Left.Previous || !Left.Previous->is(tok::period)))
      return true;
    if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
        Left.Previous->is(tok::period) && Right.is(tok::l_paren))
      return false;
    if (Left.is(Keywords.kw_as) &&
        Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
a2033 2
    if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
      return false;
a2045 7
    // Postfix non-null assertion operator, as in `foo!.bar()`.
    if (Right.is(tok::exclaim) && (Left.isOneOf(tok::identifier, tok::r_paren,
                                                tok::r_square, tok::r_brace) ||
                                   Left.Tok.isLiteral()))
      return false;
    if (Left.is(tok::exclaim) && Right.is(Keywords.kw_as))
      return true; // "x! as string"
d2114 1
a2114 1
  if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
d2117 1
a2117 2
           !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren,
                          tok::l_square) ||
d2155 2
a2156 2
    if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
        Left.Previous->is(tok::string_literal))
d2242 3
a2270 7
    const FormatToken *NonComment = Right.getPreviousNonComment();
    if (Left.isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
                     tok::kw_throw) ||
        (NonComment &&
         NonComment->isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
                             tok::kw_throw)))
      return false; // Otherwise a semicolon is inserted.
a2276 18
    if (Left.is(Keywords.kw_in))
      return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
    if (Right.is(Keywords.kw_in))
      return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
    if (Right.is(Keywords.kw_as))
      return false; // must not break before as in 'x as type' casts
    if (Left.is(Keywords.kw_declare) &&
        Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
                      Keywords.kw_function, tok::kw_class, tok::kw_enum,
                      Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
                      Keywords.kw_let, tok::kw_const))
      // See grammar for 'declare' statements at:
      // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
      return false;
    if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
        Right.isOneOf(tok::identifier, tok::string_literal)) {
      return false; // must not break in "module foo { ...}"
    }
a2308 3
  if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
      Left.isNot(TT_SelectorName))
    return true;
d2312 1
a2312 1
  if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr))
a2327 2
  if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
    return true;
d2393 1
a2393 1
                      tok::kw_class, tok::kw_struct, tok::comment) ||
d2416 1
a2416 2
    llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
    llvm::errs() << " Text='" << Tok->TokenText << "'\n";
@


1.1.1.11
log
@Import clang r309604 from branches/release_50
@
text
@d92 1
a92 3
          (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
           Style.Language != FormatStyle::LK_Proto &&
           Style.Language != FormatStyle::LK_TextProto))
a105 8
      if (Style.Language == FormatStyle::LK_Proto) {
        if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
          if (CurrentToken->is(tok::colon) ||
              (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
               Previous->isNot(tok::colon)))
            Previous->Type = TT_SelectorName;
        }
      }
d138 1
a138 3
               (Line.startsWith(Keywords.kw_type, tok::identifier) ||
                Line.startsWith(tok::kw_export, Keywords.kw_type,
                                tok::identifier))) {
a139 1
      // export type X = (...);
a144 1
         Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
d314 1
a314 1
        Style.isCpp() && Parent &&
d320 2
a321 1
        !CppArrayTemplates && Style.isCpp() &&
a339 6
      } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
                 Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
        Left->Type = TT_DesignatedInitializerLSquare;
      } else if (CurrentToken->is(tok::r_square) && Parent &&
                 Parent->is(TT_TemplateCloser)) {
        Left->Type = TT_ArraySubscriptLSquare;
d389 1
a389 2
        if (Left->isOneOf(TT_ArraySubscriptLSquare,
                          TT_DesignatedInitializerLSquare)) {
d433 1
a433 1
        if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
d436 4
a439 3
                (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
               Style.Language == FormatStyle::LK_Proto ||
               Style.Language == FormatStyle::LK_TextProto) &&
d522 1
a522 2
          Style.Language == FormatStyle::LK_Proto ||
          Style.Language == FormatStyle::LK_TextProto) {
a523 4
        if (Style.Language == FormatStyle::LK_TextProto) {
          if (FormatToken *Previous = Tok->getPreviousNonComment())
            Previous->Type = TT_SelectorName;
        }
a571 2
      if (Tok->is(tok::kw_if) && CurrentToken && CurrentToken->is(tok::kw_constexpr))
        next();
d579 3
a581 7
      if (Style.Language == FormatStyle::LK_JavaScript) {
        if (Tok->Previous && Tok->Previous->is(tok::period))
          break;
        // JS' for await ( ...
        if (CurrentToken && CurrentToken->is(Keywords.kw_await))
          next();
      }
a614 5
      if (Style.Language == FormatStyle::LK_TextProto) {
        FormatToken *Previous =Tok->getPreviousNonComment();
        if (Previous && Previous->Type != TT_DictLiteral)
          Previous->Type = TT_SelectorName;
      }
a620 5
        if (Style.Language == FormatStyle::LK_TextProto) {
          FormatToken *Previous = Tok->getPreviousNonComment();
          if (Previous && Previous->Type != TT_DictLiteral)
            Previous->Type = TT_SelectorName;
        }
a678 2
      else if (Contexts.back().InInheritanceList)
        Tok->Type = TT_InheritanceComma;
a686 6
    case tok::identifier:
      if (Tok->isOneOf(Keywords.kw___has_include,
                       Keywords.kw___has_include_next)) {
        parseHasInclude();
      }
      break;
d695 3
a697 6
     next();
     while (CurrentToken) {
        // Mark tokens up to the trailing line comments as implicit string
        // literals.
        if (CurrentToken->isNot(tok::comment) &&
            !CurrentToken->TokenText.startswith("//"))
a729 8
  void parseHasInclude() {
    if (!CurrentToken || !CurrentToken->is(tok::l_paren))
      return;
    next();  // '('
    parseIncludeDirective();
    next();  // ')'
  }

d780 1
a780 2
    while (CurrentToken) {
      FormatToken *Tok = CurrentToken;
a781 6
      if (Tok->is(tok::l_paren))
        parseParens();
      else if (Tok->isOneOf(Keywords.kw___has_include,
                       Keywords.kw___has_include_next))
        parseHasInclude();
    }
d888 1
a888 1
                               TT_TemplateString, TT_ObjCStringLiteral))
a927 1
    bool InInheritanceList = false;
d951 1
a951 2
        // Type aliases use `type X = ...;` in TypeScript and can be exported
        // using `export type ...`.
d953 1
a953 3
          (Line.startsWith(Keywords.kw_type, tok::identifier) ||
           Line.startsWith(tok::kw_export, Keywords.kw_type,
                           tok::identifier))) &&
a986 3
    } else if (Current.Previous &&
               Current.Previous->is(TT_InheritanceColon)) {
      Contexts.back().InInheritanceList = true;
a1006 18
    if (Style.Language == FormatStyle::LK_JavaScript) {
      if (Current.is(tok::exclaim)) {
        if (Current.Previous &&
            (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
                                       tok::r_paren, tok::r_square,
                                       tok::r_brace) ||
             Current.Previous->Tok.isLiteral())) {
          Current.Type = TT_JsNonNullAssertion;
          return;
        }
        if (Current.Next &&
            Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
          Current.Type = TT_JsNonNullAssertion;
          return;
        }
      }
    }

d1066 1
a1066 2
                                 tok::comma, tok::period, tok::arrow,
                                 tok::coloncolon))
d1078 16
a1093 16
    } else if (Current.is(tok::at) && Current.Next &&
               Style.Language != FormatStyle::LK_JavaScript &&
               Style.Language != FormatStyle::LK_Java) {
      // In Java & JavaScript, "@@..." is a decorator or annotation. In ObjC, it
      // marks declarations and properties that need special formatting.
      switch (Current.Next->Tok.getObjCKeywordID()) {
      case tok::objc_interface:
      case tok::objc_implementation:
      case tok::objc_protocol:
        Current.Type = TT_ObjCDecl;
        break;
      case tok::objc_property:
        Current.Type = TT_ObjCProperty;
        break;
      default:
        break;
d1140 1
a1140 2
    if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
                              Keywords.kw_as))
d1147 1
a1147 1
    FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
d1149 1
a1149 1
      PreviousNotConst = PreviousNotConst->getPreviousNonComment();
d1178 3
a1180 1
    if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
d1285 1
a1285 2
    if (!NextToken ||
        NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
d1294 1
a1294 2
                           tok::equal, tok::kw_delete, tok::kw_sizeof,
                           tok::kw_throw) ||
d1448 1
a1448 3
      if (!Current ||
          (Current->closesScope() &&
           (Current->MatchingParen || Current->is(TT_TemplateString))) ||
d1457 1
a1457 3
        // In fragment of a JavaScript template string can look like '}..${' and
        // thus close a scope and open a new one at the same time.
        while (Current && (!Current->closesScope() || Current->opensScope())) {
d1494 3
a1496 8
      if (NextNonComment && Current->is(TT_SelectorName) &&
          (NextNonComment->is(TT_DictLiteral) ||
           ((Style.Language == FormatStyle::LK_Proto ||
             Style.Language == FormatStyle::LK_TextProto) &&
            NextNonComment->is(tok::less))))
        return prec::Assignment;
      if (Current->is(TT_JsComputedPropertyName))
        return prec::Assignment;
d1501 2
a1502 1
      if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
d1513 1
a1513 1
          Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
d1597 4
a1600 18
    bool CommentLine = true;
    for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
      if (!Tok->is(tok::comment)) {
        CommentLine = false;
        break;
      }
    }

    if (NextNonCommentLine && CommentLine) {
      // If the comment is currently aligned with the line immediately following
      // it, that's probably intentional and we should keep it.
      bool AlignedWithNextLine =
          NextNonCommentLine->First->NewlinesBefore <= 1 &&
          NextNonCommentLine->First->OriginalColumn ==
              (*I)->First->OriginalColumn;
      if (AlignedWithNextLine)
        (*I)->Level = NextNonCommentLine->Level;
    } else {
a1601 1
    }
d1700 1
a1700 1
  // Check whether parameter list can belong to a function declaration.
a1713 4
    if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
      Tok = Tok->MatchingParen;
      continue;
    }
d1756 2
a1832 1
  unsigned IndentLevel = Line.Level;
a1835 8
    if (Current->MatchingParen &&
        Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
      assert(IndentLevel > 0);
      --IndentLevel;
    }
    Current->IndentLevel = IndentLevel;
    if (Current->opensBlockOrBlockTypeList(Style))
      ++IndentLevel;
d1894 1
a1894 2
                       TT_ArrayInitializerLSquare,
                       TT_DesignatedInitializerLSquare))
d1913 1
a1913 1
    return 160;
d1924 1
a1924 1
  if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon, TT_CtorInitializerColon))
d1982 1
a1982 2
      (Left.Previous->isOneOf(tok::kw_if, tok::kw_for)
       || Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
d2021 3
a2023 4
  if (Level == prec::Unknown)
    Level = Right.getPrecedence();
  if (Level == prec::Assignment)
    return Style.PenaltyBreakAssignment;
d2113 1
a2113 2
      !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
                     TT_DesignatedInitializerLSquare) &&
a2131 1
             Left.endsSequence(tok::kw_constexpr, tok::kw_if) ||
d2170 1
a2170 1
  if (Style.isCpp()) {
d2173 1
a2173 2
  } else if (Style.Language == FormatStyle::LK_Proto ||
             Style.Language == FormatStyle::LK_TextProto) {
a2180 2
    if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
      return true;
a2183 12
    // for await ( ...
    if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) &&
        Left.Previous && Left.Previous->is(tok::kw_for))
      return true;
    if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
        Right.MatchingParen) {
      const FormatToken *Next = Right.MatchingParen->getNextNonComment();
      // An async arrow function, for example: `x = async () => foo();`,
      // as opposed to calling a function called async: `x = async();`
      if (Next && Next->is(TT_JsFatArrow))
        return true;
    }
d2187 1
a2187 5
    // In tagged template literals ("html`bar baz`"), there is no space between
    // the tag identifier and the template string. getIdentifierInfo makes sure
    // that the identifier is not a pseudo keyword like `yield`, either.
    if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
        Right.is(TT_TemplateString))
d2199 2
a2200 6
    if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
                      tok::kw_const) ||
         // "of" is only a keyword if it appears after another identifier
         // (e.g. as "const x of y" in a for loop).
         (Left.is(Keywords.kw_of) && Left.Previous &&
          Left.Previous->Tok.getIdentifierInfo())) &&
d2230 4
a2233 1
    if (Right.is(TT_JsNonNullAssertion))
d2235 1
a2235 1
    if (Left.is(TT_JsNonNullAssertion) && Right.is(Keywords.kw_as))
d2299 2
a2300 3
  if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
      Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
      (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
a2304 5
  if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
    // Generally don't remove existing spaces between an identifier and "::".
    // The identifier might actually be a macro name such as ALWAYS_INLINE. If
    // this turns out to be too lenient, add analysis of the identifier itself.
    return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
d2308 3
a2310 2
           !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
                          tok::kw___super, TT_TemplateCloser, TT_TemplateOpener));
d2372 2
a2373 2
              Style.AllowShortFunctionsOnASingleLine &
                  FormatStyle::SFS_InlineOnly);
a2377 5
  } else if (Style.Language == FormatStyle::LK_Cpp ||
             Style.Language == FormatStyle::LK_ObjC ||
             Style.Language == FormatStyle::LK_Proto) {
    if (Left.isStringLiteral() && Right.isStringLiteral())
      return true;
d2380 14
a2393 21
  // If the last token before a '}', ']', or ')' is a comma or a trailing
  // comment, the intention is to insert a line break after it in order to make
  // shuffling around entries easier. Import statements, especially in
  // JavaScript, can be an exception to this rule.
  if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
    const FormatToken *BeforeClosingBrace = nullptr;
    if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
         (Style.Language == FormatStyle::LK_JavaScript &&
          Left.is(tok::l_paren))) &&
        Left.BlockKind != BK_Block && Left.MatchingParen)
      BeforeClosingBrace = Left.MatchingParen->Previous;
    else if (Right.MatchingParen &&
             (Right.MatchingParen->isOneOf(tok::l_brace,
                                           TT_ArrayInitializerLSquare) ||
              (Style.Language == FormatStyle::LK_JavaScript &&
               Right.MatchingParen->is(tok::l_paren))))
      BeforeClosingBrace = &Left;
    if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
                               BeforeClosingBrace->isTrailingComment()))
      return true;
  }
d2401 3
d2415 2
a2416 6
  if (Right.is(TT_CtorInitializerComma) &&
      Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
      !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
    return true;
  if (Right.is(TT_CtorInitializerColon) &&
      Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
a2418 4
  // Break only if we have multiple inheritance.
  if (Style.BreakBeforeInheritanceComma &&
      Right.is(TT_InheritanceComma))
   return true;
d2424 3
a2426 8
  if ((Right.Previous->is(tok::l_brace) ||
       (Right.Previous->is(tok::less) &&
        Right.Previous->Previous &&
        Right.Previous->Previous->is(tok::equal))
        ) &&
      Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
    // Don't put enums or option definitions onto single lines in protocol
    // buffers.
a2427 1
  }
d2461 6
a2466 8
    if (NonComment &&
        NonComment->isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
                            tok::kw_throw, Keywords.kw_interface,
                            Keywords.kw_type, tok::kw_static, tok::kw_public,
                            tok::kw_private, tok::kw_protected,
                            Keywords.kw_readonly, Keywords.kw_abstract,
                            Keywords.kw_get, Keywords.kw_set))
      return false; // Otherwise automatic semicolon insertion would trigger.
a2478 4
    if (Left.is(Keywords.kw_as))
      return true;
    if (Left.is(TT_JsNonNullAssertion))
      return true;
d2488 1
a2488 1
        Right.isOneOf(tok::identifier, tok::string_literal))
d2490 1
a2490 4
    if (Right.is(TT_TemplateString) && Right.closesScope())
      return false;
    if (Left.is(TT_TemplateString) && Left.opensScope())
      return true;
d2514 1
a2514 4
    return Left.BlockKind == BK_BracedInit ||
           (Left.is(TT_CtorInitializerColon) &&
            Style.BreakConstructorInitializers ==
                FormatStyle::BCIS_AfterColon);
a2586 4
  if (Left.is(TT_CtorInitializerColon))
    return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
  if (Right.is(TT_CtorInitializerColon))
    return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
d2588 1
a2588 1
      Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
d2591 1
a2591 5
      Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
    return true;
  if (Left.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
    return false;
  if (Right.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
d2618 1
a2618 2
         (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
         (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
a2629 1
                 << " BK=" << Tok->BlockKind
@


1.1.1.11.4.1
log
@Sync with HEAD
@
text
@d11 1
a11 1
/// This file implements a token annotator, i.e. creates
d28 1
a28 16
/// Returns \c true if the token can be used as an identifier in
/// an Objective-C \c @@selector, \c false otherwise.
///
/// Because getFormattingLangOpts() always lexes source code as
/// Objective-C++, C++ keywords like \c new and \c delete are
/// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
///
/// For Objective-C and Objective-C++, both identifiers and keywords
/// are valid inside @@selector(...) (or a macro which
/// invokes @@selector(...)). So, we allow treat any identifier or
/// keyword as a potential Objective-C selector component.
static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
  return Tok.Tok.getIdentifierInfo() != nullptr;
}

/// A parser that gathers additional information about tokens.
d50 1
a50 1
    const FormatToken &Previous = *CurrentToken->Previous;  // The '<'.
d82 1
a82 11
        // In TT_Proto, we must distignuish between:
        //   map<key, value>
        //   msg < item: data >
        //   msg: < item: data >
        // In TT_TextProto, map<key, value> does not occur.
        if (Style.Language == FormatStyle::LK_TextProto ||
            (Style.Language == FormatStyle::LK_Proto && Left->Previous &&
             Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral)))
          CurrentToken->Type = TT_DictLiteral;
        else
          CurrentToken->Type = TT_TemplateCloser;
d134 4
a137 1
    if (FormatToken *MaybeSel = Left->Previous) {
d155 5
a159 5
               (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
                                        tok::kw_if, tok::kw_while, tok::l_paren,
                                        tok::comma) ||
                Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
                Left->Previous->is(TT_BinaryOperator))) {
a202 7
    // MightBeFunctionType and ProbablyFunctionType are used for
    // function pointer and reference types as well as Objective-C
    // block types:
    //
    // void (*FunctionPointer)(void);
    // void (&FunctionReference)(void);
    // void (^ObjCBlock)(void);
d204 1
a204 2
    bool ProbablyFunctionType =
        CurrentToken->isOneOf(tok::star, tok::amp, tok::caret);
a208 1
    FormatToken *PossibleObjCForInToken = nullptr;
d240 1
a240 2
          Left->Type = Left->Next->is(tok::caret) ? TT_ObjCBlockLParen
                                                  : TT_FunctionTypeLParen;
d294 1
a294 1
      if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
d296 2
a297 9
        if (PossibleObjCForInToken) {
          PossibleObjCForInToken->Type = TT_Unknown;
          PossibleObjCForInToken = nullptr;
        }
      }
      if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
        PossibleObjCForInToken = CurrentToken;
        PossibleObjCForInToken->Type = TT_ObjCForIn;
      }
a312 26
  bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
    if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
      return false;
    const FormatToken *AttrTok = Tok.Next->Next;
    if (!AttrTok)
      return false;
    // C++17 '[[using ns: foo, bar(baz, blech)]]'
    // We assume nobody will name an ObjC variable 'using'.
    if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
      return true;
    if (AttrTok->isNot(tok::identifier))
      return false;
    while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
      // ObjC message send. We assume nobody will use : in a C++11 attribute
      // specifier parameter, although this is technically valid:
      // [[foo(:)]]
      if (AttrTok->is(tok::colon) ||
          AttrTok->startsSequence(tok::identifier, tok::identifier))
        return false;
      if (AttrTok->is(tok::ellipsis))
        return true;
      AttrTok = AttrTok->Next;
    }
    return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
  }

d319 1
a319 2
    // expression, it could the start of an Objective-C array literal,
    // or it could be a C++ attribute specifier [[foo::bar]].
d328 2
a329 1
        Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
a332 3
    bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
                                     Contexts.back().InCpp11AttributeSpecifier;

d334 1
a334 1
        !CppArrayTemplates && Style.isCpp() && !IsCpp11AttributeSpecifier &&
d336 1
a336 1
        !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
a340 1
         // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
d346 1
a346 3
    if (Left->isCppStructuredBinding(Style)) {
      Left->Type = TT_StructuredBindingLSquare;
    } else if (Left->is(TT_Unknown)) {
a348 2
      } else if (IsCpp11AttributeSpecifier) {
        Left->Type = TT_AttributeSquare;
d360 6
a365 42
                 Style.Language == FormatStyle::LK_TextProto) {
        // Square braces in LK_Proto can either be message field attributes:
        //
        // optional Aaa aaa = 1 [
        //   (aaa) = aaa
        // ];
        //
        // extensions 123 [
        //   (aaa) = aaa
        // ];
        //
        // or text proto extensions (in options):
        //
        // option (Aaa.options) = {
        //   [type.type/type] {
        //     key: value
        //   }
        // }
        //
        // or repeated fields (in options):
        //
        // option (Aaa.options) = {
        //   keys: [ 1, 2, 3 ]
        // }
        //
        // In the first and the third case we want to spread the contents inside
        // the square braces; in the second we want to keep them inline.
        Left->Type = TT_ArrayInitializerLSquare;
        if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
                                tok::equal) &&
            !Left->endsSequence(tok::l_square, tok::numeric_constant,
                                tok::identifier) &&
            !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
          Left->Type = TT_ProtoExtensionLSquare;
          BindingIncrease = 10;
        }
      } else if (!CppArrayTemplates && Parent &&
                 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
                                 tok::comma, tok::l_paren, tok::l_square,
                                 tok::question, tok::colon, tok::kw_return,
                                 // Should only be relevant to JavaScript:
                                 tok::kw_default)) {
a374 4
    if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
        Parent->is(TT_JsTypeColon))
      Contexts.back().IsExpression = false;

a375 1
    Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
d379 2
a380 4
        if (IsCpp11AttributeSpecifier)
          CurrentToken->Type = TT_AttributeSquare;
        else if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
                 Left->is(TT_ObjCMethodExpr)) {
a387 6
          // If we haven't seen a colon yet, make sure the last identifier
          // before the r_square is tagged as a selector name component.
          if (!ColonFound && CurrentToken->Previous &&
              CurrentToken->Previous->is(TT_Unknown) &&
              canBeObjCSelectorComponent(*CurrentToken->Previous))
            CurrentToken->Previous->Type = TT_SelectorName;
a395 14
        // FirstObjCSelectorName is set when a colon is found. This does
        // not work, however, when the method has no parameters.
        // Here, we set FirstObjCSelectorName when the end of the method call is
        // reached, in case it was not set already.
        if (!Contexts.back().FirstObjCSelectorName) {
            FormatToken* Previous = CurrentToken->getPreviousNonComment();
            if (Previous && Previous->is(TT_SelectorName)) {
              Previous->ObjCSelectorNameParts = 1;
              Contexts.back().FirstObjCSelectorName = Previous;
            }
        } else {
          Left->ParameterCount =
              Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
        }
d408 2
a409 8
        if (IsCpp11AttributeSpecifier &&
            CurrentToken->endsSequence(tok::colon, tok::identifier,
                                       tok::kw_using)) {
          // Remember that this is a [[using ns: foo]] C++ attribute, so we
          // don't add a space before the colon (unlike other colons).
          CurrentToken->Type = TT_AttributeColon;
        } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
                                 TT_DesignatedInitializerLSquare)) {
a413 1
            // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
a441 3
      if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
          Left->Previous->is(TT_JsTypeColon))
        Contexts.back().IsExpression = false;
d455 7
a461 11
          if (Previous->is(TT_JsTypeOptionalQuestion))
            Previous = Previous->getPreviousNonComment();
          if ((CurrentToken->is(tok::colon) &&
               (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
              Style.Language == FormatStyle::LK_Proto ||
              Style.Language == FormatStyle::LK_TextProto) {
            Left->Type = TT_DictLiteral;
            if (Previous->Tok.getIdentifierInfo() ||
                Previous->is(tok::string_literal))
              Previous->Type = TT_SelectorName;
          }
a476 3
    // For ObjC methods, the number of parameters is calculated differently as
    // method declarations have a different structure (the parameters are not
    // inside a bracket scope).
a533 2
            (!Contexts.back().IsExpression &&
             Contexts.back().ContextKind == tok::l_brace) || // object type
a535 1
          Contexts.back().IsExpression = false;
a551 5
        // Ensure we tag all identifiers in method declarations as
        // TT_SelectorName.
        bool UnknownIdentifierInMethodDeclaration =
            Line.startsWith(TT_ObjCMethodSpecifier) &&
            Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
a552 1
            // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
d557 1
a557 2
            Contexts.back().LongestObjCSelectorName == 0 ||
            UnknownIdentifierInMethodDeclaration) {
d559 4
a564 7
          else if (Tok->Previous->ColumnWidth >
                   Contexts.back().LongestObjCSelectorName)
            Contexts.back().LongestObjCSelectorName =
                Tok->Previous->ColumnWidth;
          Tok->Previous->ParameterIndex =
              Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
          ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
d577 2
a578 4
      } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
                 (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
                  (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
                   Tok->Next->Next->is(tok::colon)))) {
d596 1
a596 2
      if (Tok->is(tok::kw_if) && CurrentToken &&
          CurrentToken->is(tok::kw_constexpr))
d606 1
a606 3
        // x.for and {for: ...}
        if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
            (Tok->Next && Tok->Next->is(tok::colon)))
d622 2
a623 1
      if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
d646 1
a646 1
        FormatToken *Previous = Tok->getPreviousNonComment();
d656 1
a656 9
        // In TT_Proto, we must distignuish between:
        //   map<key, value>
        //   msg < item: data >
        //   msg: < item: data >
        // In TT_TextProto, map<key, value> does not occur.
        if (Style.Language == FormatStyle::LK_TextProto ||
            (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
             Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
          Tok->Type = TT_DictLiteral;
d677 1
a677 2
      if (Style.Language != FormatStyle::LK_TextProto)
        Tok->Type = TT_BinaryOperator;
a679 3
      if (Style.Language == FormatStyle::LK_TextProto ||
          Style.Language == FormatStyle::LK_Proto)
        break;
d686 1
a686 2
            CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
                                            tok::comma))
d743 2
a744 2
      next();
      while (CurrentToken) {
d784 1
a784 1
    next(); // '('
d786 1
a786 1
    next(); // ')'
d845 1
a845 1
                            Keywords.kw___has_include_next))
d858 1
a858 1
    // definitions (github.com/google/protobuf) or missing "#" (either way we
d936 5
a940 5
           Tok.Next->Next &&
           (Tok.Next->Next->TokenText == "module" ||
            Tok.Next->Next->TokenText == "provide" ||
            Tok.Next->Next->TokenText == "require" ||
            Tok.Next->Next->TokenText == "forwardDeclare") &&
d974 1
a974 1
  /// A struct to hold information valid in a specific context, e.g.
a996 1
    bool InCpp11AttributeSpecifier = false;
d999 1
a999 1
  /// Puts a new \c Context onto the stack \c Contexts for the lifetime
d1057 2
a1058 1
    } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
a1106 5
    } else if (Current.is(tok::semi)) {
      // Reset FirstStartOfName after finding a semicolon so that a for loop
      // with multiple increment statements is not confused with a for loop
      // having multiple variable declarations.
      Contexts.back().FirstStartOfName = nullptr;
d1116 4
a1119 4
      Current.Type = determineStarAmpUsage(Current,
                                           Contexts.back().CanBeExpression &&
                                               Contexts.back().IsExpression,
                                           Contexts.back().InTemplateArgument);
d1138 1
a1138 3
               (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
               (!Current.is(tok::greater) &&
                Style.Language != FormatStyle::LK_TextProto)) {
a1196 11
    } else if (canBeObjCSelectorComponent(Current) &&
               // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
               Current.Previous && Current.Previous->is(TT_CastRParen) &&
               Current.Previous->MatchingParen &&
               Current.Previous->MatchingParen->Previous &&
               Current.Previous->MatchingParen->Previous->is(
                   TT_ObjCMethodSpecifier)) {
      // This is the first part of an Objective-C selector name. (If there's no
      // colon after this, this is the only place which annotates the identifier
      // as a selector.)
      Current.Type = TT_SelectorName;
d1223 1
a1223 1
  /// Take a guess at whether \p Tok starts a name of a function or
d1268 1
a1268 1
  /// Determine whether ')' is ending a cast.
d1365 1
a1365 1
  /// Return the type of the given token assuming it is * or &.
d1399 5
a1403 7
    if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
      FormatToken *TokenBeforeMatchingParen =
          PrevToken->MatchingParen->getPreviousNonComment();
      if (TokenBeforeMatchingParen &&
          TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
        return TT_PointerOrReference;
    }
d1440 4
a1443 2
    if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
      // This must be a sequence of leading unary operators.
d1460 1
a1460 1
  /// Determine whether ++/-- are pre- or post-increments/-decrements.
d1489 1
a1489 1
/// Parses binary expressions by inserting fake parenthesis based on
d1497 1
a1497 1
  /// Parse expressions with the given operator precedence.
d1584 1
a1584 1
  /// Gets the precedence (+1) of the given token for binary operators
d1592 1
a1592 1
          (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
d1643 1
a1643 1
  /// Parse unary operator expressions and surround them with fake
d1646 3
a1648 4
    llvm::SmallVector<FormatToken *, 2> Tokens;
    while (Current && Current->is(TT_UnaryOperator)) {
      Tokens.push_back(Current);
      next();
d1650 7
a1656 4
    parse(PrecedenceArrowAndPeriod);
    for (FormatToken *Token : llvm::reverse(Tokens))
      // The actual precedence doesn't matter.
      addFakeParenthesis(Token, prec::Unknown);
d1706 9
a1714 12
    // If the comment is currently aligned with the line immediately following
    // it, that's probably intentional and we should keep it.
    if (NextNonCommentLine && CommentLine &&
        NextNonCommentLine->First->NewlinesBefore <= 1 &&
        NextNonCommentLine->First->OriginalColumn ==
            (*I)->First->OriginalColumn) {
      // Align comments for preprocessor lines with the # in column 0.
      // Otherwise, align with the next line.
      (*I)->Level = (NextNonCommentLine->Type == LT_PreprocessorDirective ||
                     NextNonCommentLine->Type == LT_ImportStatement)
                        ? 0
                        : NextNonCommentLine->Level;
d1725 1
a1725 1
  for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
d1767 1
a1767 1
  auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
d1775 2
a1776 2
        if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
            Next->Next->Next->is(tok::r_square))
d1875 1
a1875 2
      Line.First->IsMultiline ? Style.ColumnLimit
                              : Line.FirstStartColumn + Line.First->ColumnWidth;
d1944 2
a1945 14

    // Reduce penalty for aligning ObjC method arguments using the colon
    // alignment as this is the canonical way (still prefer fitting everything
    // into one line if possible). Trying to fit a whole expression into one
    // line should not force other line breaks (e.g. when ObjC method
    // expression is a part of other expression).
    Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
    if (Style.Language == FormatStyle::LK_ObjC &&
        Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
      if (Current->ParameterIndex == 1)
        Current->SplitPenalty += 5 * Current->BindingStrength;
    } else {
      Current->SplitPenalty += 20 * Current->BindingStrength;
    }
d1965 1
a1965 1
  LLVM_DEBUG({ printDebugInfo(Line); });
a2007 3
    // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
    if (Left.opensScope() && Right.closesScope())
      return 200;
d2022 1
a2022 1
                       TT_DesignatedInitializerLSquare, TT_AttributeSquare))
d2052 1
a2052 2
  if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
                   TT_CtorInitializerColon))
a2105 7
  // In Objective-C type declarations, avoid breaking after the category's
  // open paren (we'll prefer breaking after the protocol list's opening
  // angle bracket, if present).
  if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
      Left.Previous->isOneOf(tok::identifier, tok::greater))
    return 500;

d2110 2
a2111 2
      (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
       Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
a2121 2
    if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
      return 19;
d2131 1
a2131 1
    return 50;
a2146 2
  if (Left.ClosesTemplateDeclaration)
    return Style.PenaltyBreakTemplateDeclaration;
a2164 2
  if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
    return true;
d2181 3
a2183 6
  if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
    bool IsLightweightGeneric =
        Right.MatchingParen && Right.MatchingParen->Next &&
        Right.MatchingParen->Next->is(tok::colon);
    return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
  }
d2197 1
a2197 9
  if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
    if (Style.Language == FormatStyle::LK_TextProto ||
        (Style.Language == FormatStyle::LK_Proto &&
         (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
      // Format empty list as `<>`.
      if (Left.is(tok::less) && Right.is(tok::greater))
        return false;
      return !Style.Cpp11BracedListStyle;
    }
a2198 1
  }
d2204 4
a2207 11
  if (Right.is(TT_PointerOrReference)) {
    if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
      if (!Left.MatchingParen)
        return true;
      FormatToken *TokenBeforeMatchingParen =
          Left.MatchingParen->getPreviousNonComment();
      if (!TokenBeforeMatchingParen ||
          !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
        return true;
    }
    return (Left.Tok.isLiteral() ||
a2212 1
  }
a2230 9
  const auto SpaceRequiredForArrayInitializerLSquare =
      [](const FormatToken &LSquareTok, const FormatStyle &Style) {
        return Style.SpacesInContainerLiterals ||
               ((Style.Language == FormatStyle::LK_Proto ||
                 Style.Language == FormatStyle::LK_TextProto) &&
                !Style.Cpp11BracedListStyle &&
                LSquareTok.endsSequence(tok::l_square, tok::colon,
                                        TT_SelectorName));
      };
d2232 4
a2235 5
    return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
            SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
           (Left.isOneOf(TT_ArraySubscriptLSquare,
                         TT_StructuredBindingLSquare) &&
            Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
d2238 2
a2239 3
           ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
             SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
                                                     Style)) ||
d2241 1
a2241 3
             Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
                                          TT_StructuredBindingLSquare)) ||
            Right.MatchingParen->is(TT_AttributeParen));
d2244 1
a2244 2
                     TT_DesignatedInitializerLSquare,
                     TT_StructuredBindingLSquare, TT_AttributeSquare) &&
d2256 1
a2256 2
    if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
        (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
d2290 1
a2290 1
    // A.<B<C<...>>>DoSomething();
a2293 7
  if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
    // Objective-C dictionary literal -> no space after opening brace.
    return false;
  if (Right.is(tok::r_brace) && Right.MatchingParen &&
      Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
    // Objective-C dictionary literal -> no space before closing brace.
    return false;
a2304 3
    if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
        !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
      return true;
a2315 13
    // Slashes occur in text protocol extension syntax: [type/type] { ... }.
    if (Left.is(tok::slash) || Right.is(tok::slash))
      return false;
    if (Left.MatchingParen && Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
        Right.isOneOf(tok::l_brace, tok::less))
      return !Style.Cpp11BracedListStyle;
    // A percent is probably part of a formatting specification, such as %lld.
    if (Left.is(tok::percent))
      return false;
    // Preserve the existence of a space before a percent for cases like 0x%04x
    // and "%d %d"
    if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
      return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin();
d2320 2
a2321 2
    if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
        Left.Previous->is(tok::kw_for))
d2344 1
a2344 2
        Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
                     Keywords.kw_extends, Keywords.kw_implements))
d2346 4
a2349 14
    if (Right.is(tok::l_paren)) {
      // JS methods can use some keywords as names (e.g. `delete()`).
      if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
        return false;
      // Valid JS method names can include keywords, e.g. `foo.delete()` or
      // `bar.instanceof()`. Recognize call positions by preceding period.
      if (Left.Previous && Left.Previous->is(tok::period) &&
          Left.Tok.getIdentifierInfo())
        return false;
      // Additional unary JavaScript operators that need a space after.
      if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
                       tok::kw_void))
        return true;
    }
d2353 1
a2353 2
         // (e.g. as "const x of y" in a for loop), or after a destructuring
         // operation (const [x, y] of z, const {a, b} of c).
d2355 1
a2355 2
          (Left.Previous->Tok.is(tok::identifier) ||
           Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
d2387 2
a2388 3
    if (Left.is(TT_JsNonNullAssertion) &&
        Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
      return true; // "x! as string", "x! in y"
d2406 2
a2407 4
    if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
      // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
      // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
      // method declaration.
d2423 1
a2423 1
  if (Right.is(TT_ObjCBlockLParen))
a2424 7
  if (Right.is(TT_CtorInitializerColon))
    return Style.SpaceBeforeCtorInitializerColon;
  if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
    return false;
  if (Right.is(TT_RangeBasedForLoopColon) &&
      !Style.SpaceBeforeRangeBasedForLoopColon)
    return false;
a2436 2
    if (Right.is(TT_AttributeColon))
      return false;
d2448 1
a2448 4
  if (Left.is(tok::greater) && Right.is(tok::greater)) {
    if (Style.Language == FormatStyle::LK_TextProto ||
        (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
      return !Style.Cpp11BracedListStyle;
a2450 1
  }
d2467 1
a2467 3
                          tok::kw___super, TT_TemplateCloser,
                          TT_TemplateOpener)) ||
           (Left.is(tok ::l_paren) && Style.SpacesInParentheses);
a2469 8
  // Space before TT_StructuredBindingLSquare.
  if (Right.is(TT_StructuredBindingLSquare))
    return !Left.isOneOf(tok::amp, tok::ampamp) ||
           Style.PointerAlignment != FormatStyle::PAS_Right;
  // Space before & or && following a TT_StructuredBindingLSquare.
  if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
      Right.isOneOf(tok::amp, tok::ampamp))
    return Style.PointerAlignment != FormatStyle::PAS_Left;
d2519 1
a2519 3
         Line.startsWith(tok::kw_const, tok::kw_enum) ||
         Line.startsWith(tok::kw_export, tok::kw_enum) ||
         Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
d2537 1
a2537 2
             Style.Language == FormatStyle::LK_Proto ||
             Style.Language == FormatStyle::LK_TextProto) {
d2579 1
a2579 1
      Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
d2590 1
a2590 1
  if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
d2592 1
a2592 1
    return true;
d2594 4
a2597 4
    // Multiline raw string literals are special wrt. line breaks. The author
    // has made a deliberate choice and might have aligned the contents of the
    // string literal accordingly. Thus, we try keep existing line breaks.
    return Right.IsMultiline && Right.NewlinesBefore > 0;
d2599 4
a2602 2
       (Right.Previous->is(tok::less) && Right.Previous->Previous &&
        Right.Previous->Previous->is(tok::equal))) &&
a2611 2
           (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
            Style.BraceWrapping.AfterEnum) ||
a2623 88
  if (Right.is(TT_ProtoExtensionLSquare))
    return true;

  // In text proto instances if a submessage contains at least 2 entries and at
  // least one of them is a submessage, like A { ... B { ... } ... },
  // put all of the entries of A on separate lines by forcing the selector of
  // the submessage B to be put on a newline.
  //
  // Example: these can stay on one line:
  // a { scalar_1: 1 scalar_2: 2 }
  // a { b { key: value } }
  //
  // and these entries need to be on a new line even if putting them all in one
  // line is under the column limit:
  // a {
  //   scalar: 1
  //   b { key: value }
  // }
  //
  // We enforce this by breaking before a submessage field that has previous
  // siblings, *and* breaking before a field that follows a submessage field.
  //
  // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
  // the TT_SelectorName there, but we don't want to break inside the brackets.
  //
  // Another edge case is @@submessage { key: value }, which is a common
  // substitution placeholder. In this case we want to keep `@@` and `submessage`
  // together.
  //
  // We ensure elsewhere that extensions are always on their own line.
  if ((Style.Language == FormatStyle::LK_Proto ||
       Style.Language == FormatStyle::LK_TextProto) &&
      Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
    // Keep `@@submessage` together in:
    // @@submessage { key: value }
    if (Right.Previous && Right.Previous->is(tok::at))
      return false;
    // Look for the scope opener after selector in cases like:
    // selector { ...
    // selector: { ...
    // selector: @@base { ...
    FormatToken *LBrace = Right.Next;
    if (LBrace && LBrace->is(tok::colon)) {
      LBrace = LBrace->Next;
      if (LBrace && LBrace->is(tok::at)) {
        LBrace = LBrace->Next;
        if (LBrace)
          LBrace = LBrace->Next;
      }
    }
    if (LBrace &&
        // The scope opener is one of {, [, <:
        // selector { ... }
        // selector [ ... ]
        // selector < ... >
        //
        // In case of selector { ... }, the l_brace is TT_DictLiteral.
        // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
        // so we check for immediately following r_brace.
        ((LBrace->is(tok::l_brace) &&
          (LBrace->is(TT_DictLiteral) ||
           (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
         LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
      // If Left.ParameterCount is 0, then this submessage entry is not the
      // first in its parent submessage, and we want to break before this entry.
      // If Left.ParameterCount is greater than 0, then its parent submessage
      // might contain 1 or more entries and we want to break before this entry
      // if it contains at least 2 entries. We deal with this case later by
      // detecting and breaking before the next entry in the parent submessage.
      if (Left.ParameterCount == 0)
        return true;
      // However, if this submessage is the first entry in its parent
      // submessage, Left.ParameterCount might be 1 in some cases.
      // We deal with this case later by detecting an entry
      // following a closing paren of this submessage.
    }

    // If this is an entry immediately following a submessage, it will be
    // preceded by a closing paren of that submessage, like in:
    //     left---.  .---right
    //            v  v
    // sub: { ... } key: value
    // If there was a comment between `}` an `key` above, then `key` would be
    // put on a new line anyways.
    if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
      return true;
  }

d2642 6
a2647 11
        NonComment->isOneOf(
            tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
            tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
            tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
            Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
            Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
      return false; // Otherwise automatic semicolon insertion would trigger.
    if (Right.NestingLevel == 0 &&
        (Left.Tok.getIdentifierInfo() ||
         Left.isOneOf(tok::r_square, tok::r_paren)) &&
        Right.isOneOf(tok::l_square, tok::l_paren))
d2653 1
a2653 4
    // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
    if (Left.is(tok::exclaim) && Right.is(tok::colon))
      return false;
    if (Right.is(Keywords.kw_is))
d2705 2
a2706 1
            Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
a2712 2
  if (Left.is(TT_InheritanceColon))
    return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
d2714 1
a2714 1
    return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
a2717 1

d2721 1
a2721 34
  if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
    if (Style.Language == FormatStyle::LK_Proto ||
        Style.Language == FormatStyle::LK_TextProto) {
      if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
        return false;
      // Prevent cases like:
      //
      // submessage:
      //     { key: valueeeeeeeeeeee }
      //
      // when the snippet does not fit into one line.
      // Prefer:
      //
      // submessage: {
      //   key: valueeeeeeeeeeee
      // }
      //
      // instead, even if it is longer by one line.
      //
      // Note that this allows allows the "{" to go over the column limit
      // when the column limit is just between ":" and "{", but that does
      // not happen too often and alternative formattings in this case are
      // not much better.
      //
      // The code covers the cases:
      //
      // submessage: { ... }
      // submessage: < ... >
      // repeated: [ ... ]
      if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
           Right.is(TT_DictLiteral)) ||
          Right.is(TT_ArrayInitializerLSquare))
        return false;
    }
a2722 4
  }
  if (Right.is(tok::r_square) && Right.MatchingParen &&
      Right.MatchingParen->is(TT_ProtoExtensionLSquare))
    return false;
a2744 3
  if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
      !Style.Cpp11BracedListStyle)
    return false;
d2770 1
a2770 2
  if (Right.is(tok::kw___attribute) ||
      (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
d2789 1
a2789 2
  if (Left.is(TT_InheritanceComma) &&
      Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
d2791 1
a2791 2
  if (Right.is(TT_InheritanceComma) &&
      Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
a2810 3
  if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
      (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
    return false;
d2823 1
a2823 1
  llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
d2831 4
a2834 3
                 << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
                 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
                 << " PPK=" << Tok->PackingKind << " FakeLParens=";
a2837 1
    llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
@


1.1.1.11.4.2
log
@Mostly merge changes from HEAD upto 20200411
@
text
@@


1.1.1.11.2.1
log
@Sync with HEAD
@
text
@d11 1
a11 1
/// This file implements a token annotator, i.e. creates
d28 1
a28 16
/// Returns \c true if the token can be used as an identifier in
/// an Objective-C \c @@selector, \c false otherwise.
///
/// Because getFormattingLangOpts() always lexes source code as
/// Objective-C++, C++ keywords like \c new and \c delete are
/// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
///
/// For Objective-C and Objective-C++, both identifiers and keywords
/// are valid inside @@selector(...) (or a macro which
/// invokes @@selector(...)). So, we allow treat any identifier or
/// keyword as a potential Objective-C selector component.
static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
  return Tok.Tok.getIdentifierInfo() != nullptr;
}

/// A parser that gathers additional information about tokens.
d50 1
a50 1
    const FormatToken &Previous = *CurrentToken->Previous;  // The '<'.
d82 1
a82 11
        // In TT_Proto, we must distignuish between:
        //   map<key, value>
        //   msg < item: data >
        //   msg: < item: data >
        // In TT_TextProto, map<key, value> does not occur.
        if (Style.Language == FormatStyle::LK_TextProto ||
            (Style.Language == FormatStyle::LK_Proto && Left->Previous &&
             Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral)))
          CurrentToken->Type = TT_DictLiteral;
        else
          CurrentToken->Type = TT_TemplateCloser;
d134 4
a137 1
    if (FormatToken *MaybeSel = Left->Previous) {
d155 5
a159 5
               (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
                                        tok::kw_if, tok::kw_while, tok::l_paren,
                                        tok::comma) ||
                Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
                Left->Previous->is(TT_BinaryOperator))) {
a202 7
    // MightBeFunctionType and ProbablyFunctionType are used for
    // function pointer and reference types as well as Objective-C
    // block types:
    //
    // void (*FunctionPointer)(void);
    // void (&FunctionReference)(void);
    // void (^ObjCBlock)(void);
d204 1
a204 2
    bool ProbablyFunctionType =
        CurrentToken->isOneOf(tok::star, tok::amp, tok::caret);
a208 1
    FormatToken *PossibleObjCForInToken = nullptr;
d240 1
a240 2
          Left->Type = Left->Next->is(tok::caret) ? TT_ObjCBlockLParen
                                                  : TT_FunctionTypeLParen;
d294 1
a294 1
      if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
d296 2
a297 9
        if (PossibleObjCForInToken) {
          PossibleObjCForInToken->Type = TT_Unknown;
          PossibleObjCForInToken = nullptr;
        }
      }
      if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
        PossibleObjCForInToken = CurrentToken;
        PossibleObjCForInToken->Type = TT_ObjCForIn;
      }
a312 26
  bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
    if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
      return false;
    const FormatToken *AttrTok = Tok.Next->Next;
    if (!AttrTok)
      return false;
    // C++17 '[[using ns: foo, bar(baz, blech)]]'
    // We assume nobody will name an ObjC variable 'using'.
    if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
      return true;
    if (AttrTok->isNot(tok::identifier))
      return false;
    while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
      // ObjC message send. We assume nobody will use : in a C++11 attribute
      // specifier parameter, although this is technically valid:
      // [[foo(:)]]
      if (AttrTok->is(tok::colon) ||
          AttrTok->startsSequence(tok::identifier, tok::identifier))
        return false;
      if (AttrTok->is(tok::ellipsis))
        return true;
      AttrTok = AttrTok->Next;
    }
    return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
  }

d319 1
a319 2
    // expression, it could the start of an Objective-C array literal,
    // or it could be a C++ attribute specifier [[foo::bar]].
d328 2
a329 1
        Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
a332 3
    bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
                                     Contexts.back().InCpp11AttributeSpecifier;

d334 1
a334 1
        !CppArrayTemplates && Style.isCpp() && !IsCpp11AttributeSpecifier &&
d336 1
a336 1
        !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
a340 1
         // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
d346 1
a346 3
    if (Left->isCppStructuredBinding(Style)) {
      Left->Type = TT_StructuredBindingLSquare;
    } else if (Left->is(TT_Unknown)) {
a348 2
      } else if (IsCpp11AttributeSpecifier) {
        Left->Type = TT_AttributeSquare;
d360 6
a365 42
                 Style.Language == FormatStyle::LK_TextProto) {
        // Square braces in LK_Proto can either be message field attributes:
        //
        // optional Aaa aaa = 1 [
        //   (aaa) = aaa
        // ];
        //
        // extensions 123 [
        //   (aaa) = aaa
        // ];
        //
        // or text proto extensions (in options):
        //
        // option (Aaa.options) = {
        //   [type.type/type] {
        //     key: value
        //   }
        // }
        //
        // or repeated fields (in options):
        //
        // option (Aaa.options) = {
        //   keys: [ 1, 2, 3 ]
        // }
        //
        // In the first and the third case we want to spread the contents inside
        // the square braces; in the second we want to keep them inline.
        Left->Type = TT_ArrayInitializerLSquare;
        if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
                                tok::equal) &&
            !Left->endsSequence(tok::l_square, tok::numeric_constant,
                                tok::identifier) &&
            !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
          Left->Type = TT_ProtoExtensionLSquare;
          BindingIncrease = 10;
        }
      } else if (!CppArrayTemplates && Parent &&
                 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
                                 tok::comma, tok::l_paren, tok::l_square,
                                 tok::question, tok::colon, tok::kw_return,
                                 // Should only be relevant to JavaScript:
                                 tok::kw_default)) {
a374 4
    if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
        Parent->is(TT_JsTypeColon))
      Contexts.back().IsExpression = false;

a375 1
    Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
d379 2
a380 4
        if (IsCpp11AttributeSpecifier)
          CurrentToken->Type = TT_AttributeSquare;
        else if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
                 Left->is(TT_ObjCMethodExpr)) {
a387 6
          // If we haven't seen a colon yet, make sure the last identifier
          // before the r_square is tagged as a selector name component.
          if (!ColonFound && CurrentToken->Previous &&
              CurrentToken->Previous->is(TT_Unknown) &&
              canBeObjCSelectorComponent(*CurrentToken->Previous))
            CurrentToken->Previous->Type = TT_SelectorName;
a395 14
        // FirstObjCSelectorName is set when a colon is found. This does
        // not work, however, when the method has no parameters.
        // Here, we set FirstObjCSelectorName when the end of the method call is
        // reached, in case it was not set already.
        if (!Contexts.back().FirstObjCSelectorName) {
            FormatToken* Previous = CurrentToken->getPreviousNonComment();
            if (Previous && Previous->is(TT_SelectorName)) {
              Previous->ObjCSelectorNameParts = 1;
              Contexts.back().FirstObjCSelectorName = Previous;
            }
        } else {
          Left->ParameterCount =
              Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
        }
d408 2
a409 8
        if (IsCpp11AttributeSpecifier &&
            CurrentToken->endsSequence(tok::colon, tok::identifier,
                                       tok::kw_using)) {
          // Remember that this is a [[using ns: foo]] C++ attribute, so we
          // don't add a space before the colon (unlike other colons).
          CurrentToken->Type = TT_AttributeColon;
        } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
                                 TT_DesignatedInitializerLSquare)) {
a413 1
            // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
a441 3
      if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
          Left->Previous->is(TT_JsTypeColon))
        Contexts.back().IsExpression = false;
d455 7
a461 11
          if (Previous->is(TT_JsTypeOptionalQuestion))
            Previous = Previous->getPreviousNonComment();
          if ((CurrentToken->is(tok::colon) &&
               (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
              Style.Language == FormatStyle::LK_Proto ||
              Style.Language == FormatStyle::LK_TextProto) {
            Left->Type = TT_DictLiteral;
            if (Previous->Tok.getIdentifierInfo() ||
                Previous->is(tok::string_literal))
              Previous->Type = TT_SelectorName;
          }
a476 3
    // For ObjC methods, the number of parameters is calculated differently as
    // method declarations have a different structure (the parameters are not
    // inside a bracket scope).
a533 2
            (!Contexts.back().IsExpression &&
             Contexts.back().ContextKind == tok::l_brace) || // object type
a535 1
          Contexts.back().IsExpression = false;
a551 5
        // Ensure we tag all identifiers in method declarations as
        // TT_SelectorName.
        bool UnknownIdentifierInMethodDeclaration =
            Line.startsWith(TT_ObjCMethodSpecifier) &&
            Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
a552 1
            // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
d557 1
a557 2
            Contexts.back().LongestObjCSelectorName == 0 ||
            UnknownIdentifierInMethodDeclaration) {
d559 4
a564 7
          else if (Tok->Previous->ColumnWidth >
                   Contexts.back().LongestObjCSelectorName)
            Contexts.back().LongestObjCSelectorName =
                Tok->Previous->ColumnWidth;
          Tok->Previous->ParameterIndex =
              Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
          ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
d577 2
a578 4
      } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
                 (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
                  (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
                   Tok->Next->Next->is(tok::colon)))) {
d596 1
a596 2
      if (Tok->is(tok::kw_if) && CurrentToken &&
          CurrentToken->is(tok::kw_constexpr))
d606 1
a606 3
        // x.for and {for: ...}
        if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
            (Tok->Next && Tok->Next->is(tok::colon)))
d622 2
a623 1
      if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
d646 1
a646 1
        FormatToken *Previous = Tok->getPreviousNonComment();
d656 1
a656 9
        // In TT_Proto, we must distignuish between:
        //   map<key, value>
        //   msg < item: data >
        //   msg: < item: data >
        // In TT_TextProto, map<key, value> does not occur.
        if (Style.Language == FormatStyle::LK_TextProto ||
            (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
             Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
          Tok->Type = TT_DictLiteral;
d677 1
a677 2
      if (Style.Language != FormatStyle::LK_TextProto)
        Tok->Type = TT_BinaryOperator;
a679 3
      if (Style.Language == FormatStyle::LK_TextProto ||
          Style.Language == FormatStyle::LK_Proto)
        break;
d686 1
a686 2
            CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
                                            tok::comma))
d743 2
a744 2
      next();
      while (CurrentToken) {
d784 1
a784 1
    next(); // '('
d786 1
a786 1
    next(); // ')'
d845 1
a845 1
                            Keywords.kw___has_include_next))
d858 1
a858 1
    // definitions (github.com/google/protobuf) or missing "#" (either way we
d936 5
a940 5
           Tok.Next->Next &&
           (Tok.Next->Next->TokenText == "module" ||
            Tok.Next->Next->TokenText == "provide" ||
            Tok.Next->Next->TokenText == "require" ||
            Tok.Next->Next->TokenText == "forwardDeclare") &&
d974 1
a974 1
  /// A struct to hold information valid in a specific context, e.g.
a996 1
    bool InCpp11AttributeSpecifier = false;
d999 1
a999 1
  /// Puts a new \c Context onto the stack \c Contexts for the lifetime
d1057 2
a1058 1
    } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
a1106 5
    } else if (Current.is(tok::semi)) {
      // Reset FirstStartOfName after finding a semicolon so that a for loop
      // with multiple increment statements is not confused with a for loop
      // having multiple variable declarations.
      Contexts.back().FirstStartOfName = nullptr;
d1116 4
a1119 4
      Current.Type = determineStarAmpUsage(Current,
                                           Contexts.back().CanBeExpression &&
                                               Contexts.back().IsExpression,
                                           Contexts.back().InTemplateArgument);
d1138 1
a1138 3
               (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
               (!Current.is(tok::greater) &&
                Style.Language != FormatStyle::LK_TextProto)) {
a1196 11
    } else if (canBeObjCSelectorComponent(Current) &&
               // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
               Current.Previous && Current.Previous->is(TT_CastRParen) &&
               Current.Previous->MatchingParen &&
               Current.Previous->MatchingParen->Previous &&
               Current.Previous->MatchingParen->Previous->is(
                   TT_ObjCMethodSpecifier)) {
      // This is the first part of an Objective-C selector name. (If there's no
      // colon after this, this is the only place which annotates the identifier
      // as a selector.)
      Current.Type = TT_SelectorName;
d1223 1
a1223 1
  /// Take a guess at whether \p Tok starts a name of a function or
d1268 1
a1268 1
  /// Determine whether ')' is ending a cast.
d1365 1
a1365 1
  /// Return the type of the given token assuming it is * or &.
d1399 5
a1403 7
    if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
      FormatToken *TokenBeforeMatchingParen =
          PrevToken->MatchingParen->getPreviousNonComment();
      if (TokenBeforeMatchingParen &&
          TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
        return TT_PointerOrReference;
    }
d1440 4
a1443 2
    if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
      // This must be a sequence of leading unary operators.
d1460 1
a1460 1
  /// Determine whether ++/-- are pre- or post-increments/-decrements.
d1489 1
a1489 1
/// Parses binary expressions by inserting fake parenthesis based on
d1497 1
a1497 1
  /// Parse expressions with the given operator precedence.
d1584 1
a1584 1
  /// Gets the precedence (+1) of the given token for binary operators
d1592 1
a1592 1
          (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
d1643 1
a1643 1
  /// Parse unary operator expressions and surround them with fake
d1646 3
a1648 4
    llvm::SmallVector<FormatToken *, 2> Tokens;
    while (Current && Current->is(TT_UnaryOperator)) {
      Tokens.push_back(Current);
      next();
d1650 7
a1656 4
    parse(PrecedenceArrowAndPeriod);
    for (FormatToken *Token : llvm::reverse(Tokens))
      // The actual precedence doesn't matter.
      addFakeParenthesis(Token, prec::Unknown);
d1706 9
a1714 12
    // If the comment is currently aligned with the line immediately following
    // it, that's probably intentional and we should keep it.
    if (NextNonCommentLine && CommentLine &&
        NextNonCommentLine->First->NewlinesBefore <= 1 &&
        NextNonCommentLine->First->OriginalColumn ==
            (*I)->First->OriginalColumn) {
      // Align comments for preprocessor lines with the # in column 0.
      // Otherwise, align with the next line.
      (*I)->Level = (NextNonCommentLine->Type == LT_PreprocessorDirective ||
                     NextNonCommentLine->Type == LT_ImportStatement)
                        ? 0
                        : NextNonCommentLine->Level;
d1725 1
a1725 1
  for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
d1767 1
a1767 1
  auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
d1775 2
a1776 2
        if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
            Next->Next->Next->is(tok::r_square))
d1875 1
a1875 2
      Line.First->IsMultiline ? Style.ColumnLimit
                              : Line.FirstStartColumn + Line.First->ColumnWidth;
d1944 2
a1945 14

    // Reduce penalty for aligning ObjC method arguments using the colon
    // alignment as this is the canonical way (still prefer fitting everything
    // into one line if possible). Trying to fit a whole expression into one
    // line should not force other line breaks (e.g. when ObjC method
    // expression is a part of other expression).
    Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
    if (Style.Language == FormatStyle::LK_ObjC &&
        Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
      if (Current->ParameterIndex == 1)
        Current->SplitPenalty += 5 * Current->BindingStrength;
    } else {
      Current->SplitPenalty += 20 * Current->BindingStrength;
    }
d1965 1
a1965 1
  LLVM_DEBUG({ printDebugInfo(Line); });
a2007 3
    // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
    if (Left.opensScope() && Right.closesScope())
      return 200;
d2022 1
a2022 1
                       TT_DesignatedInitializerLSquare, TT_AttributeSquare))
d2052 1
a2052 2
  if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
                   TT_CtorInitializerColon))
a2105 7
  // In Objective-C type declarations, avoid breaking after the category's
  // open paren (we'll prefer breaking after the protocol list's opening
  // angle bracket, if present).
  if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
      Left.Previous->isOneOf(tok::identifier, tok::greater))
    return 500;

d2110 2
a2111 2
      (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
       Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
a2121 2
    if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
      return 19;
d2131 1
a2131 1
    return 50;
a2146 2
  if (Left.ClosesTemplateDeclaration)
    return Style.PenaltyBreakTemplateDeclaration;
a2164 2
  if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
    return true;
d2181 3
a2183 6
  if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
    bool IsLightweightGeneric =
        Right.MatchingParen && Right.MatchingParen->Next &&
        Right.MatchingParen->Next->is(tok::colon);
    return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
  }
d2197 1
a2197 9
  if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
    if (Style.Language == FormatStyle::LK_TextProto ||
        (Style.Language == FormatStyle::LK_Proto &&
         (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
      // Format empty list as `<>`.
      if (Left.is(tok::less) && Right.is(tok::greater))
        return false;
      return !Style.Cpp11BracedListStyle;
    }
a2198 1
  }
d2204 4
a2207 11
  if (Right.is(TT_PointerOrReference)) {
    if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
      if (!Left.MatchingParen)
        return true;
      FormatToken *TokenBeforeMatchingParen =
          Left.MatchingParen->getPreviousNonComment();
      if (!TokenBeforeMatchingParen ||
          !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
        return true;
    }
    return (Left.Tok.isLiteral() ||
a2212 1
  }
a2230 9
  const auto SpaceRequiredForArrayInitializerLSquare =
      [](const FormatToken &LSquareTok, const FormatStyle &Style) {
        return Style.SpacesInContainerLiterals ||
               ((Style.Language == FormatStyle::LK_Proto ||
                 Style.Language == FormatStyle::LK_TextProto) &&
                !Style.Cpp11BracedListStyle &&
                LSquareTok.endsSequence(tok::l_square, tok::colon,
                                        TT_SelectorName));
      };
d2232 4
a2235 5
    return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
            SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
           (Left.isOneOf(TT_ArraySubscriptLSquare,
                         TT_StructuredBindingLSquare) &&
            Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
d2238 2
a2239 3
           ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
             SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
                                                     Style)) ||
d2241 1
a2241 3
             Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
                                          TT_StructuredBindingLSquare)) ||
            Right.MatchingParen->is(TT_AttributeParen));
d2244 1
a2244 2
                     TT_DesignatedInitializerLSquare,
                     TT_StructuredBindingLSquare, TT_AttributeSquare) &&
d2256 1
a2256 2
    if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
        (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
d2290 1
a2290 1
    // A.<B<C<...>>>DoSomething();
a2293 7
  if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
    // Objective-C dictionary literal -> no space after opening brace.
    return false;
  if (Right.is(tok::r_brace) && Right.MatchingParen &&
      Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
    // Objective-C dictionary literal -> no space before closing brace.
    return false;
a2304 3
    if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
        !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
      return true;
a2315 13
    // Slashes occur in text protocol extension syntax: [type/type] { ... }.
    if (Left.is(tok::slash) || Right.is(tok::slash))
      return false;
    if (Left.MatchingParen && Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
        Right.isOneOf(tok::l_brace, tok::less))
      return !Style.Cpp11BracedListStyle;
    // A percent is probably part of a formatting specification, such as %lld.
    if (Left.is(tok::percent))
      return false;
    // Preserve the existence of a space before a percent for cases like 0x%04x
    // and "%d %d"
    if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
      return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin();
d2320 2
a2321 2
    if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
        Left.Previous->is(tok::kw_for))
d2344 1
a2344 2
        Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
                     Keywords.kw_extends, Keywords.kw_implements))
d2346 4
a2349 14
    if (Right.is(tok::l_paren)) {
      // JS methods can use some keywords as names (e.g. `delete()`).
      if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
        return false;
      // Valid JS method names can include keywords, e.g. `foo.delete()` or
      // `bar.instanceof()`. Recognize call positions by preceding period.
      if (Left.Previous && Left.Previous->is(tok::period) &&
          Left.Tok.getIdentifierInfo())
        return false;
      // Additional unary JavaScript operators that need a space after.
      if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
                       tok::kw_void))
        return true;
    }
d2353 1
a2353 2
         // (e.g. as "const x of y" in a for loop), or after a destructuring
         // operation (const [x, y] of z, const {a, b} of c).
d2355 1
a2355 2
          (Left.Previous->Tok.is(tok::identifier) ||
           Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
d2387 2
a2388 3
    if (Left.is(TT_JsNonNullAssertion) &&
        Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
      return true; // "x! as string", "x! in y"
d2406 2
a2407 4
    if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
      // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
      // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
      // method declaration.
d2423 1
a2423 1
  if (Right.is(TT_ObjCBlockLParen))
a2424 7
  if (Right.is(TT_CtorInitializerColon))
    return Style.SpaceBeforeCtorInitializerColon;
  if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
    return false;
  if (Right.is(TT_RangeBasedForLoopColon) &&
      !Style.SpaceBeforeRangeBasedForLoopColon)
    return false;
a2436 2
    if (Right.is(TT_AttributeColon))
      return false;
d2448 1
a2448 4
  if (Left.is(tok::greater) && Right.is(tok::greater)) {
    if (Style.Language == FormatStyle::LK_TextProto ||
        (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
      return !Style.Cpp11BracedListStyle;
a2450 1
  }
d2467 1
a2467 3
                          tok::kw___super, TT_TemplateCloser,
                          TT_TemplateOpener)) ||
           (Left.is(tok ::l_paren) && Style.SpacesInParentheses);
a2469 8
  // Space before TT_StructuredBindingLSquare.
  if (Right.is(TT_StructuredBindingLSquare))
    return !Left.isOneOf(tok::amp, tok::ampamp) ||
           Style.PointerAlignment != FormatStyle::PAS_Right;
  // Space before & or && following a TT_StructuredBindingLSquare.
  if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
      Right.isOneOf(tok::amp, tok::ampamp))
    return Style.PointerAlignment != FormatStyle::PAS_Left;
d2519 1
a2519 3
         Line.startsWith(tok::kw_const, tok::kw_enum) ||
         Line.startsWith(tok::kw_export, tok::kw_enum) ||
         Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
d2537 1
a2537 2
             Style.Language == FormatStyle::LK_Proto ||
             Style.Language == FormatStyle::LK_TextProto) {
d2579 1
a2579 1
      Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
d2590 1
a2590 1
  if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
d2592 1
a2592 1
    return true;
d2594 4
a2597 4
    // Multiline raw string literals are special wrt. line breaks. The author
    // has made a deliberate choice and might have aligned the contents of the
    // string literal accordingly. Thus, we try keep existing line breaks.
    return Right.IsMultiline && Right.NewlinesBefore > 0;
d2599 4
a2602 2
       (Right.Previous->is(tok::less) && Right.Previous->Previous &&
        Right.Previous->Previous->is(tok::equal))) &&
a2611 2
           (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
            Style.BraceWrapping.AfterEnum) ||
a2623 88
  if (Right.is(TT_ProtoExtensionLSquare))
    return true;

  // In text proto instances if a submessage contains at least 2 entries and at
  // least one of them is a submessage, like A { ... B { ... } ... },
  // put all of the entries of A on separate lines by forcing the selector of
  // the submessage B to be put on a newline.
  //
  // Example: these can stay on one line:
  // a { scalar_1: 1 scalar_2: 2 }
  // a { b { key: value } }
  //
  // and these entries need to be on a new line even if putting them all in one
  // line is under the column limit:
  // a {
  //   scalar: 1
  //   b { key: value }
  // }
  //
  // We enforce this by breaking before a submessage field that has previous
  // siblings, *and* breaking before a field that follows a submessage field.
  //
  // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
  // the TT_SelectorName there, but we don't want to break inside the brackets.
  //
  // Another edge case is @@submessage { key: value }, which is a common
  // substitution placeholder. In this case we want to keep `@@` and `submessage`
  // together.
  //
  // We ensure elsewhere that extensions are always on their own line.
  if ((Style.Language == FormatStyle::LK_Proto ||
       Style.Language == FormatStyle::LK_TextProto) &&
      Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
    // Keep `@@submessage` together in:
    // @@submessage { key: value }
    if (Right.Previous && Right.Previous->is(tok::at))
      return false;
    // Look for the scope opener after selector in cases like:
    // selector { ...
    // selector: { ...
    // selector: @@base { ...
    FormatToken *LBrace = Right.Next;
    if (LBrace && LBrace->is(tok::colon)) {
      LBrace = LBrace->Next;
      if (LBrace && LBrace->is(tok::at)) {
        LBrace = LBrace->Next;
        if (LBrace)
          LBrace = LBrace->Next;
      }
    }
    if (LBrace &&
        // The scope opener is one of {, [, <:
        // selector { ... }
        // selector [ ... ]
        // selector < ... >
        //
        // In case of selector { ... }, the l_brace is TT_DictLiteral.
        // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
        // so we check for immediately following r_brace.
        ((LBrace->is(tok::l_brace) &&
          (LBrace->is(TT_DictLiteral) ||
           (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
         LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
      // If Left.ParameterCount is 0, then this submessage entry is not the
      // first in its parent submessage, and we want to break before this entry.
      // If Left.ParameterCount is greater than 0, then its parent submessage
      // might contain 1 or more entries and we want to break before this entry
      // if it contains at least 2 entries. We deal with this case later by
      // detecting and breaking before the next entry in the parent submessage.
      if (Left.ParameterCount == 0)
        return true;
      // However, if this submessage is the first entry in its parent
      // submessage, Left.ParameterCount might be 1 in some cases.
      // We deal with this case later by detecting an entry
      // following a closing paren of this submessage.
    }

    // If this is an entry immediately following a submessage, it will be
    // preceded by a closing paren of that submessage, like in:
    //     left---.  .---right
    //            v  v
    // sub: { ... } key: value
    // If there was a comment between `}` an `key` above, then `key` would be
    // put on a new line anyways.
    if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
      return true;
  }

d2642 6
a2647 11
        NonComment->isOneOf(
            tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
            tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
            tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
            Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
            Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
      return false; // Otherwise automatic semicolon insertion would trigger.
    if (Right.NestingLevel == 0 &&
        (Left.Tok.getIdentifierInfo() ||
         Left.isOneOf(tok::r_square, tok::r_paren)) &&
        Right.isOneOf(tok::l_square, tok::l_paren))
d2653 1
a2653 4
    // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
    if (Left.is(tok::exclaim) && Right.is(tok::colon))
      return false;
    if (Right.is(Keywords.kw_is))
d2705 2
a2706 1
            Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
a2712 2
  if (Left.is(TT_InheritanceColon))
    return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
d2714 1
a2714 1
    return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
a2717 1

d2721 1
a2721 34
  if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
    if (Style.Language == FormatStyle::LK_Proto ||
        Style.Language == FormatStyle::LK_TextProto) {
      if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
        return false;
      // Prevent cases like:
      //
      // submessage:
      //     { key: valueeeeeeeeeeee }
      //
      // when the snippet does not fit into one line.
      // Prefer:
      //
      // submessage: {
      //   key: valueeeeeeeeeeee
      // }
      //
      // instead, even if it is longer by one line.
      //
      // Note that this allows allows the "{" to go over the column limit
      // when the column limit is just between ":" and "{", but that does
      // not happen too often and alternative formattings in this case are
      // not much better.
      //
      // The code covers the cases:
      //
      // submessage: { ... }
      // submessage: < ... >
      // repeated: [ ... ]
      if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
           Right.is(TT_DictLiteral)) ||
          Right.is(TT_ArrayInitializerLSquare))
        return false;
    }
a2722 4
  }
  if (Right.is(tok::r_square) && Right.MatchingParen &&
      Right.MatchingParen->is(TT_ProtoExtensionLSquare))
    return false;
a2744 3
  if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
      !Style.Cpp11BracedListStyle)
    return false;
d2770 1
a2770 2
  if (Right.is(tok::kw___attribute) ||
      (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
d2789 1
a2789 2
  if (Left.is(TT_InheritanceComma) &&
      Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
d2791 1
a2791 2
  if (Right.is(TT_InheritanceComma) &&
      Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
a2810 3
  if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
      (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
    return false;
d2823 1
a2823 1
  llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
d2831 4
a2834 3
                 << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
                 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
                 << " PPK=" << Tok->PackingKind << " FakeLParens=";
a2837 1
    llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
@


1.1.1.12
log
@Import clang r337282 from trunk
@
text
@d11 1
a11 1
/// This file implements a token annotator, i.e. creates
d28 1
a28 16
/// Returns \c true if the token can be used as an identifier in
/// an Objective-C \c @@selector, \c false otherwise.
///
/// Because getFormattingLangOpts() always lexes source code as
/// Objective-C++, C++ keywords like \c new and \c delete are
/// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
///
/// For Objective-C and Objective-C++, both identifiers and keywords
/// are valid inside @@selector(...) (or a macro which
/// invokes @@selector(...)). So, we allow treat any identifier or
/// keyword as a potential Objective-C selector component.
static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
  return Tok.Tok.getIdentifierInfo() != nullptr;
}

/// A parser that gathers additional information about tokens.
d50 1
a50 1
    const FormatToken &Previous = *CurrentToken->Previous;  // The '<'.
d82 1
a82 11
        // In TT_Proto, we must distignuish between:
        //   map<key, value>
        //   msg < item: data >
        //   msg: < item: data >
        // In TT_TextProto, map<key, value> does not occur.
        if (Style.Language == FormatStyle::LK_TextProto ||
            (Style.Language == FormatStyle::LK_Proto && Left->Previous &&
             Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral)))
          CurrentToken->Type = TT_DictLiteral;
        else
          CurrentToken->Type = TT_TemplateCloser;
d134 4
a137 1
    if (FormatToken *MaybeSel = Left->Previous) {
d155 5
a159 5
               (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
                                        tok::kw_if, tok::kw_while, tok::l_paren,
                                        tok::comma) ||
                Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
                Left->Previous->is(TT_BinaryOperator))) {
a202 7
    // MightBeFunctionType and ProbablyFunctionType are used for
    // function pointer and reference types as well as Objective-C
    // block types:
    //
    // void (*FunctionPointer)(void);
    // void (&FunctionReference)(void);
    // void (^ObjCBlock)(void);
d204 1
a204 2
    bool ProbablyFunctionType =
        CurrentToken->isOneOf(tok::star, tok::amp, tok::caret);
a208 1
    FormatToken *PossibleObjCForInToken = nullptr;
d240 1
a240 2
          Left->Type = Left->Next->is(tok::caret) ? TT_ObjCBlockLParen
                                                  : TT_FunctionTypeLParen;
d294 1
a294 1
      if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
d296 2
a297 9
        if (PossibleObjCForInToken) {
          PossibleObjCForInToken->Type = TT_Unknown;
          PossibleObjCForInToken = nullptr;
        }
      }
      if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
        PossibleObjCForInToken = CurrentToken;
        PossibleObjCForInToken->Type = TT_ObjCForIn;
      }
a312 26
  bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
    if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
      return false;
    const FormatToken *AttrTok = Tok.Next->Next;
    if (!AttrTok)
      return false;
    // C++17 '[[using ns: foo, bar(baz, blech)]]'
    // We assume nobody will name an ObjC variable 'using'.
    if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
      return true;
    if (AttrTok->isNot(tok::identifier))
      return false;
    while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
      // ObjC message send. We assume nobody will use : in a C++11 attribute
      // specifier parameter, although this is technically valid:
      // [[foo(:)]]
      if (AttrTok->is(tok::colon) ||
          AttrTok->startsSequence(tok::identifier, tok::identifier))
        return false;
      if (AttrTok->is(tok::ellipsis))
        return true;
      AttrTok = AttrTok->Next;
    }
    return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
  }

d319 1
a319 2
    // expression, it could the start of an Objective-C array literal,
    // or it could be a C++ attribute specifier [[foo::bar]].
d328 2
a329 1
        Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
a332 3
    bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
                                     Contexts.back().InCpp11AttributeSpecifier;

d334 1
a334 1
        !CppArrayTemplates && Style.isCpp() && !IsCpp11AttributeSpecifier &&
d336 1
a336 1
        !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
a340 1
         // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
d346 1
a346 3
    if (Left->isCppStructuredBinding(Style)) {
      Left->Type = TT_StructuredBindingLSquare;
    } else if (Left->is(TT_Unknown)) {
a348 2
      } else if (IsCpp11AttributeSpecifier) {
        Left->Type = TT_AttributeSquare;
d360 6
a365 42
                 Style.Language == FormatStyle::LK_TextProto) {
        // Square braces in LK_Proto can either be message field attributes:
        //
        // optional Aaa aaa = 1 [
        //   (aaa) = aaa
        // ];
        //
        // extensions 123 [
        //   (aaa) = aaa
        // ];
        //
        // or text proto extensions (in options):
        //
        // option (Aaa.options) = {
        //   [type.type/type] {
        //     key: value
        //   }
        // }
        //
        // or repeated fields (in options):
        //
        // option (Aaa.options) = {
        //   keys: [ 1, 2, 3 ]
        // }
        //
        // In the first and the third case we want to spread the contents inside
        // the square braces; in the second we want to keep them inline.
        Left->Type = TT_ArrayInitializerLSquare;
        if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
                                tok::equal) &&
            !Left->endsSequence(tok::l_square, tok::numeric_constant,
                                tok::identifier) &&
            !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
          Left->Type = TT_ProtoExtensionLSquare;
          BindingIncrease = 10;
        }
      } else if (!CppArrayTemplates && Parent &&
                 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
                                 tok::comma, tok::l_paren, tok::l_square,
                                 tok::question, tok::colon, tok::kw_return,
                                 // Should only be relevant to JavaScript:
                                 tok::kw_default)) {
a374 4
    if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
        Parent->is(TT_JsTypeColon))
      Contexts.back().IsExpression = false;

a375 1
    Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
d379 2
a380 4
        if (IsCpp11AttributeSpecifier)
          CurrentToken->Type = TT_AttributeSquare;
        else if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
                 Left->is(TT_ObjCMethodExpr)) {
a387 6
          // If we haven't seen a colon yet, make sure the last identifier
          // before the r_square is tagged as a selector name component.
          if (!ColonFound && CurrentToken->Previous &&
              CurrentToken->Previous->is(TT_Unknown) &&
              canBeObjCSelectorComponent(*CurrentToken->Previous))
            CurrentToken->Previous->Type = TT_SelectorName;
a395 14
        // FirstObjCSelectorName is set when a colon is found. This does
        // not work, however, when the method has no parameters.
        // Here, we set FirstObjCSelectorName when the end of the method call is
        // reached, in case it was not set already.
        if (!Contexts.back().FirstObjCSelectorName) {
            FormatToken* Previous = CurrentToken->getPreviousNonComment();
            if (Previous && Previous->is(TT_SelectorName)) {
              Previous->ObjCSelectorNameParts = 1;
              Contexts.back().FirstObjCSelectorName = Previous;
            }
        } else {
          Left->ParameterCount =
              Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
        }
d408 2
a409 8
        if (IsCpp11AttributeSpecifier &&
            CurrentToken->endsSequence(tok::colon, tok::identifier,
                                       tok::kw_using)) {
          // Remember that this is a [[using ns: foo]] C++ attribute, so we
          // don't add a space before the colon (unlike other colons).
          CurrentToken->Type = TT_AttributeColon;
        } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
                                 TT_DesignatedInitializerLSquare)) {
a413 1
            // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
a441 3
      if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
          Left->Previous->is(TT_JsTypeColon))
        Contexts.back().IsExpression = false;
d455 7
a461 11
          if (Previous->is(TT_JsTypeOptionalQuestion))
            Previous = Previous->getPreviousNonComment();
          if ((CurrentToken->is(tok::colon) &&
               (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
              Style.Language == FormatStyle::LK_Proto ||
              Style.Language == FormatStyle::LK_TextProto) {
            Left->Type = TT_DictLiteral;
            if (Previous->Tok.getIdentifierInfo() ||
                Previous->is(tok::string_literal))
              Previous->Type = TT_SelectorName;
          }
a476 3
    // For ObjC methods, the number of parameters is calculated differently as
    // method declarations have a different structure (the parameters are not
    // inside a bracket scope).
a533 2
            (!Contexts.back().IsExpression &&
             Contexts.back().ContextKind == tok::l_brace) || // object type
a535 1
          Contexts.back().IsExpression = false;
a551 5
        // Ensure we tag all identifiers in method declarations as
        // TT_SelectorName.
        bool UnknownIdentifierInMethodDeclaration =
            Line.startsWith(TT_ObjCMethodSpecifier) &&
            Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
a552 1
            // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
d557 1
a557 2
            Contexts.back().LongestObjCSelectorName == 0 ||
            UnknownIdentifierInMethodDeclaration) {
d559 4
a564 7
          else if (Tok->Previous->ColumnWidth >
                   Contexts.back().LongestObjCSelectorName)
            Contexts.back().LongestObjCSelectorName =
                Tok->Previous->ColumnWidth;
          Tok->Previous->ParameterIndex =
              Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
          ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
d577 2
a578 4
      } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
                 (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
                  (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
                   Tok->Next->Next->is(tok::colon)))) {
d596 1
a596 2
      if (Tok->is(tok::kw_if) && CurrentToken &&
          CurrentToken->is(tok::kw_constexpr))
d606 1
a606 3
        // x.for and {for: ...}
        if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
            (Tok->Next && Tok->Next->is(tok::colon)))
d622 2
a623 1
      if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
d646 1
a646 1
        FormatToken *Previous = Tok->getPreviousNonComment();
d656 1
a656 9
        // In TT_Proto, we must distignuish between:
        //   map<key, value>
        //   msg < item: data >
        //   msg: < item: data >
        // In TT_TextProto, map<key, value> does not occur.
        if (Style.Language == FormatStyle::LK_TextProto ||
            (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
             Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
          Tok->Type = TT_DictLiteral;
d677 1
a677 2
      if (Style.Language != FormatStyle::LK_TextProto)
        Tok->Type = TT_BinaryOperator;
a679 3
      if (Style.Language == FormatStyle::LK_TextProto ||
          Style.Language == FormatStyle::LK_Proto)
        break;
d686 1
a686 2
            CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
                                            tok::comma))
d743 2
a744 2
      next();
      while (CurrentToken) {
d784 1
a784 1
    next(); // '('
d786 1
a786 1
    next(); // ')'
d845 1
a845 1
                            Keywords.kw___has_include_next))
d858 1
a858 1
    // definitions (github.com/google/protobuf) or missing "#" (either way we
d936 5
a940 5
           Tok.Next->Next &&
           (Tok.Next->Next->TokenText == "module" ||
            Tok.Next->Next->TokenText == "provide" ||
            Tok.Next->Next->TokenText == "require" ||
            Tok.Next->Next->TokenText == "forwardDeclare") &&
d974 1
a974 1
  /// A struct to hold information valid in a specific context, e.g.
a996 1
    bool InCpp11AttributeSpecifier = false;
d999 1
a999 1
  /// Puts a new \c Context onto the stack \c Contexts for the lifetime
d1057 2
a1058 1
    } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
a1106 5
    } else if (Current.is(tok::semi)) {
      // Reset FirstStartOfName after finding a semicolon so that a for loop
      // with multiple increment statements is not confused with a for loop
      // having multiple variable declarations.
      Contexts.back().FirstStartOfName = nullptr;
d1116 4
a1119 4
      Current.Type = determineStarAmpUsage(Current,
                                           Contexts.back().CanBeExpression &&
                                               Contexts.back().IsExpression,
                                           Contexts.back().InTemplateArgument);
d1138 1
a1138 3
               (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
               (!Current.is(tok::greater) &&
                Style.Language != FormatStyle::LK_TextProto)) {
a1196 11
    } else if (canBeObjCSelectorComponent(Current) &&
               // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
               Current.Previous && Current.Previous->is(TT_CastRParen) &&
               Current.Previous->MatchingParen &&
               Current.Previous->MatchingParen->Previous &&
               Current.Previous->MatchingParen->Previous->is(
                   TT_ObjCMethodSpecifier)) {
      // This is the first part of an Objective-C selector name. (If there's no
      // colon after this, this is the only place which annotates the identifier
      // as a selector.)
      Current.Type = TT_SelectorName;
d1223 1
a1223 1
  /// Take a guess at whether \p Tok starts a name of a function or
d1268 1
a1268 1
  /// Determine whether ')' is ending a cast.
d1365 1
a1365 1
  /// Return the type of the given token assuming it is * or &.
d1399 5
a1403 7
    if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
      FormatToken *TokenBeforeMatchingParen =
          PrevToken->MatchingParen->getPreviousNonComment();
      if (TokenBeforeMatchingParen &&
          TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
        return TT_PointerOrReference;
    }
d1440 4
a1443 2
    if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
      // This must be a sequence of leading unary operators.
d1460 1
a1460 1
  /// Determine whether ++/-- are pre- or post-increments/-decrements.
d1489 1
a1489 1
/// Parses binary expressions by inserting fake parenthesis based on
d1497 1
a1497 1
  /// Parse expressions with the given operator precedence.
d1584 1
a1584 1
  /// Gets the precedence (+1) of the given token for binary operators
d1592 1
a1592 1
          (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
d1643 1
a1643 1
  /// Parse unary operator expressions and surround them with fake
d1646 3
a1648 4
    llvm::SmallVector<FormatToken *, 2> Tokens;
    while (Current && Current->is(TT_UnaryOperator)) {
      Tokens.push_back(Current);
      next();
d1650 7
a1656 4
    parse(PrecedenceArrowAndPeriod);
    for (FormatToken *Token : llvm::reverse(Tokens))
      // The actual precedence doesn't matter.
      addFakeParenthesis(Token, prec::Unknown);
d1706 9
a1714 12
    // If the comment is currently aligned with the line immediately following
    // it, that's probably intentional and we should keep it.
    if (NextNonCommentLine && CommentLine &&
        NextNonCommentLine->First->NewlinesBefore <= 1 &&
        NextNonCommentLine->First->OriginalColumn ==
            (*I)->First->OriginalColumn) {
      // Align comments for preprocessor lines with the # in column 0.
      // Otherwise, align with the next line.
      (*I)->Level = (NextNonCommentLine->Type == LT_PreprocessorDirective ||
                     NextNonCommentLine->Type == LT_ImportStatement)
                        ? 0
                        : NextNonCommentLine->Level;
d1725 1
a1725 1
  for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
d1767 1
a1767 1
  auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
d1775 2
a1776 2
        if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
            Next->Next->Next->is(tok::r_square))
d1875 1
a1875 2
      Line.First->IsMultiline ? Style.ColumnLimit
                              : Line.FirstStartColumn + Line.First->ColumnWidth;
d1944 2
a1945 14

    // Reduce penalty for aligning ObjC method arguments using the colon
    // alignment as this is the canonical way (still prefer fitting everything
    // into one line if possible). Trying to fit a whole expression into one
    // line should not force other line breaks (e.g. when ObjC method
    // expression is a part of other expression).
    Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
    if (Style.Language == FormatStyle::LK_ObjC &&
        Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
      if (Current->ParameterIndex == 1)
        Current->SplitPenalty += 5 * Current->BindingStrength;
    } else {
      Current->SplitPenalty += 20 * Current->BindingStrength;
    }
d1965 1
a1965 1
  LLVM_DEBUG({ printDebugInfo(Line); });
a2007 3
    // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
    if (Left.opensScope() && Right.closesScope())
      return 200;
d2022 1
a2022 1
                       TT_DesignatedInitializerLSquare, TT_AttributeSquare))
d2052 1
a2052 2
  if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
                   TT_CtorInitializerColon))
a2105 7
  // In Objective-C type declarations, avoid breaking after the category's
  // open paren (we'll prefer breaking after the protocol list's opening
  // angle bracket, if present).
  if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
      Left.Previous->isOneOf(tok::identifier, tok::greater))
    return 500;

d2110 2
a2111 2
      (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
       Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
a2121 2
    if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
      return 19;
d2131 1
a2131 1
    return 50;
a2146 2
  if (Left.ClosesTemplateDeclaration)
    return Style.PenaltyBreakTemplateDeclaration;
a2164 2
  if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
    return true;
d2181 3
a2183 6
  if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
    bool IsLightweightGeneric =
        Right.MatchingParen && Right.MatchingParen->Next &&
        Right.MatchingParen->Next->is(tok::colon);
    return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
  }
d2197 1
a2197 9
  if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
    if (Style.Language == FormatStyle::LK_TextProto ||
        (Style.Language == FormatStyle::LK_Proto &&
         (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
      // Format empty list as `<>`.
      if (Left.is(tok::less) && Right.is(tok::greater))
        return false;
      return !Style.Cpp11BracedListStyle;
    }
a2198 1
  }
d2204 4
a2207 11
  if (Right.is(TT_PointerOrReference)) {
    if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
      if (!Left.MatchingParen)
        return true;
      FormatToken *TokenBeforeMatchingParen =
          Left.MatchingParen->getPreviousNonComment();
      if (!TokenBeforeMatchingParen ||
          !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
        return true;
    }
    return (Left.Tok.isLiteral() ||
a2212 1
  }
a2230 9
  const auto SpaceRequiredForArrayInitializerLSquare =
      [](const FormatToken &LSquareTok, const FormatStyle &Style) {
        return Style.SpacesInContainerLiterals ||
               ((Style.Language == FormatStyle::LK_Proto ||
                 Style.Language == FormatStyle::LK_TextProto) &&
                !Style.Cpp11BracedListStyle &&
                LSquareTok.endsSequence(tok::l_square, tok::colon,
                                        TT_SelectorName));
      };
d2232 4
a2235 5
    return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
            SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
           (Left.isOneOf(TT_ArraySubscriptLSquare,
                         TT_StructuredBindingLSquare) &&
            Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
d2238 2
a2239 3
           ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
             SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
                                                     Style)) ||
d2241 1
a2241 3
             Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
                                          TT_StructuredBindingLSquare)) ||
            Right.MatchingParen->is(TT_AttributeParen));
d2244 1
a2244 2
                     TT_DesignatedInitializerLSquare,
                     TT_StructuredBindingLSquare, TT_AttributeSquare) &&
d2256 1
a2256 2
    if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
        (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
d2290 1
a2290 1
    // A.<B<C<...>>>DoSomething();
a2293 7
  if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
    // Objective-C dictionary literal -> no space after opening brace.
    return false;
  if (Right.is(tok::r_brace) && Right.MatchingParen &&
      Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
    // Objective-C dictionary literal -> no space before closing brace.
    return false;
a2304 3
    if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
        !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
      return true;
a2315 13
    // Slashes occur in text protocol extension syntax: [type/type] { ... }.
    if (Left.is(tok::slash) || Right.is(tok::slash))
      return false;
    if (Left.MatchingParen && Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
        Right.isOneOf(tok::l_brace, tok::less))
      return !Style.Cpp11BracedListStyle;
    // A percent is probably part of a formatting specification, such as %lld.
    if (Left.is(tok::percent))
      return false;
    // Preserve the existence of a space before a percent for cases like 0x%04x
    // and "%d %d"
    if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
      return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin();
d2320 2
a2321 2
    if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
        Left.Previous->is(tok::kw_for))
d2344 1
a2344 2
        Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
                     Keywords.kw_extends, Keywords.kw_implements))
d2346 4
a2349 14
    if (Right.is(tok::l_paren)) {
      // JS methods can use some keywords as names (e.g. `delete()`).
      if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
        return false;
      // Valid JS method names can include keywords, e.g. `foo.delete()` or
      // `bar.instanceof()`. Recognize call positions by preceding period.
      if (Left.Previous && Left.Previous->is(tok::period) &&
          Left.Tok.getIdentifierInfo())
        return false;
      // Additional unary JavaScript operators that need a space after.
      if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
                       tok::kw_void))
        return true;
    }
d2353 1
a2353 2
         // (e.g. as "const x of y" in a for loop), or after a destructuring
         // operation (const [x, y] of z, const {a, b} of c).
d2355 1
a2355 2
          (Left.Previous->Tok.is(tok::identifier) ||
           Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
d2387 2
a2388 3
    if (Left.is(TT_JsNonNullAssertion) &&
        Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
      return true; // "x! as string", "x! in y"
d2406 2
a2407 4
    if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
      // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
      // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
      // method declaration.
d2423 1
a2423 1
  if (Right.is(TT_ObjCBlockLParen))
a2424 7
  if (Right.is(TT_CtorInitializerColon))
    return Style.SpaceBeforeCtorInitializerColon;
  if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
    return false;
  if (Right.is(TT_RangeBasedForLoopColon) &&
      !Style.SpaceBeforeRangeBasedForLoopColon)
    return false;
a2436 2
    if (Right.is(TT_AttributeColon))
      return false;
d2448 1
a2448 4
  if (Left.is(tok::greater) && Right.is(tok::greater)) {
    if (Style.Language == FormatStyle::LK_TextProto ||
        (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
      return !Style.Cpp11BracedListStyle;
a2450 1
  }
d2467 1
a2467 3
                          tok::kw___super, TT_TemplateCloser,
                          TT_TemplateOpener)) ||
           (Left.is(tok ::l_paren) && Style.SpacesInParentheses);
a2469 8
  // Space before TT_StructuredBindingLSquare.
  if (Right.is(TT_StructuredBindingLSquare))
    return !Left.isOneOf(tok::amp, tok::ampamp) ||
           Style.PointerAlignment != FormatStyle::PAS_Right;
  // Space before & or && following a TT_StructuredBindingLSquare.
  if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
      Right.isOneOf(tok::amp, tok::ampamp))
    return Style.PointerAlignment != FormatStyle::PAS_Left;
d2519 1
a2519 3
         Line.startsWith(tok::kw_const, tok::kw_enum) ||
         Line.startsWith(tok::kw_export, tok::kw_enum) ||
         Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
d2537 1
a2537 2
             Style.Language == FormatStyle::LK_Proto ||
             Style.Language == FormatStyle::LK_TextProto) {
d2579 1
a2579 1
      Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
d2590 1
a2590 1
  if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
d2592 1
a2592 1
    return true;
d2594 4
a2597 4
    // Multiline raw string literals are special wrt. line breaks. The author
    // has made a deliberate choice and might have aligned the contents of the
    // string literal accordingly. Thus, we try keep existing line breaks.
    return Right.IsMultiline && Right.NewlinesBefore > 0;
d2599 4
a2602 2
       (Right.Previous->is(tok::less) && Right.Previous->Previous &&
        Right.Previous->Previous->is(tok::equal))) &&
a2611 2
           (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
            Style.BraceWrapping.AfterEnum) ||
a2623 88
  if (Right.is(TT_ProtoExtensionLSquare))
    return true;

  // In text proto instances if a submessage contains at least 2 entries and at
  // least one of them is a submessage, like A { ... B { ... } ... },
  // put all of the entries of A on separate lines by forcing the selector of
  // the submessage B to be put on a newline.
  //
  // Example: these can stay on one line:
  // a { scalar_1: 1 scalar_2: 2 }
  // a { b { key: value } }
  //
  // and these entries need to be on a new line even if putting them all in one
  // line is under the column limit:
  // a {
  //   scalar: 1
  //   b { key: value }
  // }
  //
  // We enforce this by breaking before a submessage field that has previous
  // siblings, *and* breaking before a field that follows a submessage field.
  //
  // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
  // the TT_SelectorName there, but we don't want to break inside the brackets.
  //
  // Another edge case is @@submessage { key: value }, which is a common
  // substitution placeholder. In this case we want to keep `@@` and `submessage`
  // together.
  //
  // We ensure elsewhere that extensions are always on their own line.
  if ((Style.Language == FormatStyle::LK_Proto ||
       Style.Language == FormatStyle::LK_TextProto) &&
      Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
    // Keep `@@submessage` together in:
    // @@submessage { key: value }
    if (Right.Previous && Right.Previous->is(tok::at))
      return false;
    // Look for the scope opener after selector in cases like:
    // selector { ...
    // selector: { ...
    // selector: @@base { ...
    FormatToken *LBrace = Right.Next;
    if (LBrace && LBrace->is(tok::colon)) {
      LBrace = LBrace->Next;
      if (LBrace && LBrace->is(tok::at)) {
        LBrace = LBrace->Next;
        if (LBrace)
          LBrace = LBrace->Next;
      }
    }
    if (LBrace &&
        // The scope opener is one of {, [, <:
        // selector { ... }
        // selector [ ... ]
        // selector < ... >
        //
        // In case of selector { ... }, the l_brace is TT_DictLiteral.
        // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
        // so we check for immediately following r_brace.
        ((LBrace->is(tok::l_brace) &&
          (LBrace->is(TT_DictLiteral) ||
           (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
         LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
      // If Left.ParameterCount is 0, then this submessage entry is not the
      // first in its parent submessage, and we want to break before this entry.
      // If Left.ParameterCount is greater than 0, then its parent submessage
      // might contain 1 or more entries and we want to break before this entry
      // if it contains at least 2 entries. We deal with this case later by
      // detecting and breaking before the next entry in the parent submessage.
      if (Left.ParameterCount == 0)
        return true;
      // However, if this submessage is the first entry in its parent
      // submessage, Left.ParameterCount might be 1 in some cases.
      // We deal with this case later by detecting an entry
      // following a closing paren of this submessage.
    }

    // If this is an entry immediately following a submessage, it will be
    // preceded by a closing paren of that submessage, like in:
    //     left---.  .---right
    //            v  v
    // sub: { ... } key: value
    // If there was a comment between `}` an `key` above, then `key` would be
    // put on a new line anyways.
    if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
      return true;
  }

d2642 6
a2647 11
        NonComment->isOneOf(
            tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
            tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
            tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
            Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
            Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
      return false; // Otherwise automatic semicolon insertion would trigger.
    if (Right.NestingLevel == 0 &&
        (Left.Tok.getIdentifierInfo() ||
         Left.isOneOf(tok::r_square, tok::r_paren)) &&
        Right.isOneOf(tok::l_square, tok::l_paren))
d2653 1
a2653 4
    // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
    if (Left.is(tok::exclaim) && Right.is(tok::colon))
      return false;
    if (Right.is(Keywords.kw_is))
d2705 2
a2706 1
            Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
a2712 2
  if (Left.is(TT_InheritanceColon))
    return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
d2714 1
a2714 1
    return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
a2717 1

d2721 1
a2721 34
  if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
    if (Style.Language == FormatStyle::LK_Proto ||
        Style.Language == FormatStyle::LK_TextProto) {
      if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
        return false;
      // Prevent cases like:
      //
      // submessage:
      //     { key: valueeeeeeeeeeee }
      //
      // when the snippet does not fit into one line.
      // Prefer:
      //
      // submessage: {
      //   key: valueeeeeeeeeeee
      // }
      //
      // instead, even if it is longer by one line.
      //
      // Note that this allows allows the "{" to go over the column limit
      // when the column limit is just between ":" and "{", but that does
      // not happen too often and alternative formattings in this case are
      // not much better.
      //
      // The code covers the cases:
      //
      // submessage: { ... }
      // submessage: < ... >
      // repeated: [ ... ]
      if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
           Right.is(TT_DictLiteral)) ||
          Right.is(TT_ArrayInitializerLSquare))
        return false;
    }
a2722 4
  }
  if (Right.is(tok::r_square) && Right.MatchingParen &&
      Right.MatchingParen->is(TT_ProtoExtensionLSquare))
    return false;
a2744 3
  if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
      !Style.Cpp11BracedListStyle)
    return false;
d2770 1
a2770 2
  if (Right.is(tok::kw___attribute) ||
      (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
d2789 1
a2789 2
  if (Left.is(TT_InheritanceComma) &&
      Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
d2791 1
a2791 2
  if (Right.is(TT_InheritanceComma) &&
      Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
a2810 3
  if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
      (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
    return false;
d2823 1
a2823 1
  llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
d2831 4
a2834 3
                 << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
                 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
                 << " PPK=" << Tok->PackingKind << " FakeLParens=";
a2837 1
    llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
@


1.1.1.13
log
@Mark old LLVM instance as dead.
@
text
@@


1.1.1.7.4.1
log
@file TokenAnnotator.cpp was added on branch tls-maxphys on 2014-08-19 23:47:28 +0000
@
text
@d1 1851
@


1.1.1.7.4.2
log
@Rebase to HEAD as of a few days ago.
@
text
@a0 1851
//===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a token annotator, i.e. creates
/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
///
//===----------------------------------------------------------------------===//

#include "TokenAnnotator.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/Debug.h"

#define DEBUG_TYPE "format-token-annotator"

namespace clang {
namespace format {

namespace {

/// \brief A parser that gathers additional information about tokens.
///
/// The \c TokenAnnotator tries to match parenthesis and square brakets and
/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
/// into template parameter lists.
class AnnotatingParser {
public:
  AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
                   IdentifierInfo &Ident_in)
      : Style(Style), Line(Line), CurrentToken(Line.First),
        KeywordVirtualFound(false), AutoFound(false), Ident_in(Ident_in) {
    Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
    resetTokenMetadata(CurrentToken);
  }

private:
  bool parseAngle() {
    if (!CurrentToken)
      return false;
    ScopedContextCreator ContextCreator(*this, tok::less, 10);
    FormatToken *Left = CurrentToken->Previous;
    Contexts.back().IsExpression = false;
    // If there's a template keyword before the opening angle bracket, this is a
    // template parameter, not an argument.
    Contexts.back().InTemplateArgument =
        Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);

    while (CurrentToken) {
      if (CurrentToken->is(tok::greater)) {
        Left->MatchingParen = CurrentToken;
        CurrentToken->MatchingParen = Left;
        CurrentToken->Type = TT_TemplateCloser;
        next();
        return true;
      }
      if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace,
                                tok::question, tok::colon))
        return false;
      // If a && or || is found and interpreted as a binary operator, this set
      // of angles is likely part of something like "a < b && c > d". If the
      // angles are inside an expression, the ||/&& might also be a binary
      // operator that was misinterpreted because we are parsing template
      // parameters.
      // FIXME: This is getting out of hand, write a decent parser.
      if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
          CurrentToken->Previous->Type == TT_BinaryOperator &&
          Contexts[Contexts.size() - 2].IsExpression &&
          Line.First->isNot(tok::kw_template))
        return false;
      updateParameterCount(Left, CurrentToken);
      if (!consumeToken())
        return false;
    }
    return false;
  }

  bool parseParens(bool LookForDecls = false) {
    if (!CurrentToken)
      return false;
    ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);

    // FIXME: This is a bit of a hack. Do better.
    Contexts.back().ColonIsForRangeExpr =
        Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;

    bool StartsObjCMethodExpr = false;
    FormatToken *Left = CurrentToken->Previous;
    if (CurrentToken->is(tok::caret)) {
      // (^ can start a block type.
      Left->Type = TT_ObjCBlockLParen;
    } else if (FormatToken *MaybeSel = Left->Previous) {
      // @@selector( starts a selector.
      if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
          MaybeSel->Previous->is(tok::at)) {
        StartsObjCMethodExpr = true;
      }
    }

    if (Left->Previous &&
        (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_if,
                                 tok::kw_while, tok::l_paren, tok::comma) ||
         Left->Previous->Type == TT_BinaryOperator)) {
      // static_assert, if and while usually contain expressions.
      Contexts.back().IsExpression = true;
    } else if (Line.InPPDirective &&
               (!Left->Previous ||
                (Left->Previous->isNot(tok::identifier) &&
                 Left->Previous->Type != TT_OverloadedOperator))) {
      Contexts.back().IsExpression = true;
    } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
               Left->Previous->MatchingParen &&
               Left->Previous->MatchingParen->Type == TT_LambdaLSquare) {
      // This is a parameter list of a lambda expression.
      Contexts.back().IsExpression = false;
    } else if (Contexts[Contexts.size() - 2].CaretFound) {
      // This is the parameter list of an ObjC block.
      Contexts.back().IsExpression = false;
    } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
      Left->Type = TT_AttributeParen;
    } else if (Left->Previous && Left->Previous->IsForEachMacro) {
      // The first argument to a foreach macro is a declaration.
      Contexts.back().IsForEachMacro = true;
      Contexts.back().IsExpression = false;
    }

    if (StartsObjCMethodExpr) {
      Contexts.back().ColonIsObjCMethodExpr = true;
      Left->Type = TT_ObjCMethodExpr;
    }

    bool MightBeFunctionType = CurrentToken->is(tok::star);
    bool HasMultipleLines = false;
    bool HasMultipleParametersOnALine = false;
    while (CurrentToken) {
      // LookForDecls is set when "if (" has been seen. Check for
      // 'identifier' '*' 'identifier' followed by not '=' -- this
      // '*' has to be a binary operator but determineStarAmpUsage() will
      // categorize it as an unary operator, so set the right type here.
      if (LookForDecls && CurrentToken->Next) {
        FormatToken *Prev = CurrentToken->getPreviousNonComment();
        if (Prev) {
          FormatToken *PrevPrev = Prev->getPreviousNonComment();
          FormatToken *Next = CurrentToken->Next;
          if (PrevPrev && PrevPrev->is(tok::identifier) &&
              Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
              CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
            Prev->Type = TT_BinaryOperator;
            LookForDecls = false;
          }
        }
      }

      if (CurrentToken->Previous->Type == TT_PointerOrReference &&
          CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
                                                    tok::coloncolon))
        MightBeFunctionType = true;
      if (CurrentToken->Previous->Type == TT_BinaryOperator)
        Contexts.back().IsExpression = true;
      if (CurrentToken->is(tok::r_paren)) {
        if (MightBeFunctionType && CurrentToken->Next &&
            (CurrentToken->Next->is(tok::l_paren) ||
             (CurrentToken->Next->is(tok::l_square) &&
              !Contexts.back().IsExpression)))
          Left->Type = TT_FunctionTypeLParen;
        Left->MatchingParen = CurrentToken;
        CurrentToken->MatchingParen = Left;

        if (StartsObjCMethodExpr) {
          CurrentToken->Type = TT_ObjCMethodExpr;
          if (Contexts.back().FirstObjCSelectorName) {
            Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
                Contexts.back().LongestObjCSelectorName;
          }
        }

        if (Left->Type == TT_AttributeParen)
          CurrentToken->Type = TT_AttributeParen;

        if (!HasMultipleLines)
          Left->PackingKind = PPK_Inconclusive;
        else if (HasMultipleParametersOnALine)
          Left->PackingKind = PPK_BinPacked;
        else
          Left->PackingKind = PPK_OnePerLine;

        next();
        return true;
      }
      if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
        return false;
      else if (CurrentToken->is(tok::l_brace))
        Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
      if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
          !CurrentToken->Next->HasUnescapedNewline &&
          !CurrentToken->Next->isTrailingComment())
        HasMultipleParametersOnALine = true;
      if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
          CurrentToken->isSimpleTypeSpecifier())
        Contexts.back().IsExpression = false;
      FormatToken *Tok = CurrentToken;
      if (!consumeToken())
        return false;
      updateParameterCount(Left, Tok);
      if (CurrentToken && CurrentToken->HasUnescapedNewline)
        HasMultipleLines = true;
    }
    return false;
  }

  bool parseSquare() {
    if (!CurrentToken)
      return false;

    // A '[' could be an index subscript (after an identifier or after
    // ')' or ']'), it could be the start of an Objective-C method
    // expression, or it could the the start of an Objective-C array literal.
    FormatToken *Left = CurrentToken->Previous;
    FormatToken *Parent = Left->getPreviousNonComment();
    bool StartsObjCMethodExpr =
        Contexts.back().CanBeExpression && Left->Type != TT_LambdaLSquare &&
        CurrentToken->isNot(tok::l_brace) &&
        (!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
                                    tok::kw_return, tok::kw_throw) ||
         Parent->isUnaryOperator() || Parent->Type == TT_ObjCForIn ||
         Parent->Type == TT_CastRParen ||
         getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
    ScopedContextCreator ContextCreator(*this, tok::l_square, 10);
    Contexts.back().IsExpression = true;
    bool ColonFound = false;

    if (StartsObjCMethodExpr) {
      Contexts.back().ColonIsObjCMethodExpr = true;
      Left->Type = TT_ObjCMethodExpr;
    } else if (Parent && Parent->is(tok::at)) {
      Left->Type = TT_ArrayInitializerLSquare;
    } else if (Left->Type == TT_Unknown) {
      Left->Type = TT_ArraySubscriptLSquare;
    }

    while (CurrentToken) {
      if (CurrentToken->is(tok::r_square)) {
        if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
            Left->Type == TT_ObjCMethodExpr) {
          // An ObjC method call is rarely followed by an open parenthesis.
          // FIXME: Do we incorrectly label ":" with this?
          StartsObjCMethodExpr = false;
          Left->Type = TT_Unknown;
        }
        if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
          CurrentToken->Type = TT_ObjCMethodExpr;
          // determineStarAmpUsage() thinks that '*' '[' is allocating an
          // array of pointers, but if '[' starts a selector then '*' is a
          // binary operator.
          if (Parent && Parent->Type == TT_PointerOrReference)
            Parent->Type = TT_BinaryOperator;
        }
        Left->MatchingParen = CurrentToken;
        CurrentToken->MatchingParen = Left;
        if (Contexts.back().FirstObjCSelectorName) {
          Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
              Contexts.back().LongestObjCSelectorName;
          if (Left->BlockParameterCount > 1)
            Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
        }
        next();
        return true;
      }
      if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
        return false;
      if (CurrentToken->is(tok::colon))
        ColonFound = true;
      if (CurrentToken->is(tok::comma) &&
          Style.Language != FormatStyle::LK_Proto &&
          (Left->Type == TT_ArraySubscriptLSquare ||
           (Left->Type == TT_ObjCMethodExpr && !ColonFound)))
        Left->Type = TT_ArrayInitializerLSquare;
      FormatToken* Tok = CurrentToken;
      if (!consumeToken())
        return false;
      updateParameterCount(Left, Tok);
    }
    return false;
  }

  bool parseBrace() {
    if (CurrentToken) {
      FormatToken *Left = CurrentToken->Previous;

      if (Contexts.back().CaretFound)
        Left->Type = TT_ObjCBlockLBrace;
      Contexts.back().CaretFound = false;

      ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
      Contexts.back().ColonIsDictLiteral = true;
      if (Left->BlockKind == BK_BracedInit)
        Contexts.back().IsExpression = true;

      while (CurrentToken) {
        if (CurrentToken->is(tok::r_brace)) {
          Left->MatchingParen = CurrentToken;
          CurrentToken->MatchingParen = Left;
          next();
          return true;
        }
        if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
          return false;
        updateParameterCount(Left, CurrentToken);
        if (CurrentToken->is(tok::colon)) {
          if (CurrentToken->getPreviousNonComment()->is(tok::identifier))
            CurrentToken->getPreviousNonComment()->Type = TT_SelectorName;
          Left->Type = TT_DictLiteral;
        }
        if (!consumeToken())
          return false;
      }
    }
    return true;
  }

  void updateParameterCount(FormatToken *Left, FormatToken *Current) {
    if (Current->Type == TT_LambdaLSquare ||
        (Current->is(tok::caret) && Current->Type == TT_UnaryOperator) ||
        (Style.Language == FormatStyle::LK_JavaScript &&
         Current->TokenText == "function")) {
      ++Left->BlockParameterCount;
    }
    if (Current->is(tok::comma)) {
      ++Left->ParameterCount;
      if (!Left->Role)
        Left->Role.reset(new CommaSeparatedList(Style));
      Left->Role->CommaFound(Current);
    } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
      Left->ParameterCount = 1;
    }
  }

  bool parseConditional() {
    while (CurrentToken) {
      if (CurrentToken->is(tok::colon)) {
        CurrentToken->Type = TT_ConditionalExpr;
        next();
        return true;
      }
      if (!consumeToken())
        return false;
    }
    return false;
  }

  bool parseTemplateDeclaration() {
    if (CurrentToken && CurrentToken->is(tok::less)) {
      CurrentToken->Type = TT_TemplateOpener;
      next();
      if (!parseAngle())
        return false;
      if (CurrentToken)
        CurrentToken->Previous->ClosesTemplateDeclaration = true;
      return true;
    }
    return false;
  }

  bool consumeToken() {
    FormatToken *Tok = CurrentToken;
    next();
    switch (Tok->Tok.getKind()) {
    case tok::plus:
    case tok::minus:
      if (!Tok->Previous && Line.MustBeDeclaration)
        Tok->Type = TT_ObjCMethodSpecifier;
      break;
    case tok::colon:
      if (!Tok->Previous)
        return false;
      // Colons from ?: are handled in parseConditional().
      if (Tok->Previous->is(tok::r_paren) && Contexts.size() == 1 &&
          Line.First->isNot(tok::kw_case)) {
        Tok->Type = TT_CtorInitializerColon;
      } else if (Contexts.back().ColonIsDictLiteral) {
        Tok->Type = TT_DictLiteral;
      } else if (Contexts.back().ColonIsObjCMethodExpr ||
                 Line.First->Type == TT_ObjCMethodSpecifier) {
        Tok->Type = TT_ObjCMethodExpr;
        Tok->Previous->Type = TT_SelectorName;
        if (Tok->Previous->ColumnWidth >
            Contexts.back().LongestObjCSelectorName) {
          Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
        }
        if (!Contexts.back().FirstObjCSelectorName)
          Contexts.back().FirstObjCSelectorName = Tok->Previous;
      } else if (Contexts.back().ColonIsForRangeExpr) {
        Tok->Type = TT_RangeBasedForLoopColon;
      } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
        Tok->Type = TT_BitFieldColon;
      } else if (Contexts.size() == 1 &&
                 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
        Tok->Type = TT_InheritanceColon;
      } else if (Contexts.back().ContextKind == tok::l_paren) {
        Tok->Type = TT_InlineASMColon;
      }
      break;
    case tok::kw_if:
    case tok::kw_while:
      if (CurrentToken && CurrentToken->is(tok::l_paren)) {
        next();
        if (!parseParens(/*LookForDecls=*/true))
          return false;
      }
      break;
    case tok::kw_for:
      Contexts.back().ColonIsForRangeExpr = true;
      next();
      if (!parseParens())
        return false;
      break;
    case tok::l_paren:
      if (!parseParens())
        return false;
      if (Line.MustBeDeclaration && Contexts.size() == 1 &&
          !Contexts.back().IsExpression &&
          Line.First->Type != TT_ObjCProperty &&
          (!Tok->Previous || Tok->Previous->isNot(tok::kw_decltype)))
        Line.MightBeFunctionDecl = true;
      break;
    case tok::l_square:
      if (!parseSquare())
        return false;
      break;
    case tok::l_brace:
      if (!parseBrace())
        return false;
      break;
    case tok::less:
      if (Tok->Previous && !Tok->Previous->Tok.isLiteral() && parseAngle())
        Tok->Type = TT_TemplateOpener;
      else {
        Tok->Type = TT_BinaryOperator;
        CurrentToken = Tok;
        next();
      }
      break;
    case tok::r_paren:
    case tok::r_square:
      return false;
    case tok::r_brace:
      // Lines can start with '}'.
      if (Tok->Previous)
        return false;
      break;
    case tok::greater:
      Tok->Type = TT_BinaryOperator;
      break;
    case tok::kw_operator:
      while (CurrentToken &&
             !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
        if (CurrentToken->isOneOf(tok::star, tok::amp))
          CurrentToken->Type = TT_PointerOrReference;
        consumeToken();
        if (CurrentToken && CurrentToken->Previous->Type == TT_BinaryOperator)
          CurrentToken->Previous->Type = TT_OverloadedOperator;
      }
      if (CurrentToken) {
        CurrentToken->Type = TT_OverloadedOperatorLParen;
        if (CurrentToken->Previous->Type == TT_BinaryOperator)
          CurrentToken->Previous->Type = TT_OverloadedOperator;
      }
      break;
    case tok::question:
      parseConditional();
      break;
    case tok::kw_template:
      parseTemplateDeclaration();
      break;
    case tok::identifier:
      if (Line.First->is(tok::kw_for) &&
          Tok->Tok.getIdentifierInfo() == &Ident_in)
        Tok->Type = TT_ObjCForIn;
      break;
    case tok::comma:
      if (Contexts.back().FirstStartOfName)
        Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
      if (Contexts.back().InCtorInitializer)
        Tok->Type = TT_CtorInitializerComma;
      if (Contexts.back().IsForEachMacro)
        Contexts.back().IsExpression = true;
      break;
    default:
      break;
    }
    return true;
  }

  void parseIncludeDirective() {
    next();
    if (CurrentToken && CurrentToken->is(tok::less)) {
      next();
      while (CurrentToken) {
        if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
          CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
    } else {
      while (CurrentToken) {
        if (CurrentToken->is(tok::string_literal))
          // Mark these string literals as "implicit" literals, too, so that
          // they are not split or line-wrapped.
          CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
    }
  }

  void parseWarningOrError() {
    next();
    // We still want to format the whitespace left of the first token of the
    // warning or error.
    next();
    while (CurrentToken) {
      CurrentToken->Type = TT_ImplicitStringLiteral;
      next();
    }
  }

  void parsePragma() {
    next(); // Consume "pragma".
    if (CurrentToken && CurrentToken->TokenText == "mark") {
      next(); // Consume "mark".
      next(); // Consume first token (so we fix leading whitespace).
      while (CurrentToken) {
        CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
    }
  }

  void parsePreprocessorDirective() {
    next();
    if (!CurrentToken)
      return;
    if (CurrentToken->Tok.is(tok::numeric_constant)) {
      CurrentToken->SpacesRequiredBefore = 1;
      return;
    }
    // Hashes in the middle of a line can lead to any strange token
    // sequence.
    if (!CurrentToken->Tok.getIdentifierInfo())
      return;
    switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
    case tok::pp_include:
    case tok::pp_import:
      parseIncludeDirective();
      break;
    case tok::pp_error:
    case tok::pp_warning:
      parseWarningOrError();
      break;
    case tok::pp_pragma:
      parsePragma();
      break;
    case tok::pp_if:
    case tok::pp_elif:
      Contexts.back().IsExpression = true;
      parseLine();
      break;
    default:
      break;
    }
    while (CurrentToken)
      next();
  }

public:
  LineType parseLine() {
    if (CurrentToken->is(tok::hash)) {
      parsePreprocessorDirective();
      return LT_PreprocessorDirective;
    }

    // Directly allow to 'import <string-literal>' to support protocol buffer
    // definitions (code.google.com/p/protobuf) or missing "#" (either way we
    // should not break the line).
    IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
    if (Info && Info->getPPKeywordID() == tok::pp_import &&
        CurrentToken->Next && CurrentToken->Next->is(tok::string_literal))
      parseIncludeDirective();

    while (CurrentToken) {
      if (CurrentToken->is(tok::kw_virtual))
        KeywordVirtualFound = true;
      if (!consumeToken())
        return LT_Invalid;
    }
    if (KeywordVirtualFound)
      return LT_VirtualFunctionDecl;

    if (Line.First->Type == TT_ObjCMethodSpecifier) {
      if (Contexts.back().FirstObjCSelectorName)
        Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
            Contexts.back().LongestObjCSelectorName;
      return LT_ObjCMethodDecl;
    }

    return LT_Other;
  }

private:
  void resetTokenMetadata(FormatToken *Token) {
    if (!Token)
      return;

    // Reset token type in case we have already looked at it and then
    // recovered from an error (e.g. failure to find the matching >).
    if (CurrentToken->Type != TT_LambdaLSquare &&
        CurrentToken->Type != TT_FunctionLBrace &&
        CurrentToken->Type != TT_ImplicitStringLiteral &&
        CurrentToken->Type != TT_RegexLiteral &&
        CurrentToken->Type != TT_TrailingReturnArrow)
      CurrentToken->Type = TT_Unknown;
    CurrentToken->Role.reset();
    CurrentToken->FakeLParens.clear();
    CurrentToken->FakeRParens = 0;
  }

  void next() {
    if (CurrentToken) {
      determineTokenType(*CurrentToken);
      CurrentToken->BindingStrength = Contexts.back().BindingStrength;
      CurrentToken->NestingLevel = Contexts.size() - 1;
      CurrentToken = CurrentToken->Next;
    }

    resetTokenMetadata(CurrentToken);
  }

  /// \brief A struct to hold information valid in a specific context, e.g.
  /// a pair of parenthesis.
  struct Context {
    Context(tok::TokenKind ContextKind, unsigned BindingStrength,
            bool IsExpression)
        : ContextKind(ContextKind), BindingStrength(BindingStrength),
          LongestObjCSelectorName(0), ColonIsForRangeExpr(false),
          ColonIsDictLiteral(false), ColonIsObjCMethodExpr(false),
          FirstObjCSelectorName(nullptr), FirstStartOfName(nullptr),
          IsExpression(IsExpression), CanBeExpression(true),
          InTemplateArgument(false), InCtorInitializer(false),
          CaretFound(false), IsForEachMacro(false) {}

    tok::TokenKind ContextKind;
    unsigned BindingStrength;
    unsigned LongestObjCSelectorName;
    bool ColonIsForRangeExpr;
    bool ColonIsDictLiteral;
    bool ColonIsObjCMethodExpr;
    FormatToken *FirstObjCSelectorName;
    FormatToken *FirstStartOfName;
    bool IsExpression;
    bool CanBeExpression;
    bool InTemplateArgument;
    bool InCtorInitializer;
    bool CaretFound;
    bool IsForEachMacro;
  };

  /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
  /// of each instance.
  struct ScopedContextCreator {
    AnnotatingParser &P;

    ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
                         unsigned Increase)
        : P(P) {
      P.Contexts.push_back(Context(ContextKind,
                                   P.Contexts.back().BindingStrength + Increase,
                                   P.Contexts.back().IsExpression));
    }

    ~ScopedContextCreator() { P.Contexts.pop_back(); }
  };

  void determineTokenType(FormatToken &Current) {
    if (Current.getPrecedence() == prec::Assignment &&
        !Line.First->isOneOf(tok::kw_template, tok::kw_using) &&
        (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
      Contexts.back().IsExpression = true;
      for (FormatToken *Previous = Current.Previous;
           Previous && !Previous->isOneOf(tok::comma, tok::semi);
           Previous = Previous->Previous) {
        if (Previous->isOneOf(tok::r_square, tok::r_paren))
          Previous = Previous->MatchingParen;
        if ((Previous->Type == TT_BinaryOperator ||
             Previous->Type == TT_UnaryOperator) &&
            Previous->isOneOf(tok::star, tok::amp)) {
          Previous->Type = TT_PointerOrReference;
        }
      }
    } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
      Contexts.back().IsExpression = true;
    } else if (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
               !Line.InPPDirective &&
               (!Current.Previous ||
                Current.Previous->isNot(tok::kw_decltype))) {
      bool ParametersOfFunctionType =
          Current.Previous && Current.Previous->is(tok::r_paren) &&
          Current.Previous->MatchingParen &&
          Current.Previous->MatchingParen->Type == TT_FunctionTypeLParen;
      bool IsForOrCatch = Current.Previous &&
                          Current.Previous->isOneOf(tok::kw_for, tok::kw_catch);
      Contexts.back().IsExpression = !ParametersOfFunctionType && !IsForOrCatch;
    } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
      for (FormatToken *Previous = Current.Previous;
           Previous && Previous->isOneOf(tok::star, tok::amp);
           Previous = Previous->Previous)
        Previous->Type = TT_PointerOrReference;
    } else if (Current.Previous &&
               Current.Previous->Type == TT_CtorInitializerColon) {
      Contexts.back().IsExpression = true;
      Contexts.back().InCtorInitializer = true;
    } else if (Current.is(tok::kw_new)) {
      Contexts.back().CanBeExpression = false;
    } else if (Current.is(tok::semi) || Current.is(tok::exclaim)) {
      // This should be the condition or increment in a for-loop.
      Contexts.back().IsExpression = true;
    }

    if (Current.Type == TT_Unknown) {
      // Line.MightBeFunctionDecl can only be true after the parentheses of a
      // function declaration have been found. In this case, 'Current' is a
      // trailing token of this declaration and thus cannot be a name.
      if (isStartOfName(Current) && !Line.MightBeFunctionDecl) {
        Contexts.back().FirstStartOfName = &Current;
        Current.Type = TT_StartOfName;
      } else if (Current.is(tok::kw_auto)) {
        AutoFound = true;
      } else if (Current.is(tok::arrow) && AutoFound &&
                 Line.MustBeDeclaration) {
        Current.Type = TT_TrailingReturnArrow;
      } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
        Current.Type =
            determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
                                               Contexts.back().IsExpression,
                                  Contexts.back().InTemplateArgument);
      } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
        Current.Type = determinePlusMinusCaretUsage(Current);
        if (Current.Type == TT_UnaryOperator && Current.is(tok::caret))
          Contexts.back().CaretFound = true;
      } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
        Current.Type = determineIncrementUsage(Current);
      } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
        Current.Type = TT_UnaryOperator;
      } else if (Current.is(tok::question)) {
        Current.Type = TT_ConditionalExpr;
      } else if (Current.isBinaryOperator() &&
                 (!Current.Previous ||
                  Current.Previous->isNot(tok::l_square))) {
        Current.Type = TT_BinaryOperator;
      } else if (Current.is(tok::comment)) {
        if (Current.TokenText.startswith("//"))
          Current.Type = TT_LineComment;
        else
          Current.Type = TT_BlockComment;
      } else if (Current.is(tok::r_paren)) {
        if (rParenEndsCast(Current))
          Current.Type = TT_CastRParen;
      } else if (Current.is(tok::at) && Current.Next) {
        switch (Current.Next->Tok.getObjCKeywordID()) {
        case tok::objc_interface:
        case tok::objc_implementation:
        case tok::objc_protocol:
          Current.Type = TT_ObjCDecl;
          break;
        case tok::objc_property:
          Current.Type = TT_ObjCProperty;
          break;
        default:
          break;
        }
      } else if (Current.is(tok::period)) {
        FormatToken *PreviousNoComment = Current.getPreviousNonComment();
        if (PreviousNoComment &&
            PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
          Current.Type = TT_DesignatedInitializerPeriod;
      } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
                 Current.Previous && Current.Previous->isNot(tok::equal) &&
                 Line.MightBeFunctionDecl && Contexts.size() == 1) {
        // Line.MightBeFunctionDecl can only be true after the parentheses of a
        // function declaration have been found.
        Current.Type = TT_TrailingAnnotation;
      }
    }
  }

  /// \brief Take a guess at whether \p Tok starts a name of a function or
  /// variable declaration.
  ///
  /// This is a heuristic based on whether \p Tok is an identifier following
  /// something that is likely a type.
  bool isStartOfName(const FormatToken &Tok) {
    if (Tok.isNot(tok::identifier) || !Tok.Previous)
      return false;

    // Skip "const" as it does not have an influence on whether this is a name.
    FormatToken *PreviousNotConst = Tok.Previous;
    while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
      PreviousNotConst = PreviousNotConst->Previous;

    if (!PreviousNotConst)
      return false;

    bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
                       PreviousNotConst->Previous &&
                       PreviousNotConst->Previous->is(tok::hash);

    if (PreviousNotConst->Type == TT_TemplateCloser)
      return PreviousNotConst && PreviousNotConst->MatchingParen &&
             PreviousNotConst->MatchingParen->Previous &&
             PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);

    if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
        PreviousNotConst->MatchingParen->Previous &&
        PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
      return true;

    return (!IsPPKeyword && PreviousNotConst->is(tok::identifier)) ||
           PreviousNotConst->Type == TT_PointerOrReference ||
           PreviousNotConst->isSimpleTypeSpecifier();
  }

  /// \brief Determine whether ')' is ending a cast.
  bool rParenEndsCast(const FormatToken &Tok) {
    FormatToken *LeftOfParens = nullptr;
    if (Tok.MatchingParen)
      LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
    if (LeftOfParens && LeftOfParens->is(tok::r_paren))
      return false;
    if (LeftOfParens && LeftOfParens->is(tok::r_square) &&
        LeftOfParens->MatchingParen &&
        LeftOfParens->MatchingParen->Type == TT_LambdaLSquare)
      return false;
    bool IsCast = false;
    bool ParensAreEmpty = Tok.Previous == Tok.MatchingParen;
    bool ParensAreType = !Tok.Previous ||
                         Tok.Previous->Type == TT_PointerOrReference ||
                         Tok.Previous->Type == TT_TemplateCloser ||
                         Tok.Previous->isSimpleTypeSpecifier();
    bool ParensCouldEndDecl =
        Tok.Next && Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
    bool IsSizeOfOrAlignOf =
        LeftOfParens && LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
    if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
        ((Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression) ||
         (Tok.Next && Tok.Next->isBinaryOperator())))
      IsCast = true;
    else if (Tok.Next && Tok.Next->isNot(tok::string_literal) &&
             (Tok.Next->Tok.isLiteral() ||
              Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
      IsCast = true;
    // If there is an identifier after the (), it is likely a cast, unless
    // there is also an identifier before the ().
    else if (LeftOfParens &&
             (LeftOfParens->Tok.getIdentifierInfo() == nullptr ||
              LeftOfParens->is(tok::kw_return)) &&
             LeftOfParens->Type != TT_OverloadedOperator &&
             LeftOfParens->isNot(tok::at) &&
             LeftOfParens->Type != TT_TemplateCloser && Tok.Next) {
      if (Tok.Next->isOneOf(tok::identifier, tok::numeric_constant)) {
        IsCast = true;
      } else {
        // Use heuristics to recognize c style casting.
        FormatToken *Prev = Tok.Previous;
        if (Prev && Prev->isOneOf(tok::amp, tok::star))
          Prev = Prev->Previous;

        if (Prev && Tok.Next && Tok.Next->Next) {
          bool NextIsUnary = Tok.Next->isUnaryOperator() ||
                             Tok.Next->isOneOf(tok::amp, tok::star);
          IsCast = NextIsUnary && Tok.Next->Next->isOneOf(
                                      tok::identifier, tok::numeric_constant);
        }

        for (; Prev != Tok.MatchingParen; Prev = Prev->Previous) {
          if (!Prev || !Prev->isOneOf(tok::kw_const, tok::identifier)) {
            IsCast = false;
            break;
          }
        }
      }
    }
    return IsCast && !ParensAreEmpty;
  }

  /// \brief Return the type of the given token assuming it is * or &.
  TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
                                  bool InTemplateArgument) {
    const FormatToken *PrevToken = Tok.getPreviousNonComment();
    if (!PrevToken)
      return TT_UnaryOperator;

    const FormatToken *NextToken = Tok.getNextNonComment();
    if (!NextToken || NextToken->is(tok::l_brace))
      return TT_Unknown;

    if (PrevToken->is(tok::coloncolon) ||
        (PrevToken->is(tok::l_paren) && !IsExpression))
      return TT_PointerOrReference;

    if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
                           tok::comma, tok::semi, tok::kw_return, tok::colon,
                           tok::equal, tok::kw_delete, tok::kw_sizeof) ||
        PrevToken->Type == TT_BinaryOperator ||
        PrevToken->Type == TT_ConditionalExpr ||
        PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
      return TT_UnaryOperator;

    if (NextToken->is(tok::l_square) && NextToken->Type != TT_LambdaLSquare)
      return TT_PointerOrReference;
    if (NextToken->isOneOf(tok::kw_operator, tok::comma))
      return TT_PointerOrReference;

    if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
        PrevToken->MatchingParen->Previous &&
        PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
                                                    tok::kw_decltype))
      return TT_PointerOrReference;

    if (PrevToken->Tok.isLiteral() ||
        PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
                           tok::kw_false) ||
        NextToken->Tok.isLiteral() ||
        NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
        NextToken->isUnaryOperator() ||
        // If we know we're in a template argument, there are no named
        // declarations. Thus, having an identifier on the right-hand side
        // indicates a binary operator.
        (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
      return TT_BinaryOperator;

    // This catches some cases where evaluation order is used as control flow:
    //   aaa && aaa->f();
    const FormatToken *NextNextToken = NextToken->getNextNonComment();
    if (NextNextToken && NextNextToken->is(tok::arrow))
      return TT_BinaryOperator;

    // It is very unlikely that we are going to find a pointer or reference type
    // definition on the RHS of an assignment.
    if (IsExpression)
      return TT_BinaryOperator;

    return TT_PointerOrReference;
  }

  TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
    const FormatToken *PrevToken = Tok.getPreviousNonComment();
    if (!PrevToken || PrevToken->Type == TT_CastRParen)
      return TT_UnaryOperator;

    // Use heuristics to recognize unary operators.
    if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
                           tok::question, tok::colon, tok::kw_return,
                           tok::kw_case, tok::at, tok::l_brace))
      return TT_UnaryOperator;

    // There can't be two consecutive binary operators.
    if (PrevToken->Type == TT_BinaryOperator)
      return TT_UnaryOperator;

    // Fall back to marking the token as binary operator.
    return TT_BinaryOperator;
  }

  /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
  TokenType determineIncrementUsage(const FormatToken &Tok) {
    const FormatToken *PrevToken = Tok.getPreviousNonComment();
    if (!PrevToken || PrevToken->Type == TT_CastRParen)
      return TT_UnaryOperator;
    if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
      return TT_TrailingUnaryOperator;

    return TT_UnaryOperator;
  }

  SmallVector<Context, 8> Contexts;

  const FormatStyle &Style;
  AnnotatedLine &Line;
  FormatToken *CurrentToken;
  bool KeywordVirtualFound;
  bool AutoFound;
  IdentifierInfo &Ident_in;
};

static int PrecedenceUnaryOperator = prec::PointerToMember + 1;
static int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;

/// \brief Parses binary expressions by inserting fake parenthesis based on
/// operator precedence.
class ExpressionParser {
public:
  ExpressionParser(AnnotatedLine &Line) : Current(Line.First) {
    // Skip leading "}", e.g. in "} else if (...) {".
    if (Current->is(tok::r_brace))
      next();
  }

  /// \brief Parse expressions with the given operatore precedence.
  void parse(int Precedence = 0) {
    // Skip 'return' and ObjC selector colons as they are not part of a binary
    // expression.
    while (Current &&
           (Current->is(tok::kw_return) ||
            (Current->is(tok::colon) && (Current->Type == TT_ObjCMethodExpr ||
                                         Current->Type == TT_DictLiteral))))
      next();

    if (!Current || Precedence > PrecedenceArrowAndPeriod)
      return;

    // Conditional expressions need to be parsed separately for proper nesting.
    if (Precedence == prec::Conditional) {
      parseConditionalExpr();
      return;
    }

    // Parse unary operators, which all have a higher precedence than binary
    // operators.
    if (Precedence == PrecedenceUnaryOperator) {
      parseUnaryOperator();
      return;
    }

    FormatToken *Start = Current;
    FormatToken *LatestOperator = nullptr;
    unsigned OperatorIndex = 0;

    while (Current) {
      // Consume operators with higher precedence.
      parse(Precedence + 1);

      int CurrentPrecedence = getCurrentPrecedence();

      if (Current && Current->Type == TT_SelectorName &&
          Precedence == CurrentPrecedence) {
        if (LatestOperator)
          addFakeParenthesis(Start, prec::Level(Precedence));
        Start = Current;
      }

      // At the end of the line or when an operator with higher precedence is
      // found, insert fake parenthesis and return.
      if (!Current || Current->closesScope() ||
          (CurrentPrecedence != -1 && CurrentPrecedence < Precedence)) {
        if (LatestOperator) {
          LatestOperator->LastOperator = true;
          if (Precedence == PrecedenceArrowAndPeriod) {
            // Call expressions don't have a binary operator precedence.
            addFakeParenthesis(Start, prec::Unknown);
          } else {
            addFakeParenthesis(Start, prec::Level(Precedence));
          }
        }
        return;
      }

      // Consume scopes: (), [], <> and {}
      if (Current->opensScope()) {
        while (Current && !Current->closesScope()) {
          next();
          parse();
        }
        next();
      } else {
        // Operator found.
        if (CurrentPrecedence == Precedence) {
          LatestOperator = Current;
          Current->OperatorIndex = OperatorIndex;
          ++OperatorIndex;
        }

        next();
      }
    }
  }

private:
  /// \brief Gets the precedence (+1) of the given token for binary operators
  /// and other tokens that we treat like binary operators.
  int getCurrentPrecedence() {
    if (Current) {
      if (Current->Type == TT_ConditionalExpr)
        return prec::Conditional;
      else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon ||
               Current->Type == TT_SelectorName)
        return 0;
      else if (Current->Type == TT_RangeBasedForLoopColon)
        return prec::Comma;
      else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
        return Current->getPrecedence();
      else if (Current->isOneOf(tok::period, tok::arrow))
        return PrecedenceArrowAndPeriod;
    }
    return -1;
  }

  void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
    Start->FakeLParens.push_back(Precedence);
    if (Precedence > prec::Unknown)
      Start->StartsBinaryExpression = true;
    if (Current) {
      ++Current->Previous->FakeRParens;
      if (Precedence > prec::Unknown)
        Current->Previous->EndsBinaryExpression = true;
    }
  }

  /// \brief Parse unary operator expressions and surround them with fake
  /// parentheses if appropriate.
  void parseUnaryOperator() {
    if (!Current || Current->Type != TT_UnaryOperator) {
      parse(PrecedenceArrowAndPeriod);
      return;
    }

    FormatToken *Start = Current;
    next();
    parseUnaryOperator();

    // The actual precedence doesn't matter.
    addFakeParenthesis(Start, prec::Unknown);
  }

  void parseConditionalExpr() {
    FormatToken *Start = Current;
    parse(prec::LogicalOr);
    if (!Current || !Current->is(tok::question))
      return;
    next();
    parseConditionalExpr();
    if (!Current || Current->Type != TT_ConditionalExpr)
      return;
    next();
    parseConditionalExpr();
    addFakeParenthesis(Start, prec::Conditional);
  }

  void next() {
    if (Current)
      Current = Current->Next;
    while (Current && Current->isTrailingComment())
      Current = Current->Next;
  }

  FormatToken *Current;
};

} // end anonymous namespace

void
TokenAnnotator::setCommentLineLevels(SmallVectorImpl<AnnotatedLine *> &Lines) {
  const AnnotatedLine *NextNonCommentLine = nullptr;
  for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
                                                          E = Lines.rend();
       I != E; ++I) {
    if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
        (*I)->First->Next == nullptr)
      (*I)->Level = NextNonCommentLine->Level;
    else
      NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;

    setCommentLineLevels((*I)->Children);
  }
}

void TokenAnnotator::annotate(AnnotatedLine &Line) {
  for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
                                                  E = Line.Children.end();
       I != E; ++I) {
    annotate(**I);
  }
  AnnotatingParser Parser(Style, Line, Ident_in);
  Line.Type = Parser.parseLine();
  if (Line.Type == LT_Invalid)
    return;

  ExpressionParser ExprParser(Line);
  ExprParser.parse();

  if (Line.First->Type == TT_ObjCMethodSpecifier)
    Line.Type = LT_ObjCMethodDecl;
  else if (Line.First->Type == TT_ObjCDecl)
    Line.Type = LT_ObjCDecl;
  else if (Line.First->Type == TT_ObjCProperty)
    Line.Type = LT_ObjCProperty;

  Line.First->SpacesRequiredBefore = 1;
  Line.First->CanBreakBefore = Line.First->MustBreakBefore;
}

// This function heuristically determines whether 'Current' starts the name of a
// function declaration.
static bool isFunctionDeclarationName(const FormatToken &Current) {
  if (Current.Type != TT_StartOfName ||
      Current.NestingLevel != 0 ||
      Current.Previous->Type == TT_StartOfName)
    return false;
  const FormatToken *Next = Current.Next;
  for (; Next; Next = Next->Next) {
    if (Next->Type == TT_TemplateOpener) {
      Next = Next->MatchingParen;
    } else if (Next->is(tok::coloncolon)) {
      Next = Next->Next;
      if (!Next || !Next->is(tok::identifier))
        return false;
    } else if (Next->is(tok::l_paren)) {
      break;
    } else {
      return false;
    }
  }
  if (!Next)
    return false;
  assert(Next->is(tok::l_paren));
  if (Next->Next == Next->MatchingParen)
    return true;
  for (const FormatToken *Tok = Next->Next; Tok != Next->MatchingParen;
       Tok = Tok->Next) {
    if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
        Tok->Type == TT_PointerOrReference || Tok->Type == TT_StartOfName)
      return true;
    if (Tok->isOneOf(tok::l_brace, tok::string_literal) || Tok->Tok.isLiteral())
      return false;
  }
  return false;
}

void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
  for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
                                                  E = Line.Children.end();
       I != E; ++I) {
    calculateFormattingInformation(**I);
  }

  Line.First->TotalLength =
      Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
  if (!Line.First->Next)
    return;
  FormatToken *Current = Line.First->Next;
  bool InFunctionDecl = Line.MightBeFunctionDecl;
  while (Current) {
    if (isFunctionDeclarationName(*Current))
      Current->Type = TT_FunctionDeclarationName;
    if (Current->Type == TT_LineComment) {
      if (Current->Previous->BlockKind == BK_BracedInit &&
          Current->Previous->opensScope())
        Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
      else
        Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;

      // If we find a trailing comment, iterate backwards to determine whether
      // it seems to relate to a specific parameter. If so, break before that
      // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
      // to the previous line in:
      //   SomeFunction(a,
      //                b, // comment
      //                c);
      if (!Current->HasUnescapedNewline) {
        for (FormatToken *Parameter = Current->Previous; Parameter;
             Parameter = Parameter->Previous) {
          if (Parameter->isOneOf(tok::comment, tok::r_brace))
            break;
          if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
            if (Parameter->Previous->Type != TT_CtorInitializerComma &&
                Parameter->HasUnescapedNewline)
              Parameter->MustBreakBefore = true;
            break;
          }
        }
      }
    } else if (Current->SpacesRequiredBefore == 0 &&
               spaceRequiredBefore(Line, *Current)) {
      Current->SpacesRequiredBefore = 1;
    }

    Current->MustBreakBefore =
        Current->MustBreakBefore || mustBreakBefore(Line, *Current);

    if (Style.AlwaysBreakAfterDefinitionReturnType &&
        InFunctionDecl && Current->Type == TT_FunctionDeclarationName &&
        Line.Last->is(tok::l_brace))  // Only for definitions.
      Current->MustBreakBefore = true;

    Current->CanBreakBefore =
        Current->MustBreakBefore || canBreakBefore(Line, *Current);
    unsigned ChildSize = 0;
    if (Current->Previous->Children.size() == 1) {
      FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
      ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
                                                  : LastOfChild.TotalLength + 1;
    }
    if (Current->MustBreakBefore || Current->Previous->Children.size() > 1 ||
        Current->IsMultiline)
      Current->TotalLength = Current->Previous->TotalLength + Style.ColumnLimit;
    else
      Current->TotalLength = Current->Previous->TotalLength +
                             Current->ColumnWidth + ChildSize +
                             Current->SpacesRequiredBefore;

    if (Current->Type == TT_CtorInitializerColon)
      InFunctionDecl = false;

    // FIXME: Only calculate this if CanBreakBefore is true once static
    // initializers etc. are sorted out.
    // FIXME: Move magic numbers to a better place.
    Current->SplitPenalty = 20 * Current->BindingStrength +
                            splitPenalty(Line, *Current, InFunctionDecl);

    Current = Current->Next;
  }

  calculateUnbreakableTailLengths(Line);
  for (Current = Line.First; Current != nullptr; Current = Current->Next) {
    if (Current->Role)
      Current->Role->precomputeFormattingInfos(Current);
  }

  DEBUG({ printDebugInfo(Line); });
}

void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
  unsigned UnbreakableTailLength = 0;
  FormatToken *Current = Line.Last;
  while (Current) {
    Current->UnbreakableTailLength = UnbreakableTailLength;
    if (Current->CanBreakBefore ||
        Current->isOneOf(tok::comment, tok::string_literal)) {
      UnbreakableTailLength = 0;
    } else {
      UnbreakableTailLength +=
          Current->ColumnWidth + Current->SpacesRequiredBefore;
    }
    Current = Current->Previous;
  }
}

unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
                                      const FormatToken &Tok,
                                      bool InFunctionDecl) {
  const FormatToken &Left = *Tok.Previous;
  const FormatToken &Right = Tok;

  if (Left.is(tok::semi))
    return 0;
  if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
                              Right.Next->Type == TT_DictLiteral))
    return 1;
  if (Right.is(tok::l_square)) {
    if (Style.Language == FormatStyle::LK_Proto)
      return 1;
    if (Right.Type != TT_ObjCMethodExpr && Right.Type != TT_LambdaLSquare)
      return 500;
  }
  if (Right.Type == TT_StartOfName ||
      Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator)) {
    if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
      return 3;
    if (Left.Type == TT_StartOfName)
      return 20;
    if (InFunctionDecl && Right.NestingLevel == 0)
      return Style.PenaltyReturnTypeOnItsOwnLine;
    return 200;
  }
  if (Left.is(tok::equal) && Right.is(tok::l_brace))
    return 150;
  if (Left.Type == TT_CastRParen)
    return 100;
  if (Left.is(tok::coloncolon) ||
      (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
    return 500;
  if (Left.isOneOf(tok::kw_class, tok::kw_struct))
    return 5000;

  if (Left.Type == TT_RangeBasedForLoopColon ||
      Left.Type == TT_InheritanceColon)
    return 2;

  if (Right.isMemberAccess()) {
    if (Left.is(tok::r_paren) && Left.MatchingParen &&
        Left.MatchingParen->ParameterCount > 0)
      return 20; // Should be smaller than breaking at a nested comma.
    return 150;
  }

  if (Right.Type == TT_TrailingAnnotation &&
      (!Right.Next || Right.Next->isNot(tok::l_paren))) {
    // Generally, breaking before a trailing annotation is bad unless it is
    // function-like. It seems to be especially preferable to keep standard
    // annotations (i.e. "const", "final" and "override") on the same line.
    // Use a slightly higher penalty after ")" so that annotations like
    // "const override" are kept together.
    bool is_short_annotation = Right.TokenText.size() < 10;
    return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
  }

  // In for-loops, prefer breaking at ',' and ';'.
  if (Line.First->is(tok::kw_for) && Left.is(tok::equal))
    return 4;

  // In Objective-C method expressions, prefer breaking before "param:" over
  // breaking after it.
  if (Right.Type == TT_SelectorName)
    return 0;
  if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
    return Line.MightBeFunctionDecl ? 50 : 500;

  if (Left.is(tok::l_paren) && InFunctionDecl)
    return 100;
  if (Left.is(tok::equal) && InFunctionDecl)
    return 110;
  if (Right.is(tok::r_brace))
    return 1;
  if (Left.opensScope())
    return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
                                   : 19;

  if (Right.is(tok::lessless)) {
    if (Left.is(tok::string_literal)) {
      StringRef Content = Left.TokenText;
      if (Content.startswith("\""))
        Content = Content.drop_front(1);
      if (Content.endswith("\""))
        Content = Content.drop_back(1);
      Content = Content.trim();
      if (Content.size() > 1 &&
          (Content.back() == ':' || Content.back() == '='))
        return 25;
    }
    return 1; // Breaking at a << is really cheap.
  }
  if (Left.Type == TT_ConditionalExpr)
    return prec::Conditional;
  prec::Level Level = Left.getPrecedence();

  if (Level != prec::Unknown)
    return Level;

  return 3;
}

bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
                                          const FormatToken &Left,
                                          const FormatToken &Right) {
  if (Style.Language == FormatStyle::LK_Proto) {
    if (Right.is(tok::period) &&
        (Left.TokenText == "optional" || Left.TokenText == "required" ||
         Left.TokenText == "repeated"))
      return true;
    if (Right.is(tok::l_paren) &&
        (Left.TokenText == "returns" || Left.TokenText == "option"))
      return true;
  } else if (Style.Language == FormatStyle::LK_JavaScript) {
    if (Left.TokenText == "var")
      return true;
  }
  if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
    return true;
  if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
      Left.Tok.getObjCKeywordID() == tok::objc_property)
    return true;
  if (Right.is(tok::hashhash))
    return Left.is(tok::hash);
  if (Left.isOneOf(tok::hashhash, tok::hash))
    return Right.is(tok::hash);
  if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
    return Style.SpaceInEmptyParentheses;
  if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
    return (Right.Type == TT_CastRParen ||
            (Left.MatchingParen && Left.MatchingParen->Type == TT_CastRParen))
               ? Style.SpacesInCStyleCastParentheses
               : Style.SpacesInParentheses;
  if (Style.SpacesInAngles &&
      ((Left.Type == TT_TemplateOpener) != (Right.Type == TT_TemplateCloser)))
    return true;
  if (Right.isOneOf(tok::semi, tok::comma))
    return false;
  if (Right.is(tok::less) &&
      (Left.isOneOf(tok::kw_template, tok::r_paren) ||
       (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
    return true;
  if (Left.is(tok::arrow) || Right.is(tok::arrow))
    return false;
  if (Left.isOneOf(tok::exclaim, tok::tilde))
    return false;
  if (Left.is(tok::at) &&
      Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
                    tok::numeric_constant, tok::l_paren, tok::l_brace,
                    tok::kw_true, tok::kw_false))
    return false;
  if (Left.is(tok::coloncolon))
    return false;
  if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
    return (Left.is(tok::less) && Style.Standard == FormatStyle::LS_Cpp03) ||
           !Left.isOneOf(tok::identifier, tok::greater, tok::l_paren,
                         tok::r_paren, tok::less);
  if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
    return false;
  if (Right.is(tok::ellipsis))
    return Left.Tok.isLiteral();
  if (Left.is(tok::l_square) && Right.is(tok::amp))
    return false;
  if (Right.Type == TT_PointerOrReference)
    return Left.Tok.isLiteral() ||
           ((Left.Type != TT_PointerOrReference) && Left.isNot(tok::l_paren) &&
            Style.PointerAlignment != FormatStyle::PAS_Left);
  if (Right.Type == TT_FunctionTypeLParen && Left.isNot(tok::l_paren) &&
      (Left.Type != TT_PointerOrReference ||
       Style.PointerAlignment != FormatStyle::PAS_Right))
    return true;
  if (Left.Type == TT_PointerOrReference)
    return Right.Tok.isLiteral() || Right.Type == TT_BlockComment ||
           ((Right.Type != TT_PointerOrReference) &&
            Right.isNot(tok::l_paren) &&
            Style.PointerAlignment != FormatStyle::PAS_Right && Left.Previous &&
            !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
  if (Right.is(tok::star) && Left.is(tok::l_paren))
    return false;
  if (Left.is(tok::l_square))
    return Left.Type == TT_ArrayInitializerLSquare &&
           Style.SpacesInContainerLiterals && Right.isNot(tok::r_square);
  if (Right.is(tok::r_square))
    return Right.MatchingParen && Style.SpacesInContainerLiterals &&
           Right.MatchingParen->Type == TT_ArrayInitializerLSquare;
  if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr &&
      Right.Type != TT_LambdaLSquare && Left.isNot(tok::numeric_constant) &&
      Left.Type != TT_DictLiteral)
    return false;
  if (Left.is(tok::colon))
    return Left.Type != TT_ObjCMethodExpr;
  if (Left.Type == TT_BlockComment)
    return !Left.TokenText.endswith("=*/");
  if (Right.is(tok::l_paren)) {
    if (Left.is(tok::r_paren) && Left.Type == TT_AttributeParen)
      return true;
    return Line.Type == LT_ObjCDecl ||
           Left.isOneOf(tok::kw_new, tok::kw_delete, tok::semi) ||
           (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
            (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
                          tok::kw_switch, tok::kw_catch, tok::kw_case) ||
             Left.IsForEachMacro)) ||
           (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
            (Left.is(tok::identifier) || Left.isFunctionLikeKeyword()) &&
            Line.Type != LT_PreprocessorDirective);
  }
  if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
    return false;
  if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
    return !Left.Children.empty(); // No spaces in "{}".
  if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
      (Right.is(tok::r_brace) && Right.MatchingParen &&
       Right.MatchingParen->BlockKind != BK_Block))
    return !Style.Cpp11BracedListStyle;
  if (Right.Type == TT_UnaryOperator)
    return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
           (Left.isNot(tok::colon) || Left.Type != TT_ObjCMethodExpr);
  if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
                    tok::r_paren) ||
       Left.isSimpleTypeSpecifier()) &&
      Right.is(tok::l_brace) && Right.getNextNonComment() &&
      Right.BlockKind != BK_Block)
    return false;
  if (Left.is(tok::period) || Right.is(tok::period))
    return false;
  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
    return false;
  return true;
}

bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
                                         const FormatToken &Tok) {
  if (Tok.Tok.getIdentifierInfo() && Tok.Previous->Tok.getIdentifierInfo())
    return true; // Never ever merge two identifiers.
  if (Tok.Previous->Type == TT_ImplicitStringLiteral)
    return Tok.WhitespaceRange.getBegin() != Tok.WhitespaceRange.getEnd();
  if (Line.Type == LT_ObjCMethodDecl) {
    if (Tok.Previous->Type == TT_ObjCMethodSpecifier)
      return true;
    if (Tok.Previous->is(tok::r_paren) && Tok.is(tok::identifier))
      // Don't space between ')' and <id>
      return false;
  }
  if (Line.Type == LT_ObjCProperty &&
      (Tok.is(tok::equal) || Tok.Previous->is(tok::equal)))
    return false;

  if (Tok.Type == TT_TrailingReturnArrow ||
      Tok.Previous->Type == TT_TrailingReturnArrow)
    return true;
  if (Tok.Previous->is(tok::comma))
    return true;
  if (Tok.is(tok::comma))
    return false;
  if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
    return true;
  if (Tok.Previous->Tok.is(tok::kw_operator))
    return Tok.is(tok::coloncolon);
  if (Tok.Type == TT_OverloadedOperatorLParen)
    return false;
  if (Tok.is(tok::colon))
    return !Line.First->isOneOf(tok::kw_case, tok::kw_default) &&
           Tok.getNextNonComment() && Tok.Type != TT_ObjCMethodExpr &&
           !Tok.Previous->is(tok::question) &&
           (Tok.Type != TT_DictLiteral || Style.SpacesInContainerLiterals);
  if (Tok.Previous->Type == TT_UnaryOperator ||
      Tok.Previous->Type == TT_CastRParen)
    return Tok.Type == TT_BinaryOperator;
  if (Tok.Previous->is(tok::greater) && Tok.is(tok::greater)) {
    return Tok.Type == TT_TemplateCloser &&
           Tok.Previous->Type == TT_TemplateCloser &&
           (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
  }
  if (Tok.isOneOf(tok::arrowstar, tok::periodstar) ||
      Tok.Previous->isOneOf(tok::arrowstar, tok::periodstar))
    return false;
  if (!Style.SpaceBeforeAssignmentOperators &&
      Tok.getPrecedence() == prec::Assignment)
    return false;
  if ((Tok.Type == TT_BinaryOperator && !Tok.Previous->is(tok::l_paren)) ||
      Tok.Previous->Type == TT_BinaryOperator ||
      Tok.Previous->Type == TT_ConditionalExpr)
    return true;
  if (Tok.Previous->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
    return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
  if (Tok.is(tok::less) && Tok.Previous->isNot(tok::l_paren) &&
      Line.First->is(tok::hash))
    return true;
  if (Tok.Type == TT_TrailingUnaryOperator)
    return false;
  if (Tok.Previous->Type == TT_RegexLiteral)
    return false;
  return spaceRequiredBetween(Line, *Tok.Previous, Tok);
}

// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
static bool isAllmanBrace(const FormatToken &Tok) {
  return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
         Tok.Type != TT_ObjCBlockLBrace && Tok.Type != TT_DictLiteral;
}

bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
                                     const FormatToken &Right) {
  const FormatToken &Left = *Right.Previous;
  if (Right.NewlinesBefore > 1)
    return true;
  if (Right.is(tok::comment)) {
    return Right.Previous->BlockKind != BK_BracedInit &&
           Right.Previous->Type != TT_CtorInitializerColon &&
           (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
  } else if (Right.Previous->isTrailingComment() ||
             (Right.isStringLiteral() && Right.Previous->isStringLiteral())) {
    return true;
  } else if (Right.Previous->IsUnterminatedLiteral) {
    return true;
  } else if (Right.is(tok::lessless) && Right.Next &&
             Right.Previous->is(tok::string_literal) &&
             Right.Next->is(tok::string_literal)) {
    return true;
  } else if (Right.Previous->ClosesTemplateDeclaration &&
             Right.Previous->MatchingParen &&
             Right.Previous->MatchingParen->NestingLevel == 0 &&
             Style.AlwaysBreakTemplateDeclarations) {
    return true;
  } else if ((Right.Type == TT_CtorInitializerComma ||
              Right.Type == TT_CtorInitializerColon) &&
             Style.BreakConstructorInitializersBeforeComma &&
             !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
    return true;
  } else if (Right.is(tok::string_literal) &&
             Right.TokenText.startswith("R\"")) {
    // Raw string literals are special wrt. line breaks. The author has made a
    // deliberate choice and might have aligned the contents of the string
    // literal accordingly. Thus, we try keep existing line breaks.
    return Right.NewlinesBefore > 0;
  } else if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
             Style.Language == FormatStyle::LK_Proto) {
    // Don't enums onto single lines in protocol buffers.
    return true;
  } else if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
    return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
           Style.BreakBeforeBraces == FormatStyle::BS_GNU;
  } else if (Style.Language == FormatStyle::LK_Proto &&
             Left.isNot(tok::l_brace) && Right.Type == TT_SelectorName) {
    return true;
  }

  // If the last token before a '}' is a comma or a comment, the intention is to
  // insert a line break after it in order to make shuffling around entries
  // easier.
  const FormatToken *BeforeClosingBrace = nullptr;
  if (Left.is(tok::l_brace) && Left.MatchingParen)
    BeforeClosingBrace = Left.MatchingParen->Previous;
  else if (Right.is(tok::r_brace))
    BeforeClosingBrace = Right.Previous;
  if (BeforeClosingBrace &&
      BeforeClosingBrace->isOneOf(tok::comma, tok::comment))
    return true;

  if (Style.Language == FormatStyle::LK_JavaScript) {
    // FIXME: This might apply to other languages and token kinds.
    if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
        Left.Previous->is(tok::char_constant))
      return true;
  }

  return false;
}

bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
                                    const FormatToken &Right) {
  const FormatToken &Left = *Right.Previous;
  if (Left.is(tok::at))
    return false;
  if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
    return false;
  if (Right.Type == TT_StartOfName ||
      Right.Type == TT_FunctionDeclarationName || Right.is(tok::kw_operator))
    return true;
  if (Right.isTrailingComment())
    // We rely on MustBreakBefore being set correctly here as we should not
    // change the "binding" behavior of a comment.
    // The first comment in a braced lists is always interpreted as belonging to
    // the first list element. Otherwise, it should be placed outside of the
    // list.
    return Left.BlockKind == BK_BracedInit;
  if (Left.is(tok::question) && Right.is(tok::colon))
    return false;
  if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
    return Style.BreakBeforeTernaryOperators;
  if (Left.Type == TT_ConditionalExpr || Left.is(tok::question))
    return !Style.BreakBeforeTernaryOperators;
  if (Right.Type == TT_InheritanceColon)
    return true;
  if (Right.is(tok::colon) && (Right.Type != TT_CtorInitializerColon &&
                               Right.Type != TT_InlineASMColon))
    return false;
  if (Left.is(tok::colon) &&
      (Left.Type == TT_DictLiteral || Left.Type == TT_ObjCMethodExpr))
    return true;
  if (Right.Type == TT_SelectorName)
    return true;
  if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
    return true;
  if (Left.ClosesTemplateDeclaration)
    return true;
  if (Right.Type == TT_RangeBasedForLoopColon ||
      Right.Type == TT_OverloadedOperatorLParen ||
      Right.Type == TT_OverloadedOperator)
    return false;
  if (Left.Type == TT_RangeBasedForLoopColon)
    return true;
  if (Right.Type == TT_RangeBasedForLoopColon)
    return false;
  if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
      Left.Type == TT_UnaryOperator || Left.is(tok::kw_operator))
    return false;
  if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
    return false;
  if (Left.is(tok::l_paren) && Left.Type == TT_AttributeParen)
    return false;
  if (Left.is(tok::l_paren) && Left.Previous &&
      (Left.Previous->Type == TT_BinaryOperator ||
       Left.Previous->Type == TT_CastRParen || Left.Previous->is(tok::kw_if)))
    return false;
  if (Right.Type == TT_ImplicitStringLiteral)
    return false;

  if (Right.is(tok::r_paren) || Right.Type == TT_TemplateCloser)
    return false;

  // We only break before r_brace if there was a corresponding break before
  // the l_brace, which is tracked by BreakBeforeClosingBrace.
  if (Right.is(tok::r_brace))
    return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;

  // Allow breaking after a trailing annotation, e.g. after a method
  // declaration.
  if (Left.Type == TT_TrailingAnnotation)
    return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
                          tok::less, tok::coloncolon);

  if (Right.is(tok::kw___attribute))
    return true;

  if (Left.is(tok::identifier) && Right.is(tok::string_literal))
    return true;

  if (Right.is(tok::identifier) && Right.Next &&
      Right.Next->Type == TT_DictLiteral)
    return true;

  if (Left.Type == TT_CtorInitializerComma &&
      Style.BreakConstructorInitializersBeforeComma)
    return false;
  if (Right.Type == TT_CtorInitializerComma &&
      Style.BreakConstructorInitializersBeforeComma)
    return true;
  if (Left.is(tok::greater) && Right.is(tok::greater) &&
      Left.Type != TT_TemplateCloser)
    return false;
  if (Right.Type == TT_BinaryOperator && Style.BreakBeforeBinaryOperators)
    return true;
  if (Left.Type == TT_ArrayInitializerLSquare)
    return true;
  return (Left.isBinaryOperator() &&
          !Left.isOneOf(tok::arrowstar, tok::lessless) &&
          !Style.BreakBeforeBinaryOperators) ||
         Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
                      tok::kw_class, tok::kw_struct) ||
         Right.isMemberAccess() ||
         Right.isOneOf(tok::lessless, tok::colon, tok::l_square, tok::at,
                       tok::kw_typename) ||
         (Left.is(tok::r_paren) &&
          Right.isOneOf(tok::identifier, tok::kw_const)) ||
         (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
}

void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
  llvm::errs() << "AnnotatedTokens:\n";
  const FormatToken *Tok = Line.First;
  while (Tok) {
    llvm::errs() << " M=" << Tok->MustBreakBefore
                 << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
                 << " S=" << Tok->SpacesRequiredBefore
                 << " B=" << Tok->BlockParameterCount
                 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
                 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
                 << " FakeLParens=";
    for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
      llvm::errs() << Tok->FakeLParens[i] << "/";
    llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
    if (!Tok->Next)
      assert(Tok == Line.Last);
    Tok = Tok->Next;
  }
  llvm::errs() << "----\n";
}

} // namespace format
} // namespace clang
@


1.1.1.5.4.1
log
@file TokenAnnotator.cpp was added on branch yamt-pagecache on 2014-05-22 16:18:27 +0000
@
text
@d1 1610
@


1.1.1.5.4.2
log
@sync with head.

for a reference, the tree before this commit was tagged
as yamt-pagecache-tag8.

this commit was splitted into small chunks to avoid
a limitation of cvs.  ("Protocol error: too many arguments")
@
text
@a0 1610
//===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a token annotator, i.e. creates
/// \c AnnotatedTokens out of \c FormatTokens with required extra information.
///
//===----------------------------------------------------------------------===//

#include "TokenAnnotator.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/Debug.h"

namespace clang {
namespace format {

namespace {

/// \brief A parser that gathers additional information about tokens.
///
/// The \c TokenAnnotator tries to match parenthesis and square brakets and
/// store a parenthesis levels. It also tries to resolve matching "<" and ">"
/// into template parameter lists.
class AnnotatingParser {
public:
  AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
                   IdentifierInfo &Ident_in)
      : Style(Style), Line(Line), CurrentToken(Line.First),
        KeywordVirtualFound(false), AutoFound(false), Ident_in(Ident_in) {
    Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
  }

private:
  bool parseAngle() {
    if (CurrentToken == NULL)
      return false;
    ScopedContextCreator ContextCreator(*this, tok::less, 10);
    FormatToken *Left = CurrentToken->Previous;
    Contexts.back().IsExpression = false;
    while (CurrentToken != NULL) {
      if (CurrentToken->is(tok::greater)) {
        Left->MatchingParen = CurrentToken;
        CurrentToken->MatchingParen = Left;
        CurrentToken->Type = TT_TemplateCloser;
        next();
        return true;
      }
      if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace,
                                tok::question, tok::colon))
        return false;
      // If a && or || is found and interpreted as a binary operator, this set
      // of angles is likely part of something like "a < b && c > d". If the
      // angles are inside an expression, the ||/&& might also be a binary
      // operator that was misinterpreted because we are parsing template
      // parameters.
      // FIXME: This is getting out of hand, write a decent parser.
      if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
          (CurrentToken->Previous->Type == TT_BinaryOperator ||
           Contexts[Contexts.size() - 2].IsExpression) &&
          Line.First->isNot(tok::kw_template))
        return false;
      updateParameterCount(Left, CurrentToken);
      if (!consumeToken())
        return false;
    }
    return false;
  }

  bool parseParens(bool LookForDecls = false) {
    if (CurrentToken == NULL)
      return false;
    bool AfterCaret = Contexts.back().CaretFound;
    Contexts.back().CaretFound = false;

    ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);

    // FIXME: This is a bit of a hack. Do better.
    Contexts.back().ColonIsForRangeExpr =
        Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;

    bool StartsObjCMethodExpr = false;
    FormatToken *Left = CurrentToken->Previous;
    if (CurrentToken->is(tok::caret)) {
      // (^ can start a block type.
      Left->Type = TT_ObjCBlockLParen;
    } else if (FormatToken *MaybeSel = Left->Previous) {
      // @@selector( starts a selector.
      if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
          MaybeSel->Previous->is(tok::at)) {
        StartsObjCMethodExpr = true;
      }
    }

    if (Left->Previous && Left->Previous->isOneOf(tok::kw_static_assert,
                                                  tok::kw_if, tok::kw_while)) {
      // static_assert, if and while usually contain expressions.
      Contexts.back().IsExpression = true;
    } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
               Left->Previous->MatchingParen &&
               Left->Previous->MatchingParen->Type == TT_LambdaLSquare) {
      // This is a parameter list of a lambda expression.
      Contexts.back().IsExpression = false;
    } else if (AfterCaret) {
      // This is the parameter list of an ObjC block.
      Contexts.back().IsExpression = false;
    } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
      Left->Type = TT_AttributeParen;
    }

    if (StartsObjCMethodExpr) {
      Contexts.back().ColonIsObjCMethodExpr = true;
      Left->Type = TT_ObjCMethodExpr;
    }

    bool MightBeFunctionType = CurrentToken->is(tok::star);
    bool HasMultipleLines = false;
    bool HasMultipleParametersOnALine = false;
    while (CurrentToken != NULL) {
      // LookForDecls is set when "if (" has been seen. Check for
      // 'identifier' '*' 'identifier' followed by not '=' -- this
      // '*' has to be a binary operator but determineStarAmpUsage() will
      // categorize it as an unary operator, so set the right type here.
      if (LookForDecls && CurrentToken->Next) {
        FormatToken *Prev = CurrentToken->getPreviousNonComment();
        if (Prev) {
          FormatToken *PrevPrev = Prev->getPreviousNonComment();
          FormatToken *Next = CurrentToken->Next;
          if (PrevPrev && PrevPrev->is(tok::identifier) &&
              Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
              CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
            Prev->Type = TT_BinaryOperator;
            LookForDecls = false;
          }
        }
      }

      if (CurrentToken->Previous->Type == TT_PointerOrReference &&
          CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
                                                    tok::coloncolon))
        MightBeFunctionType = true;
      if (CurrentToken->is(tok::r_paren)) {
        if (MightBeFunctionType && CurrentToken->Next &&
            (CurrentToken->Next->is(tok::l_paren) ||
             (CurrentToken->Next->is(tok::l_square) &&
              !Contexts.back().IsExpression)))
          Left->Type = TT_FunctionTypeLParen;
        Left->MatchingParen = CurrentToken;
        CurrentToken->MatchingParen = Left;

        if (StartsObjCMethodExpr) {
          CurrentToken->Type = TT_ObjCMethodExpr;
          if (Contexts.back().FirstObjCSelectorName != NULL) {
            Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
                Contexts.back().LongestObjCSelectorName;
          }
        }

        if (Left->Type == TT_AttributeParen)
          CurrentToken->Type = TT_AttributeParen;

        if (!HasMultipleLines)
          Left->PackingKind = PPK_Inconclusive;
        else if (HasMultipleParametersOnALine)
          Left->PackingKind = PPK_BinPacked;
        else
          Left->PackingKind = PPK_OnePerLine;

        next();
        return true;
      }
      if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
        return false;
      else if (CurrentToken->is(tok::l_brace))
        Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
      updateParameterCount(Left, CurrentToken);
      if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
          !CurrentToken->Next->HasUnescapedNewline &&
          !CurrentToken->Next->isTrailingComment())
        HasMultipleParametersOnALine = true;
      if (!consumeToken())
        return false;
      if (CurrentToken && CurrentToken->HasUnescapedNewline)
        HasMultipleLines = true;
    }
    return false;
  }

  bool parseSquare() {
    if (!CurrentToken)
      return false;

    // A '[' could be an index subscript (after an identifier or after
    // ')' or ']'), it could be the start of an Objective-C method
    // expression, or it could the the start of an Objective-C array literal.
    FormatToken *Left = CurrentToken->Previous;
    FormatToken *Parent = Left->getPreviousNonComment();
    bool StartsObjCMethodExpr =
        Contexts.back().CanBeExpression && Left->Type != TT_LambdaLSquare &&
        (!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
                                    tok::kw_return, tok::kw_throw) ||
         Parent->isUnaryOperator() || Parent->Type == TT_ObjCForIn ||
         Parent->Type == TT_CastRParen ||
         getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
    ScopedContextCreator ContextCreator(*this, tok::l_square, 10);
    Contexts.back().IsExpression = true;
    bool ColonFound = false;

    if (StartsObjCMethodExpr) {
      Contexts.back().ColonIsObjCMethodExpr = true;
      Left->Type = TT_ObjCMethodExpr;
    } else if (Parent && Parent->is(tok::at)) {
      Left->Type = TT_ArrayInitializerLSquare;
    } else if (Left->Type == TT_Unknown) {
      Left->Type = TT_ArraySubscriptLSquare;
    }

    while (CurrentToken != NULL) {
      if (CurrentToken->is(tok::r_square)) {
        if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
            Left->Type == TT_ObjCMethodExpr) {
          // An ObjC method call is rarely followed by an open parenthesis.
          // FIXME: Do we incorrectly label ":" with this?
          StartsObjCMethodExpr = false;
          Left->Type = TT_Unknown;
        }
        if (StartsObjCMethodExpr) {
          CurrentToken->Type = TT_ObjCMethodExpr;
          // determineStarAmpUsage() thinks that '*' '[' is allocating an
          // array of pointers, but if '[' starts a selector then '*' is a
          // binary operator.
          if (Parent != NULL && Parent->Type == TT_PointerOrReference)
            Parent->Type = TT_BinaryOperator;
        }
        Left->MatchingParen = CurrentToken;
        CurrentToken->MatchingParen = Left;
        if (Contexts.back().FirstObjCSelectorName != NULL) {
          Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
              Contexts.back().LongestObjCSelectorName;
          if (Contexts.back().NumBlockParameters > 1)
            Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
        }
        next();
        return true;
      }
      if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
        return false;
      if (CurrentToken->is(tok::colon))
        ColonFound = true;
      if (CurrentToken->is(tok::comma) &&
          Style.Language != FormatStyle::LK_Proto &&
          (Left->Type == TT_ArraySubscriptLSquare ||
           (Left->Type == TT_ObjCMethodExpr && !ColonFound)))
        Left->Type = TT_ArrayInitializerLSquare;
      updateParameterCount(Left, CurrentToken);
      if (!consumeToken())
        return false;
    }
    return false;
  }

  bool parseBrace() {
    if (CurrentToken != NULL) {
      FormatToken *Left = CurrentToken->Previous;
      ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
      Contexts.back().ColonIsDictLiteral = true;

      while (CurrentToken != NULL) {
        if (CurrentToken->is(tok::r_brace)) {
          Left->MatchingParen = CurrentToken;
          CurrentToken->MatchingParen = Left;
          next();
          return true;
        }
        if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
          return false;
        updateParameterCount(Left, CurrentToken);
        if (CurrentToken->is(tok::colon) &&
            Style.Language != FormatStyle::LK_Proto)
          Left->Type = TT_DictLiteral;
        if (!consumeToken())
          return false;
      }
    }
    // No closing "}" found, this probably starts a definition.
    Line.StartsDefinition = true;
    return true;
  }

  void updateParameterCount(FormatToken *Left, FormatToken *Current) {
    if (Current->is(tok::comma)) {
      ++Left->ParameterCount;
      if (!Left->Role)
        Left->Role.reset(new CommaSeparatedList(Style));
      Left->Role->CommaFound(Current);
    } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
      Left->ParameterCount = 1;
    }
  }

  bool parseConditional() {
    while (CurrentToken != NULL) {
      if (CurrentToken->is(tok::colon)) {
        CurrentToken->Type = TT_ConditionalExpr;
        next();
        return true;
      }
      if (!consumeToken())
        return false;
    }
    return false;
  }

  bool parseTemplateDeclaration() {
    if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
      CurrentToken->Type = TT_TemplateOpener;
      next();
      if (!parseAngle())
        return false;
      if (CurrentToken != NULL)
        CurrentToken->Previous->ClosesTemplateDeclaration = true;
      return true;
    }
    return false;
  }

  bool consumeToken() {
    FormatToken *Tok = CurrentToken;
    next();
    switch (Tok->Tok.getKind()) {
    case tok::plus:
    case tok::minus:
      if (Tok->Previous == NULL && Line.MustBeDeclaration)
        Tok->Type = TT_ObjCMethodSpecifier;
      break;
    case tok::colon:
      if (Tok->Previous == NULL)
        return false;
      // Colons from ?: are handled in parseConditional().
      if (Tok->Previous->is(tok::r_paren) && Contexts.size() == 1) {
        Tok->Type = TT_CtorInitializerColon;
      } else if (Contexts.back().ColonIsDictLiteral) {
        Tok->Type = TT_DictLiteral;
      } else if (Contexts.back().ColonIsObjCMethodExpr ||
                 Line.First->Type == TT_ObjCMethodSpecifier) {
        Tok->Type = TT_ObjCMethodExpr;
        Tok->Previous->Type = TT_ObjCSelectorName;
        if (Tok->Previous->ColumnWidth >
            Contexts.back().LongestObjCSelectorName) {
          Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
        }
        if (Contexts.back().FirstObjCSelectorName == NULL)
          Contexts.back().FirstObjCSelectorName = Tok->Previous;
      } else if (Contexts.back().ColonIsForRangeExpr) {
        Tok->Type = TT_RangeBasedForLoopColon;
      } else if (CurrentToken != NULL &&
                 CurrentToken->is(tok::numeric_constant)) {
        Tok->Type = TT_BitFieldColon;
      } else if (Contexts.size() == 1 && Line.First->isNot(tok::kw_enum)) {
        Tok->Type = TT_InheritanceColon;
      } else if (Contexts.back().ContextKind == tok::l_paren) {
        Tok->Type = TT_InlineASMColon;
      }
      break;
    case tok::kw_if:
    case tok::kw_while:
      if (CurrentToken != NULL && CurrentToken->is(tok::l_paren)) {
        next();
        if (!parseParens(/*LookForDecls=*/true))
          return false;
      }
      break;
    case tok::kw_for:
      Contexts.back().ColonIsForRangeExpr = true;
      next();
      if (!parseParens())
        return false;
      break;
    case tok::l_paren:
      if (!parseParens())
        return false;
      if (Line.MustBeDeclaration && Contexts.size() == 1 &&
          !Contexts.back().IsExpression && Line.First->Type != TT_ObjCProperty)
        Line.MightBeFunctionDecl = true;
      break;
    case tok::l_square:
      if (!parseSquare())
        return false;
      break;
    case tok::l_brace:
      if (!parseBrace())
        return false;
      break;
    case tok::less:
      if (Tok->Previous && !Tok->Previous->Tok.isLiteral() && parseAngle())
        Tok->Type = TT_TemplateOpener;
      else {
        Tok->Type = TT_BinaryOperator;
        CurrentToken = Tok;
        next();
      }
      break;
    case tok::r_paren:
    case tok::r_square:
      return false;
    case tok::r_brace:
      // Lines can start with '}'.
      if (Tok->Previous != NULL)
        return false;
      break;
    case tok::greater:
      Tok->Type = TT_BinaryOperator;
      break;
    case tok::kw_operator:
      while (CurrentToken &&
             !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
        if (CurrentToken->isOneOf(tok::star, tok::amp))
          CurrentToken->Type = TT_PointerOrReference;
        consumeToken();
        if (CurrentToken && CurrentToken->Previous->Type == TT_BinaryOperator)
          CurrentToken->Previous->Type = TT_OverloadedOperator;
      }
      if (CurrentToken) {
        CurrentToken->Type = TT_OverloadedOperatorLParen;
        if (CurrentToken->Previous->Type == TT_BinaryOperator)
          CurrentToken->Previous->Type = TT_OverloadedOperator;
      }
      break;
    case tok::question:
      parseConditional();
      break;
    case tok::kw_template:
      parseTemplateDeclaration();
      break;
    case tok::identifier:
      if (Line.First->is(tok::kw_for) &&
          Tok->Tok.getIdentifierInfo() == &Ident_in)
        Tok->Type = TT_ObjCForIn;
      break;
    case tok::comma:
      if (Contexts.back().FirstStartOfName)
        Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
      if (Contexts.back().InCtorInitializer)
        Tok->Type = TT_CtorInitializerComma;
      break;
    default:
      break;
    }
    return true;
  }

  void parseIncludeDirective() {
    next();
    if (CurrentToken != NULL && CurrentToken->is(tok::less)) {
      next();
      while (CurrentToken != NULL) {
        if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
          CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
    } else {
      while (CurrentToken != NULL) {
        if (CurrentToken->is(tok::string_literal))
          // Mark these string literals as "implicit" literals, too, so that
          // they are not split or line-wrapped.
          CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
    }
  }

  void parseWarningOrError() {
    next();
    // We still want to format the whitespace left of the first token of the
    // warning or error.
    next();
    while (CurrentToken != NULL) {
      CurrentToken->Type = TT_ImplicitStringLiteral;
      next();
    }
  }

  void parsePragma() {
    next(); // Consume "pragma".
    if (CurrentToken && CurrentToken->TokenText == "mark") {
      next(); // Consume "mark".
      next(); // Consume first token (so we fix leading whitespace).
      while (CurrentToken != NULL) {
        CurrentToken->Type = TT_ImplicitStringLiteral;
        next();
      }
    }
  }

  void parsePreprocessorDirective() {
    next();
    if (CurrentToken == NULL)
      return;
    if (CurrentToken->Tok.is(tok::numeric_constant)) {
      CurrentToken->SpacesRequiredBefore = 1;
      return;
    }
    // Hashes in the middle of a line can lead to any strange token
    // sequence.
    if (CurrentToken->Tok.getIdentifierInfo() == NULL)
      return;
    switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
    case tok::pp_include:
    case tok::pp_import:
      parseIncludeDirective();
      break;
    case tok::pp_error:
    case tok::pp_warning:
      parseWarningOrError();
      break;
    case tok::pp_pragma:
      parsePragma();
      break;
    case tok::pp_if:
    case tok::pp_elif:
      Contexts.back().IsExpression = true;
      parseLine();
      break;
    default:
      break;
    }
    while (CurrentToken != NULL)
      next();
  }

public:
  LineType parseLine() {
    if (CurrentToken->is(tok::hash)) {
      parsePreprocessorDirective();
      return LT_PreprocessorDirective;
    }

    // Directly allow to 'import <string-literal>' to support protocol buffer
    // definitions (code.google.com/p/protobuf) or missing "#" (either way we
    // should not break the line).
    IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
    if (Info && Info->getPPKeywordID() == tok::pp_import &&
        CurrentToken->Next && CurrentToken->Next->is(tok::string_literal))
      parseIncludeDirective();

    while (CurrentToken != NULL) {
      if (CurrentToken->is(tok::kw_virtual))
        KeywordVirtualFound = true;
      if (!consumeToken())
        return LT_Invalid;
    }
    if (KeywordVirtualFound)
      return LT_VirtualFunctionDecl;

    if (Line.First->Type == TT_ObjCMethodSpecifier) {
      if (Contexts.back().FirstObjCSelectorName != NULL)
        Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
            Contexts.back().LongestObjCSelectorName;
      return LT_ObjCMethodDecl;
    }

    return LT_Other;
  }

private:
  void next() {
    if (CurrentToken != NULL) {
      determineTokenType(*CurrentToken);
      CurrentToken->BindingStrength = Contexts.back().BindingStrength;
      CurrentToken->NestingLevel = Contexts.size() - 1;
    }

    if (CurrentToken != NULL)
      CurrentToken = CurrentToken->Next;

    if (CurrentToken != NULL) {
      // Reset token type in case we have already looked at it and then
      // recovered from an error (e.g. failure to find the matching >).
      if (CurrentToken->Type != TT_LambdaLSquare &&
          CurrentToken->Type != TT_FunctionLBrace &&
          CurrentToken->Type != TT_ImplicitStringLiteral)
        CurrentToken->Type = TT_Unknown;
      if (CurrentToken->Role)
        CurrentToken->Role.reset(NULL);
      CurrentToken->FakeLParens.clear();
      CurrentToken->FakeRParens = 0;
    }
  }

  /// \brief A struct to hold information valid in a specific context, e.g.
  /// a pair of parenthesis.
  struct Context {
    Context(tok::TokenKind ContextKind, unsigned BindingStrength,
            bool IsExpression)
        : ContextKind(ContextKind), BindingStrength(BindingStrength),
          LongestObjCSelectorName(0), NumBlockParameters(0),
          ColonIsForRangeExpr(false), ColonIsDictLiteral(false),
          ColonIsObjCMethodExpr(false), FirstObjCSelectorName(NULL),
          FirstStartOfName(NULL), IsExpression(IsExpression),
          CanBeExpression(true), InCtorInitializer(false), CaretFound(false) {}

    tok::TokenKind ContextKind;
    unsigned BindingStrength;
    unsigned LongestObjCSelectorName;
    unsigned NumBlockParameters;
    bool ColonIsForRangeExpr;
    bool ColonIsDictLiteral;
    bool ColonIsObjCMethodExpr;
    FormatToken *FirstObjCSelectorName;
    FormatToken *FirstStartOfName;
    bool IsExpression;
    bool CanBeExpression;
    bool InCtorInitializer;
    bool CaretFound;
  };

  /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
  /// of each instance.
  struct ScopedContextCreator {
    AnnotatingParser &P;

    ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
                         unsigned Increase)
        : P(P) {
      P.Contexts.push_back(Context(ContextKind,
                                   P.Contexts.back().BindingStrength + Increase,
                                   P.Contexts.back().IsExpression));
    }

    ~ScopedContextCreator() { P.Contexts.pop_back(); }
  };

  void determineTokenType(FormatToken &Current) {
    if (Current.getPrecedence() == prec::Assignment &&
        !Line.First->isOneOf(tok::kw_template, tok::kw_using) &&
        (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
      Contexts.back().IsExpression = true;
      for (FormatToken *Previous = Current.Previous;
           Previous && !Previous->isOneOf(tok::comma, tok::semi);
           Previous = Previous->Previous) {
        if (Previous->is(tok::r_square))
          Previous = Previous->MatchingParen;
        if (Previous->Type == TT_BinaryOperator &&
            Previous->isOneOf(tok::star, tok::amp)) {
          Previous->Type = TT_PointerOrReference;
        }
      }
    } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
      Contexts.back().IsExpression = true;
    } else if (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
               !Line.InPPDirective) {
      bool ParametersOfFunctionType =
          Current.Previous && Current.Previous->is(tok::r_paren) &&
          Current.Previous->MatchingParen &&
          Current.Previous->MatchingParen->Type == TT_FunctionTypeLParen;
      bool IsForOrCatch = Current.Previous &&
                          Current.Previous->isOneOf(tok::kw_for, tok::kw_catch);
      Contexts.back().IsExpression = !ParametersOfFunctionType && !IsForOrCatch;
    } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
      for (FormatToken *Previous = Current.Previous;
           Previous && Previous->isOneOf(tok::star, tok::amp);
           Previous = Previous->Previous)
        Previous->Type = TT_PointerOrReference;
    } else if (Current.Previous &&
               Current.Previous->Type == TT_CtorInitializerColon) {
      Contexts.back().IsExpression = true;
      Contexts.back().InCtorInitializer = true;
    } else if (Current.is(tok::kw_new)) {
      Contexts.back().CanBeExpression = false;
    } else if (Current.is(tok::semi) || Current.is(tok::exclaim)) {
      // This should be the condition or increment in a for-loop.
      Contexts.back().IsExpression = true;
    }

    if (Current.Type == TT_Unknown) {
      // Line.MightBeFunctionDecl can only be true after the parentheses of a
      // function declaration have been found. In this case, 'Current' is a
      // trailing token of this declaration and thus cannot be a name.
      if (isStartOfName(Current) && !Line.MightBeFunctionDecl) {
        Contexts.back().FirstStartOfName = &Current;
        Current.Type = TT_StartOfName;
      } else if (Current.is(tok::kw_auto)) {
        AutoFound = true;
      } else if (Current.is(tok::arrow) && AutoFound &&
                 Line.MustBeDeclaration) {
        Current.Type = TT_TrailingReturnArrow;
      } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
        Current.Type =
            determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
                                               Contexts.back().IsExpression);
      } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
        Current.Type = determinePlusMinusCaretUsage(Current);
        if (Current.Type == TT_UnaryOperator) {
          ++Contexts.back().NumBlockParameters;
          if (Current.is(tok::caret))
            Contexts.back().CaretFound = true;
        }
      } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
        Current.Type = determineIncrementUsage(Current);
      } else if (Current.is(tok::exclaim)) {
        Current.Type = TT_UnaryOperator;
      } else if (Current.isBinaryOperator() &&
                 (!Current.Previous ||
                  Current.Previous->isNot(tok::l_square))) {
        Current.Type = TT_BinaryOperator;
      } else if (Current.is(tok::comment)) {
        if (Current.TokenText.startswith("//"))
          Current.Type = TT_LineComment;
        else
          Current.Type = TT_BlockComment;
      } else if (Current.is(tok::r_paren)) {
        FormatToken *LeftOfParens = NULL;
        if (Current.MatchingParen)
          LeftOfParens = Current.MatchingParen->getPreviousNonComment();
        bool IsCast = false;
        bool ParensAreEmpty = Current.Previous == Current.MatchingParen;
        bool ParensAreType = !Current.Previous ||
                             Current.Previous->Type == TT_PointerOrReference ||
                             Current.Previous->Type == TT_TemplateCloser ||
                             Current.Previous->isSimpleTypeSpecifier();
        bool ParensCouldEndDecl =
            Current.Next &&
            Current.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
        bool IsSizeOfOrAlignOf =
            LeftOfParens &&
            LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
        if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
            (Contexts.back().IsExpression ||
             (Current.Next && Current.Next->isBinaryOperator())))
          IsCast = true;
        if (Current.Next && Current.Next->isNot(tok::string_literal) &&
            (Current.Next->Tok.isLiteral() ||
             Current.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
          IsCast = true;
        // If there is an identifier after the (), it is likely a cast, unless
        // there is also an identifier before the ().
        if (LeftOfParens && (LeftOfParens->Tok.getIdentifierInfo() == NULL ||
                             LeftOfParens->is(tok::kw_return)) &&
            LeftOfParens->Type != TT_OverloadedOperator &&
            LeftOfParens->isNot(tok::at) &&
            LeftOfParens->Type != TT_TemplateCloser && Current.Next &&
            Current.Next->is(tok::identifier))
          IsCast = true;
        if (IsCast && !ParensAreEmpty)
          Current.Type = TT_CastRParen;
      } else if (Current.is(tok::at) && Current.Next) {
        switch (Current.Next->Tok.getObjCKeywordID()) {
        case tok::objc_interface:
        case tok::objc_implementation:
        case tok::objc_protocol:
          Current.Type = TT_ObjCDecl;
          break;
        case tok::objc_property:
          Current.Type = TT_ObjCProperty;
          break;
        default:
          break;
        }
      } else if (Current.is(tok::period)) {
        FormatToken *PreviousNoComment = Current.getPreviousNonComment();
        if (PreviousNoComment &&
            PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
          Current.Type = TT_DesignatedInitializerPeriod;
      } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
                 Line.MightBeFunctionDecl && Contexts.size() == 1) {
        // Line.MightBeFunctionDecl can only be true after the parentheses of a
        // function declaration have been found.
        Current.Type = TT_TrailingAnnotation;
      }
    }
  }

  /// \brief Take a guess at whether \p Tok starts a name of a function or
  /// variable declaration.
  ///
  /// This is a heuristic based on whether \p Tok is an identifier following
  /// something that is likely a type.
  bool isStartOfName(const FormatToken &Tok) {
    if (Tok.isNot(tok::identifier) || Tok.Previous == NULL)
      return false;

    // Skip "const" as it does not have an influence on whether this is a name.
    FormatToken *PreviousNotConst = Tok.Previous;
    while (PreviousNotConst != NULL && PreviousNotConst->is(tok::kw_const))
      PreviousNotConst = PreviousNotConst->Previous;

    if (PreviousNotConst == NULL)
      return false;

    bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
                       PreviousNotConst->Previous &&
                       PreviousNotConst->Previous->is(tok::hash);

    if (PreviousNotConst->Type == TT_TemplateCloser)
      return PreviousNotConst && PreviousNotConst->MatchingParen &&
             PreviousNotConst->MatchingParen->Previous &&
             PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);

    return (!IsPPKeyword && PreviousNotConst->is(tok::identifier)) ||
           PreviousNotConst->Type == TT_PointerOrReference ||
           PreviousNotConst->isSimpleTypeSpecifier();
  }

  /// \brief Return the type of the given token assuming it is * or &.
  TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression) {
    const FormatToken *PrevToken = Tok.getPreviousNonComment();
    if (PrevToken == NULL)
      return TT_UnaryOperator;

    const FormatToken *NextToken = Tok.getNextNonComment();
    if (NextToken == NULL)
      return TT_Unknown;

    if (PrevToken->is(tok::coloncolon) ||
        (PrevToken->is(tok::l_paren) && !IsExpression))
      return TT_PointerOrReference;

    if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
                           tok::comma, tok::semi, tok::kw_return, tok::colon,
                           tok::equal, tok::kw_delete, tok::kw_sizeof) ||
        PrevToken->Type == TT_BinaryOperator ||
        PrevToken->Type == TT_UnaryOperator || PrevToken->Type == TT_CastRParen)
      return TT_UnaryOperator;

    if (NextToken->is(tok::l_square))
      return TT_PointerOrReference;

    if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
        PrevToken->MatchingParen->Previous &&
        PrevToken->MatchingParen->Previous->is(tok::kw_typeof))
      return TT_PointerOrReference;

    if (PrevToken->Tok.isLiteral() ||
        PrevToken->isOneOf(tok::r_paren, tok::r_square) ||
        NextToken->Tok.isLiteral() || NextToken->isUnaryOperator())
      return TT_BinaryOperator;

    // It is very unlikely that we are going to find a pointer or reference type
    // definition on the RHS of an assignment.
    if (IsExpression)
      return TT_BinaryOperator;

    return TT_PointerOrReference;
  }

  TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
    const FormatToken *PrevToken = Tok.getPreviousNonComment();
    if (PrevToken == NULL || PrevToken->Type == TT_CastRParen)
      return TT_UnaryOperator;

    // Use heuristics to recognize unary operators.
    if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
                           tok::question, tok::colon, tok::kw_return,
                           tok::kw_case, tok::at, tok::l_brace))
      return TT_UnaryOperator;

    // There can't be two consecutive binary operators.
    if (PrevToken->Type == TT_BinaryOperator)
      return TT_UnaryOperator;

    // Fall back to marking the token as binary operator.
    return TT_BinaryOperator;
  }

  /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
  TokenType determineIncrementUsage(const FormatToken &Tok) {
    const FormatToken *PrevToken = Tok.getPreviousNonComment();
    if (PrevToken == NULL || PrevToken->Type == TT_CastRParen)
      return TT_UnaryOperator;
    if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
      return TT_TrailingUnaryOperator;

    return TT_UnaryOperator;
  }


  SmallVector<Context, 8> Contexts;

  const FormatStyle &Style;
  AnnotatedLine &Line;
  FormatToken *CurrentToken;
  bool KeywordVirtualFound;
  bool AutoFound;
  IdentifierInfo &Ident_in;
};

static int PrecedenceUnaryOperator = prec::PointerToMember + 1;
static int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;

/// \brief Parses binary expressions by inserting fake parenthesis based on
/// operator precedence.
class ExpressionParser {
public:
  ExpressionParser(AnnotatedLine &Line) : Current(Line.First) {
    // Skip leading "}", e.g. in "} else if (...) {".
    if (Current->is(tok::r_brace))
      next();
  }

  /// \brief Parse expressions with the given operatore precedence.
  void parse(int Precedence = 0) {
    // Skip 'return' and ObjC selector colons as they are not part of a binary
    // expression.
    while (Current &&
           (Current->is(tok::kw_return) ||
            (Current->is(tok::colon) && Current->Type == TT_ObjCMethodExpr)))
      next();

    if (Current == NULL || Precedence > PrecedenceArrowAndPeriod)
      return;

    // Conditional expressions need to be parsed separately for proper nesting.
    if (Precedence == prec::Conditional) {
      parseConditionalExpr();
      return;
    }

    // Parse unary operators, which all have a higher precedence than binary
    // operators.
    if (Precedence == PrecedenceUnaryOperator) {
      parseUnaryOperator();
      return;
    }

    FormatToken *Start = Current;
    FormatToken *LatestOperator = NULL;

    while (Current) {
      // Consume operators with higher precedence.
      parse(Precedence + 1);

      int CurrentPrecedence = getCurrentPrecedence();

      if (Current && Current->Type == TT_ObjCSelectorName &&
          Precedence == CurrentPrecedence) {
        if (LatestOperator)
          addFakeParenthesis(Start, prec::Level(Precedence));
        Start = Current;
      }

      // At the end of the line or when an operator with higher precedence is
      // found, insert fake parenthesis and return.
      if (Current == NULL || Current->closesScope() ||
          (CurrentPrecedence != -1 && CurrentPrecedence < Precedence)) {
        if (LatestOperator) {
          if (Precedence == PrecedenceArrowAndPeriod) {
            LatestOperator->LastInChainOfCalls = true;
            // Call expressions don't have a binary operator precedence.
            addFakeParenthesis(Start, prec::Unknown);
          } else {
            addFakeParenthesis(Start, prec::Level(Precedence));
          }
        }
        return;
      }

      // Consume scopes: (), [], <> and {}
      if (Current->opensScope()) {
        while (Current && !Current->closesScope()) {
          next();
          parse();
        }
        next();
      } else {
        // Operator found.
        if (CurrentPrecedence == Precedence)
          LatestOperator = Current;

        next();
      }
    }
  }

private:
  /// \brief Gets the precedence (+1) of the given token for binary operators
  /// and other tokens that we treat like binary operators.
  int getCurrentPrecedence() {
    if (Current) {
      if (Current->Type == TT_ConditionalExpr)
        return prec::Conditional;
      else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon ||
               Current->Type == TT_ObjCSelectorName)
        return 0;
      else if (Current->Type == TT_RangeBasedForLoopColon)
        return prec::Comma;
      else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
        return Current->getPrecedence();
      else if (Current->isOneOf(tok::period, tok::arrow))
        return PrecedenceArrowAndPeriod;
    }
    return -1;
  }

  void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
    Start->FakeLParens.push_back(Precedence);
    if (Precedence > prec::Unknown)
      Start->StartsBinaryExpression = true;
    if (Current) {
      ++Current->Previous->FakeRParens;
      if (Precedence > prec::Unknown)
        Current->Previous->EndsBinaryExpression = true;
    }
  }

  /// \brief Parse unary operator expressions and surround them with fake
  /// parentheses if appropriate.
  void parseUnaryOperator() {
    if (Current == NULL || Current->Type != TT_UnaryOperator) {
      parse(PrecedenceArrowAndPeriod);
      return;
    }

    FormatToken *Start = Current;
    next();
    parseUnaryOperator();

    // The actual precedence doesn't matter.
    addFakeParenthesis(Start, prec::Unknown);
  }

  void parseConditionalExpr() {
    FormatToken *Start = Current;
    parse(prec::LogicalOr);
    if (!Current || !Current->is(tok::question))
      return;
    next();
    parse(prec::LogicalOr);
    if (!Current || Current->Type != TT_ConditionalExpr)
      return;
    next();
    parseConditionalExpr();
    addFakeParenthesis(Start, prec::Conditional);
  }

  void next() {
    if (Current)
      Current = Current->Next;
    while (Current && Current->isTrailingComment())
      Current = Current->Next;
  }

  FormatToken *Current;
};

} // end anonymous namespace

void
TokenAnnotator::setCommentLineLevels(SmallVectorImpl<AnnotatedLine *> &Lines) {
  const AnnotatedLine *NextNonCommentLine = NULL;
  for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
                                                          E = Lines.rend();
       I != E; ++I) {
    if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
        (*I)->First->Next == NULL)
      (*I)->Level = NextNonCommentLine->Level;
    else
      NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : NULL;

    setCommentLineLevels((*I)->Children);
  }
}

void TokenAnnotator::annotate(AnnotatedLine &Line) {
  for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
                                                  E = Line.Children.end();
       I != E; ++I) {
    annotate(**I);
  }
  AnnotatingParser Parser(Style, Line, Ident_in);
  Line.Type = Parser.parseLine();
  if (Line.Type == LT_Invalid)
    return;

  ExpressionParser ExprParser(Line);
  ExprParser.parse();

  if (Line.First->Type == TT_ObjCMethodSpecifier)
    Line.Type = LT_ObjCMethodDecl;
  else if (Line.First->Type == TT_ObjCDecl)
    Line.Type = LT_ObjCDecl;
  else if (Line.First->Type == TT_ObjCProperty)
    Line.Type = LT_ObjCProperty;

  Line.First->SpacesRequiredBefore = 1;
  Line.First->CanBreakBefore = Line.First->MustBreakBefore;
}

void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
  Line.First->TotalLength =
      Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
  if (!Line.First->Next)
    return;
  FormatToken *Current = Line.First->Next;
  bool InFunctionDecl = Line.MightBeFunctionDecl;
  while (Current != NULL) {
    if (Current->Type == TT_LineComment) {
      if (Current->Previous->BlockKind == BK_BracedInit)
        Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
      else
        Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
    } else if (Current->SpacesRequiredBefore == 0 &&
             spaceRequiredBefore(Line, *Current)) {
      Current->SpacesRequiredBefore = 1;
    }

    Current->MustBreakBefore =
        Current->MustBreakBefore || mustBreakBefore(Line, *Current);

    Current->CanBreakBefore =
        Current->MustBreakBefore || canBreakBefore(Line, *Current);
    if (Current->MustBreakBefore || !Current->Children.empty() ||
        Current->IsMultiline)
      Current->TotalLength = Current->Previous->TotalLength + Style.ColumnLimit;
    else
      Current->TotalLength = Current->Previous->TotalLength +
                             Current->ColumnWidth +
                             Current->SpacesRequiredBefore;

    if (Current->Type == TT_CtorInitializerColon)
      InFunctionDecl = false;

    // FIXME: Only calculate this if CanBreakBefore is true once static
    // initializers etc. are sorted out.
    // FIXME: Move magic numbers to a better place.
    Current->SplitPenalty = 20 * Current->BindingStrength +
                            splitPenalty(Line, *Current, InFunctionDecl);

    Current = Current->Next;
  }

  calculateUnbreakableTailLengths(Line);
  for (Current = Line.First; Current != NULL; Current = Current->Next) {
    if (Current->Role)
      Current->Role->precomputeFormattingInfos(Current);
  }

  DEBUG({ printDebugInfo(Line); });

  for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
                                                  E = Line.Children.end();
       I != E; ++I) {
    calculateFormattingInformation(**I);
  }
}

void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
  unsigned UnbreakableTailLength = 0;
  FormatToken *Current = Line.Last;
  while (Current != NULL) {
    Current->UnbreakableTailLength = UnbreakableTailLength;
    if (Current->CanBreakBefore ||
        Current->isOneOf(tok::comment, tok::string_literal)) {
      UnbreakableTailLength = 0;
    } else {
      UnbreakableTailLength +=
          Current->ColumnWidth + Current->SpacesRequiredBefore;
    }
    Current = Current->Previous;
  }
}

unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
                                      const FormatToken &Tok,
                                      bool InFunctionDecl) {
  const FormatToken &Left = *Tok.Previous;
  const FormatToken &Right = Tok;

  if (Left.is(tok::semi))
    return 0;
  if (Left.is(tok::comma))
    return 1;
  if (Right.is(tok::l_square)) {
    if (Style.Language == FormatStyle::LK_Proto)
      return 1;
    if (Right.Type != TT_ObjCMethodExpr)
      return 250;
  }
  if (Right.Type == TT_StartOfName || Right.is(tok::kw_operator)) {
    if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
      return 3;
    if (Left.Type == TT_StartOfName)
      return 20;
    if (InFunctionDecl && Right.NestingLevel == 0)
      return Style.PenaltyReturnTypeOnItsOwnLine;
    return 200;
  }
  if (Left.is(tok::equal) && Right.is(tok::l_brace))
    return 150;
  if (Left.Type == TT_CastRParen)
    return 100;
  if (Left.is(tok::coloncolon) ||
      (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
    return 500;
  if (Left.isOneOf(tok::kw_class, tok::kw_struct))
    return 5000;

  if (Left.Type == TT_RangeBasedForLoopColon ||
      Left.Type == TT_InheritanceColon)
    return 2;

  if (Right.isMemberAccess()) {
    if (Left.is(tok::r_paren) && Left.MatchingParen &&
        Left.MatchingParen->ParameterCount > 0)
      return 20; // Should be smaller than breaking at a nested comma.
    return 150;
  }

  if (Right.Type == TT_TrailingAnnotation && Right.Next &&
      Right.Next->isNot(tok::l_paren)) {
    // Generally, breaking before a trailing annotation is bad unless it is
    // function-like. It seems to be especially preferable to keep standard
    // annotations (i.e. "const", "final" and "override") on the same line.
    // Use a slightly higher penalty after ")" so that annotations like
    // "const override" are kept together.
    bool is_standard_annotation = Right.is(tok::kw_const) ||
                                  Right.TokenText == "override" ||
                                  Right.TokenText == "final";
    return (Left.is(tok::r_paren) ? 100 : 120) +
           (is_standard_annotation ? 50 : 0);
  }

  // In for-loops, prefer breaking at ',' and ';'.
  if (Line.First->is(tok::kw_for) && Left.is(tok::equal))
    return 4;

  // In Objective-C method expressions, prefer breaking before "param:" over
  // breaking after it.
  if (Right.Type == TT_ObjCSelectorName)
    return 0;
  if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
    return Line.MightBeFunctionDecl ? 50 : 500;

  if (Left.is(tok::l_paren) && InFunctionDecl)
    return 100;
  if (Left.is(tok::equal) && InFunctionDecl)
    return 110;
  if (Left.opensScope())
    return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
                                   : 19;

  if (Right.is(tok::lessless)) {
    if (Left.is(tok::string_literal)) {
      StringRef Content = Left.TokenText;
      if (Content.startswith("\""))
        Content = Content.drop_front(1);
      if (Content.endswith("\""))
        Content = Content.drop_back(1);
      Content = Content.trim();
      if (Content.size() > 1 &&
          (Content.back() == ':' || Content.back() == '='))
        return 25;
    }
    return 1; // Breaking at a << is really cheap.
  }
  if (Left.Type == TT_ConditionalExpr)
    return prec::Conditional;
  prec::Level Level = Left.getPrecedence();

  if (Level != prec::Unknown)
    return Level;

  return 3;
}

bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
                                          const FormatToken &Left,
                                          const FormatToken &Right) {
  if (Style.Language == FormatStyle::LK_Proto) {
    if (Right.is(tok::l_paren) &&
        (Left.TokenText == "returns" || Left.TokenText == "option"))
      return true;
  }
  if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
      Left.Tok.getObjCKeywordID() == tok::objc_property)
    return true;
  if (Right.is(tok::hashhash))
    return Left.is(tok::hash);
  if (Left.isOneOf(tok::hashhash, tok::hash))
    return Right.is(tok::hash);
  if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
    return Style.SpaceInEmptyParentheses;
  if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
    return (Right.Type == TT_CastRParen ||
            (Left.MatchingParen && Left.MatchingParen->Type == TT_CastRParen))
               ? Style.SpacesInCStyleCastParentheses
               : Style.SpacesInParentheses;
  if (Style.SpacesInAngles &&
      ((Left.Type == TT_TemplateOpener) != (Right.Type == TT_TemplateCloser)))
    return true;
  if (Right.isOneOf(tok::semi, tok::comma))
    return false;
  if (Right.is(tok::less) &&
      (Left.is(tok::kw_template) ||
       (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
    return true;
  if (Left.is(tok::arrow) || Right.is(tok::arrow))
    return false;
  if (Left.isOneOf(tok::exclaim, tok::tilde))
    return false;
  if (Left.is(tok::at) &&
      Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
                    tok::numeric_constant, tok::l_paren, tok::l_brace,
                    tok::kw_true, tok::kw_false))
    return false;
  if (Left.is(tok::coloncolon))
    return false;
  if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
    return (Left.is(tok::less) && Style.Standard == FormatStyle::LS_Cpp03) ||
           !Left.isOneOf(tok::identifier, tok::greater, tok::l_paren,
                         tok::r_paren, tok::less);
  if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
    return false;
  if (Right.is(tok::ellipsis))
    return Left.Tok.isLiteral();
  if (Left.is(tok::l_square) && Right.is(tok::amp))
    return false;
  if (Right.Type == TT_PointerOrReference)
    return Left.Tok.isLiteral() ||
           ((Left.Type != TT_PointerOrReference) && Left.isNot(tok::l_paren) &&
            !Style.PointerBindsToType);
  if (Right.Type == TT_FunctionTypeLParen && Left.isNot(tok::l_paren) &&
      (Left.Type != TT_PointerOrReference || Style.PointerBindsToType))
    return true;
  if (Left.Type == TT_PointerOrReference)
    return Right.Tok.isLiteral() || Right.Type == TT_BlockComment ||
           ((Right.Type != TT_PointerOrReference) &&
            Right.isNot(tok::l_paren) && Style.PointerBindsToType &&
            Left.Previous &&
            !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
  if (Right.is(tok::star) && Left.is(tok::l_paren))
    return false;
  if (Left.is(tok::l_square))
    return Left.Type == TT_ArrayInitializerLSquare &&
           Style.SpacesInContainerLiterals && Right.isNot(tok::r_square);
  if (Right.is(tok::r_square))
    return Right.MatchingParen && Style.SpacesInContainerLiterals &&
           Right.MatchingParen->Type == TT_ArrayInitializerLSquare;
  if (Right.is(tok::l_square) && Right.Type != TT_ObjCMethodExpr &&
      Right.Type != TT_LambdaLSquare && Left.isNot(tok::numeric_constant))
    return false;
  if (Left.is(tok::colon))
    return Left.Type != TT_ObjCMethodExpr;
  if (Right.is(tok::l_paren)) {
    if (Left.is(tok::r_paren) && Left.Type == TT_AttributeParen)
      return true;
    return Line.Type == LT_ObjCDecl ||
           Left.isOneOf(tok::kw_return, tok::kw_new, tok::kw_delete,
                        tok::semi) ||
           (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
            Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
                         tok::kw_catch)) ||
           (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
            Left.isOneOf(tok::identifier, tok::kw___attribute) &&
            Line.Type != LT_PreprocessorDirective);
  }
  if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
    return false;
  if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
    return !Left.Children.empty(); // No spaces in "{}".
  if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
      (Right.is(tok::r_brace) && Right.MatchingParen &&
       Right.MatchingParen->BlockKind != BK_Block))
    return !Style.Cpp11BracedListStyle;
  if (Left.Type == TT_BlockComment && Left.TokenText.endswith("=*/"))
    return false;
  if (Right.Type == TT_UnaryOperator)
    return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
           (Left.isNot(tok::colon) || Left.Type != TT_ObjCMethodExpr);
  if (Left.isOneOf(tok::identifier, tok::greater, tok::r_square) &&
      Right.is(tok::l_brace) && Right.getNextNonComment() &&
      Right.BlockKind != BK_Block)
    return false;
  if (Left.is(tok::period) || Right.is(tok::period))
    return false;
  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
    return false;
  return true;
}

bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
                                         const FormatToken &Tok) {
  if (Tok.Tok.getIdentifierInfo() && Tok.Previous->Tok.getIdentifierInfo())
    return true; // Never ever merge two identifiers.
  if (Tok.Previous->Type == TT_ImplicitStringLiteral)
    return Tok.WhitespaceRange.getBegin() != Tok.WhitespaceRange.getEnd();
  if (Line.Type == LT_ObjCMethodDecl) {
    if (Tok.Previous->Type == TT_ObjCMethodSpecifier)
      return true;
    if (Tok.Previous->is(tok::r_paren) && Tok.is(tok::identifier))
      // Don't space between ')' and <id>
      return false;
  }
  if (Line.Type == LT_ObjCProperty &&
      (Tok.is(tok::equal) || Tok.Previous->is(tok::equal)))
    return false;

  if (Tok.Type == TT_TrailingReturnArrow ||
      Tok.Previous->Type == TT_TrailingReturnArrow)
    return true;
  if (Tok.Previous->is(tok::comma))
    return true;
  if (Tok.is(tok::comma))
    return false;
  if (Tok.Type == TT_CtorInitializerColon || Tok.Type == TT_ObjCBlockLParen)
    return true;
  if (Tok.Previous->Tok.is(tok::kw_operator))
    return Tok.is(tok::coloncolon);
  if (Tok.Type == TT_OverloadedOperatorLParen)
    return false;
  if (Tok.is(tok::colon))
    return !Line.First->isOneOf(tok::kw_case, tok::kw_default) &&
           Tok.getNextNonComment() != NULL && Tok.Type != TT_ObjCMethodExpr &&
           !Tok.Previous->is(tok::question) &&
           (Tok.Type != TT_DictLiteral || Style.SpacesInContainerLiterals);
  if (Tok.Previous->Type == TT_UnaryOperator ||
      Tok.Previous->Type == TT_CastRParen)
    return Tok.Type == TT_BinaryOperator;
  if (Tok.Previous->is(tok::greater) && Tok.is(tok::greater)) {
    return Tok.Type == TT_TemplateCloser &&
           Tok.Previous->Type == TT_TemplateCloser &&
           (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
  }
  if (Tok.isOneOf(tok::arrowstar, tok::periodstar) ||
      Tok.Previous->isOneOf(tok::arrowstar, tok::periodstar))
    return false;
  if (!Style.SpaceBeforeAssignmentOperators &&
      Tok.getPrecedence() == prec::Assignment)
    return false;
  if ((Tok.Type == TT_BinaryOperator && !Tok.Previous->is(tok::l_paren)) ||
      Tok.Previous->Type == TT_BinaryOperator)
    return true;
  if (Tok.Previous->Type == TT_TemplateCloser && Tok.is(tok::l_paren))
    return false;
  if (Tok.is(tok::less) && Tok.Previous->isNot(tok::l_paren) &&
      Line.First->is(tok::hash))
    return true;
  if (Tok.Type == TT_TrailingUnaryOperator)
    return false;
  return spaceRequiredBetween(Line, *Tok.Previous, Tok);
}

bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
                                     const FormatToken &Right) {
  if (Right.is(tok::comment)) {
    return Right.Previous->BlockKind != BK_BracedInit &&
           Right.Previous->Type != TT_CtorInitializerColon &&
           Right.NewlinesBefore > 0;
  } else if (Right.Previous->isTrailingComment() ||
             (Right.isStringLiteral() && Right.Previous->isStringLiteral())) {
    return true;
  } else if (Right.Previous->IsUnterminatedLiteral) {
    return true;
  } else if (Right.is(tok::lessless) && Right.Next &&
             Right.Previous->is(tok::string_literal) &&
             Right.Next->is(tok::string_literal)) {
    return true;
  } else if (Right.Previous->ClosesTemplateDeclaration &&
             Right.Previous->MatchingParen &&
             Right.Previous->MatchingParen->NestingLevel == 0 &&
             Style.AlwaysBreakTemplateDeclarations) {
    return true;
  } else if ((Right.Type == TT_CtorInitializerComma ||
              Right.Type == TT_CtorInitializerColon) &&
             Style.BreakConstructorInitializersBeforeComma &&
             !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
    return true;
  } else if (Right.is(tok::l_brace) && (Right.BlockKind == BK_Block)) {
    return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
           Style.BreakBeforeBraces == FormatStyle::BS_GNU;
  } else if (Right.is(tok::string_literal) &&
             Right.TokenText.startswith("R\"")) {
    // Raw string literals are special wrt. line breaks. The author has made a
    // deliberate choice and might have aligned the contents of the string
    // literal accordingly. Thus, we try keep existing line breaks.
    return Right.NewlinesBefore > 0;
  } else if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
             Style.Language == FormatStyle::LK_Proto) {
    // Don't enums onto single lines in protocol buffers.
    return true;
  }
  return false;
}

bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
                                    const FormatToken &Right) {
  const FormatToken &Left = *Right.Previous;
  if (Left.is(tok::at))
    return false;
  if (Right.Type == TT_StartOfName || Right.is(tok::kw_operator))
    return true;
  if (Right.isTrailingComment())
    // We rely on MustBreakBefore being set correctly here as we should not
    // change the "binding" behavior of a comment.
    // The first comment in a braced lists is always interpreted as belonging to
    // the first list element. Otherwise, it should be placed outside of the
    // list.
    return Left.BlockKind == BK_BracedInit;
  if (Left.is(tok::question) && Right.is(tok::colon))
    return false;
  if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
    return Style.BreakBeforeTernaryOperators;
  if (Left.Type == TT_ConditionalExpr || Left.is(tok::question))
    return !Style.BreakBeforeTernaryOperators;
  if (Right.is(tok::colon) &&
      (Right.Type == TT_DictLiteral || Right.Type == TT_ObjCMethodExpr))
    return false;
  if (Right.Type == TT_InheritanceColon)
    return true;
  if (Left.is(tok::colon) &&
      (Left.Type == TT_DictLiteral || Left.Type == TT_ObjCMethodExpr))
    return true;
  if (Right.Type == TT_ObjCSelectorName)
    return true;
  if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
    return true;
  if (Left.ClosesTemplateDeclaration)
    return true;
  if (Right.Type == TT_RangeBasedForLoopColon ||
      Right.Type == TT_OverloadedOperatorLParen ||
      Right.Type == TT_OverloadedOperator)
    return false;
  if (Left.Type == TT_RangeBasedForLoopColon)
    return true;
  if (Right.Type == TT_RangeBasedForLoopColon)
    return false;
  if (Left.Type == TT_PointerOrReference || Left.Type == TT_TemplateCloser ||
      Left.Type == TT_UnaryOperator || Left.is(tok::kw_operator))
    return false;
  if (Left.is(tok::equal) && Line.Type == LT_VirtualFunctionDecl)
    return false;
  if (Left.is(tok::l_paren) && Left.Type == TT_AttributeParen)
    return false;
  if (Left.is(tok::l_paren) && Left.Previous &&
      (Left.Previous->Type == TT_BinaryOperator ||
       Left.Previous->Type == TT_CastRParen))
    return false;
  if (Right.Type == TT_ImplicitStringLiteral)
    return false;

  if (Right.is(tok::r_paren) || Right.Type == TT_TemplateCloser)
    return false;

  // We only break before r_brace if there was a corresponding break before
  // the l_brace, which is tracked by BreakBeforeClosingBrace.
  if (Right.is(tok::r_brace))
    return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;

  // Allow breaking after a trailing 'const', e.g. after a method declaration,
  // unless it is follow by ';', '{' or '='.
  if (Left.is(tok::kw_const) && Left.Previous != NULL &&
      Left.Previous->is(tok::r_paren))
    return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal);

  if (Right.is(tok::kw___attribute))
    return true;

  if (Left.is(tok::identifier) && Right.is(tok::string_literal))
    return true;

  if (Left.Type == TT_CtorInitializerComma &&
      Style.BreakConstructorInitializersBeforeComma)
    return false;
  if (Right.Type == TT_CtorInitializerComma &&
      Style.BreakConstructorInitializersBeforeComma)
    return true;
  if (Right.Type == TT_BinaryOperator && Style.BreakBeforeBinaryOperators)
    return true;
  if (Left.is(tok::greater) && Right.is(tok::greater) &&
      Left.Type != TT_TemplateCloser)
    return false;
  if (Left.Type == TT_ArrayInitializerLSquare)
    return true;
  return (Left.isBinaryOperator() && Left.isNot(tok::lessless) &&
          !Style.BreakBeforeBinaryOperators) ||
         Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
                      tok::kw_class, tok::kw_struct) ||
         Right.isOneOf(tok::lessless, tok::arrow, tok::period, tok::colon,
                       tok::l_square, tok::at) ||
         (Left.is(tok::r_paren) &&
          Right.isOneOf(tok::identifier, tok::kw_const)) ||
         (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
}

void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
  llvm::errs() << "AnnotatedTokens:\n";
  const FormatToken *Tok = Line.First;
  while (Tok) {
    llvm::errs() << " M=" << Tok->MustBreakBefore
                 << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
                 << " S=" << Tok->SpacesRequiredBefore
                 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
                 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
                 << " FakeLParens=";
    for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
      llvm::errs() << Tok->FakeLParens[i] << "/";
    llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
    if (Tok->Next == NULL)
      assert(Tok == Line.Last);
    Tok = Tok->Next;
  }
  llvm::errs() << "----\n";
}

} // namespace format
} // namespace clang
@


