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