Daniel Jasper | f793511 | 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 | /// |
| 14 | /// This is EXPERIMENTAL code under heavy development. It is not in a state yet, |
| 15 | /// where it can be used to format real code. |
| 16 | /// |
| 17 | //===----------------------------------------------------------------------===// |
| 18 | |
| 19 | #include "clang/Format/Format.h" |
Chandler Carruth | 3a02247 | 2012-12-04 09:13:33 +0000 | [diff] [blame] | 20 | #include "UnwrappedLineParser.h" |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 21 | #include "clang/Basic/SourceManager.h" |
| 22 | #include "clang/Lex/Lexer.h" |
| 23 | |
Daniel Jasper | 8b52971 | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 24 | #include <string> |
| 25 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 26 | namespace clang { |
| 27 | namespace format { |
| 28 | |
| 29 | // FIXME: Move somewhere sane. |
| 30 | struct TokenAnnotation { |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 31 | enum TokenType { |
| 32 | TT_Unknown, |
| 33 | TT_TemplateOpener, |
| 34 | TT_TemplateCloser, |
| 35 | TT_BinaryOperator, |
| 36 | TT_UnaryOperator, |
| 37 | TT_OverloadedOperator, |
| 38 | TT_PointerOrReference, |
| 39 | TT_ConditionalExpr, |
| 40 | TT_LineComment, |
| 41 | TT_BlockComment |
| 42 | }; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 43 | |
| 44 | TokenType Type; |
| 45 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 46 | bool SpaceRequiredBefore; |
| 47 | bool CanBreakBefore; |
| 48 | bool MustBreakBefore; |
| 49 | }; |
| 50 | |
| 51 | using llvm::MutableArrayRef; |
| 52 | |
| 53 | FormatStyle getLLVMStyle() { |
| 54 | FormatStyle LLVMStyle; |
| 55 | LLVMStyle.ColumnLimit = 80; |
| 56 | LLVMStyle.MaxEmptyLinesToKeep = 1; |
| 57 | LLVMStyle.PointerAndReferenceBindToType = false; |
| 58 | LLVMStyle.AccessModifierOffset = -2; |
| 59 | LLVMStyle.SplitTemplateClosingGreater = true; |
Alexander Kornienko | 578fdd8 | 2012-12-06 18:03:27 +0000 | [diff] [blame] | 60 | LLVMStyle.IndentCaseLabels = false; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 61 | return LLVMStyle; |
| 62 | } |
| 63 | |
| 64 | FormatStyle getGoogleStyle() { |
| 65 | FormatStyle GoogleStyle; |
| 66 | GoogleStyle.ColumnLimit = 80; |
| 67 | GoogleStyle.MaxEmptyLinesToKeep = 1; |
| 68 | GoogleStyle.PointerAndReferenceBindToType = true; |
| 69 | GoogleStyle.AccessModifierOffset = -1; |
| 70 | GoogleStyle.SplitTemplateClosingGreater = false; |
Alexander Kornienko | 578fdd8 | 2012-12-06 18:03:27 +0000 | [diff] [blame] | 71 | GoogleStyle.IndentCaseLabels = true; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 72 | return GoogleStyle; |
| 73 | } |
| 74 | |
| 75 | struct OptimizationParameters { |
| 76 | unsigned PenaltyExtraLine; |
| 77 | unsigned PenaltyIndentLevel; |
| 78 | }; |
| 79 | |
| 80 | class UnwrappedLineFormatter { |
| 81 | public: |
| 82 | UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr, |
| 83 | const UnwrappedLine &Line, |
| 84 | const std::vector<TokenAnnotation> &Annotations, |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 85 | tooling::Replacements &Replaces, bool StructuralError) |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 86 | : Style(Style), |
| 87 | SourceMgr(SourceMgr), |
| 88 | Line(Line), |
| 89 | Annotations(Annotations), |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 90 | Replaces(Replaces), |
| 91 | StructuralError(StructuralError) { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 92 | Parameters.PenaltyExtraLine = 100; |
| 93 | Parameters.PenaltyIndentLevel = 5; |
| 94 | } |
| 95 | |
| 96 | void format() { |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 97 | // Format first token and initialize indent. |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 98 | unsigned Indent = formatFirstToken(); |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 99 | |
| 100 | // Initialize state dependent on indent. |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 101 | IndentState State; |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 102 | State.Column = Indent; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 103 | State.CtorInitializerOnNewLine = false; |
| 104 | State.InCtorInitializer = false; |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 105 | State.ConsumedTokens = 0; |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 106 | State.Indent.push_back(Indent + 4); |
| 107 | State.LastSpace.push_back(Indent); |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 108 | State.FirstLessLess.push_back(0); |
| 109 | |
| 110 | // The first token has already been indented and thus consumed. |
| 111 | moveStateToNextToken(State); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 112 | |
| 113 | // Start iterating at 1 as we have correctly formatted of Token #0 above. |
| 114 | for (unsigned i = 1, n = Line.Tokens.size(); i != n; ++i) { |
| 115 | unsigned NoBreak = calcPenalty(State, false, UINT_MAX); |
| 116 | unsigned Break = calcPenalty(State, true, NoBreak); |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 117 | addTokenToState(Break < NoBreak, false, State); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 118 | } |
| 119 | } |
| 120 | |
| 121 | private: |
| 122 | /// \brief The current state when indenting a unwrapped line. |
| 123 | /// |
| 124 | /// As the indenting tries different combinations this is copied by value. |
| 125 | struct IndentState { |
| 126 | /// \brief The number of used columns in the current line. |
| 127 | unsigned Column; |
| 128 | |
| 129 | /// \brief The number of tokens already consumed. |
| 130 | unsigned ConsumedTokens; |
| 131 | |
| 132 | /// \brief The position to which a specific parenthesis level needs to be |
| 133 | /// indented. |
| 134 | std::vector<unsigned> Indent; |
| 135 | |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 136 | /// \brief The position of the last space on each level. |
| 137 | /// |
| 138 | /// Used e.g. to break like: |
| 139 | /// functionCall(Parameter, otherCall( |
| 140 | /// OtherParameter)); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 141 | std::vector<unsigned> LastSpace; |
| 142 | |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 143 | /// \brief The position the first "<<" operator encountered on each level. |
| 144 | /// |
| 145 | /// Used to align "<<" operators. 0 if no such operator has been encountered |
| 146 | /// on a level. |
| 147 | std::vector<unsigned> FirstLessLess; |
| 148 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 149 | bool CtorInitializerOnNewLine; |
| 150 | bool InCtorInitializer; |
| 151 | |
| 152 | /// \brief Comparison operator to be able to used \c IndentState in \c map. |
| 153 | bool operator<(const IndentState &Other) const { |
| 154 | if (Other.ConsumedTokens != ConsumedTokens) |
| 155 | return Other.ConsumedTokens > ConsumedTokens; |
| 156 | if (Other.Column != Column) |
| 157 | return Other.Column > Column; |
| 158 | if (Other.Indent.size() != Indent.size()) |
| 159 | return Other.Indent.size() > Indent.size(); |
| 160 | for (int i = 0, e = Indent.size(); i != e; ++i) { |
| 161 | if (Other.Indent[i] != Indent[i]) |
| 162 | return Other.Indent[i] > Indent[i]; |
| 163 | } |
| 164 | if (Other.LastSpace.size() != LastSpace.size()) |
| 165 | return Other.LastSpace.size() > LastSpace.size(); |
| 166 | for (int i = 0, e = LastSpace.size(); i != e; ++i) { |
| 167 | if (Other.LastSpace[i] != LastSpace[i]) |
| 168 | return Other.LastSpace[i] > LastSpace[i]; |
| 169 | } |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 170 | if (Other.FirstLessLess.size() != FirstLessLess.size()) |
| 171 | return Other.FirstLessLess.size() > FirstLessLess.size(); |
| 172 | for (int i = 0, e = FirstLessLess.size(); i != e; ++i) { |
| 173 | if (Other.FirstLessLess[i] != FirstLessLess[i]) |
| 174 | return Other.FirstLessLess[i] > FirstLessLess[i]; |
| 175 | } |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 176 | return false; |
| 177 | } |
| 178 | }; |
| 179 | |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 180 | /// \brief Appends the next token to \p State and updates information |
| 181 | /// necessary for indentation. |
| 182 | /// |
| 183 | /// Puts the token on the current line if \p Newline is \c true and adds a |
| 184 | /// line break and necessary indentation otherwise. |
| 185 | /// |
| 186 | /// If \p DryRun is \c false, also creates and stores the required |
| 187 | /// \c Replacement. |
| 188 | void addTokenToState(bool Newline, bool DryRun, IndentState &State) { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 189 | unsigned Index = State.ConsumedTokens; |
| 190 | const FormatToken &Current = Line.Tokens[Index]; |
| 191 | const FormatToken &Previous = Line.Tokens[Index - 1]; |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 192 | unsigned ParenLevel = State.Indent.size() - 1; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 193 | |
| 194 | if (Newline) { |
| 195 | if (Current.Tok.is(tok::string_literal) && |
| 196 | Previous.Tok.is(tok::string_literal)) |
| 197 | State.Column = State.Column - Previous.Tok.getLength(); |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 198 | else if (Current.Tok.is(tok::lessless) && |
| 199 | State.FirstLessLess[ParenLevel] != 0) |
| 200 | State.Column = State.FirstLessLess[ParenLevel]; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 201 | else if (Previous.Tok.is(tok::equal) && ParenLevel != 0) |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 202 | // Indent and extra 4 spaces after '=' as it continues an expression. |
| 203 | // Don't do that on the top level, as we already indent 4 there. |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 204 | State.Column = State.Indent[ParenLevel] + 4; |
Daniel Jasper | 9b15547 | 2012-12-04 10:50:12 +0000 | [diff] [blame] | 205 | else |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 206 | State.Column = State.Indent[ParenLevel]; |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 207 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 208 | if (!DryRun) |
| 209 | replaceWhitespace(Current, 1, State.Column); |
| 210 | |
Daniel Jasper | 9b15547 | 2012-12-04 10:50:12 +0000 | [diff] [blame] | 211 | State.LastSpace[ParenLevel] = State.Indent[ParenLevel]; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 212 | if (Current.Tok.is(tok::colon) && |
| 213 | Annotations[Index].Type != TokenAnnotation::TT_ConditionalExpr) { |
| 214 | State.Indent[ParenLevel] += 2; |
| 215 | State.CtorInitializerOnNewLine = true; |
| 216 | State.InCtorInitializer = true; |
| 217 | } |
| 218 | } else { |
| 219 | unsigned Spaces = Annotations[Index].SpaceRequiredBefore ? 1 : 0; |
| 220 | if (Annotations[Index].Type == TokenAnnotation::TT_LineComment) |
| 221 | Spaces = 2; |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 222 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 223 | if (!DryRun) |
| 224 | replaceWhitespace(Current, 0, Spaces); |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 225 | |
| 226 | if (Previous.Tok.is(tok::l_paren) || |
| 227 | Annotations[Index - 1].Type == TokenAnnotation::TT_TemplateOpener) |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 228 | State.Indent[ParenLevel] = State.Column; |
| 229 | if (Current.Tok.is(tok::colon)) { |
| 230 | State.Indent[ParenLevel] = State.Column + 3; |
| 231 | State.InCtorInitializer = true; |
| 232 | } |
| 233 | // Top-level spaces are exempt as that mostly leads to better results. |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 234 | State.Column += Spaces; |
Daniel Jasper | 9b15547 | 2012-12-04 10:50:12 +0000 | [diff] [blame] | 235 | if (Spaces > 0 && ParenLevel != 0) |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 236 | State.LastSpace[ParenLevel] = State.Column; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 237 | } |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 238 | moveStateToNextToken(State); |
| 239 | } |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 240 | |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 241 | /// \brief Mark the next token as consumed in \p State and modify its stacks |
| 242 | /// accordingly. |
| 243 | void moveStateToNextToken(IndentState &State) { |
| 244 | unsigned Index = State.ConsumedTokens; |
| 245 | const FormatToken &Current = Line.Tokens[Index]; |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 246 | unsigned ParenLevel = State.Indent.size() - 1; |
| 247 | |
| 248 | if (Current.Tok.is(tok::lessless) && State.FirstLessLess[ParenLevel] == 0) |
| 249 | State.FirstLessLess[ParenLevel] = State.Column; |
| 250 | |
| 251 | State.Column += Current.Tok.getLength(); |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 252 | |
| 253 | // If we encounter an opening (, [ or <, we add a level to our stacks to |
| 254 | // prepare for the following tokens. |
| 255 | if (Current.Tok.is(tok::l_paren) || Current.Tok.is(tok::l_square) || |
| 256 | Annotations[Index].Type == TokenAnnotation::TT_TemplateOpener) { |
| 257 | State.Indent.push_back(4 + State.LastSpace.back()); |
| 258 | State.LastSpace.push_back(State.LastSpace.back()); |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 259 | State.FirstLessLess.push_back(0); |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 260 | } |
| 261 | |
| 262 | // If we encounter a closing ), ] or >, we can remove a level from our |
| 263 | // stacks. |
Daniel Jasper | 9b15547 | 2012-12-04 10:50:12 +0000 | [diff] [blame] | 264 | if (Current.Tok.is(tok::r_paren) || Current.Tok.is(tok::r_square) || |
| 265 | Annotations[Index].Type == TokenAnnotation::TT_TemplateCloser) { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 266 | State.Indent.pop_back(); |
| 267 | State.LastSpace.pop_back(); |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 268 | State.FirstLessLess.pop_back(); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 269 | } |
| 270 | |
| 271 | ++State.ConsumedTokens; |
| 272 | } |
| 273 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 274 | unsigned splitPenalty(const FormatToken &Token) { |
| 275 | if (Token.Tok.is(tok::semi)) |
| 276 | return 0; |
| 277 | if (Token.Tok.is(tok::comma)) |
| 278 | return 1; |
| 279 | if (Token.Tok.is(tok::equal) || Token.Tok.is(tok::l_paren) || |
| 280 | Token.Tok.is(tok::pipepipe) || Token.Tok.is(tok::ampamp)) |
| 281 | return 2; |
| 282 | return 3; |
| 283 | } |
| 284 | |
| 285 | /// \brief Calculate the number of lines needed to format the remaining part |
| 286 | /// of the unwrapped line. |
| 287 | /// |
| 288 | /// Assumes the formatting so far has led to |
| 289 | /// the \c IndentState \p State. If \p NewLine is set, a new line will be |
| 290 | /// added after the previous token. |
| 291 | /// |
| 292 | /// \param StopAt is used for optimization. If we can determine that we'll |
| 293 | /// definitely need at least \p StopAt additional lines, we already know of a |
| 294 | /// better solution. |
| 295 | unsigned calcPenalty(IndentState State, bool NewLine, unsigned StopAt) { |
| 296 | // We are at the end of the unwrapped line, so we don't need any more lines. |
| 297 | if (State.ConsumedTokens >= Line.Tokens.size()) |
| 298 | return 0; |
| 299 | |
| 300 | if (!NewLine && Annotations[State.ConsumedTokens].MustBreakBefore) |
| 301 | return UINT_MAX; |
| 302 | if (NewLine && !Annotations[State.ConsumedTokens].CanBreakBefore) |
| 303 | return UINT_MAX; |
| 304 | |
| 305 | if (State.ConsumedTokens > 0 && !NewLine && |
| 306 | State.CtorInitializerOnNewLine && |
| 307 | Line.Tokens[State.ConsumedTokens - 1].Tok.is(tok::comma)) |
| 308 | return UINT_MAX; |
| 309 | |
| 310 | if (NewLine && State.InCtorInitializer && !State.CtorInitializerOnNewLine) |
| 311 | return UINT_MAX; |
| 312 | |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 313 | unsigned CurrentPenalty = 0; |
| 314 | if (NewLine) { |
| 315 | CurrentPenalty += Parameters.PenaltyIndentLevel * State.Indent.size() + |
| 316 | Parameters.PenaltyExtraLine + |
| 317 | splitPenalty(Line.Tokens[State.ConsumedTokens - 1]); |
| 318 | } |
| 319 | |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 320 | addTokenToState(NewLine, true, State); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 321 | |
| 322 | // Exceeding column limit is bad. |
| 323 | if (State.Column > Style.ColumnLimit) |
| 324 | return UINT_MAX; |
| 325 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 326 | if (StopAt <= CurrentPenalty) |
| 327 | return UINT_MAX; |
| 328 | StopAt -= CurrentPenalty; |
| 329 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 330 | StateMap::iterator I = Memory.find(State); |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 331 | if (I != Memory.end()) { |
| 332 | // If this state has already been examined, we can safely return the |
| 333 | // previous result if we |
| 334 | // - have not hit the optimatization (and thus returned UINT_MAX) OR |
| 335 | // - are now computing for a smaller or equal StopAt. |
| 336 | unsigned SavedResult = I->second.first; |
| 337 | unsigned SavedStopAt = I->second.second; |
| 338 | if (SavedResult != UINT_MAX || StopAt <= SavedStopAt) |
| 339 | return SavedResult; |
| 340 | } |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 341 | |
| 342 | unsigned NoBreak = calcPenalty(State, false, StopAt); |
| 343 | unsigned WithBreak = calcPenalty(State, true, std::min(StopAt, NoBreak)); |
| 344 | unsigned Result = std::min(NoBreak, WithBreak); |
| 345 | if (Result != UINT_MAX) |
| 346 | Result += CurrentPenalty; |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 347 | Memory[State] = std::pair<unsigned, unsigned>(Result, StopAt); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 348 | return Result; |
| 349 | } |
| 350 | |
| 351 | /// \brief Replaces the whitespace in front of \p Tok. Only call once for |
| 352 | /// each \c FormatToken. |
| 353 | void replaceWhitespace(const FormatToken &Tok, unsigned NewLines, |
| 354 | unsigned Spaces) { |
| 355 | Replaces.insert(tooling::Replacement( |
| 356 | SourceMgr, Tok.WhiteSpaceStart, Tok.WhiteSpaceLength, |
| 357 | std::string(NewLines, '\n') + std::string(Spaces, ' '))); |
| 358 | } |
| 359 | |
| 360 | /// \brief Add a new line and the required indent before the first Token |
Alexander Kornienko | bc09a7e | 2012-12-05 13:56:52 +0000 | [diff] [blame] | 361 | /// of the \c UnwrappedLine if there was no structural parsing error. |
| 362 | /// Returns the indent level of the \c UnwrappedLine. |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 363 | unsigned formatFirstToken() { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 364 | const FormatToken &Token = Line.Tokens[0]; |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 365 | if (!Token.WhiteSpaceStart.isValid() || StructuralError) |
| 366 | return SourceMgr.getSpellingColumnNumber(Token.Tok.getLocation()) - 1; |
| 367 | |
| 368 | unsigned Newlines = |
| 369 | std::min(Token.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); |
| 370 | unsigned Offset = SourceMgr.getFileOffset(Token.WhiteSpaceStart); |
| 371 | if (Newlines == 0 && Offset != 0) |
| 372 | Newlines = 1; |
| 373 | unsigned Indent = Line.Level * 2; |
Alexander Kornienko | 2ca766f | 2012-12-10 16:34:48 +0000 | [diff] [blame^] | 374 | if ((Token.Tok.is(tok::kw_public) || Token.Tok.is(tok::kw_protected) || |
| 375 | Token.Tok.is(tok::kw_private)) && |
| 376 | static_cast<int>(Indent) + Style.AccessModifierOffset >= 0) |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 377 | Indent += Style.AccessModifierOffset; |
| 378 | replaceWhitespace(Token, Newlines, Indent); |
| 379 | return Indent; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 380 | } |
| 381 | |
| 382 | FormatStyle Style; |
| 383 | SourceManager &SourceMgr; |
| 384 | const UnwrappedLine &Line; |
| 385 | const std::vector<TokenAnnotation> &Annotations; |
| 386 | tooling::Replacements &Replaces; |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 387 | bool StructuralError; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 388 | |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 389 | // A map from an indent state to a pair (Result, Used-StopAt). |
| 390 | typedef std::map<IndentState, std::pair<unsigned, unsigned> > StateMap; |
| 391 | StateMap Memory; |
| 392 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 393 | OptimizationParameters Parameters; |
| 394 | }; |
| 395 | |
| 396 | /// \brief Determines extra information about the tokens comprising an |
| 397 | /// \c UnwrappedLine. |
| 398 | class TokenAnnotator { |
| 399 | public: |
| 400 | TokenAnnotator(const UnwrappedLine &Line, const FormatStyle &Style, |
| 401 | SourceManager &SourceMgr) |
| 402 | : Line(Line), |
| 403 | Style(Style), |
| 404 | SourceMgr(SourceMgr) { |
| 405 | } |
| 406 | |
| 407 | /// \brief A parser that gathers additional information about tokens. |
| 408 | /// |
| 409 | /// The \c TokenAnnotator tries to matches parenthesis and square brakets and |
| 410 | /// store a parenthesis levels. It also tries to resolve matching "<" and ">" |
| 411 | /// into template parameter lists. |
| 412 | class AnnotatingParser { |
| 413 | public: |
Manuel Klimek | 6a5619d | 2012-12-03 20:55:42 +0000 | [diff] [blame] | 414 | AnnotatingParser(const SmallVector<FormatToken, 16> &Tokens, |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 415 | std::vector<TokenAnnotation> &Annotations) |
Manuel Klimek | 6a5619d | 2012-12-03 20:55:42 +0000 | [diff] [blame] | 416 | : Tokens(Tokens), |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 417 | Annotations(Annotations), |
| 418 | Index(0) { |
| 419 | } |
| 420 | |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 421 | bool parseAngle() { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 422 | while (Index < Tokens.size()) { |
| 423 | if (Tokens[Index].Tok.is(tok::greater)) { |
Daniel Jasper | 9b15547 | 2012-12-04 10:50:12 +0000 | [diff] [blame] | 424 | Annotations[Index].Type = TokenAnnotation::TT_TemplateCloser; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 425 | next(); |
| 426 | return true; |
| 427 | } |
| 428 | if (Tokens[Index].Tok.is(tok::r_paren) || |
| 429 | Tokens[Index].Tok.is(tok::r_square)) |
| 430 | return false; |
| 431 | if (Tokens[Index].Tok.is(tok::pipepipe) || |
| 432 | Tokens[Index].Tok.is(tok::ampamp) || |
| 433 | Tokens[Index].Tok.is(tok::question) || |
| 434 | Tokens[Index].Tok.is(tok::colon)) |
| 435 | return false; |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 436 | consumeToken(); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 437 | } |
| 438 | return false; |
| 439 | } |
| 440 | |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 441 | bool parseParens() { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 442 | while (Index < Tokens.size()) { |
| 443 | if (Tokens[Index].Tok.is(tok::r_paren)) { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 444 | next(); |
| 445 | return true; |
| 446 | } |
| 447 | if (Tokens[Index].Tok.is(tok::r_square)) |
| 448 | return false; |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 449 | consumeToken(); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 450 | } |
| 451 | return false; |
| 452 | } |
| 453 | |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 454 | bool parseSquare() { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 455 | while (Index < Tokens.size()) { |
| 456 | if (Tokens[Index].Tok.is(tok::r_square)) { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 457 | next(); |
| 458 | return true; |
| 459 | } |
| 460 | if (Tokens[Index].Tok.is(tok::r_paren)) |
| 461 | return false; |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 462 | consumeToken(); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 463 | } |
| 464 | return false; |
| 465 | } |
| 466 | |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 467 | bool parseConditional() { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 468 | while (Index < Tokens.size()) { |
| 469 | if (Tokens[Index].Tok.is(tok::colon)) { |
| 470 | Annotations[Index].Type = TokenAnnotation::TT_ConditionalExpr; |
| 471 | next(); |
| 472 | return true; |
| 473 | } |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 474 | consumeToken(); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 475 | } |
| 476 | return false; |
| 477 | } |
| 478 | |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 479 | void consumeToken() { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 480 | unsigned CurrentIndex = Index; |
| 481 | next(); |
| 482 | switch (Tokens[CurrentIndex].Tok.getKind()) { |
| 483 | case tok::l_paren: |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 484 | parseParens(); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 485 | break; |
| 486 | case tok::l_square: |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 487 | parseSquare(); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 488 | break; |
| 489 | case tok::less: |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 490 | if (parseAngle()) |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 491 | Annotations[CurrentIndex].Type = TokenAnnotation::TT_TemplateOpener; |
| 492 | else { |
| 493 | Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator; |
| 494 | Index = CurrentIndex + 1; |
| 495 | } |
| 496 | break; |
| 497 | case tok::greater: |
| 498 | Annotations[CurrentIndex].Type = TokenAnnotation::TT_BinaryOperator; |
| 499 | break; |
| 500 | case tok::kw_operator: |
| 501 | if (!Tokens[Index].Tok.is(tok::l_paren)) |
| 502 | Annotations[Index].Type = TokenAnnotation::TT_OverloadedOperator; |
| 503 | next(); |
| 504 | break; |
| 505 | case tok::question: |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 506 | parseConditional(); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 507 | break; |
| 508 | default: |
| 509 | break; |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | void parseLine() { |
| 514 | while (Index < Tokens.size()) { |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 515 | consumeToken(); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 516 | } |
| 517 | } |
| 518 | |
| 519 | void next() { |
| 520 | ++Index; |
| 521 | } |
| 522 | |
| 523 | private: |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 524 | const SmallVector<FormatToken, 16> &Tokens; |
| 525 | std::vector<TokenAnnotation> &Annotations; |
| 526 | unsigned Index; |
| 527 | }; |
| 528 | |
| 529 | void annotate() { |
| 530 | Annotations.clear(); |
| 531 | for (int i = 0, e = Line.Tokens.size(); i != e; ++i) { |
| 532 | Annotations.push_back(TokenAnnotation()); |
| 533 | } |
| 534 | |
Manuel Klimek | 6a5619d | 2012-12-03 20:55:42 +0000 | [diff] [blame] | 535 | AnnotatingParser Parser(Line.Tokens, Annotations); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 536 | Parser.parseLine(); |
| 537 | |
| 538 | determineTokenTypes(); |
| 539 | |
| 540 | for (int i = 1, e = Line.Tokens.size(); i != e; ++i) { |
| 541 | TokenAnnotation &Annotation = Annotations[i]; |
| 542 | |
| 543 | Annotation.CanBreakBefore = |
| 544 | canBreakBetween(Line.Tokens[i - 1], Line.Tokens[i]); |
| 545 | |
| 546 | if (Line.Tokens[i].Tok.is(tok::colon)) { |
Daniel Jasper | 55b6b64 | 2012-12-05 16:24:48 +0000 | [diff] [blame] | 547 | Annotation.SpaceRequiredBefore = |
| 548 | Line.Tokens[0].Tok.isNot(tok::kw_case) && i != e - 1; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 549 | } else if (Annotations[i - 1].Type == TokenAnnotation::TT_UnaryOperator) { |
| 550 | Annotation.SpaceRequiredBefore = false; |
| 551 | } else if (Annotation.Type == TokenAnnotation::TT_UnaryOperator) { |
| 552 | Annotation.SpaceRequiredBefore = |
Daniel Jasper | 8b52971 | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 553 | Line.Tokens[i - 1].Tok.isNot(tok::l_paren) && |
| 554 | Line.Tokens[i - 1].Tok.isNot(tok::l_square); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 555 | } else if (Line.Tokens[i - 1].Tok.is(tok::greater) && |
| 556 | Line.Tokens[i].Tok.is(tok::greater)) { |
Daniel Jasper | 8b52971 | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 557 | if (Annotation.Type == TokenAnnotation::TT_TemplateCloser && |
Daniel Jasper | 6021c4a | 2012-12-04 14:54:30 +0000 | [diff] [blame] | 558 | Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser) |
Daniel Jasper | 9b15547 | 2012-12-04 10:50:12 +0000 | [diff] [blame] | 559 | Annotation.SpaceRequiredBefore = Style.SplitTemplateClosingGreater; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 560 | else |
| 561 | Annotation.SpaceRequiredBefore = false; |
| 562 | } else if ( |
| 563 | Annotation.Type == TokenAnnotation::TT_BinaryOperator || |
| 564 | Annotations[i - 1].Type == TokenAnnotation::TT_BinaryOperator) { |
| 565 | Annotation.SpaceRequiredBefore = true; |
| 566 | } else if ( |
Daniel Jasper | 9b15547 | 2012-12-04 10:50:12 +0000 | [diff] [blame] | 567 | Annotations[i - 1].Type == TokenAnnotation::TT_TemplateCloser && |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 568 | Line.Tokens[i].Tok.is(tok::l_paren)) { |
| 569 | Annotation.SpaceRequiredBefore = false; |
Daniel Jasper | 8b52971 | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 570 | } else if (Line.Tokens[i].Tok.is(tok::less) && |
| 571 | Line.Tokens[0].Tok.is(tok::hash)) { |
| 572 | Annotation.SpaceRequiredBefore = true; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 573 | } else { |
| 574 | Annotation.SpaceRequiredBefore = |
| 575 | spaceRequiredBetween(Line.Tokens[i - 1].Tok, Line.Tokens[i].Tok); |
| 576 | } |
| 577 | |
| 578 | if (Annotations[i - 1].Type == TokenAnnotation::TT_LineComment || |
| 579 | (Line.Tokens[i].Tok.is(tok::string_literal) && |
| 580 | Line.Tokens[i - 1].Tok.is(tok::string_literal))) { |
| 581 | Annotation.MustBreakBefore = true; |
| 582 | } |
| 583 | |
| 584 | if (Annotation.MustBreakBefore) |
| 585 | Annotation.CanBreakBefore = true; |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | const std::vector<TokenAnnotation> &getAnnotations() { |
| 590 | return Annotations; |
| 591 | } |
| 592 | |
| 593 | private: |
| 594 | void determineTokenTypes() { |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 595 | bool AssignmentEncountered = false; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 596 | for (int i = 0, e = Line.Tokens.size(); i != e; ++i) { |
| 597 | TokenAnnotation &Annotation = Annotations[i]; |
| 598 | const FormatToken &Tok = Line.Tokens[i]; |
| 599 | |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 600 | if (Tok.Tok.is(tok::equal) || Tok.Tok.is(tok::plusequal) || |
| 601 | Tok.Tok.is(tok::minusequal) || Tok.Tok.is(tok::starequal) || |
| 602 | Tok.Tok.is(tok::slashequal)) |
| 603 | AssignmentEncountered = true; |
Daniel Jasper | 426702d | 2012-12-05 07:51:39 +0000 | [diff] [blame] | 604 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 605 | if (Tok.Tok.is(tok::star) || Tok.Tok.is(tok::amp)) |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 606 | Annotation.Type = determineStarAmpUsage(i, AssignmentEncountered); |
Daniel Jasper | 8b52971 | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 607 | else if (isUnaryOperator(i)) |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 608 | Annotation.Type = TokenAnnotation::TT_UnaryOperator; |
| 609 | else if (isBinaryOperator(Line.Tokens[i])) |
| 610 | Annotation.Type = TokenAnnotation::TT_BinaryOperator; |
| 611 | else if (Tok.Tok.is(tok::comment)) { |
| 612 | StringRef Data(SourceMgr.getCharacterData(Tok.Tok.getLocation()), |
| 613 | Tok.Tok.getLength()); |
| 614 | if (Data.startswith("//")) |
| 615 | Annotation.Type = TokenAnnotation::TT_LineComment; |
| 616 | else |
| 617 | Annotation.Type = TokenAnnotation::TT_BlockComment; |
| 618 | } |
| 619 | } |
| 620 | } |
| 621 | |
Daniel Jasper | 8b52971 | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 622 | bool isUnaryOperator(unsigned Index) { |
| 623 | const Token &Tok = Line.Tokens[Index].Tok; |
Daniel Jasper | 26333c3 | 2012-12-06 13:16:39 +0000 | [diff] [blame] | 624 | |
| 625 | // '++', '--' and '!' are always unary operators. |
| 626 | if (Tok.is(tok::minusminus) || Tok.is(tok::plusplus) || |
| 627 | Tok.is(tok::exclaim)) |
| 628 | return true; |
| 629 | |
| 630 | // The other possible unary operators are '+' and '-' as we |
| 631 | // determine the usage of '*' and '&' in determineStarAmpUsage(). |
Daniel Jasper | 8b52971 | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 632 | if (Tok.isNot(tok::minus) && Tok.isNot(tok::plus)) |
| 633 | return false; |
Daniel Jasper | 26333c3 | 2012-12-06 13:16:39 +0000 | [diff] [blame] | 634 | |
| 635 | // Use heuristics to recognize unary operators. |
Daniel Jasper | 8b52971 | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 636 | const Token &PreviousTok = Line.Tokens[Index - 1].Tok; |
| 637 | if (PreviousTok.is(tok::equal) || PreviousTok.is(tok::l_paren) || |
| 638 | PreviousTok.is(tok::comma) || PreviousTok.is(tok::l_square)) |
| 639 | return true; |
Daniel Jasper | 26333c3 | 2012-12-06 13:16:39 +0000 | [diff] [blame] | 640 | |
| 641 | // Fall back to marking the token as binary operator. |
Daniel Jasper | 8b52971 | 2012-12-04 13:02:32 +0000 | [diff] [blame] | 642 | return Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator; |
| 643 | } |
| 644 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 645 | bool isBinaryOperator(const FormatToken &Tok) { |
| 646 | switch (Tok.Tok.getKind()) { |
| 647 | case tok::equal: |
| 648 | case tok::equalequal: |
Daniel Jasper | 426702d | 2012-12-05 07:51:39 +0000 | [diff] [blame] | 649 | case tok::exclaimequal: |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 650 | case tok::star: |
| 651 | //case tok::amp: |
| 652 | case tok::plus: |
| 653 | case tok::slash: |
| 654 | case tok::minus: |
| 655 | case tok::ampamp: |
| 656 | case tok::pipe: |
| 657 | case tok::pipepipe: |
| 658 | case tok::percent: |
| 659 | return true; |
| 660 | default: |
| 661 | return false; |
| 662 | } |
| 663 | } |
| 664 | |
Daniel Jasper | 426702d | 2012-12-05 07:51:39 +0000 | [diff] [blame] | 665 | TokenAnnotation::TokenType determineStarAmpUsage(unsigned Index, |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 666 | bool AssignmentEncountered) { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 667 | if (Index == Annotations.size()) |
| 668 | return TokenAnnotation::TT_Unknown; |
| 669 | |
| 670 | if (Index == 0 || Line.Tokens[Index - 1].Tok.is(tok::l_paren) || |
| 671 | Line.Tokens[Index - 1].Tok.is(tok::comma) || |
| 672 | Annotations[Index - 1].Type == TokenAnnotation::TT_BinaryOperator) |
| 673 | return TokenAnnotation::TT_UnaryOperator; |
| 674 | |
| 675 | if (Line.Tokens[Index - 1].Tok.isLiteral() || |
| 676 | Line.Tokens[Index + 1].Tok.isLiteral()) |
| 677 | return TokenAnnotation::TT_BinaryOperator; |
| 678 | |
Daniel Jasper | 426702d | 2012-12-05 07:51:39 +0000 | [diff] [blame] | 679 | // It is very unlikely that we are going to find a pointer or reference type |
| 680 | // definition on the RHS of an assignment. |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 681 | if (AssignmentEncountered) |
Daniel Jasper | 426702d | 2012-12-05 07:51:39 +0000 | [diff] [blame] | 682 | return TokenAnnotation::TT_BinaryOperator; |
| 683 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 684 | return TokenAnnotation::TT_PointerOrReference; |
| 685 | } |
| 686 | |
| 687 | bool isIfForOrWhile(Token Tok) { |
| 688 | return Tok.is(tok::kw_if) || Tok.is(tok::kw_for) || Tok.is(tok::kw_while); |
| 689 | } |
| 690 | |
| 691 | bool spaceRequiredBetween(Token Left, Token Right) { |
| 692 | if (Left.is(tok::kw_template) && Right.is(tok::less)) |
| 693 | return true; |
| 694 | if (Left.is(tok::arrow) || Right.is(tok::arrow)) |
| 695 | return false; |
| 696 | if (Left.is(tok::exclaim) || Left.is(tok::tilde)) |
| 697 | return false; |
| 698 | if (Left.is(tok::less) || Right.is(tok::greater) || Right.is(tok::less)) |
| 699 | return false; |
Daniel Jasper | 2723403 | 2012-12-07 09:52:15 +0000 | [diff] [blame] | 700 | if (Right.is(tok::amp) || Right.is(tok::star)) |
| 701 | return Left.isLiteral() || |
| 702 | (Left.isNot(tok::star) && Left.isNot(tok::amp) && |
| 703 | !Style.PointerAndReferenceBindToType); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 704 | if (Left.is(tok::amp) || Left.is(tok::star)) |
| 705 | return Right.isLiteral() || Style.PointerAndReferenceBindToType; |
| 706 | if (Right.is(tok::star) && Left.is(tok::l_paren)) |
| 707 | return false; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 708 | if (Left.is(tok::l_square) || Right.is(tok::l_square) || |
| 709 | Right.is(tok::r_square)) |
| 710 | return false; |
Daniel Jasper | 2723403 | 2012-12-07 09:52:15 +0000 | [diff] [blame] | 711 | if (Left.is(tok::coloncolon) || |
| 712 | (Right.is(tok::coloncolon) && |
| 713 | (Left.is(tok::identifier) || Left.is(tok::greater)))) |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 714 | return false; |
| 715 | if (Left.is(tok::period) || Right.is(tok::period)) |
| 716 | return false; |
| 717 | if (Left.is(tok::colon) || Right.is(tok::colon)) |
| 718 | return true; |
| 719 | if ((Left.is(tok::plusplus) && Right.isAnyIdentifier()) || |
| 720 | (Left.isAnyIdentifier() && Right.is(tok::plusplus)) || |
| 721 | (Left.is(tok::minusminus) && Right.isAnyIdentifier()) || |
| 722 | (Left.isAnyIdentifier() && Right.is(tok::minusminus))) |
| 723 | return false; |
| 724 | if (Left.is(tok::l_paren)) |
| 725 | return false; |
| 726 | if (Left.is(tok::hash)) |
| 727 | return false; |
| 728 | if (Right.is(tok::r_paren) || Right.is(tok::semi) || Right.is(tok::comma)) |
| 729 | return false; |
| 730 | if (Right.is(tok::l_paren)) { |
| 731 | return !Left.isAnyIdentifier() || isIfForOrWhile(Left); |
| 732 | } |
| 733 | return true; |
| 734 | } |
| 735 | |
| 736 | bool canBreakBetween(const FormatToken &Left, const FormatToken &Right) { |
| 737 | if (Right.Tok.is(tok::r_paren)) |
| 738 | return false; |
| 739 | if (isBinaryOperator(Left)) |
| 740 | return true; |
Daniel Jasper | e9de260 | 2012-12-06 09:56:08 +0000 | [diff] [blame] | 741 | if (Right.Tok.is(tok::lessless)) |
| 742 | return true; |
Daniel Jasper | aa1c920 | 2012-12-05 14:57:28 +0000 | [diff] [blame] | 743 | return Right.Tok.is(tok::colon) || Left.Tok.is(tok::comma) || |
| 744 | Left.Tok.is(tok::semi) || Left.Tok.is(tok::equal) || |
| 745 | Left.Tok.is(tok::ampamp) || Left.Tok.is(tok::pipepipe) || |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 746 | (Left.Tok.is(tok::l_paren) && !Right.Tok.is(tok::r_paren)); |
| 747 | } |
| 748 | |
| 749 | const UnwrappedLine &Line; |
| 750 | FormatStyle Style; |
| 751 | SourceManager &SourceMgr; |
| 752 | std::vector<TokenAnnotation> Annotations; |
| 753 | }; |
| 754 | |
Alexander Kornienko | e327684 | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 755 | class LexerBasedFormatTokenSource : public FormatTokenSource { |
| 756 | public: |
| 757 | LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr) |
| 758 | : GreaterStashed(false), |
| 759 | Lex(Lex), |
| 760 | SourceMgr(SourceMgr), |
| 761 | IdentTable(Lex.getLangOpts()) { |
| 762 | Lex.SetKeepWhitespaceMode(true); |
| 763 | } |
| 764 | |
| 765 | virtual FormatToken getNextToken() { |
| 766 | if (GreaterStashed) { |
| 767 | FormatTok.NewlinesBefore = 0; |
| 768 | FormatTok.WhiteSpaceStart = |
| 769 | FormatTok.Tok.getLocation().getLocWithOffset(1); |
| 770 | FormatTok.WhiteSpaceLength = 0; |
| 771 | GreaterStashed = false; |
| 772 | return FormatTok; |
| 773 | } |
| 774 | |
| 775 | FormatTok = FormatToken(); |
| 776 | Lex.LexFromRawLexer(FormatTok.Tok); |
| 777 | FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation(); |
| 778 | |
| 779 | // Consume and record whitespace until we find a significant token. |
| 780 | while (FormatTok.Tok.is(tok::unknown)) { |
| 781 | FormatTok.NewlinesBefore += tokenText(FormatTok.Tok).count('\n'); |
| 782 | FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength(); |
| 783 | |
| 784 | if (FormatTok.Tok.is(tok::eof)) |
| 785 | return FormatTok; |
| 786 | Lex.LexFromRawLexer(FormatTok.Tok); |
| 787 | } |
| 788 | |
| 789 | if (FormatTok.Tok.is(tok::raw_identifier)) { |
| 790 | const IdentifierInfo &Info = IdentTable.get(tokenText(FormatTok.Tok)); |
| 791 | FormatTok.Tok.setKind(Info.getTokenID()); |
| 792 | } |
| 793 | |
| 794 | if (FormatTok.Tok.is(tok::greatergreater)) { |
| 795 | FormatTok.Tok.setKind(tok::greater); |
| 796 | GreaterStashed = true; |
| 797 | } |
| 798 | |
| 799 | return FormatTok; |
| 800 | } |
| 801 | |
| 802 | private: |
| 803 | FormatToken FormatTok; |
| 804 | bool GreaterStashed; |
| 805 | Lexer &Lex; |
| 806 | SourceManager &SourceMgr; |
| 807 | IdentifierTable IdentTable; |
| 808 | |
| 809 | /// Returns the text of \c FormatTok. |
| 810 | StringRef tokenText(Token &Tok) { |
| 811 | return StringRef(SourceMgr.getCharacterData(Tok.getLocation()), |
| 812 | Tok.getLength()); |
| 813 | } |
| 814 | }; |
| 815 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 816 | class Formatter : public UnwrappedLineConsumer { |
| 817 | public: |
| 818 | Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr, |
| 819 | const std::vector<CharSourceRange> &Ranges) |
| 820 | : Style(Style), |
| 821 | Lex(Lex), |
| 822 | SourceMgr(SourceMgr), |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 823 | Ranges(Ranges), |
| 824 | StructuralError(false) { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 825 | } |
| 826 | |
Daniel Jasper | 61bd3a1 | 2012-12-04 21:05:31 +0000 | [diff] [blame] | 827 | virtual ~Formatter() { |
| 828 | } |
| 829 | |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 830 | tooling::Replacements format() { |
Alexander Kornienko | e327684 | 2012-12-07 16:15:44 +0000 | [diff] [blame] | 831 | LexerBasedFormatTokenSource Tokens(Lex, SourceMgr); |
| 832 | UnwrappedLineParser Parser(Style, Tokens, *this); |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 833 | StructuralError = Parser.parse(); |
| 834 | for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(), |
| 835 | E = UnwrappedLines.end(); |
| 836 | I != E; ++I) |
Alexander Kornienko | bc09a7e | 2012-12-05 13:56:52 +0000 | [diff] [blame] | 837 | formatUnwrappedLine(*I); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 838 | return Replaces; |
| 839 | } |
| 840 | |
| 841 | private: |
Alexander Kornienko | bc09a7e | 2012-12-05 13:56:52 +0000 | [diff] [blame] | 842 | virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) { |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 843 | UnwrappedLines.push_back(TheLine); |
| 844 | } |
| 845 | |
Alexander Kornienko | bc09a7e | 2012-12-05 13:56:52 +0000 | [diff] [blame] | 846 | void formatUnwrappedLine(const UnwrappedLine &TheLine) { |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 847 | if (TheLine.Tokens.size() == 0) |
| 848 | return; |
| 849 | |
| 850 | CharSourceRange LineRange = |
| 851 | CharSourceRange::getTokenRange(TheLine.Tokens.front().Tok.getLocation(), |
| 852 | TheLine.Tokens.back().Tok.getLocation()); |
| 853 | |
| 854 | for (unsigned i = 0, e = Ranges.size(); i != e; ++i) { |
| 855 | if (SourceMgr.isBeforeInTranslationUnit(LineRange.getEnd(), |
| 856 | Ranges[i].getBegin()) || |
| 857 | SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(), |
| 858 | LineRange.getBegin())) |
| 859 | continue; |
| 860 | |
| 861 | TokenAnnotator Annotator(TheLine, Style, SourceMgr); |
| 862 | Annotator.annotate(); |
| 863 | UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 864 | Annotator.getAnnotations(), Replaces, |
| 865 | StructuralError); |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 866 | Formatter.format(); |
| 867 | return; |
| 868 | } |
| 869 | } |
| 870 | |
| 871 | FormatStyle Style; |
| 872 | Lexer &Lex; |
| 873 | SourceManager &SourceMgr; |
| 874 | tooling::Replacements Replaces; |
| 875 | std::vector<CharSourceRange> Ranges; |
Alexander Kornienko | 870f9eb | 2012-12-04 17:27:50 +0000 | [diff] [blame] | 876 | std::vector<UnwrappedLine> UnwrappedLines; |
| 877 | bool StructuralError; |
Daniel Jasper | f793511 | 2012-12-03 18:12:45 +0000 | [diff] [blame] | 878 | }; |
| 879 | |
| 880 | tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex, |
| 881 | SourceManager &SourceMgr, |
| 882 | std::vector<CharSourceRange> Ranges) { |
| 883 | Formatter formatter(Style, Lex, SourceMgr, Ranges); |
| 884 | return formatter.format(); |
| 885 | } |
| 886 | |
| 887 | } // namespace format |
| 888 | } // namespace clang |