Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1 | //===--- Format.cpp - Format C++ code -------------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | /// |
| 10 | /// \file |
| 11 | /// \brief This file implements functions declared in Format.h. This will be |
| 12 | /// split into separate files as we go. |
| 13 | /// |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Manuel Klimek | ca547db | 2013-01-16 14:55:28 +0000 | [diff] [blame] | 16 | #define DEBUG_TYPE "format-formatter" |
| 17 | |
Daniel Jasper | 32d28ee | 2013-01-29 21:01:14 +0000 | [diff] [blame] | 18 | #include "TokenAnnotator.h" |
Chandler Carruth | 55fc873 | 2012-12-04 09:13:33 +0000 | [diff] [blame] | 19 | #include "UnwrappedLineParser.h" |
Alexander Kornienko | 3048aea | 2013-01-10 15:05:09 +0000 | [diff] [blame] | 20 | #include "clang/Basic/Diagnostic.h" |
Daniel Jasper | 675d2e3 | 2012-12-21 10:20:02 +0000 | [diff] [blame] | 21 | #include "clang/Basic/OperatorPrecedence.h" |
Chandler Carruth | b99083e | 2013-01-02 10:28:36 +0000 | [diff] [blame] | 22 | #include "clang/Basic/SourceManager.h" |
Manuel Klimek | ca547db | 2013-01-16 14:55:28 +0000 | [diff] [blame] | 23 | #include "clang/Format/Format.h" |
Alexander Kornienko | 3048aea | 2013-01-10 15:05:09 +0000 | [diff] [blame] | 24 | #include "clang/Frontend/TextDiagnosticPrinter.h" |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 25 | #include "clang/Lex/Lexer.h" |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 26 | #include "llvm/Support/Allocator.h" |
Manuel Klimek | ca547db | 2013-01-16 14:55:28 +0000 | [diff] [blame] | 27 | #include "llvm/Support/Debug.h" |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 28 | #include <queue> |
Daniel Jasper | 8822d3a | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 29 | #include <string> |
| 30 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 31 | namespace clang { |
| 32 | namespace format { |
| 33 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 34 | FormatStyle getLLVMStyle() { |
| 35 | FormatStyle LLVMStyle; |
| 36 | LLVMStyle.ColumnLimit = 80; |
| 37 | LLVMStyle.MaxEmptyLinesToKeep = 1; |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 38 | LLVMStyle.PointerBindsToType = false; |
| 39 | LLVMStyle.DerivePointerBinding = false; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 40 | LLVMStyle.AccessModifierOffset = -2; |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 41 | LLVMStyle.Standard = FormatStyle::LS_Cpp03; |
Alexander Kornienko | 1575731 | 2012-12-06 18:03:27 +0000 | [diff] [blame] | 42 | LLVMStyle.IndentCaseLabels = false; |
Daniel Jasper | 7ad4eff | 2013-01-07 11:09:06 +0000 | [diff] [blame] | 43 | LLVMStyle.SpacesBeforeTrailingComments = 1; |
Daniel Jasper | 0df6acd | 2013-01-16 14:59:02 +0000 | [diff] [blame] | 44 | LLVMStyle.BinPackParameters = true; |
Daniel Jasper | f157960 | 2013-01-29 16:03:49 +0000 | [diff] [blame] | 45 | LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true; |
Daniel Jasper | 7e9bf8c | 2013-01-11 11:37:55 +0000 | [diff] [blame] | 46 | LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false; |
Daniel Jasper | 6f5bb2c | 2013-01-14 16:24:39 +0000 | [diff] [blame] | 47 | LLVMStyle.AllowShortIfStatementsOnASingleLine = false; |
Nico Weber | 5f500df | 2013-01-10 20:12:55 +0000 | [diff] [blame] | 48 | LLVMStyle.ObjCSpaceBeforeProtocolList = true; |
Daniel Jasper | 0178673 | 2013-02-04 07:21:18 +0000 | [diff] [blame] | 49 | LLVMStyle.PenaltyExcessCharacter = 1000000; |
Daniel Jasper | a03ab10 | 2013-02-13 20:33:44 +0000 | [diff] [blame] | 50 | LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 51 | return LLVMStyle; |
| 52 | } |
| 53 | |
| 54 | FormatStyle getGoogleStyle() { |
| 55 | FormatStyle GoogleStyle; |
| 56 | GoogleStyle.ColumnLimit = 80; |
| 57 | GoogleStyle.MaxEmptyLinesToKeep = 1; |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 58 | GoogleStyle.PointerBindsToType = true; |
| 59 | GoogleStyle.DerivePointerBinding = true; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 60 | GoogleStyle.AccessModifierOffset = -1; |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 61 | GoogleStyle.Standard = FormatStyle::LS_Auto; |
Alexander Kornienko | 1575731 | 2012-12-06 18:03:27 +0000 | [diff] [blame] | 62 | GoogleStyle.IndentCaseLabels = true; |
Daniel Jasper | 7ad4eff | 2013-01-07 11:09:06 +0000 | [diff] [blame] | 63 | GoogleStyle.SpacesBeforeTrailingComments = 2; |
Daniel Jasper | faab0d3 | 2013-02-27 09:47:53 +0000 | [diff] [blame] | 64 | GoogleStyle.BinPackParameters = true; |
Daniel Jasper | f157960 | 2013-01-29 16:03:49 +0000 | [diff] [blame] | 65 | GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true; |
Daniel Jasper | 7e9bf8c | 2013-01-11 11:37:55 +0000 | [diff] [blame] | 66 | GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; |
Daniel Jasper | df3736a | 2013-01-16 15:44:34 +0000 | [diff] [blame] | 67 | GoogleStyle.AllowShortIfStatementsOnASingleLine = false; |
Nico Weber | 5f500df | 2013-01-10 20:12:55 +0000 | [diff] [blame] | 68 | GoogleStyle.ObjCSpaceBeforeProtocolList = false; |
Daniel Jasper | 0178673 | 2013-02-04 07:21:18 +0000 | [diff] [blame] | 69 | GoogleStyle.PenaltyExcessCharacter = 1000000; |
Daniel Jasper | a03ab10 | 2013-02-13 20:33:44 +0000 | [diff] [blame] | 70 | GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 71 | return GoogleStyle; |
| 72 | } |
| 73 | |
Daniel Jasper | 6f5bb2c | 2013-01-14 16:24:39 +0000 | [diff] [blame] | 74 | FormatStyle getChromiumStyle() { |
| 75 | FormatStyle ChromiumStyle = getGoogleStyle(); |
Daniel Jasper | f157960 | 2013-01-29 16:03:49 +0000 | [diff] [blame] | 76 | ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false; |
Daniel Jasper | faab0d3 | 2013-02-27 09:47:53 +0000 | [diff] [blame] | 77 | ChromiumStyle.BinPackParameters = false; |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 78 | ChromiumStyle.Standard = FormatStyle::LS_Cpp03; |
| 79 | ChromiumStyle.DerivePointerBinding = false; |
Daniel Jasper | 6f5bb2c | 2013-01-14 16:24:39 +0000 | [diff] [blame] | 80 | return ChromiumStyle; |
| 81 | } |
| 82 | |
Daniel Jasper | 15417ef | 2013-02-06 20:07:35 +0000 | [diff] [blame] | 83 | static bool isTrailingComment(const AnnotatedToken &Tok) { |
| 84 | return Tok.is(tok::comment) && |
| 85 | (Tok.Children.empty() || Tok.Children[0].MustBreakBefore); |
| 86 | } |
| 87 | |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 88 | // Returns the length of everything up to the first possible line break after |
| 89 | // the ), ], } or > matching \c Tok. |
| 90 | static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) { |
| 91 | if (Tok.MatchingParen == NULL) |
| 92 | return 0; |
| 93 | AnnotatedToken *End = Tok.MatchingParen; |
| 94 | while (!End->Children.empty() && !End->Children[0].CanBreakBefore) { |
| 95 | End = &End->Children[0]; |
| 96 | } |
| 97 | return End->TotalLength - Tok.TotalLength + 1; |
| 98 | } |
| 99 | |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 100 | /// \brief Manages the whitespaces around tokens and their replacements. |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 101 | /// |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 102 | /// This includes special handling for certain constructs, e.g. the alignment of |
| 103 | /// trailing line comments. |
| 104 | class WhitespaceManager { |
| 105 | public: |
| 106 | WhitespaceManager(SourceManager &SourceMgr) : SourceMgr(SourceMgr) {} |
| 107 | |
| 108 | /// \brief Replaces the whitespace in front of \p Tok. Only call once for |
| 109 | /// each \c AnnotatedToken. |
| 110 | void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines, |
| 111 | unsigned Spaces, unsigned WhitespaceStartColumn, |
| 112 | const FormatStyle &Style) { |
Daniel Jasper | 821627e | 2013-01-21 22:49:20 +0000 | [diff] [blame] | 113 | // 2+ newlines mean an empty line separating logic scopes. |
| 114 | if (NewLines >= 2) |
| 115 | alignComments(); |
| 116 | |
| 117 | // Align line comments if they are trailing or if they continue other |
| 118 | // trailing comments. |
Daniel Jasper | 812c045 | 2013-03-01 16:45:59 +0000 | [diff] [blame] | 119 | if (isTrailingComment(Tok)) { |
| 120 | // Remove the comment's trailing whitespace. |
| 121 | if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength) |
| 122 | Replaces.insert(tooling::Replacement( |
| 123 | SourceMgr, Tok.FormatTok.Tok.getLocation().getLocWithOffset( |
| 124 | Tok.FormatTok.TokenLength), |
| 125 | Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, "")); |
| 126 | |
| 127 | // Align comment with other comments. |
| 128 | if (Tok.Parent != NULL || !Comments.empty()) { |
| 129 | if (Style.ColumnLimit >= |
| 130 | Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength) { |
Alexander Kornienko | f753615 | 2013-03-14 16:10:54 +0000 | [diff] [blame] | 131 | StoredComment Comment; |
| 132 | Comment.Tok = Tok.FormatTok; |
| 133 | Comment.Spaces = Spaces; |
| 134 | Comment.NewLines = NewLines; |
| 135 | Comment.MinColumn = |
| 136 | NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces; |
| 137 | Comment.MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength; |
| 138 | Comments.push_back(Comment); |
Daniel Jasper | 812c045 | 2013-03-01 16:45:59 +0000 | [diff] [blame] | 139 | return; |
| 140 | } |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 141 | } |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 142 | } |
Daniel Jasper | 821627e | 2013-01-21 22:49:20 +0000 | [diff] [blame] | 143 | |
| 144 | // If this line does not have a trailing comment, align the stored comments. |
Daniel Jasper | 15417ef | 2013-02-06 20:07:35 +0000 | [diff] [blame] | 145 | if (Tok.Children.empty() && !isTrailingComment(Tok)) |
Daniel Jasper | 821627e | 2013-01-21 22:49:20 +0000 | [diff] [blame] | 146 | alignComments(); |
Alexander Kornienko | f753615 | 2013-03-14 16:10:54 +0000 | [diff] [blame] | 147 | |
| 148 | if (Tok.Type == TT_BlockComment) |
| 149 | indentBlockComment(Tok.FormatTok, Spaces); |
| 150 | |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 151 | storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces)); |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 152 | } |
| 153 | |
| 154 | /// \brief Like \c replaceWhitespace, but additionally adds right-aligned |
| 155 | /// backslashes to escape newlines inside a preprocessor directive. |
| 156 | /// |
| 157 | /// This function and \c replaceWhitespace have the same behavior if |
| 158 | /// \c Newlines == 0. |
| 159 | void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines, |
| 160 | unsigned Spaces, unsigned WhitespaceStartColumn, |
| 161 | const FormatStyle &Style) { |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 162 | storeReplacement( |
| 163 | Tok.FormatTok, |
| 164 | getNewLineText(NewLines, Spaces, WhitespaceStartColumn, Style)); |
| 165 | } |
| 166 | |
| 167 | /// \brief Inserts a line break into the middle of a token. |
| 168 | /// |
| 169 | /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line |
| 170 | /// break and \p Postfix before the rest of the token starts in the next line. |
| 171 | /// |
| 172 | /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are |
| 173 | /// used to generate the correct line break. |
| 174 | void breakToken(const AnnotatedToken &Tok, unsigned Offset, StringRef Prefix, |
| 175 | StringRef Postfix, bool InPPDirective, unsigned Spaces, |
| 176 | unsigned WhitespaceStartColumn, const FormatStyle &Style) { |
| 177 | std::string NewLineText; |
| 178 | if (!InPPDirective) |
| 179 | NewLineText = getNewLineText(1, Spaces); |
| 180 | else |
| 181 | NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn, Style); |
| 182 | std::string ReplacementText = (Prefix + NewLineText + Postfix).str(); |
| 183 | SourceLocation InsertAt = Tok.FormatTok.WhiteSpaceStart |
| 184 | .getLocWithOffset(Tok.FormatTok.WhiteSpaceLength + Offset); |
| 185 | Replaces.insert( |
| 186 | tooling::Replacement(SourceMgr, InsertAt, 0, ReplacementText)); |
| 187 | } |
| 188 | |
| 189 | /// \brief Returns all the \c Replacements created during formatting. |
| 190 | const tooling::Replacements &generateReplacements() { |
| 191 | alignComments(); |
| 192 | return Replaces; |
| 193 | } |
| 194 | |
| 195 | private: |
Alexander Kornienko | 1fdd8b3 | 2013-03-15 13:42:02 +0000 | [diff] [blame^] | 196 | void indentBlockComment(const FormatToken &Tok, int Indent) { |
Alexander Kornienko | f753615 | 2013-03-14 16:10:54 +0000 | [diff] [blame] | 197 | SourceLocation TokenLoc = Tok.Tok.getLocation(); |
Alexander Kornienko | 1fdd8b3 | 2013-03-15 13:42:02 +0000 | [diff] [blame^] | 198 | int IndentDelta = Indent - SourceMgr.getSpellingColumnNumber(TokenLoc) + 1; |
Alexander Kornienko | f753615 | 2013-03-14 16:10:54 +0000 | [diff] [blame] | 199 | const char *Start = SourceMgr.getCharacterData(TokenLoc); |
| 200 | const char *Current = Start; |
| 201 | const char *TokEnd = Current + Tok.TokenLength; |
Alexander Kornienko | 1fdd8b3 | 2013-03-15 13:42:02 +0000 | [diff] [blame^] | 202 | llvm::SmallVector<SourceLocation, 16> LineStarts; |
Alexander Kornienko | f753615 | 2013-03-14 16:10:54 +0000 | [diff] [blame] | 203 | while (Current < TokEnd) { |
| 204 | if (*Current == '\n') { |
| 205 | ++Current; |
Alexander Kornienko | 1fdd8b3 | 2013-03-15 13:42:02 +0000 | [diff] [blame^] | 206 | LineStarts.push_back(TokenLoc.getLocWithOffset(Current - Start)); |
| 207 | // If we need to outdent the line, check that it's indented enough. |
| 208 | for (int i = 0; i < -IndentDelta; ++i, ++Current) |
| 209 | if (Current >= TokEnd || *Current != ' ') |
| 210 | return; |
Alexander Kornienko | f753615 | 2013-03-14 16:10:54 +0000 | [diff] [blame] | 211 | } else { |
| 212 | ++Current; |
| 213 | } |
| 214 | } |
Alexander Kornienko | 1fdd8b3 | 2013-03-15 13:42:02 +0000 | [diff] [blame^] | 215 | |
| 216 | for (size_t i = 0; i < LineStarts.size(); ++i) { |
| 217 | if (IndentDelta > 0) |
| 218 | Replaces.insert(tooling::Replacement(SourceMgr, LineStarts[i], 0, |
| 219 | std::string(IndentDelta, ' '))); |
| 220 | else if (IndentDelta < 0) |
| 221 | Replaces.insert( |
| 222 | tooling::Replacement(SourceMgr, LineStarts[i], -IndentDelta, "")); |
| 223 | } |
Alexander Kornienko | f753615 | 2013-03-14 16:10:54 +0000 | [diff] [blame] | 224 | } |
| 225 | |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 226 | std::string getNewLineText(unsigned NewLines, unsigned Spaces) { |
| 227 | return std::string(NewLines, '\n') + std::string(Spaces, ' '); |
| 228 | } |
| 229 | |
| 230 | std::string |
| 231 | getNewLineText(unsigned NewLines, unsigned Spaces, |
| 232 | unsigned WhitespaceStartColumn, const FormatStyle &Style) { |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 233 | std::string NewLineText; |
| 234 | if (NewLines > 0) { |
Daniel Jasper | 1a1ce83 | 2013-01-29 11:27:30 +0000 | [diff] [blame] | 235 | unsigned Offset = |
| 236 | std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn); |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 237 | for (unsigned i = 0; i < NewLines; ++i) { |
| 238 | NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' '); |
| 239 | NewLineText += "\\\n"; |
| 240 | Offset = 0; |
| 241 | } |
| 242 | } |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 243 | return NewLineText + std::string(Spaces, ' '); |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 244 | } |
| 245 | |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 246 | /// \brief Structure to store a comment for later layout and alignment. |
| 247 | struct StoredComment { |
| 248 | FormatToken Tok; |
| 249 | unsigned MinColumn; |
| 250 | unsigned MaxColumn; |
| 251 | unsigned NewLines; |
| 252 | unsigned Spaces; |
| 253 | }; |
| 254 | SmallVector<StoredComment, 16> Comments; |
| 255 | typedef SmallVector<StoredComment, 16>::iterator comment_iterator; |
| 256 | |
| 257 | /// \brief Try to align all stashed comments. |
| 258 | void alignComments() { |
| 259 | unsigned MinColumn = 0; |
| 260 | unsigned MaxColumn = UINT_MAX; |
| 261 | comment_iterator Start = Comments.begin(); |
Alexander Kornienko | f753615 | 2013-03-14 16:10:54 +0000 | [diff] [blame] | 262 | for (comment_iterator I = Start, E = Comments.end(); I != E; ++I) { |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 263 | if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) { |
| 264 | alignComments(Start, I, MinColumn); |
| 265 | MinColumn = I->MinColumn; |
| 266 | MaxColumn = I->MaxColumn; |
| 267 | Start = I; |
| 268 | } else { |
| 269 | MinColumn = std::max(MinColumn, I->MinColumn); |
| 270 | MaxColumn = std::min(MaxColumn, I->MaxColumn); |
| 271 | } |
| 272 | } |
| 273 | alignComments(Start, Comments.end(), MinColumn); |
| 274 | Comments.clear(); |
| 275 | } |
| 276 | |
| 277 | /// \brief Put all the comments between \p I and \p E into \p Column. |
| 278 | void alignComments(comment_iterator I, comment_iterator E, unsigned Column) { |
| 279 | while (I != E) { |
| 280 | unsigned Spaces = I->Spaces + Column - I->MinColumn; |
| 281 | storeReplacement(I->Tok, std::string(I->NewLines, '\n') + |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 282 | std::string(Spaces, ' ')); |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 283 | ++I; |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 284 | } |
| 285 | } |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 286 | |
| 287 | /// \brief Stores \p Text as the replacement for the whitespace in front of |
| 288 | /// \p Tok. |
| 289 | void storeReplacement(const FormatToken &Tok, const std::string Text) { |
Daniel Jasper | afcbd85 | 2013-01-30 09:46:12 +0000 | [diff] [blame] | 290 | // Don't create a replacement, if it does not change anything. |
| 291 | if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart), |
| 292 | Tok.WhiteSpaceLength) == Text) |
| 293 | return; |
| 294 | |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 295 | Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart, |
| 296 | Tok.WhiteSpaceLength, Text)); |
| 297 | } |
| 298 | |
| 299 | SourceManager &SourceMgr; |
| 300 | tooling::Replacements Replaces; |
| 301 | }; |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 302 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 303 | class UnwrappedLineFormatter { |
| 304 | public: |
Manuel Klimek | 94fc6f1 | 2013-01-10 19:17:33 +0000 | [diff] [blame] | 305 | UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr, |
Daniel Jasper | 995e820 | 2013-01-14 13:08:07 +0000 | [diff] [blame] | 306 | const AnnotatedLine &Line, unsigned FirstIndent, |
Daniel Jasper | 3f8cdbf | 2013-01-16 10:41:46 +0000 | [diff] [blame] | 307 | const AnnotatedToken &RootToken, |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 308 | WhitespaceManager &Whitespaces, bool StructuralError) |
Daniel Jasper | 1321eb5 | 2012-12-18 21:05:13 +0000 | [diff] [blame] | 309 | : Style(Style), SourceMgr(SourceMgr), Line(Line), |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 310 | FirstIndent(FirstIndent), RootToken(RootToken), |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 311 | Whitespaces(Whitespaces), Count(0) {} |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 312 | |
Manuel Klimek | d4397b9 | 2013-01-04 23:34:14 +0000 | [diff] [blame] | 313 | /// \brief Formats an \c UnwrappedLine. |
| 314 | /// |
| 315 | /// \returns The column after the last token in the last line of the |
| 316 | /// \c UnwrappedLine. |
Daniel Jasper | a4d4621 | 2013-02-28 11:05:57 +0000 | [diff] [blame] | 317 | unsigned format(const AnnotatedLine *NextLine) { |
Daniel Jasper | 3b5943f | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 318 | // Initialize state dependent on indent. |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 319 | LineState State; |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 320 | State.Column = FirstIndent; |
Daniel Jasper | 26f7e78 | 2013-01-08 14:56:18 +0000 | [diff] [blame] | 321 | State.NextToken = &RootToken; |
Daniel Jasper | 6f21a98 | 2013-03-13 07:49:51 +0000 | [diff] [blame] | 322 | State.Stack.push_back( |
| 323 | ParenState(FirstIndent + 4, FirstIndent, !Style.BinPackParameters, |
| 324 | /*HasMultiParameterLine=*/ false)); |
Daniel Jasper | 2e60377 | 2013-01-29 11:21:01 +0000 | [diff] [blame] | 325 | State.VariablePos = 0; |
Daniel Jasper | a324a0e | 2012-12-21 14:37:20 +0000 | [diff] [blame] | 326 | State.LineContainsContinuedForLoopSection = false; |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 327 | State.ParenLevel = 0; |
Manuel Klimek | b56b6d1 | 2013-02-20 15:25:48 +0000 | [diff] [blame] | 328 | State.StartOfStringLiteral = 0; |
Daniel Jasper | cf5767d | 2013-02-18 11:05:07 +0000 | [diff] [blame] | 329 | State.StartOfLineLevel = State.ParenLevel; |
Daniel Jasper | 3b5943f | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 330 | |
Manuel Klimek | ca547db | 2013-01-16 14:55:28 +0000 | [diff] [blame] | 331 | DEBUG({ |
| 332 | DebugTokenState(*State.NextToken); |
| 333 | }); |
| 334 | |
Daniel Jasper | 3b5943f | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 335 | // The first token has already been indented and thus consumed. |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 336 | moveStateToNextToken(State, /*DryRun=*/ false); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 337 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 338 | // If everything fits on a single line, just put it there. |
Daniel Jasper | a4d4621 | 2013-02-28 11:05:57 +0000 | [diff] [blame] | 339 | unsigned ColumnLimit = Style.ColumnLimit; |
| 340 | if (NextLine && NextLine->InPPDirective && |
| 341 | !NextLine->First.FormatTok.HasUnescapedNewline) |
| 342 | ColumnLimit = getColumnLimit(); |
| 343 | if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) { |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 344 | while (State.NextToken != NULL) { |
Daniel Jasper | 1321eb5 | 2012-12-18 21:05:13 +0000 | [diff] [blame] | 345 | addTokenToState(false, false, State); |
Daniel Jasper | 1321eb5 | 2012-12-18 21:05:13 +0000 | [diff] [blame] | 346 | } |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 347 | return State.Column; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 348 | } |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 349 | |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 350 | // If the ObjC method declaration does not fit on a line, we should format |
| 351 | // it with one arg per line. |
| 352 | if (Line.Type == LT_ObjCMethodDecl) |
| 353 | State.Stack.back().BreakBeforeParameter = true; |
| 354 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 355 | // Find best solution in solution space. |
| 356 | return analyzeSolutionSpace(State); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 357 | } |
| 358 | |
| 359 | private: |
Manuel Klimek | ca547db | 2013-01-16 14:55:28 +0000 | [diff] [blame] | 360 | void DebugTokenState(const AnnotatedToken &AnnotatedTok) { |
| 361 | const Token &Tok = AnnotatedTok.FormatTok.Tok; |
Daniel Jasper | 1a1ce83 | 2013-01-29 11:27:30 +0000 | [diff] [blame] | 362 | llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()), |
| 363 | Tok.getLength()); |
Manuel Klimek | ca547db | 2013-01-16 14:55:28 +0000 | [diff] [blame] | 364 | llvm::errs(); |
| 365 | } |
| 366 | |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 367 | struct ParenState { |
Daniel Jasper | d399bff | 2013-02-05 09:41:21 +0000 | [diff] [blame] | 368 | ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking, |
| 369 | bool HasMultiParameterLine) |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 370 | : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0), |
| 371 | BreakBeforeClosingBrace(false), QuestionColumn(0), |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 372 | AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false), |
Daniel Jasper | 2484971 | 2013-03-01 16:48:32 +0000 | [diff] [blame] | 373 | HasMultiParameterLine(HasMultiParameterLine), ColonPos(0), |
| 374 | StartOfFunctionCall(0) {} |
Daniel Jasper | a4974cf | 2012-12-24 16:43:00 +0000 | [diff] [blame] | 375 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 376 | /// \brief The position to which a specific parenthesis level needs to be |
| 377 | /// indented. |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 378 | unsigned Indent; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 379 | |
Daniel Jasper | 3b5943f | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 380 | /// \brief The position of the last space on each level. |
| 381 | /// |
| 382 | /// Used e.g. to break like: |
| 383 | /// functionCall(Parameter, otherCall( |
| 384 | /// OtherParameter)); |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 385 | unsigned LastSpace; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 386 | |
Daniel Jasper | 3b5943f | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 387 | /// \brief The position the first "<<" operator encountered on each level. |
| 388 | /// |
| 389 | /// Used to align "<<" operators. 0 if no such operator has been encountered |
| 390 | /// on a level. |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 391 | unsigned FirstLessLess; |
Daniel Jasper | 3b5943f | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 392 | |
Manuel Klimek | c8c8a47 | 2013-01-10 15:58:26 +0000 | [diff] [blame] | 393 | /// \brief Whether a newline needs to be inserted before the block's closing |
| 394 | /// brace. |
| 395 | /// |
| 396 | /// We only want to insert a newline before the closing brace if there also |
| 397 | /// was a newline after the beginning left brace. |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 398 | bool BreakBeforeClosingBrace; |
| 399 | |
Daniel Jasper | bfe6fd4 | 2013-01-28 12:45:14 +0000 | [diff] [blame] | 400 | /// \brief The column of a \c ? in a conditional expression; |
| 401 | unsigned QuestionColumn; |
| 402 | |
Daniel Jasper | f343cab | 2013-01-31 14:59:26 +0000 | [diff] [blame] | 403 | /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple |
| 404 | /// lines, in this context. |
| 405 | bool AvoidBinPacking; |
| 406 | |
| 407 | /// \brief Break after the next comma (or all the commas in this context if |
| 408 | /// \c AvoidBinPacking is \c true). |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 409 | bool BreakBeforeParameter; |
Daniel Jasper | f343cab | 2013-01-31 14:59:26 +0000 | [diff] [blame] | 410 | |
| 411 | /// \brief This context already has a line with more than one parameter. |
Daniel Jasper | 0df6acd | 2013-01-16 14:59:02 +0000 | [diff] [blame] | 412 | bool HasMultiParameterLine; |
Daniel Jasper | 7e9bf8c | 2013-01-11 11:37:55 +0000 | [diff] [blame] | 413 | |
Daniel Jasper | 63d7ced | 2013-02-05 10:07:47 +0000 | [diff] [blame] | 414 | /// \brief The position of the colon in an ObjC method declaration/call. |
| 415 | unsigned ColonPos; |
Daniel Jasper | c4615b7 | 2013-02-20 12:56:39 +0000 | [diff] [blame] | 416 | |
Daniel Jasper | 2484971 | 2013-03-01 16:48:32 +0000 | [diff] [blame] | 417 | /// \brief The start of the most recent function in a builder-type call. |
| 418 | unsigned StartOfFunctionCall; |
| 419 | |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 420 | bool operator<(const ParenState &Other) const { |
| 421 | if (Indent != Other.Indent) |
Daniel Jasper | 7d19bc2 | 2013-01-11 14:23:32 +0000 | [diff] [blame] | 422 | return Indent < Other.Indent; |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 423 | if (LastSpace != Other.LastSpace) |
| 424 | return LastSpace < Other.LastSpace; |
| 425 | if (FirstLessLess != Other.FirstLessLess) |
| 426 | return FirstLessLess < Other.FirstLessLess; |
Daniel Jasper | 7e9bf8c | 2013-01-11 11:37:55 +0000 | [diff] [blame] | 427 | if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace) |
| 428 | return BreakBeforeClosingBrace; |
Daniel Jasper | bfe6fd4 | 2013-01-28 12:45:14 +0000 | [diff] [blame] | 429 | if (QuestionColumn != Other.QuestionColumn) |
| 430 | return QuestionColumn < Other.QuestionColumn; |
Daniel Jasper | f343cab | 2013-01-31 14:59:26 +0000 | [diff] [blame] | 431 | if (AvoidBinPacking != Other.AvoidBinPacking) |
| 432 | return AvoidBinPacking; |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 433 | if (BreakBeforeParameter != Other.BreakBeforeParameter) |
| 434 | return BreakBeforeParameter; |
Daniel Jasper | 0df6acd | 2013-01-16 14:59:02 +0000 | [diff] [blame] | 435 | if (HasMultiParameterLine != Other.HasMultiParameterLine) |
| 436 | return HasMultiParameterLine; |
Daniel Jasper | 63d7ced | 2013-02-05 10:07:47 +0000 | [diff] [blame] | 437 | if (ColonPos != Other.ColonPos) |
| 438 | return ColonPos < Other.ColonPos; |
Daniel Jasper | 2484971 | 2013-03-01 16:48:32 +0000 | [diff] [blame] | 439 | if (StartOfFunctionCall != Other.StartOfFunctionCall) |
| 440 | return StartOfFunctionCall < Other.StartOfFunctionCall; |
Daniel Jasper | b312314 | 2013-01-12 07:36:22 +0000 | [diff] [blame] | 441 | return false; |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 442 | } |
| 443 | }; |
| 444 | |
| 445 | /// \brief The current state when indenting a unwrapped line. |
| 446 | /// |
| 447 | /// As the indenting tries different combinations this is copied by value. |
| 448 | struct LineState { |
| 449 | /// \brief The number of used columns in the current line. |
| 450 | unsigned Column; |
| 451 | |
| 452 | /// \brief The token that needs to be next formatted. |
| 453 | const AnnotatedToken *NextToken; |
| 454 | |
Daniel Jasper | 1a1ce83 | 2013-01-29 11:27:30 +0000 | [diff] [blame] | 455 | /// \brief The column of the first variable name in a variable declaration. |
Daniel Jasper | a324a0e | 2012-12-21 14:37:20 +0000 | [diff] [blame] | 456 | /// |
Daniel Jasper | 1a1ce83 | 2013-01-29 11:27:30 +0000 | [diff] [blame] | 457 | /// Used to align further variables if necessary. |
Daniel Jasper | 2e60377 | 2013-01-29 11:21:01 +0000 | [diff] [blame] | 458 | unsigned VariablePos; |
Daniel Jasper | a324a0e | 2012-12-21 14:37:20 +0000 | [diff] [blame] | 459 | |
| 460 | /// \brief \c true if this line contains a continued for-loop section. |
| 461 | bool LineContainsContinuedForLoopSection; |
| 462 | |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 463 | /// \brief The level of nesting inside (), [], <> and {}. |
| 464 | unsigned ParenLevel; |
| 465 | |
Daniel Jasper | cf5767d | 2013-02-18 11:05:07 +0000 | [diff] [blame] | 466 | /// \brief The \c ParenLevel at the start of this line. |
| 467 | unsigned StartOfLineLevel; |
| 468 | |
Manuel Klimek | b56b6d1 | 2013-02-20 15:25:48 +0000 | [diff] [blame] | 469 | /// \brief The start column of the string literal, if we're in a string |
| 470 | /// literal sequence, 0 otherwise. |
| 471 | unsigned StartOfStringLiteral; |
| 472 | |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 473 | /// \brief A stack keeping track of properties applying to parenthesis |
| 474 | /// levels. |
| 475 | std::vector<ParenState> Stack; |
| 476 | |
| 477 | /// \brief Comparison operator to be able to used \c LineState in \c map. |
| 478 | bool operator<(const LineState &Other) const { |
Daniel Jasper | d789670 | 2013-02-19 09:28:55 +0000 | [diff] [blame] | 479 | if (NextToken != Other.NextToken) |
| 480 | return NextToken < Other.NextToken; |
| 481 | if (Column != Other.Column) |
| 482 | return Column < Other.Column; |
| 483 | if (VariablePos != Other.VariablePos) |
| 484 | return VariablePos < Other.VariablePos; |
| 485 | if (LineContainsContinuedForLoopSection != |
| 486 | Other.LineContainsContinuedForLoopSection) |
Daniel Jasper | a324a0e | 2012-12-21 14:37:20 +0000 | [diff] [blame] | 487 | return LineContainsContinuedForLoopSection; |
Daniel Jasper | d789670 | 2013-02-19 09:28:55 +0000 | [diff] [blame] | 488 | if (ParenLevel != Other.ParenLevel) |
| 489 | return ParenLevel < Other.ParenLevel; |
| 490 | if (StartOfLineLevel != Other.StartOfLineLevel) |
| 491 | return StartOfLineLevel < Other.StartOfLineLevel; |
Manuel Klimek | b56b6d1 | 2013-02-20 15:25:48 +0000 | [diff] [blame] | 492 | if (StartOfStringLiteral != Other.StartOfStringLiteral) |
| 493 | return StartOfStringLiteral < Other.StartOfStringLiteral; |
Daniel Jasper | d789670 | 2013-02-19 09:28:55 +0000 | [diff] [blame] | 494 | return Stack < Other.Stack; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 495 | } |
| 496 | }; |
| 497 | |
Daniel Jasper | 2040915 | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 498 | /// \brief Appends the next token to \p State and updates information |
| 499 | /// necessary for indentation. |
| 500 | /// |
| 501 | /// Puts the token on the current line if \p Newline is \c true and adds a |
| 502 | /// line break and necessary indentation otherwise. |
| 503 | /// |
| 504 | /// If \p DryRun is \c false, also creates and stores the required |
| 505 | /// \c Replacement. |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 506 | unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) { |
Daniel Jasper | 9c837d0 | 2013-01-09 07:06:56 +0000 | [diff] [blame] | 507 | const AnnotatedToken &Current = *State.NextToken; |
| 508 | const AnnotatedToken &Previous = *State.NextToken->Parent; |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 509 | assert(State.Stack.size()); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 510 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 511 | if (Current.Type == TT_ImplicitStringLiteral) { |
| 512 | State.Column += State.NextToken->FormatTok.WhiteSpaceLength + |
| 513 | State.NextToken->FormatTok.TokenLength; |
| 514 | if (State.NextToken->Children.empty()) |
| 515 | State.NextToken = NULL; |
| 516 | else |
| 517 | State.NextToken = &State.NextToken->Children[0]; |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 518 | return 0; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 519 | } |
| 520 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 521 | if (Newline) { |
Manuel Klimek | 060143e | 2013-01-02 18:33:23 +0000 | [diff] [blame] | 522 | unsigned WhitespaceStartColumn = State.Column; |
Manuel Klimek | bb42bf1 | 2013-01-10 11:52:21 +0000 | [diff] [blame] | 523 | if (Current.is(tok::r_brace)) { |
| 524 | State.Column = Line.Level * 2; |
Daniel Jasper | 9c837d0 | 2013-01-09 07:06:56 +0000 | [diff] [blame] | 525 | } else if (Current.is(tok::string_literal) && |
Manuel Klimek | b56b6d1 | 2013-02-20 15:25:48 +0000 | [diff] [blame] | 526 | State.StartOfStringLiteral != 0) { |
| 527 | State.Column = State.StartOfStringLiteral; |
Daniel Jasper | 66d19bd | 2013-02-18 11:59:17 +0000 | [diff] [blame] | 528 | State.Stack.back().BreakBeforeParameter = true; |
Daniel Jasper | 9c837d0 | 2013-01-09 07:06:56 +0000 | [diff] [blame] | 529 | } else if (Current.is(tok::lessless) && |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 530 | State.Stack.back().FirstLessLess != 0) { |
| 531 | State.Column = State.Stack.back().FirstLessLess; |
| 532 | } else if (State.ParenLevel != 0 && |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 533 | (Previous.isOneOf(tok::equal, tok::coloncolon) || |
| 534 | Current.isOneOf(tok::period, tok::arrow, tok::question))) { |
Daniel Jasper | 9c837d0 | 2013-01-09 07:06:56 +0000 | [diff] [blame] | 535 | // Indent and extra 4 spaces after if we know the current expression is |
| 536 | // continued. Don't do that on the top level, as we already indent 4 |
| 537 | // there. |
Daniel Jasper | bfe6fd4 | 2013-01-28 12:45:14 +0000 | [diff] [blame] | 538 | State.Column = std::max(State.Stack.back().LastSpace, |
| 539 | State.Stack.back().Indent) + 4; |
| 540 | } else if (Current.Type == TT_ConditionalExpr) { |
| 541 | State.Column = State.Stack.back().QuestionColumn; |
Daniel Jasper | 2e60377 | 2013-01-29 11:21:01 +0000 | [diff] [blame] | 542 | } else if (Previous.is(tok::comma) && State.VariablePos != 0 && |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 543 | ((RootToken.is(tok::kw_for) && State.ParenLevel == 1) || |
| 544 | State.ParenLevel == 0)) { |
Daniel Jasper | 2e60377 | 2013-01-29 11:21:01 +0000 | [diff] [blame] | 545 | State.Column = State.VariablePos; |
Daniel Jasper | 3c08a81 | 2013-02-24 18:54:32 +0000 | [diff] [blame] | 546 | } else if (Previous.ClosesTemplateDeclaration || |
| 547 | (Current.Type == TT_StartOfName && State.ParenLevel == 0)) { |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 548 | State.Column = State.Stack.back().Indent - 4; |
Daniel Jasper | 63d7ced | 2013-02-05 10:07:47 +0000 | [diff] [blame] | 549 | } else if (Current.Type == TT_ObjCSelectorName) { |
| 550 | if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) { |
| 551 | State.Column = |
| 552 | State.Stack.back().ColonPos - Current.FormatTok.TokenLength; |
| 553 | } else { |
| 554 | State.Column = State.Stack.back().Indent; |
| 555 | State.Stack.back().ColonPos = |
| 556 | State.Column + Current.FormatTok.TokenLength; |
| 557 | } |
Daniel Jasper | 3c08a81 | 2013-02-24 18:54:32 +0000 | [diff] [blame] | 558 | } else if (Previous.Type == TT_ObjCMethodExpr || |
| 559 | Current.Type == TT_StartOfName) { |
Daniel Jasper | 63d7ced | 2013-02-05 10:07:47 +0000 | [diff] [blame] | 560 | State.Column = State.Stack.back().Indent + 4; |
Daniel Jasper | a324a0e | 2012-12-21 14:37:20 +0000 | [diff] [blame] | 561 | } else { |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 562 | State.Column = State.Stack.back().Indent; |
Daniel Jasper | a324a0e | 2012-12-21 14:37:20 +0000 | [diff] [blame] | 563 | } |
| 564 | |
Daniel Jasper | 7878a7b | 2013-02-15 11:07:25 +0000 | [diff] [blame] | 565 | if (Current.is(tok::question)) |
Daniel Jasper | 237d4c1 | 2013-02-23 21:01:55 +0000 | [diff] [blame] | 566 | State.Stack.back().BreakBeforeParameter = true; |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 567 | if (Previous.isOneOf(tok::comma, tok::semi) && |
Daniel Jasper | 237d4c1 | 2013-02-23 21:01:55 +0000 | [diff] [blame] | 568 | !State.Stack.back().AvoidBinPacking) |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 569 | State.Stack.back().BreakBeforeParameter = false; |
Daniel Jasper | f343cab | 2013-01-31 14:59:26 +0000 | [diff] [blame] | 570 | |
Manuel Klimek | 060143e | 2013-01-02 18:33:23 +0000 | [diff] [blame] | 571 | if (!DryRun) { |
Daniel Jasper | 1ef81d5 | 2013-02-26 13:10:34 +0000 | [diff] [blame] | 572 | unsigned NewLines = 1; |
| 573 | if (Current.Type == TT_LineComment) |
| 574 | NewLines = |
| 575 | std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore, |
| 576 | Style.MaxEmptyLinesToKeep + 1)); |
Manuel Klimek | 060143e | 2013-01-02 18:33:23 +0000 | [diff] [blame] | 577 | if (!Line.InPPDirective) |
Daniel Jasper | c4615b7 | 2013-02-20 12:56:39 +0000 | [diff] [blame] | 578 | Whitespaces.replaceWhitespace(Current, NewLines, State.Column, |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 579 | WhitespaceStartColumn, Style); |
Manuel Klimek | 060143e | 2013-01-02 18:33:23 +0000 | [diff] [blame] | 580 | else |
Daniel Jasper | c4615b7 | 2013-02-20 12:56:39 +0000 | [diff] [blame] | 581 | Whitespaces.replacePPWhitespace(Current, NewLines, State.Column, |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 582 | WhitespaceStartColumn, Style); |
Manuel Klimek | 060143e | 2013-01-02 18:33:23 +0000 | [diff] [blame] | 583 | } |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 584 | |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 585 | State.Stack.back().LastSpace = State.Column; |
Daniel Jasper | cf5767d | 2013-02-18 11:05:07 +0000 | [diff] [blame] | 586 | State.StartOfLineLevel = State.ParenLevel; |
Daniel Jasper | 237d4c1 | 2013-02-23 21:01:55 +0000 | [diff] [blame] | 587 | |
| 588 | // Any break on this level means that the parent level has been broken |
| 589 | // and we need to avoid bin packing there. |
| 590 | for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) { |
| 591 | State.Stack[i].BreakBeforeParameter = true; |
| 592 | } |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 593 | if (Current.isOneOf(tok::period, tok::arrow)) |
Daniel Jasper | faab0d3 | 2013-02-27 09:47:53 +0000 | [diff] [blame] | 594 | State.Stack.back().BreakBeforeParameter = true; |
| 595 | |
Daniel Jasper | 237d4c1 | 2013-02-23 21:01:55 +0000 | [diff] [blame] | 596 | // If we break after {, we should also break before the corresponding }. |
| 597 | if (Previous.is(tok::l_brace)) |
| 598 | State.Stack.back().BreakBeforeClosingBrace = true; |
| 599 | |
| 600 | if (State.Stack.back().AvoidBinPacking) { |
| 601 | // If we are breaking after '(', '{', '<', this is not bin packing |
| 602 | // unless AllowAllParametersOfDeclarationOnNextLine is false. |
Daniel Jasper | 3c08a81 | 2013-02-24 18:54:32 +0000 | [diff] [blame] | 603 | if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) || |
Daniel Jasper | 237d4c1 | 2013-02-23 21:01:55 +0000 | [diff] [blame] | 604 | (!Style.AllowAllParametersOfDeclarationOnNextLine && |
| 605 | Line.MustBeDeclaration)) |
| 606 | State.Stack.back().BreakBeforeParameter = true; |
| 607 | } |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 608 | } else { |
Daniel Jasper | 9c3e71a | 2013-02-25 15:59:54 +0000 | [diff] [blame] | 609 | // FIXME: Put VariablePos into ParenState and remove second part of if(). |
| 610 | if (Current.is(tok::equal) && |
| 611 | (RootToken.is(tok::kw_for) || State.ParenLevel == 0)) |
Daniel Jasper | 2e60377 | 2013-01-29 11:21:01 +0000 | [diff] [blame] | 612 | State.VariablePos = State.Column - Previous.FormatTok.TokenLength; |
Daniel Jasper | a324a0e | 2012-12-21 14:37:20 +0000 | [diff] [blame] | 613 | |
Daniel Jasper | 729a743 | 2013-02-11 12:36:37 +0000 | [diff] [blame] | 614 | unsigned Spaces = State.NextToken->SpacesRequiredBefore; |
Daniel Jasper | 2040915 | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 615 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 616 | if (!DryRun) |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 617 | Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column, Style); |
Daniel Jasper | 2040915 | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 618 | |
Daniel Jasper | 63d7ced | 2013-02-05 10:07:47 +0000 | [diff] [blame] | 619 | if (Current.Type == TT_ObjCSelectorName && |
| 620 | State.Stack.back().ColonPos == 0) { |
| 621 | if (State.Stack.back().Indent + Current.LongestObjCSelectorName > |
| 622 | State.Column + Spaces + Current.FormatTok.TokenLength) |
| 623 | State.Stack.back().ColonPos = |
| 624 | State.Stack.back().Indent + Current.LongestObjCSelectorName; |
| 625 | else |
| 626 | State.Stack.back().ColonPos = |
Daniel Jasper | 9e9e6e0 | 2013-02-06 16:00:26 +0000 | [diff] [blame] | 627 | State.Column + Spaces + Current.FormatTok.TokenLength; |
Daniel Jasper | 63d7ced | 2013-02-05 10:07:47 +0000 | [diff] [blame] | 628 | } |
| 629 | |
Daniel Jasper | d4f2c2e | 2013-01-29 19:41:55 +0000 | [diff] [blame] | 630 | if (Current.Type != TT_LineComment && |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 631 | (Previous.isOneOf(tok::l_paren, tok::l_brace) || |
Daniel Jasper | d4f2c2e | 2013-01-29 19:41:55 +0000 | [diff] [blame] | 632 | State.NextToken->Parent->Type == TT_TemplateOpener)) |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 633 | State.Stack.back().Indent = State.Column + Spaces; |
Daniel Jasper | cda1650 | 2013-02-04 08:34:57 +0000 | [diff] [blame] | 634 | if (Previous.is(tok::comma) && !isTrailingComment(Current)) |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 635 | State.Stack.back().HasMultiParameterLine = true; |
Daniel Jasper | 0df6acd | 2013-01-16 14:59:02 +0000 | [diff] [blame] | 636 | |
Daniel Jasper | 3b5943f | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 637 | State.Column += Spaces; |
Daniel Jasper | e438bac | 2013-01-23 20:41:06 +0000 | [diff] [blame] | 638 | if (Current.is(tok::l_paren) && Previous.is(tok::kw_if)) |
| 639 | // Treat the condition inside an if as if it was a second function |
| 640 | // parameter, i.e. let nested calls have an indent of 4. |
| 641 | State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(". |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 642 | else if (Previous.is(tok::comma) && State.ParenLevel != 0) |
Daniel Jasper | e438bac | 2013-01-23 20:41:06 +0000 | [diff] [blame] | 643 | // Top-level spaces are exempt as that mostly leads to better results. |
| 644 | State.Stack.back().LastSpace = State.Column; |
Daniel Jasper | bfe6fd4 | 2013-01-28 12:45:14 +0000 | [diff] [blame] | 645 | else if ((Previous.Type == TT_BinaryOperator || |
Daniel Jasper | 02b771e | 2013-01-28 13:31:35 +0000 | [diff] [blame] | 646 | Previous.Type == TT_ConditionalExpr || |
| 647 | Previous.Type == TT_CtorInitializerColon) && |
Daniel Jasper | ae8699b | 2013-01-28 09:35:24 +0000 | [diff] [blame] | 648 | getPrecedence(Previous) != prec::Assignment) |
| 649 | State.Stack.back().LastSpace = State.Column; |
Daniel Jasper | 6cabab4 | 2013-02-14 08:42:54 +0000 | [diff] [blame] | 650 | else if (Previous.Type == TT_InheritanceColon) |
| 651 | State.Stack.back().Indent = State.Column; |
Daniel Jasper | 986e17f | 2013-01-28 07:35:34 +0000 | [diff] [blame] | 652 | else if (Previous.ParameterCount > 1 && |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 653 | (Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) || |
Daniel Jasper | 986e17f | 2013-01-28 07:35:34 +0000 | [diff] [blame] | 654 | Previous.Type == TT_TemplateOpener)) |
| 655 | // If this function has multiple parameters, indent nested calls from |
| 656 | // the start of the first parameter. |
| 657 | State.Stack.back().LastSpace = State.Column; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 658 | } |
Daniel Jasper | 0df6acd | 2013-01-16 14:59:02 +0000 | [diff] [blame] | 659 | |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 660 | return moveStateToNextToken(State, DryRun); |
Daniel Jasper | 2040915 | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 661 | } |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 662 | |
Daniel Jasper | 2040915 | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 663 | /// \brief Mark the next token as consumed in \p State and modify its stacks |
| 664 | /// accordingly. |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 665 | unsigned moveStateToNextToken(LineState &State, bool DryRun) { |
Daniel Jasper | 26f7e78 | 2013-01-08 14:56:18 +0000 | [diff] [blame] | 666 | const AnnotatedToken &Current = *State.NextToken; |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 667 | assert(State.Stack.size()); |
Daniel Jasper | 3b5943f | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 668 | |
Daniel Jasper | 6cabab4 | 2013-02-14 08:42:54 +0000 | [diff] [blame] | 669 | if (Current.Type == TT_InheritanceColon) |
| 670 | State.Stack.back().AvoidBinPacking = true; |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 671 | if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0) |
| 672 | State.Stack.back().FirstLessLess = State.Column; |
Daniel Jasper | bfe6fd4 | 2013-01-28 12:45:14 +0000 | [diff] [blame] | 673 | if (Current.is(tok::question)) |
| 674 | State.Stack.back().QuestionColumn = State.Column; |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 675 | if (Current.isOneOf(tok::period, tok::arrow) && |
Daniel Jasper | 2484971 | 2013-03-01 16:48:32 +0000 | [diff] [blame] | 676 | Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0) |
| 677 | State.Stack.back().StartOfFunctionCall = |
| 678 | Current.LastInChainOfCalls ? 0 : State.Column; |
Daniel Jasper | 7d81281 | 2013-02-21 15:00:29 +0000 | [diff] [blame] | 679 | if (Current.Type == TT_CtorInitializerColon) { |
| 680 | if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) |
| 681 | State.Stack.back().AvoidBinPacking = true; |
| 682 | State.Stack.back().BreakBeforeParameter = false; |
Daniel Jasper | f343cab | 2013-01-31 14:59:26 +0000 | [diff] [blame] | 683 | } |
Daniel Jasper | 3b5943f | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 684 | |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 685 | // Insert scopes created by fake parenthesis. |
| 686 | for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) { |
| 687 | ParenState NewParenState = State.Stack.back(); |
| 688 | NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent); |
Daniel Jasper | 237d4c1 | 2013-02-23 21:01:55 +0000 | [diff] [blame] | 689 | NewParenState.BreakBeforeParameter = false; |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 690 | State.Stack.push_back(NewParenState); |
| 691 | } |
| 692 | |
Daniel Jasper | cf225b6 | 2012-12-24 13:43:52 +0000 | [diff] [blame] | 693 | // If we encounter an opening (, [, { or <, we add a level to our stacks to |
Daniel Jasper | 2040915 | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 694 | // prepare for the following tokens. |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 695 | if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) || |
Daniel Jasper | 26f7e78 | 2013-01-08 14:56:18 +0000 | [diff] [blame] | 696 | State.NextToken->Type == TT_TemplateOpener) { |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 697 | unsigned NewIndent; |
Daniel Jasper | f343cab | 2013-01-31 14:59:26 +0000 | [diff] [blame] | 698 | bool AvoidBinPacking; |
Manuel Klimek | 2851c16 | 2013-01-10 14:36:46 +0000 | [diff] [blame] | 699 | if (Current.is(tok::l_brace)) { |
Daniel Jasper | f343cab | 2013-01-31 14:59:26 +0000 | [diff] [blame] | 700 | NewIndent = 2 + State.Stack.back().LastSpace; |
| 701 | AvoidBinPacking = false; |
Manuel Klimek | 2851c16 | 2013-01-10 14:36:46 +0000 | [diff] [blame] | 702 | } else { |
Daniel Jasper | 2484971 | 2013-03-01 16:48:32 +0000 | [diff] [blame] | 703 | NewIndent = 4 + std::max(State.Stack.back().LastSpace, |
| 704 | State.Stack.back().StartOfFunctionCall); |
Daniel Jasper | 3a39ac7 | 2013-02-28 09:39:12 +0000 | [diff] [blame] | 705 | AvoidBinPacking = |
| 706 | !Style.BinPackParameters || State.Stack.back().AvoidBinPacking; |
Manuel Klimek | 2851c16 | 2013-01-10 14:36:46 +0000 | [diff] [blame] | 707 | } |
Daniel Jasper | d399bff | 2013-02-05 09:41:21 +0000 | [diff] [blame] | 708 | State.Stack.push_back( |
| 709 | ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking, |
| 710 | State.Stack.back().HasMultiParameterLine)); |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 711 | ++State.ParenLevel; |
Daniel Jasper | 2040915 | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 712 | } |
| 713 | |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 714 | // If this '[' opens an ObjC call, determine whether all parameters fit into |
| 715 | // one line and put one per line if they don't. |
| 716 | if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr && |
| 717 | Current.MatchingParen != NULL) { |
| 718 | if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit()) |
| 719 | State.Stack.back().BreakBeforeParameter = true; |
| 720 | } |
| 721 | |
Daniel Jasper | cf225b6 | 2012-12-24 13:43:52 +0000 | [diff] [blame] | 722 | // If we encounter a closing ), ], } or >, we can remove a level from our |
Daniel Jasper | 2040915 | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 723 | // stacks. |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 724 | if (Current.isOneOf(tok::r_paren, tok::r_square) || |
Daniel Jasper | 26f7e78 | 2013-01-08 14:56:18 +0000 | [diff] [blame] | 725 | (Current.is(tok::r_brace) && State.NextToken != &RootToken) || |
| 726 | State.NextToken->Type == TT_TemplateCloser) { |
Daniel Jasper | 604eb4c | 2013-01-11 10:22:12 +0000 | [diff] [blame] | 727 | State.Stack.pop_back(); |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 728 | --State.ParenLevel; |
| 729 | } |
| 730 | |
| 731 | // Remove scopes created by fake parenthesis. |
| 732 | for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) { |
| 733 | State.Stack.pop_back(); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 734 | } |
Manuel Klimek | 2851c16 | 2013-01-10 14:36:46 +0000 | [diff] [blame] | 735 | |
Manuel Klimek | e9a6226 | 2013-02-20 15:32:58 +0000 | [diff] [blame] | 736 | if (Current.is(tok::string_literal)) { |
Manuel Klimek | b56b6d1 | 2013-02-20 15:25:48 +0000 | [diff] [blame] | 737 | State.StartOfStringLiteral = State.Column; |
| 738 | } else if (Current.isNot(tok::comment)) { |
| 739 | State.StartOfStringLiteral = 0; |
| 740 | } |
| 741 | |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 742 | State.Column += Current.FormatTok.TokenLength; |
| 743 | |
Daniel Jasper | 26f7e78 | 2013-01-08 14:56:18 +0000 | [diff] [blame] | 744 | if (State.NextToken->Children.empty()) |
| 745 | State.NextToken = NULL; |
| 746 | else |
| 747 | State.NextToken = &State.NextToken->Children[0]; |
Manuel Klimek | 2851c16 | 2013-01-10 14:36:46 +0000 | [diff] [blame] | 748 | |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 749 | return breakProtrudingToken(Current, State, DryRun); |
| 750 | } |
| 751 | |
| 752 | /// \brief If the current token sticks out over the end of the line, break |
| 753 | /// it if possible. |
| 754 | unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State, |
| 755 | bool DryRun) { |
| 756 | if (Current.isNot(tok::string_literal)) |
| 757 | return 0; |
Manuel Klimek | aa62d0c | 2013-03-08 18:59:48 +0000 | [diff] [blame] | 758 | // Only break up default narrow strings. |
| 759 | if (StringRef(Current.FormatTok.Tok.getLiteralData()).find('"') != 0) |
| 760 | return 0; |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 761 | |
| 762 | unsigned Penalty = 0; |
| 763 | unsigned TailOffset = 0; |
| 764 | unsigned TailLength = Current.FormatTok.TokenLength; |
| 765 | unsigned StartColumn = State.Column - Current.FormatTok.TokenLength; |
| 766 | unsigned OffsetFromStart = 0; |
| 767 | while (StartColumn + TailLength > getColumnLimit()) { |
Daniel Jasper | 6f21a98 | 2013-03-13 07:49:51 +0000 | [diff] [blame] | 768 | StringRef Text = StringRef( |
| 769 | Current.FormatTok.Tok.getLiteralData() + TailOffset, TailLength); |
Manuel Klimek | bc30c71 | 2013-03-01 13:29:19 +0000 | [diff] [blame] | 770 | if (StartColumn + OffsetFromStart + 1 > getColumnLimit()) |
Manuel Klimek | af31fd7 | 2013-03-01 13:14:08 +0000 | [diff] [blame] | 771 | break; |
Manuel Klimek | bc30c71 | 2013-03-01 13:29:19 +0000 | [diff] [blame] | 772 | StringRef::size_type SplitPoint = getSplitPoint( |
| 773 | Text, getColumnLimit() - StartColumn - OffsetFromStart - 1); |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 774 | if (SplitPoint == StringRef::npos) |
| 775 | break; |
| 776 | assert(SplitPoint != 0); |
| 777 | // +2, because 'Text' starts after the opening quotes, and does not |
| 778 | // include the closing quote we need to insert. |
| 779 | unsigned WhitespaceStartColumn = |
| 780 | StartColumn + OffsetFromStart + SplitPoint + 2; |
| 781 | State.Stack.back().LastSpace = StartColumn; |
| 782 | if (!DryRun) { |
| 783 | Whitespaces.breakToken(Current, TailOffset + SplitPoint + 1, "\"", "\"", |
| 784 | Line.InPPDirective, StartColumn, |
| 785 | WhitespaceStartColumn, Style); |
| 786 | } |
| 787 | TailOffset += SplitPoint + 1; |
| 788 | TailLength -= SplitPoint + 1; |
| 789 | OffsetFromStart = 1; |
Daniel Jasper | 0fb382b | 2013-02-26 12:52:34 +0000 | [diff] [blame] | 790 | Penalty += Style.PenaltyExcessCharacter; |
Daniel Jasper | faab0d3 | 2013-02-27 09:47:53 +0000 | [diff] [blame] | 791 | for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) |
| 792 | State.Stack[i].BreakBeforeParameter = true; |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 793 | } |
| 794 | State.Column = StartColumn + TailLength; |
| 795 | return Penalty; |
| 796 | } |
| 797 | |
| 798 | StringRef::size_type |
| 799 | getSplitPoint(StringRef Text, StringRef::size_type Offset) { |
Manuel Klimek | af31fd7 | 2013-03-01 13:14:08 +0000 | [diff] [blame] | 800 | StringRef::size_type SpaceOffset = Text.rfind(' ', Offset); |
Manuel Klimek | 0090591 | 2013-03-04 20:03:38 +0000 | [diff] [blame] | 801 | if (SpaceOffset != StringRef::npos && SpaceOffset != 0) |
Manuel Klimek | bc30c71 | 2013-03-01 13:29:19 +0000 | [diff] [blame] | 802 | return SpaceOffset; |
| 803 | StringRef::size_type SlashOffset = Text.rfind('/', Offset); |
Manuel Klimek | 0090591 | 2013-03-04 20:03:38 +0000 | [diff] [blame] | 804 | if (SlashOffset != StringRef::npos && SlashOffset != 0) |
Manuel Klimek | bc30c71 | 2013-03-01 13:29:19 +0000 | [diff] [blame] | 805 | return SlashOffset; |
Manuel Klimek | aa62d0c | 2013-03-08 18:59:48 +0000 | [diff] [blame] | 806 | StringRef::size_type Split = getStartOfCharacter(Text, Offset); |
| 807 | if (Split != StringRef::npos && Split > 1) |
Manuel Klimek | bc30c71 | 2013-03-01 13:29:19 +0000 | [diff] [blame] | 808 | // Do not split at 0. |
Manuel Klimek | aa62d0c | 2013-03-08 18:59:48 +0000 | [diff] [blame] | 809 | return Split - 1; |
Manuel Klimek | bc30c71 | 2013-03-01 13:29:19 +0000 | [diff] [blame] | 810 | return StringRef::npos; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 811 | } |
| 812 | |
Manuel Klimek | aa62d0c | 2013-03-08 18:59:48 +0000 | [diff] [blame] | 813 | StringRef::size_type |
| 814 | getStartOfCharacter(StringRef Text, StringRef::size_type Offset) { |
| 815 | StringRef::size_type NextEscape = Text.find('\\'); |
| 816 | while (NextEscape != StringRef::npos && NextEscape < Offset) { |
| 817 | StringRef::size_type SequenceLength = |
| 818 | getEscapeSequenceLength(Text.substr(NextEscape)); |
| 819 | if (Offset < NextEscape + SequenceLength) |
| 820 | return NextEscape; |
| 821 | NextEscape = Text.find('\\', NextEscape + SequenceLength); |
| 822 | } |
| 823 | return Offset; |
| 824 | } |
| 825 | |
| 826 | unsigned getEscapeSequenceLength(StringRef Text) { |
| 827 | assert(Text[0] == '\\'); |
| 828 | if (Text.size() < 2) |
| 829 | return 1; |
| 830 | |
| 831 | switch (Text[1]) { |
| 832 | case 'u': |
| 833 | return 6; |
| 834 | case 'U': |
| 835 | return 10; |
| 836 | case 'x': |
| 837 | return getHexLength(Text); |
| 838 | default: |
| 839 | if (Text[1] >= '0' && Text[1] <= '7') |
| 840 | return getOctalLength(Text); |
| 841 | return 2; |
| 842 | } |
| 843 | } |
| 844 | |
| 845 | unsigned getHexLength(StringRef Text) { |
| 846 | unsigned I = 2; // Point after '\x'. |
| 847 | while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') || |
| 848 | (Text[I] >= 'a' && Text[I] <= 'f') || |
| 849 | (Text[I] >= 'A' && Text[I] <= 'F'))) { |
| 850 | ++I; |
| 851 | } |
| 852 | return I; |
| 853 | } |
| 854 | |
| 855 | unsigned getOctalLength(StringRef Text) { |
| 856 | unsigned I = 1; |
| 857 | while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) { |
| 858 | ++I; |
| 859 | } |
| 860 | return I; |
| 861 | } |
| 862 | |
Daniel Jasper | ceb99ab | 2013-01-09 10:16:05 +0000 | [diff] [blame] | 863 | unsigned getColumnLimit() { |
Daniel Jasper | a4d4621 | 2013-02-28 11:05:57 +0000 | [diff] [blame] | 864 | return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0); |
Daniel Jasper | ceb99ab | 2013-01-09 10:16:05 +0000 | [diff] [blame] | 865 | } |
| 866 | |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 867 | /// \brief An edge in the solution space from \c Previous->State to \c State, |
| 868 | /// inserting a newline dependent on the \c NewLine. |
| 869 | struct StateNode { |
| 870 | StateNode(const LineState &State, bool NewLine, StateNode *Previous) |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 871 | : State(State), NewLine(NewLine), Previous(Previous) {} |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 872 | LineState State; |
| 873 | bool NewLine; |
| 874 | StateNode *Previous; |
| 875 | }; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 876 | |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 877 | /// \brief A pair of <penalty, count> that is used to prioritize the BFS on. |
| 878 | /// |
| 879 | /// In case of equal penalties, we want to prefer states that were inserted |
| 880 | /// first. During state generation we make sure that we insert states first |
| 881 | /// that break the line as late as possible. |
| 882 | typedef std::pair<unsigned, unsigned> OrderedPenalty; |
| 883 | |
| 884 | /// \brief An item in the prioritized BFS search queue. The \c StateNode's |
| 885 | /// \c State has the given \c OrderedPenalty. |
| 886 | typedef std::pair<OrderedPenalty, StateNode *> QueueItem; |
| 887 | |
| 888 | /// \brief The BFS queue type. |
| 889 | typedef std::priority_queue<QueueItem, std::vector<QueueItem>, |
| 890 | std::greater<QueueItem> > QueueType; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 891 | |
| 892 | /// \brief Analyze the entire solution space starting from \p InitialState. |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 893 | /// |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 894 | /// This implements a variant of Dijkstra's algorithm on the graph that spans |
| 895 | /// the solution space (\c LineStates are the nodes). The algorithm tries to |
| 896 | /// find the shortest path (the one with lowest penalty) from \p InitialState |
| 897 | /// to a state where all tokens are placed. |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 898 | unsigned analyzeSolutionSpace(LineState &InitialState) { |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 899 | std::set<LineState> Seen; |
| 900 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 901 | // Insert start element into queue. |
Daniel Jasper | fc75908 | 2013-02-14 14:26:07 +0000 | [diff] [blame] | 902 | StateNode *Node = |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 903 | new (Allocator.Allocate()) StateNode(InitialState, false, NULL); |
| 904 | Queue.push(QueueItem(OrderedPenalty(0, Count), Node)); |
| 905 | ++Count; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 906 | |
| 907 | // While not empty, take first element and follow edges. |
| 908 | while (!Queue.empty()) { |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 909 | unsigned Penalty = Queue.top().first.first; |
Daniel Jasper | fc75908 | 2013-02-14 14:26:07 +0000 | [diff] [blame] | 910 | StateNode *Node = Queue.top().second; |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 911 | if (Node->State.NextToken == NULL) { |
Daniel Jasper | 0178673 | 2013-02-04 07:21:18 +0000 | [diff] [blame] | 912 | DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n"); |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 913 | break; |
Daniel Jasper | 0178673 | 2013-02-04 07:21:18 +0000 | [diff] [blame] | 914 | } |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 915 | Queue.pop(); |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 916 | |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 917 | if (!Seen.insert(Node->State).second) |
| 918 | // State already examined with lower penalty. |
| 919 | continue; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 920 | |
Manuel Klimek | 62a48fb | 2013-02-13 10:54:19 +0000 | [diff] [blame] | 921 | addNextStateToQueue(Penalty, Node, /*NewLine=*/ false); |
| 922 | addNextStateToQueue(Penalty, Node, /*NewLine=*/ true); |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 923 | } |
| 924 | |
| 925 | if (Queue.empty()) |
| 926 | // We were unable to find a solution, do nothing. |
| 927 | // FIXME: Add diagnostic? |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 928 | return 0; |
| 929 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 930 | // Reconstruct the solution. |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 931 | reconstructPath(InitialState, Queue.top().second); |
Daniel Jasper | 0178673 | 2013-02-04 07:21:18 +0000 | [diff] [blame] | 932 | DEBUG(llvm::errs() << "---\n"); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 933 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 934 | // Return the column after the last token of the solution. |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 935 | return Queue.top().second->State.Column; |
| 936 | } |
| 937 | |
| 938 | void reconstructPath(LineState &State, StateNode *Current) { |
| 939 | // FIXME: This recursive implementation limits the possible number |
| 940 | // of tokens per line if compiled into a binary with small stack space. |
| 941 | // To become more independent of stack frame limitations we would need |
| 942 | // to also change the TokenAnnotator. |
| 943 | if (Current->Previous == NULL) |
| 944 | return; |
| 945 | reconstructPath(State, Current->Previous); |
| 946 | DEBUG({ |
| 947 | if (Current->NewLine) { |
Daniel Jasper | a03ab10 | 2013-02-13 20:33:44 +0000 | [diff] [blame] | 948 | llvm::errs() |
| 949 | << "Penalty for splitting before " |
| 950 | << Current->Previous->State.NextToken->FormatTok.Tok.getName() |
| 951 | << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n"; |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 952 | } |
| 953 | }); |
| 954 | addTokenToState(Current->NewLine, false, State); |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 955 | } |
| 956 | |
Manuel Klimek | 62a48fb | 2013-02-13 10:54:19 +0000 | [diff] [blame] | 957 | /// \brief Add the following state to the analysis queue \c Queue. |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 958 | /// |
Manuel Klimek | 62a48fb | 2013-02-13 10:54:19 +0000 | [diff] [blame] | 959 | /// Assume the current state is \p PreviousNode and has been reached with a |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 960 | /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. |
Manuel Klimek | 62a48fb | 2013-02-13 10:54:19 +0000 | [diff] [blame] | 961 | void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, |
| 962 | bool NewLine) { |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 963 | if (NewLine && !canBreak(PreviousNode->State)) |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 964 | return; |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 965 | if (!NewLine && mustBreak(PreviousNode->State)) |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 966 | return; |
Daniel Jasper | ae8699b | 2013-01-28 09:35:24 +0000 | [diff] [blame] | 967 | if (NewLine) |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 968 | Penalty += PreviousNode->State.NextToken->SplitPenalty; |
| 969 | |
| 970 | StateNode *Node = new (Allocator.Allocate()) |
| 971 | StateNode(PreviousNode->State, NewLine, PreviousNode); |
Manuel Klimek | 8092a94 | 2013-02-20 10:15:13 +0000 | [diff] [blame] | 972 | Penalty += addTokenToState(NewLine, true, Node->State); |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 973 | if (Node->State.Column > getColumnLimit()) { |
| 974 | unsigned ExcessCharacters = Node->State.Column - getColumnLimit(); |
Daniel Jasper | 0178673 | 2013-02-04 07:21:18 +0000 | [diff] [blame] | 975 | Penalty += Style.PenaltyExcessCharacter * ExcessCharacters; |
Daniel Jasper | ceb99ab | 2013-01-09 10:16:05 +0000 | [diff] [blame] | 976 | } |
Manuel Klimek | 32a2fd7 | 2013-02-13 10:46:36 +0000 | [diff] [blame] | 977 | |
| 978 | Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node)); |
| 979 | ++Count; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 980 | } |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 981 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 982 | /// \brief Returns \c true, if a line break after \p State is allowed. |
| 983 | bool canBreak(const LineState &State) { |
| 984 | if (!State.NextToken->CanBreakBefore && |
| 985 | !(State.NextToken->is(tok::r_brace) && |
| 986 | State.Stack.back().BreakBeforeClosingBrace)) |
| 987 | return false; |
Daniel Jasper | cf5767d | 2013-02-18 11:05:07 +0000 | [diff] [blame] | 988 | // This prevents breaks like: |
| 989 | // ... |
| 990 | // SomeParameter, OtherParameter).DoSomething( |
| 991 | // ... |
| 992 | // As they hide "DoSomething" and generally bad for readability. |
| 993 | if (State.NextToken->Parent->is(tok::l_paren) && |
| 994 | State.ParenLevel <= State.StartOfLineLevel) |
| 995 | return false; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 996 | // Trying to insert a parameter on a new line if there are already more than |
| 997 | // one parameter on the current line is bin packing. |
Daniel Jasper | d399bff | 2013-02-05 09:41:21 +0000 | [diff] [blame] | 998 | if (State.Stack.back().HasMultiParameterLine && |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 999 | State.Stack.back().AvoidBinPacking) |
| 1000 | return false; |
| 1001 | return true; |
| 1002 | } |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1003 | |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 1004 | /// \brief Returns \c true, if a line break after \p State is mandatory. |
| 1005 | bool mustBreak(const LineState &State) { |
| 1006 | if (State.NextToken->MustBreakBefore) |
| 1007 | return true; |
| 1008 | if (State.NextToken->is(tok::r_brace) && |
| 1009 | State.Stack.back().BreakBeforeClosingBrace) |
| 1010 | return true; |
| 1011 | if (State.NextToken->Parent->is(tok::semi) && |
| 1012 | State.LineContainsContinuedForLoopSection) |
| 1013 | return true; |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1014 | if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) || |
Daniel Jasper | 237d4c1 | 2013-02-23 21:01:55 +0000 | [diff] [blame] | 1015 | State.NextToken->is(tok::question) || |
| 1016 | State.NextToken->Type == TT_ConditionalExpr) && |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 1017 | State.Stack.back().BreakBeforeParameter && |
Daniel Jasper | c5cfa49 | 2013-02-14 09:19:04 +0000 | [diff] [blame] | 1018 | !isTrailingComment(*State.NextToken) && |
Daniel Jasper | 7d81281 | 2013-02-21 15:00:29 +0000 | [diff] [blame] | 1019 | State.NextToken->isNot(tok::r_paren) && |
| 1020 | State.NextToken->isNot(tok::r_brace)) |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 1021 | return true; |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 1022 | // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding |
| 1023 | // out whether it is the first parameter. Clean this up. |
Daniel Jasper | 63d7ced | 2013-02-05 10:07:47 +0000 | [diff] [blame] | 1024 | if (State.NextToken->Type == TT_ObjCSelectorName && |
Daniel Jasper | ce3d1a6 | 2013-02-08 08:22:00 +0000 | [diff] [blame] | 1025 | State.NextToken->LongestObjCSelectorName == 0 && |
| 1026 | State.Stack.back().BreakBeforeParameter) |
Daniel Jasper | 63d7ced | 2013-02-05 10:07:47 +0000 | [diff] [blame] | 1027 | return true; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 1028 | if ((State.NextToken->Type == TT_CtorInitializerColon || |
| 1029 | (State.NextToken->Parent->ClosesTemplateDeclaration && |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 1030 | State.ParenLevel == 0))) |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 1031 | return true; |
Daniel Jasper | 923ebef | 2013-03-14 13:45:21 +0000 | [diff] [blame] | 1032 | if (State.NextToken->Type == TT_InlineASMColon) |
| 1033 | return true; |
Daniel Jasper | 68ef0df | 2013-02-01 11:00:45 +0000 | [diff] [blame] | 1034 | return false; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1035 | } |
| 1036 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1037 | FormatStyle Style; |
| 1038 | SourceManager &SourceMgr; |
Daniel Jasper | 995e820 | 2013-01-14 13:08:07 +0000 | [diff] [blame] | 1039 | const AnnotatedLine &Line; |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 1040 | const unsigned FirstIndent; |
Daniel Jasper | 26f7e78 | 2013-01-08 14:56:18 +0000 | [diff] [blame] | 1041 | const AnnotatedToken &RootToken; |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 1042 | WhitespaceManager &Whitespaces; |
Manuel Klimek | 62a48fb | 2013-02-13 10:54:19 +0000 | [diff] [blame] | 1043 | |
| 1044 | llvm::SpecificBumpPtrAllocator<StateNode> Allocator; |
| 1045 | QueueType Queue; |
| 1046 | // Increasing count of \c StateNode items we have created. This is used |
| 1047 | // to create a deterministic order independent of the container. |
| 1048 | unsigned Count; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1049 | }; |
| 1050 | |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1051 | class LexerBasedFormatTokenSource : public FormatTokenSource { |
| 1052 | public: |
| 1053 | LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr) |
Daniel Jasper | 1321eb5 | 2012-12-18 21:05:13 +0000 | [diff] [blame] | 1054 | : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr), |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1055 | IdentTable(Lex.getLangOpts()) { |
| 1056 | Lex.SetKeepWhitespaceMode(true); |
| 1057 | } |
| 1058 | |
| 1059 | virtual FormatToken getNextToken() { |
| 1060 | if (GreaterStashed) { |
| 1061 | FormatTok.NewlinesBefore = 0; |
| 1062 | FormatTok.WhiteSpaceStart = |
| 1063 | FormatTok.Tok.getLocation().getLocWithOffset(1); |
| 1064 | FormatTok.WhiteSpaceLength = 0; |
| 1065 | GreaterStashed = false; |
| 1066 | return FormatTok; |
| 1067 | } |
| 1068 | |
| 1069 | FormatTok = FormatToken(); |
| 1070 | Lex.LexFromRawLexer(FormatTok.Tok); |
Manuel Klimek | 9541938 | 2013-01-07 07:56:50 +0000 | [diff] [blame] | 1071 | StringRef Text = rawTokenText(FormatTok.Tok); |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1072 | FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation(); |
Manuel Klimek | f6fd00b | 2013-01-05 22:56:06 +0000 | [diff] [blame] | 1073 | if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0) |
| 1074 | FormatTok.IsFirst = true; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1075 | |
| 1076 | // Consume and record whitespace until we find a significant token. |
| 1077 | while (FormatTok.Tok.is(tok::unknown)) { |
Manuel Klimek | a28fc06 | 2013-02-11 12:33:24 +0000 | [diff] [blame] | 1078 | unsigned Newlines = Text.count('\n'); |
Daniel Jasper | 1eee6c4 | 2013-03-04 13:43:19 +0000 | [diff] [blame] | 1079 | if (Newlines > 0) |
| 1080 | FormatTok.LastNewlineOffset = |
| 1081 | FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1; |
Manuel Klimek | a28fc06 | 2013-02-11 12:33:24 +0000 | [diff] [blame] | 1082 | unsigned EscapedNewlines = Text.count("\\\n"); |
| 1083 | FormatTok.NewlinesBefore += Newlines; |
| 1084 | FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1085 | FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength(); |
| 1086 | |
| 1087 | if (FormatTok.Tok.is(tok::eof)) |
| 1088 | return FormatTok; |
| 1089 | Lex.LexFromRawLexer(FormatTok.Tok); |
Manuel Klimek | 9541938 | 2013-01-07 07:56:50 +0000 | [diff] [blame] | 1090 | Text = rawTokenText(FormatTok.Tok); |
Manuel Klimek | d4397b9 | 2013-01-04 23:34:14 +0000 | [diff] [blame] | 1091 | } |
Manuel Klimek | 9541938 | 2013-01-07 07:56:50 +0000 | [diff] [blame] | 1092 | |
| 1093 | // Now FormatTok is the next non-whitespace token. |
| 1094 | FormatTok.TokenLength = Text.size(); |
| 1095 | |
Manuel Klimek | d4397b9 | 2013-01-04 23:34:14 +0000 | [diff] [blame] | 1096 | // In case the token starts with escaped newlines, we want to |
| 1097 | // take them into account as whitespace - this pattern is quite frequent |
| 1098 | // in macro definitions. |
| 1099 | // FIXME: What do we want to do with other escaped spaces, and escaped |
| 1100 | // spaces or newlines in the middle of tokens? |
| 1101 | // FIXME: Add a more explicit test. |
| 1102 | unsigned i = 0; |
Daniel Jasper | 7160751 | 2013-01-07 10:48:50 +0000 | [diff] [blame] | 1103 | while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') { |
Manuel Klimek | 86721d2 | 2013-01-22 16:31:55 +0000 | [diff] [blame] | 1104 | // FIXME: ++FormatTok.NewlinesBefore is missing... |
Manuel Klimek | d4397b9 | 2013-01-04 23:34:14 +0000 | [diff] [blame] | 1105 | FormatTok.WhiteSpaceLength += 2; |
Manuel Klimek | 9541938 | 2013-01-07 07:56:50 +0000 | [diff] [blame] | 1106 | FormatTok.TokenLength -= 2; |
Manuel Klimek | d4397b9 | 2013-01-04 23:34:14 +0000 | [diff] [blame] | 1107 | i += 2; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1108 | } |
| 1109 | |
| 1110 | if (FormatTok.Tok.is(tok::raw_identifier)) { |
Manuel Klimek | d4397b9 | 2013-01-04 23:34:14 +0000 | [diff] [blame] | 1111 | IdentifierInfo &Info = IdentTable.get(Text); |
Daniel Jasper | cd1a32b | 2012-12-21 17:58:39 +0000 | [diff] [blame] | 1112 | FormatTok.Tok.setIdentifierInfo(&Info); |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1113 | FormatTok.Tok.setKind(Info.getTokenID()); |
| 1114 | } |
| 1115 | |
| 1116 | if (FormatTok.Tok.is(tok::greatergreater)) { |
| 1117 | FormatTok.Tok.setKind(tok::greater); |
Daniel Jasper | b6f02f3 | 2013-02-28 10:06:05 +0000 | [diff] [blame] | 1118 | FormatTok.TokenLength = 1; |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1119 | GreaterStashed = true; |
| 1120 | } |
| 1121 | |
Daniel Jasper | 812c045 | 2013-03-01 16:45:59 +0000 | [diff] [blame] | 1122 | // If we reformat comments, we remove trailing whitespace. Update the length |
| 1123 | // accordingly. |
| 1124 | if (FormatTok.Tok.is(tok::comment)) |
| 1125 | FormatTok.TokenLength = Text.rtrim().size(); |
| 1126 | |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1127 | return FormatTok; |
| 1128 | } |
| 1129 | |
Nico Weber | c2e6d2a | 2013-02-11 15:32:15 +0000 | [diff] [blame] | 1130 | IdentifierTable &getIdentTable() { return IdentTable; } |
| 1131 | |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1132 | private: |
| 1133 | FormatToken FormatTok; |
| 1134 | bool GreaterStashed; |
| 1135 | Lexer &Lex; |
| 1136 | SourceManager &SourceMgr; |
| 1137 | IdentifierTable IdentTable; |
| 1138 | |
| 1139 | /// Returns the text of \c FormatTok. |
Manuel Klimek | 9541938 | 2013-01-07 07:56:50 +0000 | [diff] [blame] | 1140 | StringRef rawTokenText(Token &Tok) { |
Alexander Kornienko | 469a21b | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 1141 | return StringRef(SourceMgr.getCharacterData(Tok.getLocation()), |
| 1142 | Tok.getLength()); |
| 1143 | } |
| 1144 | }; |
| 1145 | |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1146 | class Formatter : public UnwrappedLineConsumer { |
| 1147 | public: |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1148 | Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex, |
| 1149 | SourceManager &SourceMgr, |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1150 | const std::vector<CharSourceRange> &Ranges) |
Alexander Kornienko | 3048aea | 2013-01-10 15:05:09 +0000 | [diff] [blame] | 1151 | : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr), |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 1152 | Whitespaces(SourceMgr), Ranges(Ranges) {} |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1153 | |
Daniel Jasper | 7d19bc2 | 2013-01-11 14:23:32 +0000 | [diff] [blame] | 1154 | virtual ~Formatter() {} |
Daniel Jasper | accb0b0 | 2012-12-04 21:05:31 +0000 | [diff] [blame] | 1155 | |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1156 | tooling::Replacements format() { |
| 1157 | LexerBasedFormatTokenSource Tokens(Lex, SourceMgr); |
| 1158 | UnwrappedLineParser Parser(Diag, Style, Tokens, *this); |
| 1159 | StructuralError = Parser.parse(); |
| 1160 | unsigned PreviousEndOfLineColumn = 0; |
| 1161 | TokenAnnotator Annotator(Style, SourceMgr, Lex, |
| 1162 | Tokens.getIdentTable().get("in")); |
| 1163 | for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { |
| 1164 | Annotator.annotate(AnnotatedLines[i]); |
| 1165 | } |
| 1166 | deriveLocalStyle(); |
| 1167 | for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { |
| 1168 | Annotator.calculateFormattingInformation(AnnotatedLines[i]); |
Daniel Jasper | 6050a1e | 2013-03-13 15:53:12 +0000 | [diff] [blame] | 1169 | |
| 1170 | // Adapt level to the next line if this is a comment. |
| 1171 | // FIXME: Can/should this be done in the UnwrappedLineParser? |
| 1172 | if (i + 1 != e && AnnotatedLines[i].First.is(tok::comment) && |
| 1173 | AnnotatedLines[i].First.Children.empty() && |
| 1174 | AnnotatedLines[i + 1].First.isNot(tok::r_brace)) |
| 1175 | AnnotatedLines[i].Level = AnnotatedLines[i + 1].Level; |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1176 | } |
| 1177 | std::vector<int> IndentForLevel; |
| 1178 | bool PreviousLineWasTouched = false; |
| 1179 | for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(), |
| 1180 | E = AnnotatedLines.end(); |
| 1181 | I != E; ++I) { |
| 1182 | const AnnotatedLine &TheLine = *I; |
| 1183 | const FormatToken &FirstTok = TheLine.First.FormatTok; |
| 1184 | int Offset = getIndentOffset(TheLine.First); |
| 1185 | while (IndentForLevel.size() <= TheLine.Level) |
| 1186 | IndentForLevel.push_back(-1); |
| 1187 | IndentForLevel.resize(TheLine.Level + 1); |
| 1188 | bool WasMoved = |
| 1189 | PreviousLineWasTouched && FirstTok.NewlinesBefore == 0; |
| 1190 | if (TheLine.First.is(tok::eof)) { |
| 1191 | if (PreviousLineWasTouched) { |
| 1192 | unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u); |
| 1193 | Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0, |
| 1194 | /*WhitespaceStartColumn*/ 0, Style); |
| 1195 | } |
| 1196 | } else if (TheLine.Type != LT_Invalid && |
| 1197 | (WasMoved || touchesLine(TheLine))) { |
| 1198 | unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level); |
| 1199 | unsigned Indent = LevelIndent; |
| 1200 | if (static_cast<int>(Indent) + Offset >= 0) |
| 1201 | Indent += Offset; |
| 1202 | if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) { |
| 1203 | Indent = LevelIndent = SourceMgr.getSpellingColumnNumber( |
| 1204 | FirstTok.Tok.getLocation()) - 1; |
| 1205 | } else { |
| 1206 | formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective, |
| 1207 | PreviousEndOfLineColumn); |
| 1208 | } |
| 1209 | tryFitMultipleLinesInOne(Indent, I, E); |
| 1210 | UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent, |
| 1211 | TheLine.First, Whitespaces, |
| 1212 | StructuralError); |
| 1213 | PreviousEndOfLineColumn = |
| 1214 | Formatter.format(I + 1 != E ? &*(I + 1) : NULL); |
| 1215 | IndentForLevel[TheLine.Level] = LevelIndent; |
| 1216 | PreviousLineWasTouched = true; |
| 1217 | } else { |
| 1218 | if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) { |
| 1219 | unsigned Indent = |
| 1220 | SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1; |
| 1221 | unsigned LevelIndent = Indent; |
| 1222 | if (static_cast<int>(LevelIndent) - Offset >= 0) |
| 1223 | LevelIndent -= Offset; |
| 1224 | IndentForLevel[TheLine.Level] = LevelIndent; |
| 1225 | |
| 1226 | // Remove trailing whitespace of the previous line if it was touched. |
| 1227 | if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) |
| 1228 | formatFirstToken(TheLine.First, Indent, TheLine.InPPDirective, |
| 1229 | PreviousEndOfLineColumn); |
| 1230 | } |
| 1231 | // If we did not reformat this unwrapped line, the column at the end of |
| 1232 | // the last token is unchanged - thus, we can calculate the end of the |
| 1233 | // last token. |
| 1234 | SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation(); |
| 1235 | PreviousEndOfLineColumn = |
| 1236 | SourceMgr.getSpellingColumnNumber(LastLoc) + |
| 1237 | Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1; |
| 1238 | PreviousLineWasTouched = false; |
| 1239 | } |
| 1240 | } |
| 1241 | return Whitespaces.generateReplacements(); |
| 1242 | } |
| 1243 | |
| 1244 | private: |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 1245 | void deriveLocalStyle() { |
| 1246 | unsigned CountBoundToVariable = 0; |
| 1247 | unsigned CountBoundToType = 0; |
| 1248 | bool HasCpp03IncompatibleFormat = false; |
| 1249 | for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { |
| 1250 | if (AnnotatedLines[i].First.Children.empty()) |
| 1251 | continue; |
| 1252 | AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0]; |
| 1253 | while (!Tok->Children.empty()) { |
| 1254 | if (Tok->Type == TT_PointerOrReference) { |
| 1255 | bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0; |
| 1256 | bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0; |
| 1257 | if (SpacesBefore && !SpacesAfter) |
| 1258 | ++CountBoundToVariable; |
| 1259 | else if (!SpacesBefore && SpacesAfter) |
| 1260 | ++CountBoundToType; |
| 1261 | } |
| 1262 | |
Daniel Jasper | 29f123b | 2013-02-08 15:28:42 +0000 | [diff] [blame] | 1263 | if (Tok->Type == TT_TemplateCloser && |
| 1264 | Tok->Parent->Type == TT_TemplateCloser && |
| 1265 | Tok->FormatTok.WhiteSpaceLength == 0) |
Daniel Jasper | 8ff690a | 2013-02-06 14:22:40 +0000 | [diff] [blame] | 1266 | HasCpp03IncompatibleFormat = true; |
| 1267 | Tok = &Tok->Children[0]; |
| 1268 | } |
| 1269 | } |
| 1270 | if (Style.DerivePointerBinding) { |
| 1271 | if (CountBoundToType > CountBoundToVariable) |
| 1272 | Style.PointerBindsToType = true; |
| 1273 | else if (CountBoundToType < CountBoundToVariable) |
| 1274 | Style.PointerBindsToType = false; |
| 1275 | } |
| 1276 | if (Style.Standard == FormatStyle::LS_Auto) { |
| 1277 | Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11 |
| 1278 | : FormatStyle::LS_Cpp03; |
| 1279 | } |
| 1280 | } |
| 1281 | |
Manuel Klimek | 547d5db | 2013-02-08 17:38:27 +0000 | [diff] [blame] | 1282 | /// \brief Get the indent of \p Level from \p IndentForLevel. |
| 1283 | /// |
| 1284 | /// \p IndentForLevel must contain the indent for the level \c l |
| 1285 | /// at \p IndentForLevel[l], or a value < 0 if the indent for |
| 1286 | /// that level is unknown. |
Daniel Jasper | fc75908 | 2013-02-14 14:26:07 +0000 | [diff] [blame] | 1287 | unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) { |
Manuel Klimek | 547d5db | 2013-02-08 17:38:27 +0000 | [diff] [blame] | 1288 | if (IndentForLevel[Level] != -1) |
| 1289 | return IndentForLevel[Level]; |
Manuel Klimek | 52635ff | 2013-02-08 19:53:32 +0000 | [diff] [blame] | 1290 | if (Level == 0) |
| 1291 | return 0; |
Daniel Jasper | c78c6b3 | 2013-02-14 09:58:41 +0000 | [diff] [blame] | 1292 | return getIndent(IndentForLevel, Level - 1) + 2; |
Manuel Klimek | 547d5db | 2013-02-08 17:38:27 +0000 | [diff] [blame] | 1293 | } |
| 1294 | |
| 1295 | /// \brief Get the offset of the line relatively to the level. |
| 1296 | /// |
| 1297 | /// For example, 'public:' labels in classes are offset by 1 or 2 |
| 1298 | /// characters to the left from their level. |
Daniel Jasper | c78c6b3 | 2013-02-14 09:58:41 +0000 | [diff] [blame] | 1299 | int getIndentOffset(const AnnotatedToken &RootToken) { |
Manuel Klimek | 547d5db | 2013-02-08 17:38:27 +0000 | [diff] [blame] | 1300 | bool IsAccessModifier = false; |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1301 | if (RootToken.isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private)) |
Manuel Klimek | 547d5db | 2013-02-08 17:38:27 +0000 | [diff] [blame] | 1302 | IsAccessModifier = true; |
| 1303 | else if (RootToken.is(tok::at) && !RootToken.Children.empty() && |
| 1304 | (RootToken.Children[0].isObjCAtKeyword(tok::objc_public) || |
| 1305 | RootToken.Children[0].isObjCAtKeyword(tok::objc_protected) || |
| 1306 | RootToken.Children[0].isObjCAtKeyword(tok::objc_package) || |
| 1307 | RootToken.Children[0].isObjCAtKeyword(tok::objc_private))) |
| 1308 | IsAccessModifier = true; |
| 1309 | |
| 1310 | if (IsAccessModifier) |
| 1311 | return Style.AccessModifierOffset; |
| 1312 | return 0; |
| 1313 | } |
| 1314 | |
Manuel Klimek | 517e894 | 2013-01-11 17:54:10 +0000 | [diff] [blame] | 1315 | /// \brief Tries to merge lines into one. |
| 1316 | /// |
| 1317 | /// This will change \c Line and \c AnnotatedLine to contain the merged line, |
| 1318 | /// if possible; note that \c I will be incremented when lines are merged. |
| 1319 | /// |
| 1320 | /// Returns whether the resulting \c Line can fit in a single line. |
Daniel Jasper | 3f8cdbf | 2013-01-16 10:41:46 +0000 | [diff] [blame] | 1321 | void tryFitMultipleLinesInOne(unsigned Indent, |
Daniel Jasper | 995e820 | 2013-01-14 13:08:07 +0000 | [diff] [blame] | 1322 | std::vector<AnnotatedLine>::iterator &I, |
| 1323 | std::vector<AnnotatedLine>::iterator E) { |
Daniel Jasper | 3f8cdbf | 2013-01-16 10:41:46 +0000 | [diff] [blame] | 1324 | // We can never merge stuff if there are trailing line comments. |
| 1325 | if (I->Last->Type == TT_LineComment) |
| 1326 | return; |
| 1327 | |
Daniel Jasper | a4d4621 | 2013-02-28 11:05:57 +0000 | [diff] [blame] | 1328 | unsigned Limit = Style.ColumnLimit - Indent; |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 1329 | // If we already exceed the column limit, we set 'Limit' to 0. The different |
| 1330 | // tryMerge..() functions can then decide whether to still do merging. |
| 1331 | Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength; |
Daniel Jasper | 55b08e7 | 2013-01-16 07:02:34 +0000 | [diff] [blame] | 1332 | |
Daniel Jasper | 9c8c40e | 2013-01-21 14:18:28 +0000 | [diff] [blame] | 1333 | if (I + 1 == E || (I + 1)->Type == LT_Invalid) |
Daniel Jasper | 3f8cdbf | 2013-01-16 10:41:46 +0000 | [diff] [blame] | 1334 | return; |
Manuel Klimek | 517e894 | 2013-01-11 17:54:10 +0000 | [diff] [blame] | 1335 | |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1336 | if (I->Last->is(tok::l_brace)) { |
| 1337 | tryMergeSimpleBlock(I, E, Limit); |
| 1338 | } else if (I->First.is(tok::kw_if)) { |
| 1339 | tryMergeSimpleIf(I, E, Limit); |
Daniel Jasper | e0b15ea | 2013-01-14 15:40:57 +0000 | [diff] [blame] | 1340 | } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline || |
| 1341 | I->First.FormatTok.IsFirst)) { |
| 1342 | tryMergeSimplePPDirective(I, E, Limit); |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1343 | } |
Daniel Jasper | 3f8cdbf | 2013-01-16 10:41:46 +0000 | [diff] [blame] | 1344 | return; |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1345 | } |
| 1346 | |
Daniel Jasper | e0b15ea | 2013-01-14 15:40:57 +0000 | [diff] [blame] | 1347 | void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I, |
| 1348 | std::vector<AnnotatedLine>::iterator E, |
| 1349 | unsigned Limit) { |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 1350 | if (Limit == 0) |
| 1351 | return; |
Daniel Jasper | e0b15ea | 2013-01-14 15:40:57 +0000 | [diff] [blame] | 1352 | AnnotatedLine &Line = *I; |
Daniel Jasper | 2b9c10b | 2013-01-14 15:52:06 +0000 | [diff] [blame] | 1353 | if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline) |
| 1354 | return; |
Daniel Jasper | e0b15ea | 2013-01-14 15:40:57 +0000 | [diff] [blame] | 1355 | if (I + 2 != E && (I + 2)->InPPDirective && |
| 1356 | !(I + 2)->First.FormatTok.HasUnescapedNewline) |
| 1357 | return; |
Manuel Klimek | 2f1ac41 | 2013-01-21 16:42:44 +0000 | [diff] [blame] | 1358 | if (1 + (I + 1)->Last->TotalLength > Limit) |
Daniel Jasper | 3f8cdbf | 2013-01-16 10:41:46 +0000 | [diff] [blame] | 1359 | return; |
Daniel Jasper | e0b15ea | 2013-01-14 15:40:57 +0000 | [diff] [blame] | 1360 | join(Line, *(++I)); |
| 1361 | } |
| 1362 | |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1363 | void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I, |
| 1364 | std::vector<AnnotatedLine>::iterator E, |
| 1365 | unsigned Limit) { |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 1366 | if (Limit == 0) |
| 1367 | return; |
Daniel Jasper | 6f5bb2c | 2013-01-14 16:24:39 +0000 | [diff] [blame] | 1368 | if (!Style.AllowShortIfStatementsOnASingleLine) |
| 1369 | return; |
Manuel Klimek | 4c12812 | 2013-01-18 14:46:43 +0000 | [diff] [blame] | 1370 | if ((I + 1)->InPPDirective != I->InPPDirective || |
| 1371 | ((I + 1)->InPPDirective && |
| 1372 | (I + 1)->First.FormatTok.HasUnescapedNewline)) |
| 1373 | return; |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1374 | AnnotatedLine &Line = *I; |
Daniel Jasper | 55b08e7 | 2013-01-16 07:02:34 +0000 | [diff] [blame] | 1375 | if (Line.Last->isNot(tok::r_paren)) |
| 1376 | return; |
Manuel Klimek | 2f1ac41 | 2013-01-21 16:42:44 +0000 | [diff] [blame] | 1377 | if (1 + (I + 1)->Last->TotalLength > Limit) |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1378 | return; |
| 1379 | if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment) |
| 1380 | return; |
| 1381 | // Only inline simple if's (no nested if or else). |
| 1382 | if (I + 2 != E && (I + 2)->First.is(tok::kw_else)) |
| 1383 | return; |
| 1384 | join(Line, *(++I)); |
| 1385 | } |
| 1386 | |
| 1387 | void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I, |
Daniel Jasper | 1a1ce83 | 2013-01-29 11:27:30 +0000 | [diff] [blame] | 1388 | std::vector<AnnotatedLine>::iterator E, |
| 1389 | unsigned Limit) { |
Manuel Klimek | 517e894 | 2013-01-11 17:54:10 +0000 | [diff] [blame] | 1390 | // First, check that the current line allows merging. This is the case if |
| 1391 | // we're not in a control flow statement and the last token is an opening |
| 1392 | // brace. |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1393 | AnnotatedLine &Line = *I; |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1394 | if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace, |
| 1395 | tok::kw_else, tok::kw_try, tok::kw_catch, |
| 1396 | tok::kw_for, |
| 1397 | // This gets rid of all ObjC @ keywords and methods. |
| 1398 | tok::at, tok::minus, tok::plus)) |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1399 | return; |
Manuel Klimek | 517e894 | 2013-01-11 17:54:10 +0000 | [diff] [blame] | 1400 | |
Manuel Klimek | 2f1ac41 | 2013-01-21 16:42:44 +0000 | [diff] [blame] | 1401 | AnnotatedToken *Tok = &(I + 1)->First; |
| 1402 | if (Tok->Children.empty() && Tok->is(tok::r_brace) && |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 1403 | !Tok->MustBreakBefore) { |
| 1404 | // We merge empty blocks even if the line exceeds the column limit. |
Daniel Jasper | 729a743 | 2013-02-11 12:36:37 +0000 | [diff] [blame] | 1405 | Tok->SpacesRequiredBefore = 0; |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 1406 | Tok->CanBreakBefore = true; |
Manuel Klimek | 2f1ac41 | 2013-01-21 16:42:44 +0000 | [diff] [blame] | 1407 | join(Line, *(I + 1)); |
| 1408 | I += 1; |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 1409 | } else if (Limit != 0) { |
Manuel Klimek | 2f1ac41 | 2013-01-21 16:42:44 +0000 | [diff] [blame] | 1410 | // Check that we still have three lines and they fit into the limit. |
| 1411 | if (I + 2 == E || (I + 2)->Type == LT_Invalid || |
| 1412 | !nextTwoLinesFitInto(I, Limit)) |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1413 | return; |
Manuel Klimek | 517e894 | 2013-01-11 17:54:10 +0000 | [diff] [blame] | 1414 | |
Manuel Klimek | 2f1ac41 | 2013-01-21 16:42:44 +0000 | [diff] [blame] | 1415 | // Second, check that the next line does not contain any braces - if it |
| 1416 | // does, readability declines when putting it into a single line. |
| 1417 | if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore) |
| 1418 | return; |
| 1419 | do { |
Alexander Kornienko | e74de28 | 2013-03-13 14:41:29 +0000 | [diff] [blame] | 1420 | if (Tok->isOneOf(tok::l_brace, tok::r_brace)) |
Manuel Klimek | 2f1ac41 | 2013-01-21 16:42:44 +0000 | [diff] [blame] | 1421 | return; |
| 1422 | Tok = Tok->Children.empty() ? NULL : &Tok->Children.back(); |
| 1423 | } while (Tok != NULL); |
Manuel Klimek | 517e894 | 2013-01-11 17:54:10 +0000 | [diff] [blame] | 1424 | |
Manuel Klimek | 2f1ac41 | 2013-01-21 16:42:44 +0000 | [diff] [blame] | 1425 | // Last, check that the third line contains a single closing brace. |
| 1426 | Tok = &(I + 2)->First; |
| 1427 | if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) || |
| 1428 | Tok->MustBreakBefore) |
| 1429 | return; |
| 1430 | |
| 1431 | join(Line, *(I + 1)); |
| 1432 | join(Line, *(I + 2)); |
| 1433 | I += 2; |
Manuel Klimek | 517e894 | 2013-01-11 17:54:10 +0000 | [diff] [blame] | 1434 | } |
Daniel Jasper | feb18f5 | 2013-01-14 14:14:23 +0000 | [diff] [blame] | 1435 | } |
| 1436 | |
| 1437 | bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I, |
| 1438 | unsigned Limit) { |
Manuel Klimek | 2f1ac41 | 2013-01-21 16:42:44 +0000 | [diff] [blame] | 1439 | return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <= |
| 1440 | Limit; |
Manuel Klimek | 517e894 | 2013-01-11 17:54:10 +0000 | [diff] [blame] | 1441 | } |
| 1442 | |
Daniel Jasper | 995e820 | 2013-01-14 13:08:07 +0000 | [diff] [blame] | 1443 | void join(AnnotatedLine &A, const AnnotatedLine &B) { |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 1444 | unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore; |
Daniel Jasper | 995e820 | 2013-01-14 13:08:07 +0000 | [diff] [blame] | 1445 | A.Last->Children.push_back(B.First); |
| 1446 | while (!A.Last->Children.empty()) { |
| 1447 | A.Last->Children[0].Parent = A.Last; |
Daniel Jasper | f11a705 | 2013-02-21 21:33:55 +0000 | [diff] [blame] | 1448 | A.Last->Children[0].TotalLength += LengthA; |
Daniel Jasper | 995e820 | 2013-01-14 13:08:07 +0000 | [diff] [blame] | 1449 | A.Last = &A.Last->Children[0]; |
| 1450 | } |
Manuel Klimek | f9ea2ed | 2013-01-10 19:49:59 +0000 | [diff] [blame] | 1451 | } |
| 1452 | |
Daniel Jasper | 6f21a98 | 2013-03-13 07:49:51 +0000 | [diff] [blame] | 1453 | bool touchesRanges(const CharSourceRange &Range) { |
Daniel Jasper | f302354 | 2013-03-07 20:50:00 +0000 | [diff] [blame] | 1454 | for (unsigned i = 0, e = Ranges.size(); i != e; ++i) { |
| 1455 | if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), |
| 1456 | Ranges[i].getBegin()) && |
| 1457 | !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(), |
| 1458 | Range.getBegin())) |
| 1459 | return true; |
| 1460 | } |
| 1461 | return false; |
| 1462 | } |
| 1463 | |
| 1464 | bool touchesLine(const AnnotatedLine &TheLine) { |
Daniel Jasper | 995e820 | 2013-01-14 13:08:07 +0000 | [diff] [blame] | 1465 | const FormatToken *First = &TheLine.First.FormatTok; |
| 1466 | const FormatToken *Last = &TheLine.Last->FormatTok; |
Daniel Jasper | cd16238 | 2013-01-07 13:26:07 +0000 | [diff] [blame] | 1467 | CharSourceRange LineRange = CharSourceRange::getTokenRange( |
Daniel Jasper | 1eee6c4 | 2013-03-04 13:43:19 +0000 | [diff] [blame] | 1468 | First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset), |
| 1469 | Last->Tok.getLocation()); |
Daniel Jasper | f302354 | 2013-03-07 20:50:00 +0000 | [diff] [blame] | 1470 | return touchesRanges(LineRange); |
| 1471 | } |
| 1472 | |
| 1473 | bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) { |
| 1474 | const FormatToken *First = &TheLine.First.FormatTok; |
| 1475 | CharSourceRange LineRange = CharSourceRange::getCharRange( |
| 1476 | First->WhiteSpaceStart, |
| 1477 | First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset)); |
| 1478 | return touchesRanges(LineRange); |
Manuel Klimek | f9ea2ed | 2013-01-10 19:49:59 +0000 | [diff] [blame] | 1479 | } |
| 1480 | |
| 1481 | virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) { |
Daniel Jasper | cbb6c41 | 2013-01-16 09:10:19 +0000 | [diff] [blame] | 1482 | AnnotatedLines.push_back(AnnotatedLine(TheLine)); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1483 | } |
| 1484 | |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 1485 | /// \brief Add a new line and the required indent before the first Token |
| 1486 | /// of the \c UnwrappedLine if there was no structural parsing error. |
| 1487 | /// Returns the indent level of the \c UnwrappedLine. |
Manuel Klimek | 547d5db | 2013-02-08 17:38:27 +0000 | [diff] [blame] | 1488 | void formatFirstToken(const AnnotatedToken &RootToken, unsigned Indent, |
| 1489 | bool InPPDirective, unsigned PreviousEndOfLineColumn) { |
Daniel Jasper | 7d19bc2 | 2013-01-11 14:23:32 +0000 | [diff] [blame] | 1490 | const FormatToken &Tok = RootToken.FormatTok; |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 1491 | |
Daniel Jasper | 1a1ce83 | 2013-01-29 11:27:30 +0000 | [diff] [blame] | 1492 | unsigned Newlines = |
| 1493 | std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 1494 | if (Newlines == 0 && !Tok.IsFirst) |
| 1495 | Newlines = 1; |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 1496 | |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 1497 | if (!InPPDirective || Tok.HasUnescapedNewline) { |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 1498 | Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0, Style); |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 1499 | } else { |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 1500 | Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent, |
| 1501 | PreviousEndOfLineColumn, Style); |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 1502 | } |
Manuel Klimek | 3f8c7f3 | 2013-01-10 18:45:26 +0000 | [diff] [blame] | 1503 | } |
| 1504 | |
Alexander Kornienko | a4ae9f3 | 2013-01-14 11:34:14 +0000 | [diff] [blame] | 1505 | DiagnosticsEngine &Diag; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1506 | FormatStyle Style; |
| 1507 | Lexer &Lex; |
| 1508 | SourceManager &SourceMgr; |
Daniel Jasper | dcc2a62 | 2013-01-18 08:44:07 +0000 | [diff] [blame] | 1509 | WhitespaceManager Whitespaces; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1510 | std::vector<CharSourceRange> Ranges; |
Daniel Jasper | 995e820 | 2013-01-14 13:08:07 +0000 | [diff] [blame] | 1511 | std::vector<AnnotatedLine> AnnotatedLines; |
Alexander Kornienko | cff563c | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 1512 | bool StructuralError; |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1513 | }; |
| 1514 | |
Daniel Jasper | 1a1ce83 | 2013-01-29 11:27:30 +0000 | [diff] [blame] | 1515 | tooling::Replacements |
| 1516 | reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr, |
| 1517 | std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) { |
Alexander Kornienko | 3048aea | 2013-01-10 15:05:09 +0000 | [diff] [blame] | 1518 | IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); |
Alexander Kornienko | a4ae9f3 | 2013-01-14 11:34:14 +0000 | [diff] [blame] | 1519 | OwningPtr<DiagnosticConsumer> DiagPrinter; |
| 1520 | if (DiagClient == 0) { |
| 1521 | DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts)); |
| 1522 | DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP()); |
| 1523 | DiagClient = DiagPrinter.get(); |
| 1524 | } |
Alexander Kornienko | 3048aea | 2013-01-10 15:05:09 +0000 | [diff] [blame] | 1525 | DiagnosticsEngine Diagnostics( |
Dmitri Gribenko | cfa88f8 | 2013-01-12 19:30:44 +0000 | [diff] [blame] | 1526 | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, |
Alexander Kornienko | a4ae9f3 | 2013-01-14 11:34:14 +0000 | [diff] [blame] | 1527 | DiagClient, false); |
Alexander Kornienko | 3048aea | 2013-01-10 15:05:09 +0000 | [diff] [blame] | 1528 | Diagnostics.setSourceManager(&SourceMgr); |
| 1529 | Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges); |
Daniel Jasper | bac016b | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 1530 | return formatter.format(); |
| 1531 | } |
| 1532 | |
Daniel Jasper | 46ef852 | 2013-01-10 13:08:12 +0000 | [diff] [blame] | 1533 | LangOptions getFormattingLangOpts() { |
| 1534 | LangOptions LangOpts; |
| 1535 | LangOpts.CPlusPlus = 1; |
| 1536 | LangOpts.CPlusPlus11 = 1; |
| 1537 | LangOpts.Bool = 1; |
| 1538 | LangOpts.ObjC1 = 1; |
| 1539 | LangOpts.ObjC2 = 1; |
| 1540 | return LangOpts; |
| 1541 | } |
| 1542 | |
Daniel Jasper | cd16238 | 2013-01-07 13:26:07 +0000 | [diff] [blame] | 1543 | } // namespace format |
| 1544 | } // namespace clang |