Home | History | Annotate | Line # | Download | only in Format
      1      1.1  joerg //===--- ContinuationIndenter.cpp - Format C++ code -----------------------===//
      2      1.1  joerg //
      3      1.1  joerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4      1.1  joerg // See https://llvm.org/LICENSE.txt for license information.
      5      1.1  joerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6      1.1  joerg //
      7      1.1  joerg //===----------------------------------------------------------------------===//
      8      1.1  joerg ///
      9      1.1  joerg /// \file
     10      1.1  joerg /// This file implements the continuation indenter.
     11      1.1  joerg ///
     12      1.1  joerg //===----------------------------------------------------------------------===//
     13      1.1  joerg 
     14      1.1  joerg #include "ContinuationIndenter.h"
     15      1.1  joerg #include "BreakableToken.h"
     16      1.1  joerg #include "FormatInternal.h"
     17      1.1  joerg #include "WhitespaceManager.h"
     18      1.1  joerg #include "clang/Basic/OperatorPrecedence.h"
     19      1.1  joerg #include "clang/Basic/SourceManager.h"
     20      1.1  joerg #include "clang/Format/Format.h"
     21      1.1  joerg #include "llvm/Support/Debug.h"
     22      1.1  joerg 
     23      1.1  joerg #define DEBUG_TYPE "format-indenter"
     24      1.1  joerg 
     25      1.1  joerg namespace clang {
     26      1.1  joerg namespace format {
     27      1.1  joerg 
     28      1.1  joerg // Returns true if a TT_SelectorName should be indented when wrapped,
     29      1.1  joerg // false otherwise.
     30      1.1  joerg static bool shouldIndentWrappedSelectorName(const FormatStyle &Style,
     31      1.1  joerg                                             LineType LineType) {
     32      1.1  joerg   return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;
     33      1.1  joerg }
     34      1.1  joerg 
     35      1.1  joerg // Returns the length of everything up to the first possible line break after
     36      1.1  joerg // the ), ], } or > matching \c Tok.
     37      1.1  joerg static unsigned getLengthToMatchingParen(const FormatToken &Tok,
     38      1.1  joerg                                          const std::vector<ParenState> &Stack) {
     39      1.1  joerg   // Normally whether or not a break before T is possible is calculated and
     40      1.1  joerg   // stored in T.CanBreakBefore. Braces, array initializers and text proto
     41      1.1  joerg   // messages like `key: < ... >` are an exception: a break is possible
     42      1.1  joerg   // before a closing brace R if a break was inserted after the corresponding
     43      1.1  joerg   // opening brace. The information about whether or not a break is needed
     44      1.1  joerg   // before a closing brace R is stored in the ParenState field
     45      1.1  joerg   // S.BreakBeforeClosingBrace where S is the state that R closes.
     46      1.1  joerg   //
     47      1.1  joerg   // In order to decide whether there can be a break before encountered right
     48      1.1  joerg   // braces, this implementation iterates over the sequence of tokens and over
     49      1.1  joerg   // the paren stack in lockstep, keeping track of the stack level which visited
     50      1.1  joerg   // right braces correspond to in MatchingStackIndex.
     51      1.1  joerg   //
     52      1.1  joerg   // For example, consider:
     53      1.1  joerg   // L. <- line number
     54      1.1  joerg   // 1. {
     55      1.1  joerg   // 2. {1},
     56      1.1  joerg   // 3. {2},
     57      1.1  joerg   // 4. {{3}}}
     58      1.1  joerg   //     ^ where we call this method with this token.
     59      1.1  joerg   // The paren stack at this point contains 3 brace levels:
     60      1.1  joerg   //  0. { at line 1, BreakBeforeClosingBrace: true
     61      1.1  joerg   //  1. first { at line 4, BreakBeforeClosingBrace: false
     62      1.1  joerg   //  2. second { at line 4, BreakBeforeClosingBrace: false,
     63      1.1  joerg   //  where there might be fake parens levels in-between these levels.
     64      1.1  joerg   // The algorithm will start at the first } on line 4, which is the matching
     65      1.1  joerg   // brace of the initial left brace and at level 2 of the stack. Then,
     66      1.1  joerg   // examining BreakBeforeClosingBrace: false at level 2, it will continue to
     67      1.1  joerg   // the second } on line 4, and will traverse the stack downwards until it
     68      1.1  joerg   // finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:
     69      1.1  joerg   // false at level 1, it will continue to the third } on line 4 and will
     70      1.1  joerg   // traverse the stack downwards until it finds the matching { on level 0.
     71      1.1  joerg   // Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm
     72      1.1  joerg   // will stop and will use the second } on line 4 to determine the length to
     73      1.1  joerg   // return, as in this example the range will include the tokens: {3}}
     74      1.1  joerg   //
     75      1.1  joerg   // The algorithm will only traverse the stack if it encounters braces, array
     76      1.1  joerg   // initializer squares or text proto angle brackets.
     77      1.1  joerg   if (!Tok.MatchingParen)
     78      1.1  joerg     return 0;
     79      1.1  joerg   FormatToken *End = Tok.MatchingParen;
     80      1.1  joerg   // Maintains a stack level corresponding to the current End token.
     81      1.1  joerg   int MatchingStackIndex = Stack.size() - 1;
     82      1.1  joerg   // Traverses the stack downwards, looking for the level to which LBrace
     83      1.1  joerg   // corresponds. Returns either a pointer to the matching level or nullptr if
     84      1.1  joerg   // LParen is not found in the initial portion of the stack up to
     85      1.1  joerg   // MatchingStackIndex.
     86      1.1  joerg   auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
     87      1.1  joerg     while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
     88      1.1  joerg       --MatchingStackIndex;
     89      1.1  joerg     return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
     90      1.1  joerg   };
     91      1.1  joerg   for (; End->Next; End = End->Next) {
     92      1.1  joerg     if (End->Next->CanBreakBefore)
     93      1.1  joerg       break;
     94      1.1  joerg     if (!End->Next->closesScope())
     95      1.1  joerg       continue;
     96      1.1  joerg     if (End->Next->MatchingParen &&
     97      1.1  joerg         End->Next->MatchingParen->isOneOf(
     98      1.1  joerg             tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
     99      1.1  joerg       const ParenState *State = FindParenState(End->Next->MatchingParen);
    100      1.1  joerg       if (State && State->BreakBeforeClosingBrace)
    101      1.1  joerg         break;
    102      1.1  joerg     }
    103      1.1  joerg   }
    104      1.1  joerg   return End->TotalLength - Tok.TotalLength + 1;
    105      1.1  joerg }
    106      1.1  joerg 
    107      1.1  joerg static unsigned getLengthToNextOperator(const FormatToken &Tok) {
    108      1.1  joerg   if (!Tok.NextOperator)
    109      1.1  joerg     return 0;
    110      1.1  joerg   return Tok.NextOperator->TotalLength - Tok.TotalLength;
    111      1.1  joerg }
    112      1.1  joerg 
    113      1.1  joerg // Returns \c true if \c Tok is the "." or "->" of a call and starts the next
    114      1.1  joerg // segment of a builder type call.
    115      1.1  joerg static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
    116      1.1  joerg   return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
    117      1.1  joerg }
    118      1.1  joerg 
    119      1.1  joerg // Returns \c true if \c Current starts a new parameter.
    120      1.1  joerg static bool startsNextParameter(const FormatToken &Current,
    121      1.1  joerg                                 const FormatStyle &Style) {
    122      1.1  joerg   const FormatToken &Previous = *Current.Previous;
    123      1.1  joerg   if (Current.is(TT_CtorInitializerComma) &&
    124      1.1  joerg       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
    125      1.1  joerg     return true;
    126      1.1  joerg   if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName))
    127      1.1  joerg     return true;
    128      1.1  joerg   return Previous.is(tok::comma) && !Current.isTrailingComment() &&
    129      1.1  joerg          ((Previous.isNot(TT_CtorInitializerComma) ||
    130      1.1  joerg            Style.BreakConstructorInitializers !=
    131      1.1  joerg                FormatStyle::BCIS_BeforeComma) &&
    132      1.1  joerg           (Previous.isNot(TT_InheritanceComma) ||
    133      1.1  joerg            Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma));
    134      1.1  joerg }
    135      1.1  joerg 
    136      1.1  joerg static bool opensProtoMessageField(const FormatToken &LessTok,
    137      1.1  joerg                                    const FormatStyle &Style) {
    138      1.1  joerg   if (LessTok.isNot(tok::less))
    139      1.1  joerg     return false;
    140      1.1  joerg   return Style.Language == FormatStyle::LK_TextProto ||
    141      1.1  joerg          (Style.Language == FormatStyle::LK_Proto &&
    142      1.1  joerg           (LessTok.NestingLevel > 0 ||
    143      1.1  joerg            (LessTok.Previous && LessTok.Previous->is(tok::equal))));
    144      1.1  joerg }
    145      1.1  joerg 
    146      1.1  joerg // Returns the delimiter of a raw string literal, or None if TokenText is not
    147      1.1  joerg // the text of a raw string literal. The delimiter could be the empty string.
    148      1.1  joerg // For example, the delimiter of R"deli(cont)deli" is deli.
    149      1.1  joerg static llvm::Optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
    150      1.1  joerg   if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
    151      1.1  joerg       || !TokenText.startswith("R\"") || !TokenText.endswith("\""))
    152      1.1  joerg     return None;
    153      1.1  joerg 
    154      1.1  joerg   // A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has
    155      1.1  joerg   // size at most 16 by the standard, so the first '(' must be among the first
    156      1.1  joerg   // 19 bytes.
    157      1.1  joerg   size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
    158      1.1  joerg   if (LParenPos == StringRef::npos)
    159      1.1  joerg     return None;
    160      1.1  joerg   StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
    161      1.1  joerg 
    162      1.1  joerg   // Check that the string ends in ')Delimiter"'.
    163      1.1  joerg   size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
    164      1.1  joerg   if (TokenText[RParenPos] != ')')
    165      1.1  joerg     return None;
    166      1.1  joerg   if (!TokenText.substr(RParenPos + 1).startswith(Delimiter))
    167      1.1  joerg     return None;
    168      1.1  joerg   return Delimiter;
    169      1.1  joerg }
    170      1.1  joerg 
    171      1.1  joerg // Returns the canonical delimiter for \p Language, or the empty string if no
    172      1.1  joerg // canonical delimiter is specified.
    173      1.1  joerg static StringRef
    174      1.1  joerg getCanonicalRawStringDelimiter(const FormatStyle &Style,
    175      1.1  joerg                                FormatStyle::LanguageKind Language) {
    176      1.1  joerg   for (const auto &Format : Style.RawStringFormats) {
    177      1.1  joerg     if (Format.Language == Language)
    178      1.1  joerg       return StringRef(Format.CanonicalDelimiter);
    179      1.1  joerg   }
    180      1.1  joerg   return "";
    181      1.1  joerg }
    182      1.1  joerg 
    183      1.1  joerg RawStringFormatStyleManager::RawStringFormatStyleManager(
    184      1.1  joerg     const FormatStyle &CodeStyle) {
    185      1.1  joerg   for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
    186      1.1  joerg     llvm::Optional<FormatStyle> LanguageStyle =
    187      1.1  joerg         CodeStyle.GetLanguageStyle(RawStringFormat.Language);
    188      1.1  joerg     if (!LanguageStyle) {
    189      1.1  joerg       FormatStyle PredefinedStyle;
    190      1.1  joerg       if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
    191      1.1  joerg                               RawStringFormat.Language, &PredefinedStyle)) {
    192      1.1  joerg         PredefinedStyle = getLLVMStyle();
    193      1.1  joerg         PredefinedStyle.Language = RawStringFormat.Language;
    194      1.1  joerg       }
    195      1.1  joerg       LanguageStyle = PredefinedStyle;
    196      1.1  joerg     }
    197      1.1  joerg     LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
    198      1.1  joerg     for (StringRef Delimiter : RawStringFormat.Delimiters) {
    199      1.1  joerg       DelimiterStyle.insert({Delimiter, *LanguageStyle});
    200      1.1  joerg     }
    201      1.1  joerg     for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions) {
    202      1.1  joerg       EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
    203      1.1  joerg     }
    204      1.1  joerg   }
    205      1.1  joerg }
    206      1.1  joerg 
    207      1.1  joerg llvm::Optional<FormatStyle>
    208      1.1  joerg RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {
    209      1.1  joerg   auto It = DelimiterStyle.find(Delimiter);
    210      1.1  joerg   if (It == DelimiterStyle.end())
    211      1.1  joerg     return None;
    212      1.1  joerg   return It->second;
    213      1.1  joerg }
    214      1.1  joerg 
    215      1.1  joerg llvm::Optional<FormatStyle>
    216      1.1  joerg RawStringFormatStyleManager::getEnclosingFunctionStyle(
    217      1.1  joerg     StringRef EnclosingFunction) const {
    218      1.1  joerg   auto It = EnclosingFunctionStyle.find(EnclosingFunction);
    219      1.1  joerg   if (It == EnclosingFunctionStyle.end())
    220      1.1  joerg     return None;
    221      1.1  joerg   return It->second;
    222      1.1  joerg }
    223      1.1  joerg 
    224      1.1  joerg ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
    225      1.1  joerg                                            const AdditionalKeywords &Keywords,
    226      1.1  joerg                                            const SourceManager &SourceMgr,
    227      1.1  joerg                                            WhitespaceManager &Whitespaces,
    228      1.1  joerg                                            encoding::Encoding Encoding,
    229      1.1  joerg                                            bool BinPackInconclusiveFunctions)
    230      1.1  joerg     : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
    231      1.1  joerg       Whitespaces(Whitespaces), Encoding(Encoding),
    232      1.1  joerg       BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
    233      1.1  joerg       CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
    234      1.1  joerg 
    235      1.1  joerg LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
    236      1.1  joerg                                                 unsigned FirstStartColumn,
    237      1.1  joerg                                                 const AnnotatedLine *Line,
    238      1.1  joerg                                                 bool DryRun) {
    239      1.1  joerg   LineState State;
    240      1.1  joerg   State.FirstIndent = FirstIndent;
    241      1.1  joerg   if (FirstStartColumn && Line->First->NewlinesBefore == 0)
    242      1.1  joerg     State.Column = FirstStartColumn;
    243      1.1  joerg   else
    244      1.1  joerg     State.Column = FirstIndent;
    245      1.1  joerg   // With preprocessor directive indentation, the line starts on column 0
    246      1.1  joerg   // since it's indented after the hash, but FirstIndent is set to the
    247      1.1  joerg   // preprocessor indent.
    248      1.1  joerg   if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
    249      1.1  joerg       (Line->Type == LT_PreprocessorDirective ||
    250      1.1  joerg        Line->Type == LT_ImportStatement))
    251      1.1  joerg     State.Column = 0;
    252      1.1  joerg   State.Line = Line;
    253      1.1  joerg   State.NextToken = Line->First;
    254      1.1  joerg   State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,
    255      1.1  joerg                                    /*AvoidBinPacking=*/false,
    256      1.1  joerg                                    /*NoLineBreak=*/false));
    257      1.1  joerg   State.LineContainsContinuedForLoopSection = false;
    258      1.1  joerg   State.NoContinuation = false;
    259      1.1  joerg   State.StartOfStringLiteral = 0;
    260      1.1  joerg   State.StartOfLineLevel = 0;
    261      1.1  joerg   State.LowestLevelOnLine = 0;
    262      1.1  joerg   State.IgnoreStackForComparison = false;
    263      1.1  joerg 
    264      1.1  joerg   if (Style.Language == FormatStyle::LK_TextProto) {
    265      1.1  joerg     // We need this in order to deal with the bin packing of text fields at
    266      1.1  joerg     // global scope.
    267      1.1  joerg     State.Stack.back().AvoidBinPacking = true;
    268      1.1  joerg     State.Stack.back().BreakBeforeParameter = true;
    269      1.1  joerg     State.Stack.back().AlignColons = false;
    270      1.1  joerg   }
    271      1.1  joerg 
    272      1.1  joerg   // The first token has already been indented and thus consumed.
    273      1.1  joerg   moveStateToNextToken(State, DryRun, /*Newline=*/false);
    274      1.1  joerg   return State;
    275      1.1  joerg }
    276      1.1  joerg 
    277      1.1  joerg bool ContinuationIndenter::canBreak(const LineState &State) {
    278      1.1  joerg   const FormatToken &Current = *State.NextToken;
    279      1.1  joerg   const FormatToken &Previous = *Current.Previous;
    280      1.1  joerg   assert(&Previous == Current.Previous);
    281      1.1  joerg   if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace &&
    282      1.1  joerg                                    Current.closesBlockOrBlockTypeList(Style)))
    283      1.1  joerg     return false;
    284      1.1  joerg   // The opening "{" of a braced list has to be on the same line as the first
    285      1.1  joerg   // element if it is nested in another braced init list or function call.
    286      1.1  joerg   if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
    287  1.1.1.2  joerg       Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) &&
    288      1.1  joerg       Previous.Previous &&
    289      1.1  joerg       Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma))
    290      1.1  joerg     return false;
    291      1.1  joerg   // This prevents breaks like:
    292      1.1  joerg   //   ...
    293      1.1  joerg   //   SomeParameter, OtherParameter).DoSomething(
    294      1.1  joerg   //   ...
    295      1.1  joerg   // As they hide "DoSomething" and are generally bad for readability.
    296      1.1  joerg   if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
    297      1.1  joerg       State.LowestLevelOnLine < State.StartOfLineLevel &&
    298      1.1  joerg       State.LowestLevelOnLine < Current.NestingLevel)
    299      1.1  joerg     return false;
    300      1.1  joerg   if (Current.isMemberAccess() && State.Stack.back().ContainsUnwrappedBuilder)
    301      1.1  joerg     return false;
    302      1.1  joerg 
    303      1.1  joerg   // Don't create a 'hanging' indent if there are multiple blocks in a single
    304      1.1  joerg   // statement.
    305      1.1  joerg   if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
    306      1.1  joerg       State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
    307      1.1  joerg       State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks)
    308      1.1  joerg     return false;
    309      1.1  joerg 
    310      1.1  joerg   // Don't break after very short return types (e.g. "void") as that is often
    311      1.1  joerg   // unexpected.
    312      1.1  joerg   if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
    313      1.1  joerg     if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
    314      1.1  joerg       return false;
    315      1.1  joerg   }
    316      1.1  joerg 
    317      1.1  joerg   // If binary operators are moved to the next line (including commas for some
    318      1.1  joerg   // styles of constructor initializers), that's always ok.
    319      1.1  joerg   if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
    320      1.1  joerg       State.Stack.back().NoLineBreakInOperand)
    321      1.1  joerg     return false;
    322      1.1  joerg 
    323      1.1  joerg   if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
    324      1.1  joerg     return false;
    325      1.1  joerg 
    326      1.1  joerg   return !State.Stack.back().NoLineBreak;
    327      1.1  joerg }
    328      1.1  joerg 
    329      1.1  joerg bool ContinuationIndenter::mustBreak(const LineState &State) {
    330      1.1  joerg   const FormatToken &Current = *State.NextToken;
    331      1.1  joerg   const FormatToken &Previous = *Current.Previous;
    332  1.1.1.2  joerg   if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
    333  1.1.1.2  joerg       Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
    334  1.1.1.2  joerg     auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
    335  1.1.1.2  joerg     return (LambdaBodyLength > getColumnLimit(State));
    336  1.1.1.2  joerg   }
    337      1.1  joerg   if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
    338      1.1  joerg     return true;
    339      1.1  joerg   if (State.Stack.back().BreakBeforeClosingBrace &&
    340      1.1  joerg       Current.closesBlockOrBlockTypeList(Style))
    341      1.1  joerg     return true;
    342      1.1  joerg   if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection)
    343      1.1  joerg     return true;
    344      1.1  joerg   if (Style.Language == FormatStyle::LK_ObjC &&
    345  1.1.1.2  joerg       Style.ObjCBreakBeforeNestedBlockParam &&
    346      1.1  joerg       Current.ObjCSelectorNameParts > 1 &&
    347      1.1  joerg       Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
    348      1.1  joerg     return true;
    349      1.1  joerg   }
    350  1.1.1.2  joerg   // Avoid producing inconsistent states by requiring breaks where they are not
    351  1.1.1.2  joerg   // permitted for C# generic type constraints.
    352  1.1.1.2  joerg   if (State.Stack.back().IsCSharpGenericTypeConstraint &&
    353  1.1.1.2  joerg       Previous.isNot(TT_CSharpGenericTypeConstraintComma))
    354  1.1.1.2  joerg     return false;
    355      1.1  joerg   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
    356      1.1  joerg        (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
    357      1.1  joerg         Style.isCpp() &&
    358      1.1  joerg         // FIXME: This is a temporary workaround for the case where clang-format
    359      1.1  joerg         // sets BreakBeforeParameter to avoid bin packing and this creates a
    360      1.1  joerg         // completely unnecessary line break after a template type that isn't
    361      1.1  joerg         // line-wrapped.
    362      1.1  joerg         (Previous.NestingLevel == 1 || Style.BinPackParameters)) ||
    363      1.1  joerg        (Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
    364      1.1  joerg         Previous.isNot(tok::question)) ||
    365      1.1  joerg        (!Style.BreakBeforeTernaryOperators &&
    366      1.1  joerg         Previous.is(TT_ConditionalExpr))) &&
    367      1.1  joerg       State.Stack.back().BreakBeforeParameter && !Current.isTrailingComment() &&
    368      1.1  joerg       !Current.isOneOf(tok::r_paren, tok::r_brace))
    369      1.1  joerg     return true;
    370  1.1.1.2  joerg   if (State.Stack.back().IsChainedConditional &&
    371  1.1.1.2  joerg       ((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
    372  1.1.1.2  joerg         Current.is(tok::colon)) ||
    373  1.1.1.2  joerg        (!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) &&
    374  1.1.1.2  joerg         Previous.is(tok::colon))))
    375  1.1.1.2  joerg     return true;
    376      1.1  joerg   if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
    377      1.1  joerg        (Previous.is(TT_ArrayInitializerLSquare) &&
    378      1.1  joerg         Previous.ParameterCount > 1) ||
    379      1.1  joerg        opensProtoMessageField(Previous, Style)) &&
    380      1.1  joerg       Style.ColumnLimit > 0 &&
    381      1.1  joerg       getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
    382      1.1  joerg           getColumnLimit(State))
    383      1.1  joerg     return true;
    384      1.1  joerg 
    385      1.1  joerg   const FormatToken &BreakConstructorInitializersToken =
    386      1.1  joerg       Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
    387      1.1  joerg           ? Previous
    388      1.1  joerg           : Current;
    389      1.1  joerg   if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
    390      1.1  joerg       (State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
    391      1.1  joerg            getColumnLimit(State) ||
    392      1.1  joerg        State.Stack.back().BreakBeforeParameter) &&
    393      1.1  joerg       (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All ||
    394      1.1  joerg        Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon ||
    395      1.1  joerg        Style.ColumnLimit != 0))
    396      1.1  joerg     return true;
    397      1.1  joerg 
    398      1.1  joerg   if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
    399      1.1  joerg       State.Line->startsWith(TT_ObjCMethodSpecifier))
    400      1.1  joerg     return true;
    401      1.1  joerg   if (Current.is(TT_SelectorName) && !Previous.is(tok::at) &&
    402      1.1  joerg       State.Stack.back().ObjCSelectorNameFound &&
    403  1.1.1.2  joerg       State.Stack.back().BreakBeforeParameter &&
    404  1.1.1.2  joerg       (Style.ObjCBreakBeforeNestedBlockParam ||
    405  1.1.1.2  joerg        !Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)))
    406      1.1  joerg     return true;
    407      1.1  joerg 
    408      1.1  joerg   unsigned NewLineColumn = getNewLineColumn(State);
    409      1.1  joerg   if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
    410      1.1  joerg       State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
    411      1.1  joerg       (State.Column > NewLineColumn ||
    412      1.1  joerg        Current.NestingLevel < State.StartOfLineLevel))
    413      1.1  joerg     return true;
    414      1.1  joerg 
    415      1.1  joerg   if (startsSegmentOfBuilderTypeCall(Current) &&
    416      1.1  joerg       (State.Stack.back().CallContinuation != 0 ||
    417      1.1  joerg        State.Stack.back().BreakBeforeParameter) &&
    418      1.1  joerg       // JavaScript is treated different here as there is a frequent pattern:
    419      1.1  joerg       //   SomeFunction(function() {
    420      1.1  joerg       //     ...
    421      1.1  joerg       //   }.bind(...));
    422      1.1  joerg       // FIXME: We should find a more generic solution to this problem.
    423      1.1  joerg       !(State.Column <= NewLineColumn &&
    424      1.1  joerg         Style.Language == FormatStyle::LK_JavaScript) &&
    425      1.1  joerg       !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn))
    426      1.1  joerg     return true;
    427      1.1  joerg 
    428      1.1  joerg   // If the template declaration spans multiple lines, force wrap before the
    429      1.1  joerg   // function/class declaration
    430      1.1  joerg   if (Previous.ClosesTemplateDeclaration &&
    431      1.1  joerg       State.Stack.back().BreakBeforeParameter && Current.CanBreakBefore)
    432      1.1  joerg     return true;
    433      1.1  joerg 
    434  1.1.1.2  joerg   if (!State.Line->First->is(tok::kw_enum) && State.Column <= NewLineColumn)
    435      1.1  joerg     return false;
    436      1.1  joerg 
    437      1.1  joerg   if (Style.AlwaysBreakBeforeMultilineStrings &&
    438      1.1  joerg       (NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
    439      1.1  joerg        Previous.is(tok::comma) || Current.NestingLevel < 2) &&
    440      1.1  joerg       !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,
    441      1.1  joerg                         Keywords.kw_dollar) &&
    442      1.1  joerg       !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
    443      1.1  joerg       nextIsMultilineString(State))
    444      1.1  joerg     return true;
    445      1.1  joerg 
    446      1.1  joerg   // Using CanBreakBefore here and below takes care of the decision whether the
    447      1.1  joerg   // current style uses wrapping before or after operators for the given
    448      1.1  joerg   // operator.
    449      1.1  joerg   if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
    450      1.1  joerg     // If we need to break somewhere inside the LHS of a binary expression, we
    451      1.1  joerg     // should also break after the operator. Otherwise, the formatting would
    452      1.1  joerg     // hide the operator precedence, e.g. in:
    453      1.1  joerg     //   if (aaaaaaaaaaaaaa ==
    454      1.1  joerg     //           bbbbbbbbbbbbbb && c) {..
    455      1.1  joerg     // For comparisons, we only apply this rule, if the LHS is a binary
    456      1.1  joerg     // expression itself as otherwise, the line breaks seem superfluous.
    457      1.1  joerg     // We need special cases for ">>" which we have split into two ">" while
    458      1.1  joerg     // lexing in order to make template parsing easier.
    459      1.1  joerg     bool IsComparison = (Previous.getPrecedence() == prec::Relational ||
    460      1.1  joerg                          Previous.getPrecedence() == prec::Equality ||
    461      1.1  joerg                          Previous.getPrecedence() == prec::Spaceship) &&
    462      1.1  joerg                         Previous.Previous &&
    463      1.1  joerg                         Previous.Previous->isNot(TT_BinaryOperator); // For >>.
    464      1.1  joerg     bool LHSIsBinaryExpr =
    465      1.1  joerg         Previous.Previous && Previous.Previous->EndsBinaryExpression;
    466      1.1  joerg     if ((!IsComparison || LHSIsBinaryExpr) && !Current.isTrailingComment() &&
    467      1.1  joerg         Previous.getPrecedence() != prec::Assignment &&
    468      1.1  joerg         State.Stack.back().BreakBeforeParameter)
    469      1.1  joerg       return true;
    470      1.1  joerg   } else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
    471      1.1  joerg              State.Stack.back().BreakBeforeParameter) {
    472      1.1  joerg     return true;
    473      1.1  joerg   }
    474      1.1  joerg 
    475      1.1  joerg   // Same as above, but for the first "<<" operator.
    476      1.1  joerg   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
    477      1.1  joerg       State.Stack.back().BreakBeforeParameter &&
    478      1.1  joerg       State.Stack.back().FirstLessLess == 0)
    479      1.1  joerg     return true;
    480      1.1  joerg 
    481      1.1  joerg   if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
    482      1.1  joerg     // Always break after "template <...>" and leading annotations. This is only
    483      1.1  joerg     // for cases where the entire line does not fit on a single line as a
    484      1.1  joerg     // different LineFormatter would be used otherwise.
    485      1.1  joerg     if (Previous.ClosesTemplateDeclaration)
    486      1.1  joerg       return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No;
    487      1.1  joerg     if (Previous.is(TT_FunctionAnnotationRParen))
    488      1.1  joerg       return true;
    489      1.1  joerg     if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
    490      1.1  joerg         Current.isNot(TT_LeadingJavaAnnotation))
    491      1.1  joerg       return true;
    492      1.1  joerg   }
    493      1.1  joerg 
    494      1.1  joerg   // If the return type spans multiple lines, wrap before the function name.
    495      1.1  joerg   if (((Current.is(TT_FunctionDeclarationName) &&
    496      1.1  joerg         // Don't break before a C# function when no break after return type
    497      1.1  joerg         (!Style.isCSharp() ||
    498      1.1  joerg          Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None)) ||
    499      1.1  joerg        (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
    500      1.1  joerg       !Previous.is(tok::kw_template) && State.Stack.back().BreakBeforeParameter)
    501      1.1  joerg     return true;
    502      1.1  joerg 
    503      1.1  joerg   // The following could be precomputed as they do not depend on the state.
    504      1.1  joerg   // However, as they should take effect only if the UnwrappedLine does not fit
    505      1.1  joerg   // into the ColumnLimit, they are checked here in the ContinuationIndenter.
    506  1.1.1.2  joerg   if (Style.ColumnLimit != 0 && Previous.is(BK_Block) &&
    507      1.1  joerg       Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment))
    508      1.1  joerg     return true;
    509      1.1  joerg 
    510      1.1  joerg   if (Current.is(tok::lessless) &&
    511      1.1  joerg       ((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
    512      1.1  joerg        (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") ||
    513      1.1  joerg                                      Previous.TokenText == "\'\\n\'"))))
    514      1.1  joerg     return true;
    515      1.1  joerg 
    516      1.1  joerg   if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
    517      1.1  joerg     return true;
    518      1.1  joerg 
    519      1.1  joerg   if (State.NoContinuation)
    520      1.1  joerg     return true;
    521      1.1  joerg 
    522      1.1  joerg   return false;
    523      1.1  joerg }
    524      1.1  joerg 
    525      1.1  joerg unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
    526      1.1  joerg                                                bool DryRun,
    527      1.1  joerg                                                unsigned ExtraSpaces) {
    528      1.1  joerg   const FormatToken &Current = *State.NextToken;
    529      1.1  joerg 
    530      1.1  joerg   assert(!State.Stack.empty());
    531      1.1  joerg   State.NoContinuation = false;
    532      1.1  joerg 
    533      1.1  joerg   if ((Current.is(TT_ImplicitStringLiteral) &&
    534      1.1  joerg        (Current.Previous->Tok.getIdentifierInfo() == nullptr ||
    535      1.1  joerg         Current.Previous->Tok.getIdentifierInfo()->getPPKeywordID() ==
    536      1.1  joerg             tok::pp_not_keyword))) {
    537      1.1  joerg     unsigned EndColumn =
    538      1.1  joerg         SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
    539      1.1  joerg     if (Current.LastNewlineOffset != 0) {
    540      1.1  joerg       // If there is a newline within this token, the final column will solely
    541      1.1  joerg       // determined by the current end column.
    542      1.1  joerg       State.Column = EndColumn;
    543      1.1  joerg     } else {
    544      1.1  joerg       unsigned StartColumn =
    545      1.1  joerg           SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
    546      1.1  joerg       assert(EndColumn >= StartColumn);
    547      1.1  joerg       State.Column += EndColumn - StartColumn;
    548      1.1  joerg     }
    549      1.1  joerg     moveStateToNextToken(State, DryRun, /*Newline=*/false);
    550      1.1  joerg     return 0;
    551      1.1  joerg   }
    552      1.1  joerg 
    553      1.1  joerg   unsigned Penalty = 0;
    554      1.1  joerg   if (Newline)
    555      1.1  joerg     Penalty = addTokenOnNewLine(State, DryRun);
    556      1.1  joerg   else
    557      1.1  joerg     addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
    558      1.1  joerg 
    559      1.1  joerg   return moveStateToNextToken(State, DryRun, Newline) + Penalty;
    560      1.1  joerg }
    561      1.1  joerg 
    562      1.1  joerg void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
    563      1.1  joerg                                                  unsigned ExtraSpaces) {
    564      1.1  joerg   FormatToken &Current = *State.NextToken;
    565      1.1  joerg   const FormatToken &Previous = *State.NextToken->Previous;
    566      1.1  joerg   if (Current.is(tok::equal) &&
    567      1.1  joerg       (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
    568      1.1  joerg       State.Stack.back().VariablePos == 0) {
    569      1.1  joerg     State.Stack.back().VariablePos = State.Column;
    570      1.1  joerg     // Move over * and & if they are bound to the variable name.
    571      1.1  joerg     const FormatToken *Tok = &Previous;
    572      1.1  joerg     while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) {
    573      1.1  joerg       State.Stack.back().VariablePos -= Tok->ColumnWidth;
    574      1.1  joerg       if (Tok->SpacesRequiredBefore != 0)
    575      1.1  joerg         break;
    576      1.1  joerg       Tok = Tok->Previous;
    577      1.1  joerg     }
    578      1.1  joerg     if (Previous.PartOfMultiVariableDeclStmt)
    579      1.1  joerg       State.Stack.back().LastSpace = State.Stack.back().VariablePos;
    580      1.1  joerg   }
    581      1.1  joerg 
    582      1.1  joerg   unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
    583      1.1  joerg 
    584      1.1  joerg   // Indent preprocessor directives after the hash if required.
    585      1.1  joerg   int PPColumnCorrection = 0;
    586      1.1  joerg   if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
    587      1.1  joerg       Previous.is(tok::hash) && State.FirstIndent > 0 &&
    588      1.1  joerg       (State.Line->Type == LT_PreprocessorDirective ||
    589      1.1  joerg        State.Line->Type == LT_ImportStatement)) {
    590      1.1  joerg     Spaces += State.FirstIndent;
    591      1.1  joerg 
    592      1.1  joerg     // For preprocessor indent with tabs, State.Column will be 1 because of the
    593      1.1  joerg     // hash. This causes second-level indents onward to have an extra space
    594      1.1  joerg     // after the tabs. We avoid this misalignment by subtracting 1 from the
    595      1.1  joerg     // column value passed to replaceWhitespace().
    596      1.1  joerg     if (Style.UseTab != FormatStyle::UT_Never)
    597      1.1  joerg       PPColumnCorrection = -1;
    598      1.1  joerg   }
    599      1.1  joerg 
    600      1.1  joerg   if (!DryRun)
    601      1.1  joerg     Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
    602      1.1  joerg                                   State.Column + Spaces + PPColumnCorrection);
    603      1.1  joerg 
    604      1.1  joerg   // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
    605      1.1  joerg   // declaration unless there is multiple inheritance.
    606      1.1  joerg   if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
    607      1.1  joerg       Current.is(TT_InheritanceColon))
    608      1.1  joerg     State.Stack.back().NoLineBreak = true;
    609      1.1  joerg   if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon &&
    610      1.1  joerg       Previous.is(TT_InheritanceColon))
    611      1.1  joerg     State.Stack.back().NoLineBreak = true;
    612      1.1  joerg 
    613      1.1  joerg   if (Current.is(TT_SelectorName) &&
    614      1.1  joerg       !State.Stack.back().ObjCSelectorNameFound) {
    615      1.1  joerg     unsigned MinIndent =
    616      1.1  joerg         std::max(State.FirstIndent + Style.ContinuationIndentWidth,
    617      1.1  joerg                  State.Stack.back().Indent);
    618      1.1  joerg     unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
    619      1.1  joerg     if (Current.LongestObjCSelectorName == 0)
    620      1.1  joerg       State.Stack.back().AlignColons = false;
    621      1.1  joerg     else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
    622      1.1  joerg       State.Stack.back().ColonPos = MinIndent + Current.LongestObjCSelectorName;
    623      1.1  joerg     else
    624      1.1  joerg       State.Stack.back().ColonPos = FirstColonPos;
    625      1.1  joerg   }
    626      1.1  joerg 
    627      1.1  joerg   // In "AlwaysBreak" mode, enforce wrapping directly after the parenthesis by
    628      1.1  joerg   // disallowing any further line breaks if there is no line break after the
    629      1.1  joerg   // opening parenthesis. Don't break if it doesn't conserve columns.
    630      1.1  joerg   if (Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak &&
    631      1.1  joerg       (Previous.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) ||
    632  1.1.1.2  joerg        (Previous.is(tok::l_brace) && Previous.isNot(BK_Block) &&
    633      1.1  joerg         Style.Cpp11BracedListStyle)) &&
    634      1.1  joerg       State.Column > getNewLineColumn(State) &&
    635      1.1  joerg       (!Previous.Previous || !Previous.Previous->isOneOf(
    636      1.1  joerg                                  tok::kw_for, tok::kw_while, tok::kw_switch)) &&
    637      1.1  joerg       // Don't do this for simple (no expressions) one-argument function calls
    638      1.1  joerg       // as that feels like needlessly wasting whitespace, e.g.:
    639      1.1  joerg       //
    640      1.1  joerg       //   caaaaaaaaaaaall(
    641      1.1  joerg       //       caaaaaaaaaaaall(
    642      1.1  joerg       //           caaaaaaaaaaaall(
    643      1.1  joerg       //               caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
    644      1.1  joerg       Current.FakeLParens.size() > 0 &&
    645      1.1  joerg       Current.FakeLParens.back() > prec::Unknown)
    646      1.1  joerg     State.Stack.back().NoLineBreak = true;
    647      1.1  joerg   if (Previous.is(TT_TemplateString) && Previous.opensScope())
    648      1.1  joerg     State.Stack.back().NoLineBreak = true;
    649      1.1  joerg 
    650      1.1  joerg   if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
    651  1.1.1.2  joerg       !State.Stack.back().IsCSharpGenericTypeConstraint &&
    652      1.1  joerg       Previous.opensScope() && Previous.isNot(TT_ObjCMethodExpr) &&
    653  1.1.1.2  joerg       (Current.isNot(TT_LineComment) || Previous.is(BK_BracedInit))) {
    654      1.1  joerg     State.Stack.back().Indent = State.Column + Spaces;
    655  1.1.1.2  joerg     State.Stack.back().IsAligned = true;
    656  1.1.1.2  joerg   }
    657      1.1  joerg   if (State.Stack.back().AvoidBinPacking && startsNextParameter(Current, Style))
    658      1.1  joerg     State.Stack.back().NoLineBreak = true;
    659      1.1  joerg   if (startsSegmentOfBuilderTypeCall(Current) &&
    660      1.1  joerg       State.Column > getNewLineColumn(State))
    661      1.1  joerg     State.Stack.back().ContainsUnwrappedBuilder = true;
    662      1.1  joerg 
    663      1.1  joerg   if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
    664      1.1  joerg     State.Stack.back().NoLineBreak = true;
    665      1.1  joerg   if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
    666      1.1  joerg       (Previous.MatchingParen &&
    667      1.1  joerg        (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10)))
    668      1.1  joerg     // If there is a function call with long parameters, break before trailing
    669      1.1  joerg     // calls. This prevents things like:
    670      1.1  joerg     //   EXPECT_CALL(SomeLongParameter).Times(
    671      1.1  joerg     //       2);
    672      1.1  joerg     // We don't want to do this for short parameters as they can just be
    673      1.1  joerg     // indexes.
    674      1.1  joerg     State.Stack.back().NoLineBreak = true;
    675      1.1  joerg 
    676      1.1  joerg   // Don't allow the RHS of an operator to be split over multiple lines unless
    677      1.1  joerg   // there is a line-break right after the operator.
    678      1.1  joerg   // Exclude relational operators, as there, it is always more desirable to
    679      1.1  joerg   // have the LHS 'left' of the RHS.
    680      1.1  joerg   const FormatToken *P = Current.getPreviousNonComment();
    681      1.1  joerg   if (!Current.is(tok::comment) && P &&
    682      1.1  joerg       (P->isOneOf(TT_BinaryOperator, tok::comma) ||
    683      1.1  joerg        (P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
    684      1.1  joerg       !P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
    685      1.1  joerg       P->getPrecedence() != prec::Assignment &&
    686      1.1  joerg       P->getPrecedence() != prec::Relational &&
    687      1.1  joerg       P->getPrecedence() != prec::Spaceship) {
    688      1.1  joerg     bool BreakBeforeOperator =
    689      1.1  joerg         P->MustBreakBefore || P->is(tok::lessless) ||
    690      1.1  joerg         (P->is(TT_BinaryOperator) &&
    691      1.1  joerg          Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
    692      1.1  joerg         (P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
    693      1.1  joerg     // Don't do this if there are only two operands. In these cases, there is
    694      1.1  joerg     // always a nice vertical separation between them and the extra line break
    695      1.1  joerg     // does not help.
    696      1.1  joerg     bool HasTwoOperands =
    697      1.1  joerg         P->OperatorIndex == 0 && !P->NextOperator && !P->is(TT_ConditionalExpr);
    698  1.1.1.2  joerg     if ((!BreakBeforeOperator &&
    699  1.1.1.2  joerg          !(HasTwoOperands &&
    700  1.1.1.2  joerg            Style.AlignOperands != FormatStyle::OAS_DontAlign)) ||
    701      1.1  joerg         (!State.Stack.back().LastOperatorWrapped && BreakBeforeOperator))
    702      1.1  joerg       State.Stack.back().NoLineBreakInOperand = true;
    703      1.1  joerg   }
    704      1.1  joerg 
    705      1.1  joerg   State.Column += Spaces;
    706      1.1  joerg   if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
    707      1.1  joerg       Previous.Previous &&
    708      1.1  joerg       (Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
    709      1.1  joerg     // Treat the condition inside an if as if it was a second function
    710      1.1  joerg     // parameter, i.e. let nested calls have a continuation indent.
    711      1.1  joerg     State.Stack.back().LastSpace = State.Column;
    712      1.1  joerg     State.Stack.back().NestedBlockIndent = State.Column;
    713      1.1  joerg   } else if (!Current.isOneOf(tok::comment, tok::caret) &&
    714      1.1  joerg              ((Previous.is(tok::comma) &&
    715      1.1  joerg                !Previous.is(TT_OverloadedOperator)) ||
    716      1.1  joerg               (Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
    717      1.1  joerg     State.Stack.back().LastSpace = State.Column;
    718      1.1  joerg   } else if (Previous.is(TT_CtorInitializerColon) &&
    719      1.1  joerg              Style.BreakConstructorInitializers ==
    720      1.1  joerg                  FormatStyle::BCIS_AfterColon) {
    721      1.1  joerg     State.Stack.back().Indent = State.Column;
    722      1.1  joerg     State.Stack.back().LastSpace = State.Column;
    723      1.1  joerg   } else if ((Previous.isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
    724      1.1  joerg                                TT_CtorInitializerColon)) &&
    725      1.1  joerg              ((Previous.getPrecedence() != prec::Assignment &&
    726      1.1  joerg                (Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
    727      1.1  joerg                 Previous.NextOperator)) ||
    728      1.1  joerg               Current.StartsBinaryExpression)) {
    729      1.1  joerg     // Indent relative to the RHS of the expression unless this is a simple
    730      1.1  joerg     // assignment without binary expression on the RHS. Also indent relative to
    731      1.1  joerg     // unary operators and the colons of constructor initializers.
    732      1.1  joerg     if (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None)
    733      1.1  joerg       State.Stack.back().LastSpace = State.Column;
    734      1.1  joerg   } else if (Previous.is(TT_InheritanceColon)) {
    735      1.1  joerg     State.Stack.back().Indent = State.Column;
    736      1.1  joerg     State.Stack.back().LastSpace = State.Column;
    737  1.1.1.2  joerg   } else if (Current.is(TT_CSharpGenericTypeConstraintColon)) {
    738  1.1.1.2  joerg     State.Stack.back().ColonPos = State.Column;
    739      1.1  joerg   } else if (Previous.opensScope()) {
    740      1.1  joerg     // If a function has a trailing call, indent all parameters from the
    741      1.1  joerg     // opening parenthesis. This avoids confusing indents like:
    742      1.1  joerg     //   OuterFunction(InnerFunctionCall( // break
    743      1.1  joerg     //       ParameterToInnerFunction))   // break
    744      1.1  joerg     //       .SecondInnerFunctionCall();
    745      1.1  joerg     bool HasTrailingCall = false;
    746      1.1  joerg     if (Previous.MatchingParen) {
    747      1.1  joerg       const FormatToken *Next = Previous.MatchingParen->getNextNonComment();
    748      1.1  joerg       HasTrailingCall = Next && Next->isMemberAccess();
    749      1.1  joerg     }
    750      1.1  joerg     if (HasTrailingCall && State.Stack.size() > 1 &&
    751      1.1  joerg         State.Stack[State.Stack.size() - 2].CallContinuation == 0)
    752      1.1  joerg       State.Stack.back().LastSpace = State.Column;
    753      1.1  joerg   }
    754      1.1  joerg }
    755      1.1  joerg 
    756      1.1  joerg unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
    757      1.1  joerg                                                  bool DryRun) {
    758      1.1  joerg   FormatToken &Current = *State.NextToken;
    759      1.1  joerg   const FormatToken &Previous = *State.NextToken->Previous;
    760      1.1  joerg 
    761      1.1  joerg   // Extra penalty that needs to be added because of the way certain line
    762      1.1  joerg   // breaks are chosen.
    763      1.1  joerg   unsigned Penalty = 0;
    764      1.1  joerg 
    765      1.1  joerg   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
    766      1.1  joerg   const FormatToken *NextNonComment = Previous.getNextNonComment();
    767      1.1  joerg   if (!NextNonComment)
    768      1.1  joerg     NextNonComment = &Current;
    769      1.1  joerg   // The first line break on any NestingLevel causes an extra penalty in order
    770      1.1  joerg   // prefer similar line breaks.
    771      1.1  joerg   if (!State.Stack.back().ContainsLineBreak)
    772      1.1  joerg     Penalty += 15;
    773      1.1  joerg   State.Stack.back().ContainsLineBreak = true;
    774      1.1  joerg 
    775      1.1  joerg   Penalty += State.NextToken->SplitPenalty;
    776      1.1  joerg 
    777      1.1  joerg   // Breaking before the first "<<" is generally not desirable if the LHS is
    778      1.1  joerg   // short. Also always add the penalty if the LHS is split over multiple lines
    779      1.1  joerg   // to avoid unnecessary line breaks that just work around this penalty.
    780      1.1  joerg   if (NextNonComment->is(tok::lessless) &&
    781      1.1  joerg       State.Stack.back().FirstLessLess == 0 &&
    782      1.1  joerg       (State.Column <= Style.ColumnLimit / 3 ||
    783      1.1  joerg        State.Stack.back().BreakBeforeParameter))
    784      1.1  joerg     Penalty += Style.PenaltyBreakFirstLessLess;
    785      1.1  joerg 
    786      1.1  joerg   State.Column = getNewLineColumn(State);
    787      1.1  joerg 
    788  1.1.1.2  joerg   // Add Penalty proportional to amount of whitespace away from FirstColumn
    789  1.1.1.2  joerg   // This tends to penalize several lines that are far-right indented,
    790  1.1.1.2  joerg   // and prefers a line-break prior to such a block, e.g:
    791  1.1.1.2  joerg   //
    792  1.1.1.2  joerg   // Constructor() :
    793  1.1.1.2  joerg   //   member(value), looooooooooooooooong_member(
    794  1.1.1.2  joerg   //                      looooooooooong_call(param_1, param_2, param_3))
    795  1.1.1.2  joerg   // would then become
    796  1.1.1.2  joerg   // Constructor() :
    797  1.1.1.2  joerg   //   member(value),
    798  1.1.1.2  joerg   //   looooooooooooooooong_member(
    799  1.1.1.2  joerg   //       looooooooooong_call(param_1, param_2, param_3))
    800  1.1.1.2  joerg   if (State.Column > State.FirstIndent)
    801  1.1.1.2  joerg     Penalty +=
    802  1.1.1.2  joerg         Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent);
    803  1.1.1.2  joerg 
    804      1.1  joerg   // Indent nested blocks relative to this column, unless in a very specific
    805      1.1  joerg   // JavaScript special case where:
    806      1.1  joerg   //
    807      1.1  joerg   //   var loooooong_name =
    808      1.1  joerg   //       function() {
    809      1.1  joerg   //     // code
    810      1.1  joerg   //   }
    811      1.1  joerg   //
    812      1.1  joerg   // is common and should be formatted like a free-standing function. The same
    813      1.1  joerg   // goes for wrapping before the lambda return type arrow.
    814      1.1  joerg   if (!Current.is(TT_LambdaArrow) &&
    815      1.1  joerg       (Style.Language != FormatStyle::LK_JavaScript ||
    816      1.1  joerg        Current.NestingLevel != 0 || !PreviousNonComment ||
    817      1.1  joerg        !PreviousNonComment->is(tok::equal) ||
    818      1.1  joerg        !Current.isOneOf(Keywords.kw_async, Keywords.kw_function)))
    819      1.1  joerg     State.Stack.back().NestedBlockIndent = State.Column;
    820      1.1  joerg 
    821      1.1  joerg   if (NextNonComment->isMemberAccess()) {
    822      1.1  joerg     if (State.Stack.back().CallContinuation == 0)
    823      1.1  joerg       State.Stack.back().CallContinuation = State.Column;
    824      1.1  joerg   } else if (NextNonComment->is(TT_SelectorName)) {
    825      1.1  joerg     if (!State.Stack.back().ObjCSelectorNameFound) {
    826      1.1  joerg       if (NextNonComment->LongestObjCSelectorName == 0) {
    827      1.1  joerg         State.Stack.back().AlignColons = false;
    828      1.1  joerg       } else {
    829      1.1  joerg         State.Stack.back().ColonPos =
    830      1.1  joerg             (shouldIndentWrappedSelectorName(Style, State.Line->Type)
    831      1.1  joerg                  ? std::max(State.Stack.back().Indent,
    832      1.1  joerg                             State.FirstIndent + Style.ContinuationIndentWidth)
    833      1.1  joerg                  : State.Stack.back().Indent) +
    834      1.1  joerg             std::max(NextNonComment->LongestObjCSelectorName,
    835      1.1  joerg                      NextNonComment->ColumnWidth);
    836      1.1  joerg       }
    837      1.1  joerg     } else if (State.Stack.back().AlignColons &&
    838      1.1  joerg                State.Stack.back().ColonPos <= NextNonComment->ColumnWidth) {
    839      1.1  joerg       State.Stack.back().ColonPos = State.Column + NextNonComment->ColumnWidth;
    840      1.1  joerg     }
    841      1.1  joerg   } else if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
    842      1.1  joerg              PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) {
    843      1.1  joerg     // FIXME: This is hacky, find a better way. The problem is that in an ObjC
    844      1.1  joerg     // method expression, the block should be aligned to the line starting it,
    845      1.1  joerg     // e.g.:
    846      1.1  joerg     //   [aaaaaaaaaaaaaaa aaaaaaaaa: \\ break for some reason
    847      1.1  joerg     //                        ^(int *i) {
    848      1.1  joerg     //                            // ...
    849      1.1  joerg     //                        }];
    850      1.1  joerg     // Thus, we set LastSpace of the next higher NestingLevel, to which we move
    851      1.1  joerg     // when we consume all of the "}"'s FakeRParens at the "{".
    852      1.1  joerg     if (State.Stack.size() > 1)
    853      1.1  joerg       State.Stack[State.Stack.size() - 2].LastSpace =
    854      1.1  joerg           std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
    855      1.1  joerg           Style.ContinuationIndentWidth;
    856      1.1  joerg   }
    857      1.1  joerg 
    858      1.1  joerg   if ((PreviousNonComment &&
    859      1.1  joerg        PreviousNonComment->isOneOf(tok::comma, tok::semi) &&
    860      1.1  joerg        !State.Stack.back().AvoidBinPacking) ||
    861      1.1  joerg       Previous.is(TT_BinaryOperator))
    862      1.1  joerg     State.Stack.back().BreakBeforeParameter = false;
    863      1.1  joerg   if (PreviousNonComment &&
    864      1.1  joerg       PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
    865      1.1  joerg       Current.NestingLevel == 0)
    866      1.1  joerg     State.Stack.back().BreakBeforeParameter = false;
    867      1.1  joerg   if (NextNonComment->is(tok::question) ||
    868      1.1  joerg       (PreviousNonComment && PreviousNonComment->is(tok::question)))
    869      1.1  joerg     State.Stack.back().BreakBeforeParameter = true;
    870      1.1  joerg   if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore)
    871      1.1  joerg     State.Stack.back().BreakBeforeParameter = false;
    872      1.1  joerg 
    873      1.1  joerg   if (!DryRun) {
    874      1.1  joerg     unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
    875      1.1  joerg     if (Current.is(tok::r_brace) && Current.MatchingParen &&
    876      1.1  joerg         // Only strip trailing empty lines for l_braces that have children, i.e.
    877      1.1  joerg         // for function expressions (lambdas, arrows, etc).
    878      1.1  joerg         !Current.MatchingParen->Children.empty()) {
    879      1.1  joerg       // lambdas and arrow functions are expressions, thus their r_brace is not
    880      1.1  joerg       // on its own line, and thus not covered by UnwrappedLineFormatter's logic
    881      1.1  joerg       // about removing empty lines on closing blocks. Special case them here.
    882      1.1  joerg       MaxEmptyLinesToKeep = 1;
    883      1.1  joerg     }
    884      1.1  joerg     unsigned Newlines =
    885      1.1  joerg         std::max(1u, std::min(Current.NewlinesBefore, MaxEmptyLinesToKeep));
    886      1.1  joerg     bool ContinuePPDirective =
    887      1.1  joerg         State.Line->InPPDirective && State.Line->Type != LT_ImportStatement;
    888      1.1  joerg     Whitespaces.replaceWhitespace(Current, Newlines, State.Column, State.Column,
    889  1.1.1.2  joerg                                   State.Stack.back().IsAligned,
    890      1.1  joerg                                   ContinuePPDirective);
    891      1.1  joerg   }
    892      1.1  joerg 
    893      1.1  joerg   if (!Current.isTrailingComment())
    894      1.1  joerg     State.Stack.back().LastSpace = State.Column;
    895      1.1  joerg   if (Current.is(tok::lessless))
    896      1.1  joerg     // If we are breaking before a "<<", we always want to indent relative to
    897      1.1  joerg     // RHS. This is necessary only for "<<", as we special-case it and don't
    898      1.1  joerg     // always indent relative to the RHS.
    899      1.1  joerg     State.Stack.back().LastSpace += 3; // 3 -> width of "<< ".
    900      1.1  joerg 
    901      1.1  joerg   State.StartOfLineLevel = Current.NestingLevel;
    902      1.1  joerg   State.LowestLevelOnLine = Current.NestingLevel;
    903      1.1  joerg 
    904      1.1  joerg   // Any break on this level means that the parent level has been broken
    905      1.1  joerg   // and we need to avoid bin packing there.
    906      1.1  joerg   bool NestedBlockSpecialCase =
    907  1.1.1.2  joerg       (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
    908  1.1.1.2  joerg        State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
    909  1.1.1.2  joerg       (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
    910  1.1.1.2  joerg        State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
    911      1.1  joerg   if (!NestedBlockSpecialCase)
    912      1.1  joerg     for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
    913      1.1  joerg       State.Stack[i].BreakBeforeParameter = true;
    914      1.1  joerg 
    915      1.1  joerg   if (PreviousNonComment &&
    916      1.1  joerg       !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
    917      1.1  joerg       (PreviousNonComment->isNot(TT_TemplateCloser) ||
    918      1.1  joerg        Current.NestingLevel != 0) &&
    919      1.1  joerg       !PreviousNonComment->isOneOf(
    920      1.1  joerg           TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
    921      1.1  joerg           TT_LeadingJavaAnnotation) &&
    922      1.1  joerg       Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope())
    923      1.1  joerg     State.Stack.back().BreakBeforeParameter = true;
    924      1.1  joerg 
    925      1.1  joerg   // If we break after { or the [ of an array initializer, we should also break
    926      1.1  joerg   // before the corresponding } or ].
    927      1.1  joerg   if (PreviousNonComment &&
    928      1.1  joerg       (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
    929      1.1  joerg        opensProtoMessageField(*PreviousNonComment, Style)))
    930      1.1  joerg     State.Stack.back().BreakBeforeClosingBrace = true;
    931      1.1  joerg 
    932      1.1  joerg   if (State.Stack.back().AvoidBinPacking) {
    933      1.1  joerg     // If we are breaking after '(', '{', '<', or this is the break after a ':'
    934      1.1  joerg     // to start a member initializater list in a constructor, this should not
    935      1.1  joerg     // be considered bin packing unless the relevant AllowAll option is false or
    936      1.1  joerg     // this is a dict/object literal.
    937      1.1  joerg     bool PreviousIsBreakingCtorInitializerColon =
    938      1.1  joerg         Previous.is(TT_CtorInitializerColon) &&
    939      1.1  joerg         Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
    940      1.1  joerg     if (!(Previous.isOneOf(tok::l_paren, tok::l_brace, TT_BinaryOperator) ||
    941      1.1  joerg           PreviousIsBreakingCtorInitializerColon) ||
    942      1.1  joerg         (!Style.AllowAllParametersOfDeclarationOnNextLine &&
    943      1.1  joerg          State.Line->MustBeDeclaration) ||
    944      1.1  joerg         (!Style.AllowAllArgumentsOnNextLine &&
    945      1.1  joerg          !State.Line->MustBeDeclaration) ||
    946      1.1  joerg         (!Style.AllowAllConstructorInitializersOnNextLine &&
    947      1.1  joerg          PreviousIsBreakingCtorInitializerColon) ||
    948      1.1  joerg         Previous.is(TT_DictLiteral))
    949      1.1  joerg       State.Stack.back().BreakBeforeParameter = true;
    950      1.1  joerg 
    951      1.1  joerg     // If we are breaking after a ':' to start a member initializer list,
    952      1.1  joerg     // and we allow all arguments on the next line, we should not break
    953      1.1  joerg     // before the next parameter.
    954      1.1  joerg     if (PreviousIsBreakingCtorInitializerColon &&
    955      1.1  joerg         Style.AllowAllConstructorInitializersOnNextLine)
    956      1.1  joerg       State.Stack.back().BreakBeforeParameter = false;
    957      1.1  joerg   }
    958      1.1  joerg 
    959      1.1  joerg   return Penalty;
    960      1.1  joerg }
    961      1.1  joerg 
    962      1.1  joerg unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
    963      1.1  joerg   if (!State.NextToken || !State.NextToken->Previous)
    964      1.1  joerg     return 0;
    965  1.1.1.2  joerg 
    966      1.1  joerg   FormatToken &Current = *State.NextToken;
    967  1.1.1.2  joerg 
    968  1.1.1.2  joerg   if (State.Stack.back().IsCSharpGenericTypeConstraint &&
    969  1.1.1.2  joerg       Current.isNot(TT_CSharpGenericTypeConstraint))
    970  1.1.1.2  joerg     return State.Stack.back().ColonPos + 2;
    971  1.1.1.2  joerg 
    972      1.1  joerg   const FormatToken &Previous = *Current.Previous;
    973      1.1  joerg   // If we are continuing an expression, we want to use the continuation indent.
    974      1.1  joerg   unsigned ContinuationIndent =
    975      1.1  joerg       std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) +
    976      1.1  joerg       Style.ContinuationIndentWidth;
    977      1.1  joerg   const FormatToken *PreviousNonComment = Current.getPreviousNonComment();
    978      1.1  joerg   const FormatToken *NextNonComment = Previous.getNextNonComment();
    979      1.1  joerg   if (!NextNonComment)
    980      1.1  joerg     NextNonComment = &Current;
    981      1.1  joerg 
    982      1.1  joerg   // Java specific bits.
    983      1.1  joerg   if (Style.Language == FormatStyle::LK_Java &&
    984      1.1  joerg       Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends))
    985      1.1  joerg     return std::max(State.Stack.back().LastSpace,
    986      1.1  joerg                     State.Stack.back().Indent + Style.ContinuationIndentWidth);
    987      1.1  joerg 
    988      1.1  joerg   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
    989      1.1  joerg       State.Line->First->is(tok::kw_enum))
    990      1.1  joerg     return (Style.IndentWidth * State.Line->First->IndentLevel) +
    991      1.1  joerg            Style.IndentWidth;
    992      1.1  joerg 
    993  1.1.1.2  joerg   if (NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block))
    994      1.1  joerg     return Current.NestingLevel == 0 ? State.FirstIndent
    995      1.1  joerg                                      : State.Stack.back().Indent;
    996      1.1  joerg   if ((Current.isOneOf(tok::r_brace, tok::r_square) ||
    997      1.1  joerg        (Current.is(tok::greater) &&
    998      1.1  joerg         (Style.Language == FormatStyle::LK_Proto ||
    999      1.1  joerg          Style.Language == FormatStyle::LK_TextProto))) &&
   1000      1.1  joerg       State.Stack.size() > 1) {
   1001      1.1  joerg     if (Current.closesBlockOrBlockTypeList(Style))
   1002      1.1  joerg       return State.Stack[State.Stack.size() - 2].NestedBlockIndent;
   1003  1.1.1.2  joerg     if (Current.MatchingParen && Current.MatchingParen->is(BK_BracedInit))
   1004      1.1  joerg       return State.Stack[State.Stack.size() - 2].LastSpace;
   1005      1.1  joerg     return State.FirstIndent;
   1006      1.1  joerg   }
   1007      1.1  joerg   // Indent a closing parenthesis at the previous level if followed by a semi,
   1008      1.1  joerg   // const, or opening brace. This allows indentations such as:
   1009      1.1  joerg   //     foo(
   1010      1.1  joerg   //       a,
   1011      1.1  joerg   //     );
   1012      1.1  joerg   //     int Foo::getter(
   1013      1.1  joerg   //         //
   1014      1.1  joerg   //     ) const {
   1015      1.1  joerg   //       return foo;
   1016      1.1  joerg   //     }
   1017      1.1  joerg   //     function foo(
   1018      1.1  joerg   //       a,
   1019      1.1  joerg   //     ) {
   1020      1.1  joerg   //       code(); //
   1021      1.1  joerg   //     }
   1022      1.1  joerg   if (Current.is(tok::r_paren) && State.Stack.size() > 1 &&
   1023      1.1  joerg       (!Current.Next ||
   1024      1.1  joerg        Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace)))
   1025      1.1  joerg     return State.Stack[State.Stack.size() - 2].LastSpace;
   1026      1.1  joerg   if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope())
   1027      1.1  joerg     return State.Stack[State.Stack.size() - 2].LastSpace;
   1028      1.1  joerg   if (Current.is(tok::identifier) && Current.Next &&
   1029      1.1  joerg       (Current.Next->is(TT_DictLiteral) ||
   1030      1.1  joerg        ((Style.Language == FormatStyle::LK_Proto ||
   1031      1.1  joerg          Style.Language == FormatStyle::LK_TextProto) &&
   1032      1.1  joerg         Current.Next->isOneOf(tok::less, tok::l_brace))))
   1033      1.1  joerg     return State.Stack.back().Indent;
   1034      1.1  joerg   if (NextNonComment->is(TT_ObjCStringLiteral) &&
   1035      1.1  joerg       State.StartOfStringLiteral != 0)
   1036      1.1  joerg     return State.StartOfStringLiteral - 1;
   1037      1.1  joerg   if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0)
   1038      1.1  joerg     return State.StartOfStringLiteral;
   1039      1.1  joerg   if (NextNonComment->is(tok::lessless) &&
   1040      1.1  joerg       State.Stack.back().FirstLessLess != 0)
   1041      1.1  joerg     return State.Stack.back().FirstLessLess;
   1042      1.1  joerg   if (NextNonComment->isMemberAccess()) {
   1043      1.1  joerg     if (State.Stack.back().CallContinuation == 0)
   1044      1.1  joerg       return ContinuationIndent;
   1045      1.1  joerg     return State.Stack.back().CallContinuation;
   1046      1.1  joerg   }
   1047      1.1  joerg   if (State.Stack.back().QuestionColumn != 0 &&
   1048      1.1  joerg       ((NextNonComment->is(tok::colon) &&
   1049      1.1  joerg         NextNonComment->is(TT_ConditionalExpr)) ||
   1050  1.1.1.2  joerg        Previous.is(TT_ConditionalExpr))) {
   1051  1.1.1.2  joerg     if (((NextNonComment->is(tok::colon) && NextNonComment->Next &&
   1052  1.1.1.2  joerg           !NextNonComment->Next->FakeLParens.empty() &&
   1053  1.1.1.2  joerg           NextNonComment->Next->FakeLParens.back() == prec::Conditional) ||
   1054  1.1.1.2  joerg          (Previous.is(tok::colon) && !Current.FakeLParens.empty() &&
   1055  1.1.1.2  joerg           Current.FakeLParens.back() == prec::Conditional)) &&
   1056  1.1.1.2  joerg         !State.Stack.back().IsWrappedConditional) {
   1057  1.1.1.2  joerg       // NOTE: we may tweak this slightly:
   1058  1.1.1.2  joerg       //    * not remove the 'lead' ContinuationIndentWidth
   1059  1.1.1.2  joerg       //    * always un-indent by the operator when
   1060  1.1.1.2  joerg       //    BreakBeforeTernaryOperators=true
   1061  1.1.1.2  joerg       unsigned Indent = State.Stack.back().Indent;
   1062  1.1.1.2  joerg       if (Style.AlignOperands != FormatStyle::OAS_DontAlign) {
   1063  1.1.1.2  joerg         Indent -= Style.ContinuationIndentWidth;
   1064  1.1.1.2  joerg       }
   1065  1.1.1.2  joerg       if (Style.BreakBeforeTernaryOperators &&
   1066  1.1.1.2  joerg           State.Stack.back().UnindentOperator)
   1067  1.1.1.2  joerg         Indent -= 2;
   1068  1.1.1.2  joerg       return Indent;
   1069  1.1.1.2  joerg     }
   1070      1.1  joerg     return State.Stack.back().QuestionColumn;
   1071  1.1.1.2  joerg   }
   1072      1.1  joerg   if (Previous.is(tok::comma) && State.Stack.back().VariablePos != 0)
   1073      1.1  joerg     return State.Stack.back().VariablePos;
   1074      1.1  joerg   if ((PreviousNonComment &&
   1075      1.1  joerg        (PreviousNonComment->ClosesTemplateDeclaration ||
   1076      1.1  joerg         PreviousNonComment->isOneOf(
   1077      1.1  joerg             TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
   1078      1.1  joerg             TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
   1079      1.1  joerg       (!Style.IndentWrappedFunctionNames &&
   1080      1.1  joerg        NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
   1081      1.1  joerg     return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
   1082      1.1  joerg   if (NextNonComment->is(TT_SelectorName)) {
   1083      1.1  joerg     if (!State.Stack.back().ObjCSelectorNameFound) {
   1084      1.1  joerg       unsigned MinIndent = State.Stack.back().Indent;
   1085      1.1  joerg       if (shouldIndentWrappedSelectorName(Style, State.Line->Type))
   1086      1.1  joerg         MinIndent = std::max(MinIndent,
   1087      1.1  joerg                              State.FirstIndent + Style.ContinuationIndentWidth);
   1088      1.1  joerg       // If LongestObjCSelectorName is 0, we are indenting the first
   1089      1.1  joerg       // part of an ObjC selector (or a selector component which is
   1090      1.1  joerg       // not colon-aligned due to block formatting).
   1091      1.1  joerg       //
   1092      1.1  joerg       // Otherwise, we are indenting a subsequent part of an ObjC
   1093      1.1  joerg       // selector which should be colon-aligned to the longest
   1094      1.1  joerg       // component of the ObjC selector.
   1095      1.1  joerg       //
   1096      1.1  joerg       // In either case, we want to respect Style.IndentWrappedFunctionNames.
   1097      1.1  joerg       return MinIndent +
   1098      1.1  joerg              std::max(NextNonComment->LongestObjCSelectorName,
   1099      1.1  joerg                       NextNonComment->ColumnWidth) -
   1100      1.1  joerg              NextNonComment->ColumnWidth;
   1101      1.1  joerg     }
   1102      1.1  joerg     if (!State.Stack.back().AlignColons)
   1103      1.1  joerg       return State.Stack.back().Indent;
   1104      1.1  joerg     if (State.Stack.back().ColonPos > NextNonComment->ColumnWidth)
   1105      1.1  joerg       return State.Stack.back().ColonPos - NextNonComment->ColumnWidth;
   1106      1.1  joerg     return State.Stack.back().Indent;
   1107      1.1  joerg   }
   1108      1.1  joerg   if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr))
   1109      1.1  joerg     return State.Stack.back().ColonPos;
   1110      1.1  joerg   if (NextNonComment->is(TT_ArraySubscriptLSquare)) {
   1111      1.1  joerg     if (State.Stack.back().StartOfArraySubscripts != 0)
   1112      1.1  joerg       return State.Stack.back().StartOfArraySubscripts;
   1113  1.1.1.2  joerg     else if (Style.isCSharp()) // C# allows `["key"] = value` inside object
   1114  1.1.1.2  joerg                                // initializers.
   1115  1.1.1.2  joerg       return State.Stack.back().Indent;
   1116      1.1  joerg     return ContinuationIndent;
   1117      1.1  joerg   }
   1118      1.1  joerg 
   1119      1.1  joerg   // This ensure that we correctly format ObjC methods calls without inputs,
   1120      1.1  joerg   // i.e. where the last element isn't selector like: [callee method];
   1121      1.1  joerg   if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 &&
   1122      1.1  joerg       NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr))
   1123      1.1  joerg     return State.Stack.back().Indent;
   1124      1.1  joerg 
   1125      1.1  joerg   if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) ||
   1126      1.1  joerg       Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon))
   1127      1.1  joerg     return ContinuationIndent;
   1128      1.1  joerg   if (PreviousNonComment && PreviousNonComment->is(tok::colon) &&
   1129      1.1  joerg       PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))
   1130      1.1  joerg     return ContinuationIndent;
   1131      1.1  joerg   if (NextNonComment->is(TT_CtorInitializerComma))
   1132      1.1  joerg     return State.Stack.back().Indent;
   1133      1.1  joerg   if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) &&
   1134      1.1  joerg       Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon)
   1135      1.1  joerg     return State.Stack.back().Indent;
   1136      1.1  joerg   if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) &&
   1137      1.1  joerg       Style.BreakInheritanceList == FormatStyle::BILS_AfterColon)
   1138      1.1  joerg     return State.Stack.back().Indent;
   1139      1.1  joerg   if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon,
   1140      1.1  joerg                               TT_InheritanceComma))
   1141      1.1  joerg     return State.FirstIndent + Style.ConstructorInitializerIndentWidth;
   1142      1.1  joerg   if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() &&
   1143      1.1  joerg       !Current.isOneOf(tok::colon, tok::comment))
   1144      1.1  joerg     return ContinuationIndent;
   1145      1.1  joerg   if (Current.is(TT_ProtoExtensionLSquare))
   1146      1.1  joerg     return State.Stack.back().Indent;
   1147  1.1.1.2  joerg   if (Current.isBinaryOperator() && State.Stack.back().UnindentOperator)
   1148  1.1.1.2  joerg     return State.Stack.back().Indent - Current.Tok.getLength() -
   1149  1.1.1.2  joerg            Current.SpacesRequiredBefore;
   1150  1.1.1.2  joerg   if (Current.isOneOf(tok::comment, TT_BlockComment, TT_LineComment) &&
   1151  1.1.1.2  joerg       NextNonComment->isBinaryOperator() && State.Stack.back().UnindentOperator)
   1152  1.1.1.2  joerg     return State.Stack.back().Indent - NextNonComment->Tok.getLength() -
   1153  1.1.1.2  joerg            NextNonComment->SpacesRequiredBefore;
   1154      1.1  joerg   if (State.Stack.back().Indent == State.FirstIndent && PreviousNonComment &&
   1155      1.1  joerg       !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma))
   1156      1.1  joerg     // Ensure that we fall back to the continuation indent width instead of
   1157      1.1  joerg     // just flushing continuations left.
   1158      1.1  joerg     return State.Stack.back().Indent + Style.ContinuationIndentWidth;
   1159      1.1  joerg   return State.Stack.back().Indent;
   1160      1.1  joerg }
   1161      1.1  joerg 
   1162  1.1.1.2  joerg static bool hasNestedBlockInlined(const FormatToken *Previous,
   1163  1.1.1.2  joerg                                   const FormatToken &Current,
   1164  1.1.1.2  joerg                                   const FormatStyle &Style) {
   1165  1.1.1.2  joerg   if (Previous->isNot(tok::l_paren))
   1166  1.1.1.2  joerg     return true;
   1167  1.1.1.2  joerg   if (Previous->ParameterCount > 1)
   1168  1.1.1.2  joerg     return true;
   1169  1.1.1.2  joerg 
   1170  1.1.1.2  joerg   // Also a nested block if contains a lambda inside function with 1 parameter
   1171  1.1.1.2  joerg   return (Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare));
   1172  1.1.1.2  joerg }
   1173  1.1.1.2  joerg 
   1174      1.1  joerg unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
   1175      1.1  joerg                                                     bool DryRun, bool Newline) {
   1176      1.1  joerg   assert(State.Stack.size());
   1177      1.1  joerg   const FormatToken &Current = *State.NextToken;
   1178      1.1  joerg 
   1179  1.1.1.2  joerg   if (Current.is(TT_CSharpGenericTypeConstraint))
   1180  1.1.1.2  joerg     State.Stack.back().IsCSharpGenericTypeConstraint = true;
   1181      1.1  joerg   if (Current.isOneOf(tok::comma, TT_BinaryOperator))
   1182      1.1  joerg     State.Stack.back().NoLineBreakInOperand = false;
   1183  1.1.1.2  joerg   if (Current.isOneOf(TT_InheritanceColon, TT_CSharpGenericTypeConstraintColon))
   1184      1.1  joerg     State.Stack.back().AvoidBinPacking = true;
   1185      1.1  joerg   if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator)) {
   1186      1.1  joerg     if (State.Stack.back().FirstLessLess == 0)
   1187      1.1  joerg       State.Stack.back().FirstLessLess = State.Column;
   1188      1.1  joerg     else
   1189      1.1  joerg       State.Stack.back().LastOperatorWrapped = Newline;
   1190      1.1  joerg   }
   1191      1.1  joerg   if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless))
   1192      1.1  joerg     State.Stack.back().LastOperatorWrapped = Newline;
   1193      1.1  joerg   if (Current.is(TT_ConditionalExpr) && Current.Previous &&
   1194      1.1  joerg       !Current.Previous->is(TT_ConditionalExpr))
   1195      1.1  joerg     State.Stack.back().LastOperatorWrapped = Newline;
   1196      1.1  joerg   if (Current.is(TT_ArraySubscriptLSquare) &&
   1197      1.1  joerg       State.Stack.back().StartOfArraySubscripts == 0)
   1198      1.1  joerg     State.Stack.back().StartOfArraySubscripts = State.Column;
   1199  1.1.1.2  joerg   if (Current.is(TT_ConditionalExpr) && Current.is(tok::question) &&
   1200  1.1.1.2  joerg       ((Current.MustBreakBefore) ||
   1201  1.1.1.2  joerg        (Current.getNextNonComment() &&
   1202  1.1.1.2  joerg         Current.getNextNonComment()->MustBreakBefore)))
   1203  1.1.1.2  joerg     State.Stack.back().IsWrappedConditional = true;
   1204      1.1  joerg   if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
   1205      1.1  joerg     State.Stack.back().QuestionColumn = State.Column;
   1206      1.1  joerg   if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) {
   1207      1.1  joerg     const FormatToken *Previous = Current.Previous;
   1208      1.1  joerg     while (Previous && Previous->isTrailingComment())
   1209      1.1  joerg       Previous = Previous->Previous;
   1210      1.1  joerg     if (Previous && Previous->is(tok::question))
   1211      1.1  joerg       State.Stack.back().QuestionColumn = State.Column;
   1212      1.1  joerg   }
   1213      1.1  joerg   if (!Current.opensScope() && !Current.closesScope() &&
   1214      1.1  joerg       !Current.is(TT_PointerOrReference))
   1215      1.1  joerg     State.LowestLevelOnLine =
   1216      1.1  joerg         std::min(State.LowestLevelOnLine, Current.NestingLevel);
   1217      1.1  joerg   if (Current.isMemberAccess())
   1218      1.1  joerg     State.Stack.back().StartOfFunctionCall =
   1219      1.1  joerg         !Current.NextOperator ? 0 : State.Column;
   1220      1.1  joerg   if (Current.is(TT_SelectorName))
   1221      1.1  joerg     State.Stack.back().ObjCSelectorNameFound = true;
   1222      1.1  joerg   if (Current.is(TT_CtorInitializerColon) &&
   1223      1.1  joerg       Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
   1224      1.1  joerg     // Indent 2 from the column, so:
   1225      1.1  joerg     // SomeClass::SomeClass()
   1226      1.1  joerg     //     : First(...), ...
   1227      1.1  joerg     //       Next(...)
   1228      1.1  joerg     //       ^ line up here.
   1229      1.1  joerg     State.Stack.back().Indent =
   1230      1.1  joerg         State.Column +
   1231      1.1  joerg         (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma
   1232      1.1  joerg              ? 0
   1233      1.1  joerg              : 2);
   1234      1.1  joerg     State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
   1235      1.1  joerg     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) {
   1236      1.1  joerg       State.Stack.back().AvoidBinPacking = true;
   1237      1.1  joerg       State.Stack.back().BreakBeforeParameter =
   1238      1.1  joerg           !Style.AllowAllConstructorInitializersOnNextLine;
   1239      1.1  joerg     } else {
   1240      1.1  joerg       State.Stack.back().BreakBeforeParameter = false;
   1241      1.1  joerg     }
   1242      1.1  joerg   }
   1243      1.1  joerg   if (Current.is(TT_CtorInitializerColon) &&
   1244      1.1  joerg       Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) {
   1245      1.1  joerg     State.Stack.back().Indent =
   1246      1.1  joerg         State.FirstIndent + Style.ConstructorInitializerIndentWidth;
   1247      1.1  joerg     State.Stack.back().NestedBlockIndent = State.Stack.back().Indent;
   1248      1.1  joerg     if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
   1249      1.1  joerg       State.Stack.back().AvoidBinPacking = true;
   1250      1.1  joerg   }
   1251      1.1  joerg   if (Current.is(TT_InheritanceColon))
   1252      1.1  joerg     State.Stack.back().Indent =
   1253      1.1  joerg         State.FirstIndent + Style.ConstructorInitializerIndentWidth;
   1254      1.1  joerg   if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline)
   1255      1.1  joerg     State.Stack.back().NestedBlockIndent =
   1256      1.1  joerg         State.Column + Current.ColumnWidth + 1;
   1257      1.1  joerg   if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
   1258      1.1  joerg     State.Stack.back().LastSpace = State.Column;
   1259      1.1  joerg 
   1260      1.1  joerg   // Insert scopes created by fake parenthesis.
   1261      1.1  joerg   const FormatToken *Previous = Current.getPreviousNonComment();
   1262      1.1  joerg 
   1263      1.1  joerg   // Add special behavior to support a format commonly used for JavaScript
   1264      1.1  joerg   // closures:
   1265      1.1  joerg   //   SomeFunction(function() {
   1266      1.1  joerg   //     foo();
   1267      1.1  joerg   //     bar();
   1268      1.1  joerg   //   }, a, b, c);
   1269      1.1  joerg   if (Current.isNot(tok::comment) && Previous &&
   1270      1.1  joerg       Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
   1271      1.1  joerg       !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
   1272      1.1  joerg       !State.Stack.back().HasMultipleNestedBlocks) {
   1273      1.1  joerg     if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
   1274      1.1  joerg       for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
   1275      1.1  joerg         State.Stack[i].NoLineBreak = true;
   1276      1.1  joerg     State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
   1277      1.1  joerg   }
   1278      1.1  joerg   if (Previous &&
   1279      1.1  joerg       (Previous->isOneOf(tok::l_paren, tok::comma, tok::colon) ||
   1280      1.1  joerg        Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr)) &&
   1281      1.1  joerg       !Previous->isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
   1282      1.1  joerg     State.Stack.back().NestedBlockInlined =
   1283  1.1.1.2  joerg         !Newline && hasNestedBlockInlined(Previous, Current, Style);
   1284      1.1  joerg   }
   1285      1.1  joerg 
   1286      1.1  joerg   moveStatePastFakeLParens(State, Newline);
   1287      1.1  joerg   moveStatePastScopeCloser(State);
   1288      1.1  joerg   bool AllowBreak = !State.Stack.back().NoLineBreak &&
   1289      1.1  joerg                     !State.Stack.back().NoLineBreakInOperand;
   1290      1.1  joerg   moveStatePastScopeOpener(State, Newline);
   1291      1.1  joerg   moveStatePastFakeRParens(State);
   1292      1.1  joerg 
   1293      1.1  joerg   if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0)
   1294      1.1  joerg     State.StartOfStringLiteral = State.Column + 1;
   1295      1.1  joerg   if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0)
   1296      1.1  joerg     State.StartOfStringLiteral = State.Column + 1;
   1297      1.1  joerg   else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0)
   1298      1.1  joerg     State.StartOfStringLiteral = State.Column;
   1299      1.1  joerg   else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
   1300      1.1  joerg            !Current.isStringLiteral())
   1301      1.1  joerg     State.StartOfStringLiteral = 0;
   1302      1.1  joerg 
   1303      1.1  joerg   State.Column += Current.ColumnWidth;
   1304      1.1  joerg   State.NextToken = State.NextToken->Next;
   1305      1.1  joerg 
   1306      1.1  joerg   unsigned Penalty =
   1307      1.1  joerg       handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
   1308      1.1  joerg 
   1309      1.1  joerg   if (Current.Role)
   1310      1.1  joerg     Current.Role->formatFromToken(State, this, DryRun);
   1311      1.1  joerg   // If the previous has a special role, let it consume tokens as appropriate.
   1312      1.1  joerg   // It is necessary to start at the previous token for the only implemented
   1313      1.1  joerg   // role (comma separated list). That way, the decision whether or not to break
   1314      1.1  joerg   // after the "{" is already done and both options are tried and evaluated.
   1315      1.1  joerg   // FIXME: This is ugly, find a better way.
   1316      1.1  joerg   if (Previous && Previous->Role)
   1317      1.1  joerg     Penalty += Previous->Role->formatAfterToken(State, this, DryRun);
   1318      1.1  joerg 
   1319      1.1  joerg   return Penalty;
   1320      1.1  joerg }
   1321      1.1  joerg 
   1322      1.1  joerg void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
   1323      1.1  joerg                                                     bool Newline) {
   1324      1.1  joerg   const FormatToken &Current = *State.NextToken;
   1325      1.1  joerg   const FormatToken *Previous = Current.getPreviousNonComment();
   1326      1.1  joerg 
   1327      1.1  joerg   // Don't add extra indentation for the first fake parenthesis after
   1328      1.1  joerg   // 'return', assignments or opening <({[. The indentation for these cases
   1329      1.1  joerg   // is special cased.
   1330      1.1  joerg   bool SkipFirstExtraIndent =
   1331      1.1  joerg       (Previous && (Previous->opensScope() ||
   1332      1.1  joerg                     Previous->isOneOf(tok::semi, tok::kw_return) ||
   1333      1.1  joerg                     (Previous->getPrecedence() == prec::Assignment &&
   1334  1.1.1.2  joerg                      Style.AlignOperands != FormatStyle::OAS_DontAlign) ||
   1335      1.1  joerg                     Previous->is(TT_ObjCMethodExpr)));
   1336      1.1  joerg   for (SmallVectorImpl<prec::Level>::const_reverse_iterator
   1337      1.1  joerg            I = Current.FakeLParens.rbegin(),
   1338      1.1  joerg            E = Current.FakeLParens.rend();
   1339      1.1  joerg        I != E; ++I) {
   1340      1.1  joerg     ParenState NewParenState = State.Stack.back();
   1341      1.1  joerg     NewParenState.Tok = nullptr;
   1342      1.1  joerg     NewParenState.ContainsLineBreak = false;
   1343      1.1  joerg     NewParenState.LastOperatorWrapped = true;
   1344  1.1.1.2  joerg     NewParenState.IsChainedConditional = false;
   1345  1.1.1.2  joerg     NewParenState.IsWrappedConditional = false;
   1346  1.1.1.2  joerg     NewParenState.UnindentOperator = false;
   1347      1.1  joerg     NewParenState.NoLineBreak =
   1348      1.1  joerg         NewParenState.NoLineBreak || State.Stack.back().NoLineBreakInOperand;
   1349      1.1  joerg 
   1350      1.1  joerg     // Don't propagate AvoidBinPacking into subexpressions of arg/param lists.
   1351      1.1  joerg     if (*I > prec::Comma)
   1352      1.1  joerg       NewParenState.AvoidBinPacking = false;
   1353      1.1  joerg 
   1354      1.1  joerg     // Indent from 'LastSpace' unless these are fake parentheses encapsulating
   1355      1.1  joerg     // a builder type call after 'return' or, if the alignment after opening
   1356      1.1  joerg     // brackets is disabled.
   1357      1.1  joerg     if (!Current.isTrailingComment() &&
   1358  1.1.1.2  joerg         (Style.AlignOperands != FormatStyle::OAS_DontAlign ||
   1359  1.1.1.2  joerg          *I < prec::Assignment) &&
   1360      1.1  joerg         (!Previous || Previous->isNot(tok::kw_return) ||
   1361      1.1  joerg          (Style.Language != FormatStyle::LK_Java && *I > 0)) &&
   1362      1.1  joerg         (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
   1363  1.1.1.2  joerg          *I != prec::Comma || Current.NestingLevel == 0)) {
   1364      1.1  joerg       NewParenState.Indent =
   1365      1.1  joerg           std::max(std::max(State.Column, NewParenState.Indent),
   1366      1.1  joerg                    State.Stack.back().LastSpace);
   1367  1.1.1.2  joerg     }
   1368  1.1.1.2  joerg 
   1369  1.1.1.2  joerg     if (Previous &&
   1370  1.1.1.2  joerg         (Previous->getPrecedence() == prec::Assignment ||
   1371  1.1.1.2  joerg          Previous->is(tok::kw_return) ||
   1372  1.1.1.2  joerg          (*I == prec::Conditional && Previous->is(tok::question) &&
   1373  1.1.1.2  joerg           Previous->is(TT_ConditionalExpr))) &&
   1374  1.1.1.2  joerg         !Newline) {
   1375  1.1.1.2  joerg       // If BreakBeforeBinaryOperators is set, un-indent a bit to account for
   1376  1.1.1.2  joerg       // the operator and keep the operands aligned
   1377  1.1.1.2  joerg       if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator)
   1378  1.1.1.2  joerg         NewParenState.UnindentOperator = true;
   1379  1.1.1.2  joerg       // Mark indentation as alignment if the expression is aligned.
   1380  1.1.1.2  joerg       if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
   1381  1.1.1.2  joerg         NewParenState.IsAligned = true;
   1382  1.1.1.2  joerg     }
   1383      1.1  joerg 
   1384      1.1  joerg     // Do not indent relative to the fake parentheses inserted for "." or "->".
   1385      1.1  joerg     // This is a special case to make the following to statements consistent:
   1386      1.1  joerg     //   OuterFunction(InnerFunctionCall( // break
   1387      1.1  joerg     //       ParameterToInnerFunction));
   1388      1.1  joerg     //   OuterFunction(SomeObject.InnerFunctionCall( // break
   1389      1.1  joerg     //       ParameterToInnerFunction));
   1390      1.1  joerg     if (*I > prec::Unknown)
   1391      1.1  joerg       NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column);
   1392      1.1  joerg     if (*I != prec::Conditional && !Current.is(TT_UnaryOperator) &&
   1393      1.1  joerg         Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
   1394      1.1  joerg       NewParenState.StartOfFunctionCall = State.Column;
   1395      1.1  joerg 
   1396  1.1.1.2  joerg     // Indent conditional expressions, unless they are chained "else-if"
   1397  1.1.1.2  joerg     // conditionals. Never indent expression where the 'operator' is ',', ';' or
   1398  1.1.1.2  joerg     // an assignment (i.e. *I <= prec::Assignment) as those have different
   1399  1.1.1.2  joerg     // indentation rules. Indent other expression, unless the indentation needs
   1400  1.1.1.2  joerg     // to be skipped.
   1401  1.1.1.2  joerg     if (*I == prec::Conditional && Previous && Previous->is(tok::colon) &&
   1402  1.1.1.2  joerg         Previous->is(TT_ConditionalExpr) && I == Current.FakeLParens.rbegin() &&
   1403  1.1.1.2  joerg         !State.Stack.back().IsWrappedConditional) {
   1404  1.1.1.2  joerg       NewParenState.IsChainedConditional = true;
   1405  1.1.1.2  joerg       NewParenState.UnindentOperator = State.Stack.back().UnindentOperator;
   1406  1.1.1.2  joerg     } else if (*I == prec::Conditional ||
   1407  1.1.1.2  joerg                (!SkipFirstExtraIndent && *I > prec::Assignment &&
   1408  1.1.1.2  joerg                 !Current.isTrailingComment())) {
   1409      1.1  joerg       NewParenState.Indent += Style.ContinuationIndentWidth;
   1410  1.1.1.2  joerg     }
   1411      1.1  joerg     if ((Previous && !Previous->opensScope()) || *I != prec::Comma)
   1412      1.1  joerg       NewParenState.BreakBeforeParameter = false;
   1413      1.1  joerg     State.Stack.push_back(NewParenState);
   1414      1.1  joerg     SkipFirstExtraIndent = false;
   1415      1.1  joerg   }
   1416      1.1  joerg }
   1417      1.1  joerg 
   1418      1.1  joerg void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
   1419      1.1  joerg   for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
   1420      1.1  joerg     unsigned VariablePos = State.Stack.back().VariablePos;
   1421      1.1  joerg     if (State.Stack.size() == 1) {
   1422      1.1  joerg       // Do not pop the last element.
   1423      1.1  joerg       break;
   1424      1.1  joerg     }
   1425      1.1  joerg     State.Stack.pop_back();
   1426      1.1  joerg     State.Stack.back().VariablePos = VariablePos;
   1427      1.1  joerg   }
   1428      1.1  joerg }
   1429      1.1  joerg 
   1430      1.1  joerg void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
   1431      1.1  joerg                                                     bool Newline) {
   1432      1.1  joerg   const FormatToken &Current = *State.NextToken;
   1433      1.1  joerg   if (!Current.opensScope())
   1434      1.1  joerg     return;
   1435      1.1  joerg 
   1436  1.1.1.2  joerg   // Don't allow '<' or '(' in C# generic type constraints to start new scopes.
   1437  1.1.1.2  joerg   if (Current.isOneOf(tok::less, tok::l_paren) &&
   1438  1.1.1.2  joerg       State.Stack.back().IsCSharpGenericTypeConstraint)
   1439  1.1.1.2  joerg     return;
   1440  1.1.1.2  joerg 
   1441  1.1.1.2  joerg   if (Current.MatchingParen && Current.is(BK_Block)) {
   1442      1.1  joerg     moveStateToNewBlock(State);
   1443      1.1  joerg     return;
   1444      1.1  joerg   }
   1445      1.1  joerg 
   1446      1.1  joerg   unsigned NewIndent;
   1447      1.1  joerg   unsigned LastSpace = State.Stack.back().LastSpace;
   1448      1.1  joerg   bool AvoidBinPacking;
   1449      1.1  joerg   bool BreakBeforeParameter = false;
   1450      1.1  joerg   unsigned NestedBlockIndent = std::max(State.Stack.back().StartOfFunctionCall,
   1451      1.1  joerg                                         State.Stack.back().NestedBlockIndent);
   1452      1.1  joerg   if (Current.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
   1453      1.1  joerg       opensProtoMessageField(Current, Style)) {
   1454      1.1  joerg     if (Current.opensBlockOrBlockTypeList(Style)) {
   1455      1.1  joerg       NewIndent = Style.IndentWidth +
   1456      1.1  joerg                   std::min(State.Column, State.Stack.back().NestedBlockIndent);
   1457      1.1  joerg     } else {
   1458      1.1  joerg       NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth;
   1459      1.1  joerg     }
   1460      1.1  joerg     const FormatToken *NextNoComment = Current.getNextNonComment();
   1461      1.1  joerg     bool EndsInComma = Current.MatchingParen &&
   1462      1.1  joerg                        Current.MatchingParen->Previous &&
   1463      1.1  joerg                        Current.MatchingParen->Previous->is(tok::comma);
   1464      1.1  joerg     AvoidBinPacking = EndsInComma || Current.is(TT_DictLiteral) ||
   1465      1.1  joerg                       Style.Language == FormatStyle::LK_Proto ||
   1466      1.1  joerg                       Style.Language == FormatStyle::LK_TextProto ||
   1467      1.1  joerg                       !Style.BinPackArguments ||
   1468      1.1  joerg                       (NextNoComment &&
   1469      1.1  joerg                        NextNoComment->isOneOf(TT_DesignatedInitializerPeriod,
   1470      1.1  joerg                                               TT_DesignatedInitializerLSquare));
   1471      1.1  joerg     BreakBeforeParameter = EndsInComma;
   1472      1.1  joerg     if (Current.ParameterCount > 1)
   1473      1.1  joerg       NestedBlockIndent = std::max(NestedBlockIndent, State.Column + 1);
   1474      1.1  joerg   } else {
   1475      1.1  joerg     NewIndent = Style.ContinuationIndentWidth +
   1476      1.1  joerg                 std::max(State.Stack.back().LastSpace,
   1477      1.1  joerg                          State.Stack.back().StartOfFunctionCall);
   1478      1.1  joerg 
   1479      1.1  joerg     // Ensure that different different brackets force relative alignment, e.g.:
   1480      1.1  joerg     // void SomeFunction(vector<  // break
   1481      1.1  joerg     //                       int> v);
   1482      1.1  joerg     // FIXME: We likely want to do this for more combinations of brackets.
   1483      1.1  joerg     if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
   1484      1.1  joerg       NewIndent = std::max(NewIndent, State.Stack.back().Indent);
   1485      1.1  joerg       LastSpace = std::max(LastSpace, State.Stack.back().Indent);
   1486      1.1  joerg     }
   1487      1.1  joerg 
   1488      1.1  joerg     bool EndsInComma =
   1489      1.1  joerg         Current.MatchingParen &&
   1490      1.1  joerg         Current.MatchingParen->getPreviousNonComment() &&
   1491      1.1  joerg         Current.MatchingParen->getPreviousNonComment()->is(tok::comma);
   1492      1.1  joerg 
   1493      1.1  joerg     // If ObjCBinPackProtocolList is unspecified, fall back to BinPackParameters
   1494      1.1  joerg     // for backwards compatibility.
   1495      1.1  joerg     bool ObjCBinPackProtocolList =
   1496      1.1  joerg         (Style.ObjCBinPackProtocolList == FormatStyle::BPS_Auto &&
   1497      1.1  joerg          Style.BinPackParameters) ||
   1498      1.1  joerg         Style.ObjCBinPackProtocolList == FormatStyle::BPS_Always;
   1499      1.1  joerg 
   1500      1.1  joerg     bool BinPackDeclaration =
   1501      1.1  joerg         (State.Line->Type != LT_ObjCDecl && Style.BinPackParameters) ||
   1502      1.1  joerg         (State.Line->Type == LT_ObjCDecl && ObjCBinPackProtocolList);
   1503      1.1  joerg 
   1504      1.1  joerg     AvoidBinPacking =
   1505  1.1.1.2  joerg         (State.Stack.back().IsCSharpGenericTypeConstraint) ||
   1506      1.1  joerg         (Style.Language == FormatStyle::LK_JavaScript && EndsInComma) ||
   1507      1.1  joerg         (State.Line->MustBeDeclaration && !BinPackDeclaration) ||
   1508      1.1  joerg         (!State.Line->MustBeDeclaration && !Style.BinPackArguments) ||
   1509      1.1  joerg         (Style.ExperimentalAutoDetectBinPacking &&
   1510  1.1.1.2  joerg          (Current.is(PPK_OnePerLine) ||
   1511  1.1.1.2  joerg           (!BinPackInconclusiveFunctions && Current.is(PPK_Inconclusive))));
   1512      1.1  joerg 
   1513  1.1.1.2  joerg     if (Current.is(TT_ObjCMethodExpr) && Current.MatchingParen &&
   1514  1.1.1.2  joerg         Style.ObjCBreakBeforeNestedBlockParam) {
   1515      1.1  joerg       if (Style.ColumnLimit) {
   1516      1.1  joerg         // If this '[' opens an ObjC call, determine whether all parameters fit
   1517      1.1  joerg         // into one line and put one per line if they don't.
   1518      1.1  joerg         if (getLengthToMatchingParen(Current, State.Stack) + State.Column >
   1519      1.1  joerg             getColumnLimit(State))
   1520      1.1  joerg           BreakBeforeParameter = true;
   1521      1.1  joerg       } else {
   1522      1.1  joerg         // For ColumnLimit = 0, we have to figure out whether there is or has to
   1523      1.1  joerg         // be a line break within this call.
   1524      1.1  joerg         for (const FormatToken *Tok = &Current;
   1525      1.1  joerg              Tok && Tok != Current.MatchingParen; Tok = Tok->Next) {
   1526      1.1  joerg           if (Tok->MustBreakBefore ||
   1527      1.1  joerg               (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) {
   1528      1.1  joerg             BreakBeforeParameter = true;
   1529      1.1  joerg             break;
   1530      1.1  joerg           }
   1531      1.1  joerg         }
   1532      1.1  joerg       }
   1533      1.1  joerg     }
   1534      1.1  joerg 
   1535      1.1  joerg     if (Style.Language == FormatStyle::LK_JavaScript && EndsInComma)
   1536      1.1  joerg       BreakBeforeParameter = true;
   1537      1.1  joerg   }
   1538      1.1  joerg   // Generally inherit NoLineBreak from the current scope to nested scope.
   1539      1.1  joerg   // However, don't do this for non-empty nested blocks, dict literals and
   1540      1.1  joerg   // array literals as these follow different indentation rules.
   1541      1.1  joerg   bool NoLineBreak =
   1542      1.1  joerg       Current.Children.empty() &&
   1543      1.1  joerg       !Current.isOneOf(TT_DictLiteral, TT_ArrayInitializerLSquare) &&
   1544      1.1  joerg       (State.Stack.back().NoLineBreak ||
   1545      1.1  joerg        State.Stack.back().NoLineBreakInOperand ||
   1546      1.1  joerg        (Current.is(TT_TemplateOpener) &&
   1547      1.1  joerg         State.Stack.back().ContainsUnwrappedBuilder));
   1548      1.1  joerg   State.Stack.push_back(
   1549      1.1  joerg       ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
   1550      1.1  joerg   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
   1551      1.1  joerg   State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
   1552  1.1.1.2  joerg   State.Stack.back().HasMultipleNestedBlocks =
   1553  1.1.1.2  joerg       (Current.BlockParameterCount > 1);
   1554  1.1.1.2  joerg 
   1555  1.1.1.2  joerg   if (Style.BraceWrapping.BeforeLambdaBody && Current.Next != nullptr &&
   1556  1.1.1.2  joerg       Current.Tok.is(tok::l_paren)) {
   1557  1.1.1.2  joerg     // Search for any parameter that is a lambda
   1558  1.1.1.2  joerg     FormatToken const *next = Current.Next;
   1559  1.1.1.2  joerg     while (next != nullptr) {
   1560  1.1.1.2  joerg       if (next->is(TT_LambdaLSquare)) {
   1561  1.1.1.2  joerg         State.Stack.back().HasMultipleNestedBlocks = true;
   1562  1.1.1.2  joerg         break;
   1563  1.1.1.2  joerg       }
   1564  1.1.1.2  joerg       next = next->Next;
   1565  1.1.1.2  joerg     }
   1566  1.1.1.2  joerg   }
   1567  1.1.1.2  joerg 
   1568      1.1  joerg   State.Stack.back().IsInsideObjCArrayLiteral =
   1569      1.1  joerg       Current.is(TT_ArrayInitializerLSquare) && Current.Previous &&
   1570      1.1  joerg       Current.Previous->is(tok::at);
   1571      1.1  joerg }
   1572      1.1  joerg 
   1573      1.1  joerg void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
   1574      1.1  joerg   const FormatToken &Current = *State.NextToken;
   1575      1.1  joerg   if (!Current.closesScope())
   1576      1.1  joerg     return;
   1577      1.1  joerg 
   1578      1.1  joerg   // If we encounter a closing ), ], } or >, we can remove a level from our
   1579      1.1  joerg   // stacks.
   1580      1.1  joerg   if (State.Stack.size() > 1 &&
   1581      1.1  joerg       (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) ||
   1582      1.1  joerg        (Current.is(tok::r_brace) && State.NextToken != State.Line->First) ||
   1583      1.1  joerg        State.NextToken->is(TT_TemplateCloser) ||
   1584      1.1  joerg        (Current.is(tok::greater) && Current.is(TT_DictLiteral))))
   1585      1.1  joerg     State.Stack.pop_back();
   1586      1.1  joerg 
   1587      1.1  joerg   // Reevaluate whether ObjC message arguments fit into one line.
   1588      1.1  joerg   // If a receiver spans multiple lines, e.g.:
   1589      1.1  joerg   //   [[object block:^{
   1590      1.1  joerg   //     return 42;
   1591      1.1  joerg   //   }] a:42 b:42];
   1592      1.1  joerg   // BreakBeforeParameter is calculated based on an incorrect assumption
   1593      1.1  joerg   // (it is checked whether the whole expression fits into one line without
   1594      1.1  joerg   // considering a line break inside a message receiver).
   1595      1.1  joerg   // We check whether arguements fit after receiver scope closer (into the same
   1596      1.1  joerg   // line).
   1597      1.1  joerg   if (State.Stack.back().BreakBeforeParameter && Current.MatchingParen &&
   1598      1.1  joerg       Current.MatchingParen->Previous) {
   1599      1.1  joerg     const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
   1600      1.1  joerg     if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
   1601      1.1  joerg         CurrentScopeOpener.MatchingParen) {
   1602      1.1  joerg       int NecessarySpaceInLine =
   1603      1.1  joerg           getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
   1604      1.1  joerg           CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
   1605      1.1  joerg       if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
   1606      1.1  joerg           Style.ColumnLimit)
   1607      1.1  joerg         State.Stack.back().BreakBeforeParameter = false;
   1608      1.1  joerg     }
   1609      1.1  joerg   }
   1610      1.1  joerg 
   1611      1.1  joerg   if (Current.is(tok::r_square)) {
   1612      1.1  joerg     // If this ends the array subscript expr, reset the corresponding value.
   1613      1.1  joerg     const FormatToken *NextNonComment = Current.getNextNonComment();
   1614      1.1  joerg     if (NextNonComment && NextNonComment->isNot(tok::l_square))
   1615      1.1  joerg       State.Stack.back().StartOfArraySubscripts = 0;
   1616      1.1  joerg   }
   1617      1.1  joerg }
   1618      1.1  joerg 
   1619      1.1  joerg void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
   1620      1.1  joerg   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
   1621      1.1  joerg   // ObjC block sometimes follow special indentation rules.
   1622      1.1  joerg   unsigned NewIndent =
   1623      1.1  joerg       NestedBlockIndent + (State.NextToken->is(TT_ObjCBlockLBrace)
   1624      1.1  joerg                                ? Style.ObjCBlockIndentWidth
   1625      1.1  joerg                                : Style.IndentWidth);
   1626      1.1  joerg   State.Stack.push_back(ParenState(State.NextToken, NewIndent,
   1627      1.1  joerg                                    State.Stack.back().LastSpace,
   1628      1.1  joerg                                    /*AvoidBinPacking=*/true,
   1629      1.1  joerg                                    /*NoLineBreak=*/false));
   1630      1.1  joerg   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
   1631      1.1  joerg   State.Stack.back().BreakBeforeParameter = true;
   1632      1.1  joerg }
   1633      1.1  joerg 
   1634      1.1  joerg static unsigned getLastLineEndColumn(StringRef Text, unsigned StartColumn,
   1635      1.1  joerg                                      unsigned TabWidth,
   1636      1.1  joerg                                      encoding::Encoding Encoding) {
   1637      1.1  joerg   size_t LastNewlinePos = Text.find_last_of("\n");
   1638      1.1  joerg   if (LastNewlinePos == StringRef::npos) {
   1639      1.1  joerg     return StartColumn +
   1640      1.1  joerg            encoding::columnWidthWithTabs(Text, StartColumn, TabWidth, Encoding);
   1641      1.1  joerg   } else {
   1642      1.1  joerg     return encoding::columnWidthWithTabs(Text.substr(LastNewlinePos),
   1643      1.1  joerg                                          /*StartColumn=*/0, TabWidth, Encoding);
   1644      1.1  joerg   }
   1645      1.1  joerg }
   1646      1.1  joerg 
   1647      1.1  joerg unsigned ContinuationIndenter::reformatRawStringLiteral(
   1648      1.1  joerg     const FormatToken &Current, LineState &State,
   1649      1.1  joerg     const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
   1650      1.1  joerg   unsigned StartColumn = State.Column - Current.ColumnWidth;
   1651      1.1  joerg   StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
   1652      1.1  joerg   StringRef NewDelimiter =
   1653      1.1  joerg       getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
   1654  1.1.1.2  joerg   if (NewDelimiter.empty())
   1655      1.1  joerg     NewDelimiter = OldDelimiter;
   1656      1.1  joerg   // The text of a raw string is between the leading 'R"delimiter(' and the
   1657      1.1  joerg   // trailing 'delimiter)"'.
   1658      1.1  joerg   unsigned OldPrefixSize = 3 + OldDelimiter.size();
   1659      1.1  joerg   unsigned OldSuffixSize = 2 + OldDelimiter.size();
   1660      1.1  joerg   // We create a virtual text environment which expects a null-terminated
   1661      1.1  joerg   // string, so we cannot use StringRef.
   1662  1.1.1.2  joerg   std::string RawText = std::string(
   1663  1.1.1.2  joerg       Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize));
   1664      1.1  joerg   if (NewDelimiter != OldDelimiter) {
   1665      1.1  joerg     // Don't update to the canonical delimiter 'deli' if ')deli"' occurs in the
   1666      1.1  joerg     // raw string.
   1667      1.1  joerg     std::string CanonicalDelimiterSuffix = (")" + NewDelimiter + "\"").str();
   1668      1.1  joerg     if (StringRef(RawText).contains(CanonicalDelimiterSuffix))
   1669      1.1  joerg       NewDelimiter = OldDelimiter;
   1670      1.1  joerg   }
   1671      1.1  joerg 
   1672      1.1  joerg   unsigned NewPrefixSize = 3 + NewDelimiter.size();
   1673      1.1  joerg   unsigned NewSuffixSize = 2 + NewDelimiter.size();
   1674      1.1  joerg 
   1675      1.1  joerg   // The first start column is the column the raw text starts after formatting.
   1676      1.1  joerg   unsigned FirstStartColumn = StartColumn + NewPrefixSize;
   1677      1.1  joerg 
   1678      1.1  joerg   // The next start column is the intended indentation a line break inside
   1679      1.1  joerg   // the raw string at level 0. It is determined by the following rules:
   1680      1.1  joerg   //   - if the content starts on newline, it is one level more than the current
   1681      1.1  joerg   //     indent, and
   1682      1.1  joerg   //   - if the content does not start on a newline, it is the first start
   1683      1.1  joerg   //     column.
   1684      1.1  joerg   // These rules have the advantage that the formatted content both does not
   1685      1.1  joerg   // violate the rectangle rule and visually flows within the surrounding
   1686      1.1  joerg   // source.
   1687      1.1  joerg   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
   1688      1.1  joerg   // If this token is the last parameter (checked by looking if it's followed by
   1689      1.1  joerg   // `)` and is not on a newline, the base the indent off the line's nested
   1690      1.1  joerg   // block indent. Otherwise, base the indent off the arguments indent, so we
   1691      1.1  joerg   // can achieve:
   1692      1.1  joerg   //
   1693      1.1  joerg   // fffffffffff(1, 2, 3, R"pb(
   1694      1.1  joerg   //     key1: 1  #
   1695      1.1  joerg   //     key2: 2)pb");
   1696      1.1  joerg   //
   1697      1.1  joerg   // fffffffffff(1, 2, 3,
   1698      1.1  joerg   //             R"pb(
   1699      1.1  joerg   //               key1: 1  #
   1700      1.1  joerg   //               key2: 2
   1701      1.1  joerg   //             )pb");
   1702      1.1  joerg   //
   1703      1.1  joerg   // fffffffffff(1, 2, 3,
   1704      1.1  joerg   //             R"pb(
   1705      1.1  joerg   //               key1: 1  #
   1706      1.1  joerg   //               key2: 2
   1707      1.1  joerg   //             )pb",
   1708      1.1  joerg   //             5);
   1709      1.1  joerg   unsigned CurrentIndent =
   1710      1.1  joerg       (!Newline && Current.Next && Current.Next->is(tok::r_paren))
   1711      1.1  joerg           ? State.Stack.back().NestedBlockIndent
   1712      1.1  joerg           : State.Stack.back().Indent;
   1713      1.1  joerg   unsigned NextStartColumn = ContentStartsOnNewline
   1714      1.1  joerg                                  ? CurrentIndent + Style.IndentWidth
   1715      1.1  joerg                                  : FirstStartColumn;
   1716      1.1  joerg 
   1717      1.1  joerg   // The last start column is the column the raw string suffix starts if it is
   1718      1.1  joerg   // put on a newline.
   1719      1.1  joerg   // The last start column is the intended indentation of the raw string postfix
   1720      1.1  joerg   // if it is put on a newline. It is determined by the following rules:
   1721      1.1  joerg   //   - if the raw string prefix starts on a newline, it is the column where
   1722      1.1  joerg   //     that raw string prefix starts, and
   1723      1.1  joerg   //   - if the raw string prefix does not start on a newline, it is the current
   1724      1.1  joerg   //     indent.
   1725      1.1  joerg   unsigned LastStartColumn =
   1726      1.1  joerg       Current.NewlinesBefore ? FirstStartColumn - NewPrefixSize : CurrentIndent;
   1727      1.1  joerg 
   1728      1.1  joerg   std::pair<tooling::Replacements, unsigned> Fixes = internal::reformat(
   1729      1.1  joerg       RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
   1730      1.1  joerg       FirstStartColumn, NextStartColumn, LastStartColumn, "<stdin>",
   1731      1.1  joerg       /*Status=*/nullptr);
   1732      1.1  joerg 
   1733      1.1  joerg   auto NewCode = applyAllReplacements(RawText, Fixes.first);
   1734      1.1  joerg   tooling::Replacements NoFixes;
   1735      1.1  joerg   if (!NewCode) {
   1736      1.1  joerg     return addMultilineToken(Current, State);
   1737      1.1  joerg   }
   1738      1.1  joerg   if (!DryRun) {
   1739      1.1  joerg     if (NewDelimiter != OldDelimiter) {
   1740      1.1  joerg       // In 'R"delimiter(...', the delimiter starts 2 characters after the start
   1741      1.1  joerg       // of the token.
   1742      1.1  joerg       SourceLocation PrefixDelimiterStart =
   1743      1.1  joerg           Current.Tok.getLocation().getLocWithOffset(2);
   1744      1.1  joerg       auto PrefixErr = Whitespaces.addReplacement(tooling::Replacement(
   1745      1.1  joerg           SourceMgr, PrefixDelimiterStart, OldDelimiter.size(), NewDelimiter));
   1746      1.1  joerg       if (PrefixErr) {
   1747      1.1  joerg         llvm::errs()
   1748      1.1  joerg             << "Failed to update the prefix delimiter of a raw string: "
   1749      1.1  joerg             << llvm::toString(std::move(PrefixErr)) << "\n";
   1750      1.1  joerg       }
   1751      1.1  joerg       // In 'R"delimiter(...)delimiter"', the suffix delimiter starts at
   1752      1.1  joerg       // position length - 1 - |delimiter|.
   1753      1.1  joerg       SourceLocation SuffixDelimiterStart =
   1754      1.1  joerg           Current.Tok.getLocation().getLocWithOffset(Current.TokenText.size() -
   1755      1.1  joerg                                                      1 - OldDelimiter.size());
   1756      1.1  joerg       auto SuffixErr = Whitespaces.addReplacement(tooling::Replacement(
   1757      1.1  joerg           SourceMgr, SuffixDelimiterStart, OldDelimiter.size(), NewDelimiter));
   1758      1.1  joerg       if (SuffixErr) {
   1759      1.1  joerg         llvm::errs()
   1760      1.1  joerg             << "Failed to update the suffix delimiter of a raw string: "
   1761      1.1  joerg             << llvm::toString(std::move(SuffixErr)) << "\n";
   1762      1.1  joerg       }
   1763      1.1  joerg     }
   1764      1.1  joerg     SourceLocation OriginLoc =
   1765      1.1  joerg         Current.Tok.getLocation().getLocWithOffset(OldPrefixSize);
   1766      1.1  joerg     for (const tooling::Replacement &Fix : Fixes.first) {
   1767      1.1  joerg       auto Err = Whitespaces.addReplacement(tooling::Replacement(
   1768      1.1  joerg           SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()),
   1769      1.1  joerg           Fix.getLength(), Fix.getReplacementText()));
   1770      1.1  joerg       if (Err) {
   1771      1.1  joerg         llvm::errs() << "Failed to reformat raw string: "
   1772      1.1  joerg                      << llvm::toString(std::move(Err)) << "\n";
   1773      1.1  joerg       }
   1774      1.1  joerg     }
   1775      1.1  joerg   }
   1776      1.1  joerg   unsigned RawLastLineEndColumn = getLastLineEndColumn(
   1777      1.1  joerg       *NewCode, FirstStartColumn, Style.TabWidth, Encoding);
   1778      1.1  joerg   State.Column = RawLastLineEndColumn + NewSuffixSize;
   1779      1.1  joerg   // Since we're updating the column to after the raw string literal here, we
   1780      1.1  joerg   // have to manually add the penalty for the prefix R"delim( over the column
   1781      1.1  joerg   // limit.
   1782      1.1  joerg   unsigned PrefixExcessCharacters =
   1783      1.1  joerg       StartColumn + NewPrefixSize > Style.ColumnLimit
   1784      1.1  joerg           ? StartColumn + NewPrefixSize - Style.ColumnLimit
   1785      1.1  joerg           : 0;
   1786      1.1  joerg   bool IsMultiline =
   1787      1.1  joerg       ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
   1788      1.1  joerg   if (IsMultiline) {
   1789      1.1  joerg     // Break before further function parameters on all levels.
   1790      1.1  joerg     for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
   1791      1.1  joerg       State.Stack[i].BreakBeforeParameter = true;
   1792      1.1  joerg   }
   1793      1.1  joerg   return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
   1794      1.1  joerg }
   1795      1.1  joerg 
   1796      1.1  joerg unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current,
   1797      1.1  joerg                                                  LineState &State) {
   1798      1.1  joerg   // Break before further function parameters on all levels.
   1799      1.1  joerg   for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
   1800      1.1  joerg     State.Stack[i].BreakBeforeParameter = true;
   1801      1.1  joerg 
   1802      1.1  joerg   unsigned ColumnsUsed = State.Column;
   1803      1.1  joerg   // We can only affect layout of the first and the last line, so the penalty
   1804      1.1  joerg   // for all other lines is constant, and we ignore it.
   1805      1.1  joerg   State.Column = Current.LastLineColumnWidth;
   1806      1.1  joerg 
   1807      1.1  joerg   if (ColumnsUsed > getColumnLimit(State))
   1808      1.1  joerg     return Style.PenaltyExcessCharacter * (ColumnsUsed - getColumnLimit(State));
   1809      1.1  joerg   return 0;
   1810      1.1  joerg }
   1811      1.1  joerg 
   1812      1.1  joerg unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
   1813      1.1  joerg                                                LineState &State, bool DryRun,
   1814      1.1  joerg                                                bool AllowBreak, bool Newline) {
   1815      1.1  joerg   unsigned Penalty = 0;
   1816      1.1  joerg   // Compute the raw string style to use in case this is a raw string literal
   1817      1.1  joerg   // that can be reformatted.
   1818      1.1  joerg   auto RawStringStyle = getRawStringStyle(Current, State);
   1819      1.1  joerg   if (RawStringStyle && !Current.Finalized) {
   1820      1.1  joerg     Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
   1821      1.1  joerg                                        Newline);
   1822      1.1  joerg   } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
   1823      1.1  joerg     // Don't break multi-line tokens other than block comments and raw string
   1824      1.1  joerg     // literals. Instead, just update the state.
   1825      1.1  joerg     Penalty = addMultilineToken(Current, State);
   1826      1.1  joerg   } else if (State.Line->Type != LT_ImportStatement) {
   1827      1.1  joerg     // We generally don't break import statements.
   1828      1.1  joerg     LineState OriginalState = State;
   1829      1.1  joerg 
   1830      1.1  joerg     // Whether we force the reflowing algorithm to stay strictly within the
   1831      1.1  joerg     // column limit.
   1832      1.1  joerg     bool Strict = false;
   1833      1.1  joerg     // Whether the first non-strict attempt at reflowing did intentionally
   1834      1.1  joerg     // exceed the column limit.
   1835      1.1  joerg     bool Exceeded = false;
   1836      1.1  joerg     std::tie(Penalty, Exceeded) = breakProtrudingToken(
   1837      1.1  joerg         Current, State, AllowBreak, /*DryRun=*/true, Strict);
   1838      1.1  joerg     if (Exceeded) {
   1839      1.1  joerg       // If non-strict reflowing exceeds the column limit, try whether strict
   1840      1.1  joerg       // reflowing leads to an overall lower penalty.
   1841      1.1  joerg       LineState StrictState = OriginalState;
   1842      1.1  joerg       unsigned StrictPenalty =
   1843      1.1  joerg           breakProtrudingToken(Current, StrictState, AllowBreak,
   1844      1.1  joerg                                /*DryRun=*/true, /*Strict=*/true)
   1845      1.1  joerg               .first;
   1846      1.1  joerg       Strict = StrictPenalty <= Penalty;
   1847      1.1  joerg       if (Strict) {
   1848      1.1  joerg         Penalty = StrictPenalty;
   1849      1.1  joerg         State = StrictState;
   1850      1.1  joerg       }
   1851      1.1  joerg     }
   1852      1.1  joerg     if (!DryRun) {
   1853      1.1  joerg       // If we're not in dry-run mode, apply the changes with the decision on
   1854      1.1  joerg       // strictness made above.
   1855      1.1  joerg       breakProtrudingToken(Current, OriginalState, AllowBreak, /*DryRun=*/false,
   1856      1.1  joerg                            Strict);
   1857      1.1  joerg     }
   1858      1.1  joerg   }
   1859      1.1  joerg   if (State.Column > getColumnLimit(State)) {
   1860      1.1  joerg     unsigned ExcessCharacters = State.Column - getColumnLimit(State);
   1861      1.1  joerg     Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
   1862      1.1  joerg   }
   1863      1.1  joerg   return Penalty;
   1864      1.1  joerg }
   1865      1.1  joerg 
   1866      1.1  joerg // Returns the enclosing function name of a token, or the empty string if not
   1867      1.1  joerg // found.
   1868      1.1  joerg static StringRef getEnclosingFunctionName(const FormatToken &Current) {
   1869      1.1  joerg   // Look for: 'function(' or 'function<templates>(' before Current.
   1870      1.1  joerg   auto Tok = Current.getPreviousNonComment();
   1871      1.1  joerg   if (!Tok || !Tok->is(tok::l_paren))
   1872      1.1  joerg     return "";
   1873      1.1  joerg   Tok = Tok->getPreviousNonComment();
   1874      1.1  joerg   if (!Tok)
   1875      1.1  joerg     return "";
   1876      1.1  joerg   if (Tok->is(TT_TemplateCloser)) {
   1877      1.1  joerg     Tok = Tok->MatchingParen;
   1878      1.1  joerg     if (Tok)
   1879      1.1  joerg       Tok = Tok->getPreviousNonComment();
   1880      1.1  joerg   }
   1881      1.1  joerg   if (!Tok || !Tok->is(tok::identifier))
   1882      1.1  joerg     return "";
   1883      1.1  joerg   return Tok->TokenText;
   1884      1.1  joerg }
   1885      1.1  joerg 
   1886      1.1  joerg llvm::Optional<FormatStyle>
   1887      1.1  joerg ContinuationIndenter::getRawStringStyle(const FormatToken &Current,
   1888      1.1  joerg                                         const LineState &State) {
   1889      1.1  joerg   if (!Current.isStringLiteral())
   1890      1.1  joerg     return None;
   1891      1.1  joerg   auto Delimiter = getRawStringDelimiter(Current.TokenText);
   1892      1.1  joerg   if (!Delimiter)
   1893      1.1  joerg     return None;
   1894      1.1  joerg   auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
   1895      1.1  joerg   if (!RawStringStyle && Delimiter->empty())
   1896      1.1  joerg     RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
   1897      1.1  joerg         getEnclosingFunctionName(Current));
   1898      1.1  joerg   if (!RawStringStyle)
   1899      1.1  joerg     return None;
   1900      1.1  joerg   RawStringStyle->ColumnLimit = getColumnLimit(State);
   1901      1.1  joerg   return RawStringStyle;
   1902      1.1  joerg }
   1903      1.1  joerg 
   1904      1.1  joerg std::unique_ptr<BreakableToken>
   1905      1.1  joerg ContinuationIndenter::createBreakableToken(const FormatToken &Current,
   1906      1.1  joerg                                            LineState &State, bool AllowBreak) {
   1907      1.1  joerg   unsigned StartColumn = State.Column - Current.ColumnWidth;
   1908      1.1  joerg   if (Current.isStringLiteral()) {
   1909  1.1.1.2  joerg     // FIXME: String literal breaking is currently disabled for C#, Java and
   1910      1.1  joerg     // JavaScript, as it requires strings to be merged using "+" which we
   1911      1.1  joerg     // don't support.
   1912      1.1  joerg     if (Style.Language == FormatStyle::LK_Java ||
   1913      1.1  joerg         Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp() ||
   1914      1.1  joerg         !Style.BreakStringLiterals || !AllowBreak)
   1915      1.1  joerg       return nullptr;
   1916      1.1  joerg 
   1917      1.1  joerg     // Don't break string literals inside preprocessor directives (except for
   1918      1.1  joerg     // #define directives, as their contents are stored in separate lines and
   1919      1.1  joerg     // are not affected by this check).
   1920      1.1  joerg     // This way we avoid breaking code with line directives and unknown
   1921      1.1  joerg     // preprocessor directives that contain long string literals.
   1922      1.1  joerg     if (State.Line->Type == LT_PreprocessorDirective)
   1923      1.1  joerg       return nullptr;
   1924      1.1  joerg     // Exempts unterminated string literals from line breaking. The user will
   1925      1.1  joerg     // likely want to terminate the string before any line breaking is done.
   1926      1.1  joerg     if (Current.IsUnterminatedLiteral)
   1927      1.1  joerg       return nullptr;
   1928      1.1  joerg     // Don't break string literals inside Objective-C array literals (doing so
   1929      1.1  joerg     // raises the warning -Wobjc-string-concatenation).
   1930      1.1  joerg     if (State.Stack.back().IsInsideObjCArrayLiteral) {
   1931      1.1  joerg       return nullptr;
   1932      1.1  joerg     }
   1933      1.1  joerg 
   1934      1.1  joerg     StringRef Text = Current.TokenText;
   1935      1.1  joerg     StringRef Prefix;
   1936      1.1  joerg     StringRef Postfix;
   1937      1.1  joerg     // FIXME: Handle whitespace between '_T', '(', '"..."', and ')'.
   1938      1.1  joerg     // FIXME: Store Prefix and Suffix (or PrefixLength and SuffixLength to
   1939      1.1  joerg     // reduce the overhead) for each FormatToken, which is a string, so that we
   1940      1.1  joerg     // don't run multiple checks here on the hot path.
   1941      1.1  joerg     if ((Text.endswith(Postfix = "\"") &&
   1942      1.1  joerg          (Text.startswith(Prefix = "@\"") || Text.startswith(Prefix = "\"") ||
   1943      1.1  joerg           Text.startswith(Prefix = "u\"") || Text.startswith(Prefix = "U\"") ||
   1944      1.1  joerg           Text.startswith(Prefix = "u8\"") ||
   1945      1.1  joerg           Text.startswith(Prefix = "L\""))) ||
   1946      1.1  joerg         (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))) {
   1947      1.1  joerg       // We need this to address the case where there is an unbreakable tail
   1948      1.1  joerg       // only if certain other formatting decisions have been taken. The
   1949      1.1  joerg       // UnbreakableTailLength of Current is an overapproximation is that case
   1950      1.1  joerg       // and we need to be correct here.
   1951      1.1  joerg       unsigned UnbreakableTailLength = (State.NextToken && canBreak(State))
   1952      1.1  joerg                                            ? 0
   1953      1.1  joerg                                            : Current.UnbreakableTailLength;
   1954      1.1  joerg       return std::make_unique<BreakableStringLiteral>(
   1955      1.1  joerg           Current, StartColumn, Prefix, Postfix, UnbreakableTailLength,
   1956      1.1  joerg           State.Line->InPPDirective, Encoding, Style);
   1957      1.1  joerg     }
   1958      1.1  joerg   } else if (Current.is(TT_BlockComment)) {
   1959      1.1  joerg     if (!Style.ReflowComments ||
   1960      1.1  joerg         // If a comment token switches formatting, like
   1961      1.1  joerg         // /* clang-format on */, we don't want to break it further,
   1962      1.1  joerg         // but we may still want to adjust its indentation.
   1963      1.1  joerg         switchesFormatting(Current)) {
   1964      1.1  joerg       return nullptr;
   1965      1.1  joerg     }
   1966      1.1  joerg     return std::make_unique<BreakableBlockComment>(
   1967      1.1  joerg         Current, StartColumn, Current.OriginalColumn, !Current.Previous,
   1968      1.1  joerg         State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
   1969      1.1  joerg   } else if (Current.is(TT_LineComment) &&
   1970      1.1  joerg              (Current.Previous == nullptr ||
   1971      1.1  joerg               Current.Previous->isNot(TT_ImplicitStringLiteral))) {
   1972      1.1  joerg     if (!Style.ReflowComments ||
   1973      1.1  joerg         CommentPragmasRegex.match(Current.TokenText.substr(2)) ||
   1974      1.1  joerg         switchesFormatting(Current))
   1975      1.1  joerg       return nullptr;
   1976      1.1  joerg     return std::make_unique<BreakableLineCommentSection>(
   1977  1.1.1.2  joerg         Current, StartColumn, /*InPPDirective=*/false, Encoding, Style);
   1978      1.1  joerg   }
   1979      1.1  joerg   return nullptr;
   1980      1.1  joerg }
   1981      1.1  joerg 
   1982      1.1  joerg std::pair<unsigned, bool>
   1983      1.1  joerg ContinuationIndenter::breakProtrudingToken(const FormatToken &Current,
   1984      1.1  joerg                                            LineState &State, bool AllowBreak,
   1985      1.1  joerg                                            bool DryRun, bool Strict) {
   1986      1.1  joerg   std::unique_ptr<const BreakableToken> Token =
   1987      1.1  joerg       createBreakableToken(Current, State, AllowBreak);
   1988      1.1  joerg   if (!Token)
   1989      1.1  joerg     return {0, false};
   1990      1.1  joerg   assert(Token->getLineCount() > 0);
   1991      1.1  joerg   unsigned ColumnLimit = getColumnLimit(State);
   1992      1.1  joerg   if (Current.is(TT_LineComment)) {
   1993      1.1  joerg     // We don't insert backslashes when breaking line comments.
   1994      1.1  joerg     ColumnLimit = Style.ColumnLimit;
   1995      1.1  joerg   }
   1996  1.1.1.2  joerg   if (ColumnLimit == 0) {
   1997  1.1.1.2  joerg     // To make the rest of the function easier set the column limit to the
   1998  1.1.1.2  joerg     // maximum, if there should be no limit.
   1999  1.1.1.2  joerg     ColumnLimit = std::numeric_limits<decltype(ColumnLimit)>::max();
   2000  1.1.1.2  joerg   }
   2001      1.1  joerg   if (Current.UnbreakableTailLength >= ColumnLimit)
   2002      1.1  joerg     return {0, false};
   2003      1.1  joerg   // ColumnWidth was already accounted into State.Column before calling
   2004      1.1  joerg   // breakProtrudingToken.
   2005      1.1  joerg   unsigned StartColumn = State.Column - Current.ColumnWidth;
   2006      1.1  joerg   unsigned NewBreakPenalty = Current.isStringLiteral()
   2007      1.1  joerg                                  ? Style.PenaltyBreakString
   2008      1.1  joerg                                  : Style.PenaltyBreakComment;
   2009      1.1  joerg   // Stores whether we intentionally decide to let a line exceed the column
   2010      1.1  joerg   // limit.
   2011      1.1  joerg   bool Exceeded = false;
   2012      1.1  joerg   // Stores whether we introduce a break anywhere in the token.
   2013      1.1  joerg   bool BreakInserted = Token->introducesBreakBeforeToken();
   2014      1.1  joerg   // Store whether we inserted a new line break at the end of the previous
   2015      1.1  joerg   // logical line.
   2016      1.1  joerg   bool NewBreakBefore = false;
   2017      1.1  joerg   // We use a conservative reflowing strategy. Reflow starts after a line is
   2018      1.1  joerg   // broken or the corresponding whitespace compressed. Reflow ends as soon as a
   2019      1.1  joerg   // line that doesn't get reflown with the previous line is reached.
   2020      1.1  joerg   bool Reflow = false;
   2021      1.1  joerg   // Keep track of where we are in the token:
   2022      1.1  joerg   // Where we are in the content of the current logical line.
   2023      1.1  joerg   unsigned TailOffset = 0;
   2024      1.1  joerg   // The column number we're currently at.
   2025      1.1  joerg   unsigned ContentStartColumn =
   2026      1.1  joerg       Token->getContentStartColumn(0, /*Break=*/false);
   2027      1.1  joerg   // The number of columns left in the current logical line after TailOffset.
   2028      1.1  joerg   unsigned RemainingTokenColumns =
   2029      1.1  joerg       Token->getRemainingLength(0, TailOffset, ContentStartColumn);
   2030      1.1  joerg   // Adapt the start of the token, for example indent.
   2031      1.1  joerg   if (!DryRun)
   2032      1.1  joerg     Token->adaptStartOfLine(0, Whitespaces);
   2033      1.1  joerg 
   2034      1.1  joerg   unsigned ContentIndent = 0;
   2035      1.1  joerg   unsigned Penalty = 0;
   2036      1.1  joerg   LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
   2037      1.1  joerg                           << StartColumn << ".\n");
   2038      1.1  joerg   for (unsigned LineIndex = 0, EndIndex = Token->getLineCount();
   2039      1.1  joerg        LineIndex != EndIndex; ++LineIndex) {
   2040      1.1  joerg     LLVM_DEBUG(llvm::dbgs()
   2041      1.1  joerg                << "  Line: " << LineIndex << " (Reflow: " << Reflow << ")\n");
   2042      1.1  joerg     NewBreakBefore = false;
   2043      1.1  joerg     // If we did reflow the previous line, we'll try reflowing again. Otherwise
   2044      1.1  joerg     // we'll start reflowing if the current line is broken or whitespace is
   2045      1.1  joerg     // compressed.
   2046      1.1  joerg     bool TryReflow = Reflow;
   2047      1.1  joerg     // Break the current token until we can fit the rest of the line.
   2048      1.1  joerg     while (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
   2049      1.1  joerg       LLVM_DEBUG(llvm::dbgs() << "    Over limit, need: "
   2050      1.1  joerg                               << (ContentStartColumn + RemainingTokenColumns)
   2051      1.1  joerg                               << ", space: " << ColumnLimit
   2052      1.1  joerg                               << ", reflown prefix: " << ContentStartColumn
   2053      1.1  joerg                               << ", offset in line: " << TailOffset << "\n");
   2054      1.1  joerg       // If the current token doesn't fit, find the latest possible split in the
   2055      1.1  joerg       // current line so that breaking at it will be under the column limit.
   2056      1.1  joerg       // FIXME: Use the earliest possible split while reflowing to correctly
   2057      1.1  joerg       // compress whitespace within a line.
   2058      1.1  joerg       BreakableToken::Split Split =
   2059      1.1  joerg           Token->getSplit(LineIndex, TailOffset, ColumnLimit,
   2060      1.1  joerg                           ContentStartColumn, CommentPragmasRegex);
   2061      1.1  joerg       if (Split.first == StringRef::npos) {
   2062      1.1  joerg         // No break opportunity - update the penalty and continue with the next
   2063      1.1  joerg         // logical line.
   2064      1.1  joerg         if (LineIndex < EndIndex - 1)
   2065      1.1  joerg           // The last line's penalty is handled in addNextStateToQueue() or when
   2066      1.1  joerg           // calling replaceWhitespaceAfterLastLine below.
   2067      1.1  joerg           Penalty += Style.PenaltyExcessCharacter *
   2068      1.1  joerg                      (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
   2069      1.1  joerg         LLVM_DEBUG(llvm::dbgs() << "    No break opportunity.\n");
   2070      1.1  joerg         break;
   2071      1.1  joerg       }
   2072      1.1  joerg       assert(Split.first != 0);
   2073      1.1  joerg 
   2074      1.1  joerg       if (Token->supportsReflow()) {
   2075      1.1  joerg         // Check whether the next natural split point after the current one can
   2076      1.1  joerg         // still fit the line, either because we can compress away whitespace,
   2077      1.1  joerg         // or because the penalty the excess characters introduce is lower than
   2078      1.1  joerg         // the break penalty.
   2079      1.1  joerg         // We only do this for tokens that support reflowing, and thus allow us
   2080      1.1  joerg         // to change the whitespace arbitrarily (e.g. comments).
   2081      1.1  joerg         // Other tokens, like string literals, can be broken on arbitrary
   2082      1.1  joerg         // positions.
   2083      1.1  joerg 
   2084      1.1  joerg         // First, compute the columns from TailOffset to the next possible split
   2085      1.1  joerg         // position.
   2086      1.1  joerg         // For example:
   2087      1.1  joerg         // ColumnLimit:     |
   2088      1.1  joerg         // // Some text   that    breaks
   2089      1.1  joerg         //    ^ tail offset
   2090      1.1  joerg         //             ^-- split
   2091      1.1  joerg         //    ^-------- to split columns
   2092      1.1  joerg         //                    ^--- next split
   2093      1.1  joerg         //    ^--------------- to next split columns
   2094      1.1  joerg         unsigned ToSplitColumns = Token->getRangeLength(
   2095      1.1  joerg             LineIndex, TailOffset, Split.first, ContentStartColumn);
   2096      1.1  joerg         LLVM_DEBUG(llvm::dbgs() << "    ToSplit: " << ToSplitColumns << "\n");
   2097      1.1  joerg 
   2098      1.1  joerg         BreakableToken::Split NextSplit = Token->getSplit(
   2099      1.1  joerg             LineIndex, TailOffset + Split.first + Split.second, ColumnLimit,
   2100      1.1  joerg             ContentStartColumn + ToSplitColumns + 1, CommentPragmasRegex);
   2101      1.1  joerg         // Compute the columns necessary to fit the next non-breakable sequence
   2102      1.1  joerg         // into the current line.
   2103      1.1  joerg         unsigned ToNextSplitColumns = 0;
   2104      1.1  joerg         if (NextSplit.first == StringRef::npos) {
   2105      1.1  joerg           ToNextSplitColumns = Token->getRemainingLength(LineIndex, TailOffset,
   2106      1.1  joerg                                                          ContentStartColumn);
   2107      1.1  joerg         } else {
   2108      1.1  joerg           ToNextSplitColumns = Token->getRangeLength(
   2109      1.1  joerg               LineIndex, TailOffset,
   2110      1.1  joerg               Split.first + Split.second + NextSplit.first, ContentStartColumn);
   2111      1.1  joerg         }
   2112      1.1  joerg         // Compress the whitespace between the break and the start of the next
   2113      1.1  joerg         // unbreakable sequence.
   2114      1.1  joerg         ToNextSplitColumns =
   2115      1.1  joerg             Token->getLengthAfterCompression(ToNextSplitColumns, Split);
   2116      1.1  joerg         LLVM_DEBUG(llvm::dbgs()
   2117      1.1  joerg                    << "    ContentStartColumn: " << ContentStartColumn << "\n");
   2118      1.1  joerg         LLVM_DEBUG(llvm::dbgs()
   2119      1.1  joerg                    << "    ToNextSplit: " << ToNextSplitColumns << "\n");
   2120      1.1  joerg         // If the whitespace compression makes us fit, continue on the current
   2121      1.1  joerg         // line.
   2122      1.1  joerg         bool ContinueOnLine =
   2123      1.1  joerg             ContentStartColumn + ToNextSplitColumns <= ColumnLimit;
   2124      1.1  joerg         unsigned ExcessCharactersPenalty = 0;
   2125      1.1  joerg         if (!ContinueOnLine && !Strict) {
   2126      1.1  joerg           // Similarly, if the excess characters' penalty is lower than the
   2127      1.1  joerg           // penalty of introducing a new break, continue on the current line.
   2128      1.1  joerg           ExcessCharactersPenalty =
   2129      1.1  joerg               (ContentStartColumn + ToNextSplitColumns - ColumnLimit) *
   2130      1.1  joerg               Style.PenaltyExcessCharacter;
   2131      1.1  joerg           LLVM_DEBUG(llvm::dbgs()
   2132      1.1  joerg                      << "    Penalty excess: " << ExcessCharactersPenalty
   2133      1.1  joerg                      << "\n            break : " << NewBreakPenalty << "\n");
   2134      1.1  joerg           if (ExcessCharactersPenalty < NewBreakPenalty) {
   2135      1.1  joerg             Exceeded = true;
   2136      1.1  joerg             ContinueOnLine = true;
   2137      1.1  joerg           }
   2138      1.1  joerg         }
   2139      1.1  joerg         if (ContinueOnLine) {
   2140      1.1  joerg           LLVM_DEBUG(llvm::dbgs() << "    Continuing on line...\n");
   2141      1.1  joerg           // The current line fits after compressing the whitespace - reflow
   2142      1.1  joerg           // the next line into it if possible.
   2143      1.1  joerg           TryReflow = true;
   2144      1.1  joerg           if (!DryRun)
   2145      1.1  joerg             Token->compressWhitespace(LineIndex, TailOffset, Split,
   2146      1.1  joerg                                       Whitespaces);
   2147      1.1  joerg           // When we continue on the same line, leave one space between content.
   2148      1.1  joerg           ContentStartColumn += ToSplitColumns + 1;
   2149      1.1  joerg           Penalty += ExcessCharactersPenalty;
   2150      1.1  joerg           TailOffset += Split.first + Split.second;
   2151      1.1  joerg           RemainingTokenColumns = Token->getRemainingLength(
   2152      1.1  joerg               LineIndex, TailOffset, ContentStartColumn);
   2153      1.1  joerg           continue;
   2154      1.1  joerg         }
   2155      1.1  joerg       }
   2156      1.1  joerg       LLVM_DEBUG(llvm::dbgs() << "    Breaking...\n");
   2157      1.1  joerg       // Update the ContentIndent only if the current line was not reflown with
   2158      1.1  joerg       // the previous line, since in that case the previous line should still
   2159      1.1  joerg       // determine the ContentIndent. Also never intent the last line.
   2160      1.1  joerg       if (!Reflow)
   2161      1.1  joerg         ContentIndent = Token->getContentIndent(LineIndex);
   2162      1.1  joerg       LLVM_DEBUG(llvm::dbgs()
   2163      1.1  joerg                  << "    ContentIndent: " << ContentIndent << "\n");
   2164      1.1  joerg       ContentStartColumn = ContentIndent + Token->getContentStartColumn(
   2165      1.1  joerg                                                LineIndex, /*Break=*/true);
   2166      1.1  joerg 
   2167      1.1  joerg       unsigned NewRemainingTokenColumns = Token->getRemainingLength(
   2168      1.1  joerg           LineIndex, TailOffset + Split.first + Split.second,
   2169      1.1  joerg           ContentStartColumn);
   2170      1.1  joerg       if (NewRemainingTokenColumns == 0) {
   2171      1.1  joerg         // No content to indent.
   2172      1.1  joerg         ContentIndent = 0;
   2173      1.1  joerg         ContentStartColumn =
   2174      1.1  joerg             Token->getContentStartColumn(LineIndex, /*Break=*/true);
   2175      1.1  joerg         NewRemainingTokenColumns = Token->getRemainingLength(
   2176      1.1  joerg             LineIndex, TailOffset + Split.first + Split.second,
   2177      1.1  joerg             ContentStartColumn);
   2178      1.1  joerg       }
   2179      1.1  joerg 
   2180      1.1  joerg       // When breaking before a tab character, it may be moved by a few columns,
   2181      1.1  joerg       // but will still be expanded to the next tab stop, so we don't save any
   2182      1.1  joerg       // columns.
   2183      1.1  joerg       if (NewRemainingTokenColumns == RemainingTokenColumns) {
   2184      1.1  joerg         // FIXME: Do we need to adjust the penalty?
   2185      1.1  joerg         break;
   2186      1.1  joerg       }
   2187      1.1  joerg       assert(NewRemainingTokenColumns < RemainingTokenColumns);
   2188      1.1  joerg 
   2189      1.1  joerg       LLVM_DEBUG(llvm::dbgs() << "    Breaking at: " << TailOffset + Split.first
   2190      1.1  joerg                               << ", " << Split.second << "\n");
   2191      1.1  joerg       if (!DryRun)
   2192      1.1  joerg         Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent,
   2193      1.1  joerg                            Whitespaces);
   2194      1.1  joerg 
   2195      1.1  joerg       Penalty += NewBreakPenalty;
   2196      1.1  joerg       TailOffset += Split.first + Split.second;
   2197      1.1  joerg       RemainingTokenColumns = NewRemainingTokenColumns;
   2198      1.1  joerg       BreakInserted = true;
   2199      1.1  joerg       NewBreakBefore = true;
   2200      1.1  joerg     }
   2201      1.1  joerg     // In case there's another line, prepare the state for the start of the next
   2202      1.1  joerg     // line.
   2203      1.1  joerg     if (LineIndex + 1 != EndIndex) {
   2204      1.1  joerg       unsigned NextLineIndex = LineIndex + 1;
   2205      1.1  joerg       if (NewBreakBefore)
   2206      1.1  joerg         // After breaking a line, try to reflow the next line into the current
   2207      1.1  joerg         // one once RemainingTokenColumns fits.
   2208      1.1  joerg         TryReflow = true;
   2209      1.1  joerg       if (TryReflow) {
   2210      1.1  joerg         // We decided that we want to try reflowing the next line into the
   2211      1.1  joerg         // current one.
   2212      1.1  joerg         // We will now adjust the state as if the reflow is successful (in
   2213      1.1  joerg         // preparation for the next line), and see whether that works. If we
   2214      1.1  joerg         // decide that we cannot reflow, we will later reset the state to the
   2215      1.1  joerg         // start of the next line.
   2216      1.1  joerg         Reflow = false;
   2217      1.1  joerg         // As we did not continue breaking the line, RemainingTokenColumns is
   2218      1.1  joerg         // known to fit after ContentStartColumn. Adapt ContentStartColumn to
   2219      1.1  joerg         // the position at which we want to format the next line if we do
   2220      1.1  joerg         // actually reflow.
   2221      1.1  joerg         // When we reflow, we need to add a space between the end of the current
   2222      1.1  joerg         // line and the next line's start column.
   2223      1.1  joerg         ContentStartColumn += RemainingTokenColumns + 1;
   2224      1.1  joerg         // Get the split that we need to reflow next logical line into the end
   2225      1.1  joerg         // of the current one; the split will include any leading whitespace of
   2226      1.1  joerg         // the next logical line.
   2227      1.1  joerg         BreakableToken::Split SplitBeforeNext =
   2228      1.1  joerg             Token->getReflowSplit(NextLineIndex, CommentPragmasRegex);
   2229      1.1  joerg         LLVM_DEBUG(llvm::dbgs()
   2230      1.1  joerg                    << "    Size of reflown text: " << ContentStartColumn
   2231      1.1  joerg                    << "\n    Potential reflow split: ");
   2232      1.1  joerg         if (SplitBeforeNext.first != StringRef::npos) {
   2233      1.1  joerg           LLVM_DEBUG(llvm::dbgs() << SplitBeforeNext.first << ", "
   2234      1.1  joerg                                   << SplitBeforeNext.second << "\n");
   2235      1.1  joerg           TailOffset = SplitBeforeNext.first + SplitBeforeNext.second;
   2236      1.1  joerg           // If the rest of the next line fits into the current line below the
   2237      1.1  joerg           // column limit, we can safely reflow.
   2238      1.1  joerg           RemainingTokenColumns = Token->getRemainingLength(
   2239      1.1  joerg               NextLineIndex, TailOffset, ContentStartColumn);
   2240      1.1  joerg           Reflow = true;
   2241      1.1  joerg           if (ContentStartColumn + RemainingTokenColumns > ColumnLimit) {
   2242      1.1  joerg             LLVM_DEBUG(llvm::dbgs()
   2243      1.1  joerg                        << "    Over limit after reflow, need: "
   2244      1.1  joerg                        << (ContentStartColumn + RemainingTokenColumns)
   2245      1.1  joerg                        << ", space: " << ColumnLimit
   2246      1.1  joerg                        << ", reflown prefix: " << ContentStartColumn
   2247      1.1  joerg                        << ", offset in line: " << TailOffset << "\n");
   2248      1.1  joerg             // If the whole next line does not fit, try to find a point in
   2249      1.1  joerg             // the next line at which we can break so that attaching the part
   2250      1.1  joerg             // of the next line to that break point onto the current line is
   2251      1.1  joerg             // below the column limit.
   2252      1.1  joerg             BreakableToken::Split Split =
   2253      1.1  joerg                 Token->getSplit(NextLineIndex, TailOffset, ColumnLimit,
   2254      1.1  joerg                                 ContentStartColumn, CommentPragmasRegex);
   2255      1.1  joerg             if (Split.first == StringRef::npos) {
   2256      1.1  joerg               LLVM_DEBUG(llvm::dbgs() << "    Did not find later break\n");
   2257      1.1  joerg               Reflow = false;
   2258      1.1  joerg             } else {
   2259      1.1  joerg               // Check whether the first split point gets us below the column
   2260      1.1  joerg               // limit. Note that we will execute this split below as part of
   2261      1.1  joerg               // the normal token breaking and reflow logic within the line.
   2262      1.1  joerg               unsigned ToSplitColumns = Token->getRangeLength(
   2263      1.1  joerg                   NextLineIndex, TailOffset, Split.first, ContentStartColumn);
   2264      1.1  joerg               if (ContentStartColumn + ToSplitColumns > ColumnLimit) {
   2265      1.1  joerg                 LLVM_DEBUG(llvm::dbgs() << "    Next split protrudes, need: "
   2266      1.1  joerg                                         << (ContentStartColumn + ToSplitColumns)
   2267      1.1  joerg                                         << ", space: " << ColumnLimit);
   2268      1.1  joerg                 unsigned ExcessCharactersPenalty =
   2269      1.1  joerg                     (ContentStartColumn + ToSplitColumns - ColumnLimit) *
   2270      1.1  joerg                     Style.PenaltyExcessCharacter;
   2271      1.1  joerg                 if (NewBreakPenalty < ExcessCharactersPenalty) {
   2272      1.1  joerg                   Reflow = false;
   2273      1.1  joerg                 }
   2274      1.1  joerg               }
   2275      1.1  joerg             }
   2276      1.1  joerg           }
   2277      1.1  joerg         } else {
   2278      1.1  joerg           LLVM_DEBUG(llvm::dbgs() << "not found.\n");
   2279      1.1  joerg         }
   2280      1.1  joerg       }
   2281      1.1  joerg       if (!Reflow) {
   2282      1.1  joerg         // If we didn't reflow into the next line, the only space to consider is
   2283      1.1  joerg         // the next logical line. Reset our state to match the start of the next
   2284      1.1  joerg         // line.
   2285      1.1  joerg         TailOffset = 0;
   2286      1.1  joerg         ContentStartColumn =
   2287      1.1  joerg             Token->getContentStartColumn(NextLineIndex, /*Break=*/false);
   2288      1.1  joerg         RemainingTokenColumns = Token->getRemainingLength(
   2289      1.1  joerg             NextLineIndex, TailOffset, ContentStartColumn);
   2290      1.1  joerg         // Adapt the start of the token, for example indent.
   2291      1.1  joerg         if (!DryRun)
   2292      1.1  joerg           Token->adaptStartOfLine(NextLineIndex, Whitespaces);
   2293      1.1  joerg       } else {
   2294      1.1  joerg         // If we found a reflow split and have added a new break before the next
   2295      1.1  joerg         // line, we are going to remove the line break at the start of the next
   2296      1.1  joerg         // logical line. For example, here we'll add a new line break after
   2297      1.1  joerg         // 'text', and subsequently delete the line break between 'that' and
   2298      1.1  joerg         // 'reflows'.
   2299      1.1  joerg         //   // some text that
   2300      1.1  joerg         //   // reflows
   2301      1.1  joerg         // ->
   2302      1.1  joerg         //   // some text
   2303      1.1  joerg         //   // that reflows
   2304      1.1  joerg         // When adding the line break, we also added the penalty for it, so we
   2305      1.1  joerg         // need to subtract that penalty again when we remove the line break due
   2306      1.1  joerg         // to reflowing.
   2307      1.1  joerg         if (NewBreakBefore) {
   2308      1.1  joerg           assert(Penalty >= NewBreakPenalty);
   2309      1.1  joerg           Penalty -= NewBreakPenalty;
   2310      1.1  joerg         }
   2311      1.1  joerg         if (!DryRun)
   2312      1.1  joerg           Token->reflow(NextLineIndex, Whitespaces);
   2313      1.1  joerg       }
   2314      1.1  joerg     }
   2315      1.1  joerg   }
   2316      1.1  joerg 
   2317      1.1  joerg   BreakableToken::Split SplitAfterLastLine =
   2318      1.1  joerg       Token->getSplitAfterLastLine(TailOffset);
   2319      1.1  joerg   if (SplitAfterLastLine.first != StringRef::npos) {
   2320      1.1  joerg     LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
   2321      1.1  joerg 
   2322      1.1  joerg     // We add the last line's penalty here, since that line is going to be split
   2323      1.1  joerg     // now.
   2324      1.1  joerg     Penalty += Style.PenaltyExcessCharacter *
   2325      1.1  joerg                (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
   2326      1.1  joerg 
   2327      1.1  joerg     if (!DryRun)
   2328      1.1  joerg       Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
   2329      1.1  joerg                                             Whitespaces);
   2330      1.1  joerg     ContentStartColumn =
   2331      1.1  joerg         Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true);
   2332      1.1  joerg     RemainingTokenColumns = Token->getRemainingLength(
   2333      1.1  joerg         Token->getLineCount() - 1,
   2334      1.1  joerg         TailOffset + SplitAfterLastLine.first + SplitAfterLastLine.second,
   2335      1.1  joerg         ContentStartColumn);
   2336      1.1  joerg   }
   2337      1.1  joerg 
   2338      1.1  joerg   State.Column = ContentStartColumn + RemainingTokenColumns -
   2339      1.1  joerg                  Current.UnbreakableTailLength;
   2340      1.1  joerg 
   2341      1.1  joerg   if (BreakInserted) {
   2342      1.1  joerg     // If we break the token inside a parameter list, we need to break before
   2343      1.1  joerg     // the next parameter on all levels, so that the next parameter is clearly
   2344      1.1  joerg     // visible. Line comments already introduce a break.
   2345      1.1  joerg     if (Current.isNot(TT_LineComment)) {
   2346      1.1  joerg       for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
   2347      1.1  joerg         State.Stack[i].BreakBeforeParameter = true;
   2348      1.1  joerg     }
   2349      1.1  joerg 
   2350      1.1  joerg     if (Current.is(TT_BlockComment))
   2351      1.1  joerg       State.NoContinuation = true;
   2352      1.1  joerg 
   2353      1.1  joerg     State.Stack.back().LastSpace = StartColumn;
   2354      1.1  joerg   }
   2355      1.1  joerg 
   2356      1.1  joerg   Token->updateNextToken(State);
   2357      1.1  joerg 
   2358      1.1  joerg   return {Penalty, Exceeded};
   2359      1.1  joerg }
   2360      1.1  joerg 
   2361      1.1  joerg unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const {
   2362      1.1  joerg   // In preprocessor directives reserve two chars for trailing " \"
   2363      1.1  joerg   return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0);
   2364      1.1  joerg }
   2365      1.1  joerg 
   2366      1.1  joerg bool ContinuationIndenter::nextIsMultilineString(const LineState &State) {
   2367      1.1  joerg   const FormatToken &Current = *State.NextToken;
   2368      1.1  joerg   if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral))
   2369      1.1  joerg     return false;
   2370      1.1  joerg   // We never consider raw string literals "multiline" for the purpose of
   2371      1.1  joerg   // AlwaysBreakBeforeMultilineStrings implementation as they are special-cased
   2372      1.1  joerg   // (see TokenAnnotator::mustBreakBefore().
   2373      1.1  joerg   if (Current.TokenText.startswith("R\""))
   2374      1.1  joerg     return false;
   2375      1.1  joerg   if (Current.IsMultiline)
   2376      1.1  joerg     return true;
   2377      1.1  joerg   if (Current.getNextNonComment() &&
   2378      1.1  joerg       Current.getNextNonComment()->isStringLiteral())
   2379      1.1  joerg     return true; // Implicit concatenation.
   2380      1.1  joerg   if (Style.ColumnLimit != 0 && Style.BreakStringLiterals &&
   2381      1.1  joerg       State.Column + Current.ColumnWidth + Current.UnbreakableTailLength >
   2382      1.1  joerg           Style.ColumnLimit)
   2383      1.1  joerg     return true; // String will be split.
   2384      1.1  joerg   return false;
   2385      1.1  joerg }
   2386      1.1  joerg 
   2387      1.1  joerg } // namespace format
   2388      1.1  joerg } // namespace clang
   2389