Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1 | //===--- UnwrappedLineFormatter.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 | #include "UnwrappedLineFormatter.h" |
| 11 | #include "WhitespaceManager.h" |
| 12 | #include "llvm/Support/Debug.h" |
Mehdi Amini | 9670f84 | 2016-07-18 19:02:11 +0000 | [diff] [blame] | 13 | #include <queue> |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 14 | |
| 15 | #define DEBUG_TYPE "format-formatter" |
| 16 | |
| 17 | namespace clang { |
| 18 | namespace format { |
| 19 | |
| 20 | namespace { |
| 21 | |
| 22 | bool startsExternCBlock(const AnnotatedLine &Line) { |
| 23 | const FormatToken *Next = Line.First->getNextNonComment(); |
| 24 | const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr; |
Daniel Jasper | e285b8d | 2015-06-17 09:43:56 +0000 | [diff] [blame] | 25 | return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() && |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 26 | NextNext && NextNext->is(tok::l_brace); |
| 27 | } |
| 28 | |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 29 | /// \brief Tracks the indent level of \c AnnotatedLines across levels. |
| 30 | /// |
| 31 | /// \c nextLine must be called for each \c AnnotatedLine, after which \c |
| 32 | /// getIndent() will return the indent for the last line \c nextLine was called |
| 33 | /// with. |
| 34 | /// If the line is not formatted (and thus the indent does not change), calling |
| 35 | /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause |
| 36 | /// subsequent lines on the same level to be indented at the same level as the |
| 37 | /// given line. |
| 38 | class LevelIndentTracker { |
| 39 | public: |
| 40 | LevelIndentTracker(const FormatStyle &Style, |
| 41 | const AdditionalKeywords &Keywords, unsigned StartLevel, |
| 42 | int AdditionalIndent) |
Daniel Jasper | 5fc133e | 2015-05-12 10:16:02 +0000 | [diff] [blame] | 43 | : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) { |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 44 | for (unsigned i = 0; i != StartLevel; ++i) |
| 45 | IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent); |
| 46 | } |
| 47 | |
| 48 | /// \brief Returns the indent for the current line. |
| 49 | unsigned getIndent() const { return Indent; } |
| 50 | |
| 51 | /// \brief Update the indent state given that \p Line is going to be formatted |
| 52 | /// next. |
| 53 | void nextLine(const AnnotatedLine &Line) { |
| 54 | Offset = getIndentOffset(*Line.First); |
Manuel Klimek | f0c95b3 | 2015-06-11 10:14:13 +0000 | [diff] [blame] | 55 | // Update the indent level cache size so that we can rely on it |
| 56 | // having the right size in adjustToUnmodifiedline. |
| 57 | while (IndentForLevel.size() <= Line.Level) |
| 58 | IndentForLevel.push_back(-1); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 59 | if (Line.InPPDirective) { |
Daniel Jasper | 5fc133e | 2015-05-12 10:16:02 +0000 | [diff] [blame] | 60 | Indent = Line.Level * Style.IndentWidth + AdditionalIndent; |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 61 | } else { |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 62 | IndentForLevel.resize(Line.Level + 1); |
| 63 | Indent = getIndent(IndentForLevel, Line.Level); |
| 64 | } |
| 65 | if (static_cast<int>(Indent) + Offset >= 0) |
| 66 | Indent += Offset; |
| 67 | } |
| 68 | |
Francois Ferrand | e56a829 | 2017-06-14 12:29:47 +0000 | [diff] [blame] | 69 | /// \brief Update the indent state given that \p Line indent should be |
| 70 | /// skipped. |
| 71 | void skipLine(const AnnotatedLine &Line) { |
| 72 | while (IndentForLevel.size() <= Line.Level) |
| 73 | IndentForLevel.push_back(Indent); |
| 74 | } |
| 75 | |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 76 | /// \brief Update the level indent to adapt to the given \p Line. |
| 77 | /// |
| 78 | /// When a line is not formatted, we move the subsequent lines on the same |
| 79 | /// level to the same indent. |
| 80 | /// Note that \c nextLine must have been called before this method. |
| 81 | void adjustToUnmodifiedLine(const AnnotatedLine &Line) { |
| 82 | unsigned LevelIndent = Line.First->OriginalColumn; |
| 83 | if (static_cast<int>(LevelIndent) - Offset >= 0) |
| 84 | LevelIndent -= Offset; |
Daniel Jasper | e285b8d | 2015-06-17 09:43:56 +0000 | [diff] [blame] | 85 | if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) && |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 86 | !Line.InPPDirective) |
| 87 | IndentForLevel[Line.Level] = LevelIndent; |
| 88 | } |
| 89 | |
| 90 | private: |
| 91 | /// \brief Get the offset of the line relatively to the level. |
| 92 | /// |
| 93 | /// For example, 'public:' labels in classes are offset by 1 or 2 |
| 94 | /// characters to the left from their level. |
| 95 | int getIndentOffset(const FormatToken &RootToken) { |
| 96 | if (Style.Language == FormatStyle::LK_Java || |
| 97 | Style.Language == FormatStyle::LK_JavaScript) |
| 98 | return 0; |
| 99 | if (RootToken.isAccessSpecifier(false) || |
| 100 | RootToken.isObjCAccessSpecifier() || |
Daniel Jasper | a00de63 | 2015-12-01 12:05:04 +0000 | [diff] [blame] | 101 | (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) && |
| 102 | RootToken.Next && RootToken.Next->is(tok::colon))) |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 103 | return Style.AccessModifierOffset; |
| 104 | return 0; |
| 105 | } |
| 106 | |
| 107 | /// \brief Get the indent of \p Level from \p IndentForLevel. |
| 108 | /// |
| 109 | /// \p IndentForLevel must contain the indent for the level \c l |
| 110 | /// at \p IndentForLevel[l], or a value < 0 if the indent for |
| 111 | /// that level is unknown. |
| 112 | unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) { |
| 113 | if (IndentForLevel[Level] != -1) |
| 114 | return IndentForLevel[Level]; |
| 115 | if (Level == 0) |
| 116 | return 0; |
| 117 | return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth; |
| 118 | } |
| 119 | |
| 120 | const FormatStyle &Style; |
| 121 | const AdditionalKeywords &Keywords; |
Daniel Jasper | 56807c1 | 2015-05-12 11:14:06 +0000 | [diff] [blame] | 122 | const unsigned AdditionalIndent; |
Daniel Jasper | 5fc133e | 2015-05-12 10:16:02 +0000 | [diff] [blame] | 123 | |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 124 | /// \brief The indent in characters for each level. |
| 125 | std::vector<int> IndentForLevel; |
| 126 | |
| 127 | /// \brief Offset of the current line relative to the indent level. |
| 128 | /// |
| 129 | /// For example, the 'public' keywords is often indented with a negative |
| 130 | /// offset. |
| 131 | int Offset = 0; |
| 132 | |
| 133 | /// \brief The current line's indent. |
| 134 | unsigned Indent = 0; |
| 135 | }; |
| 136 | |
Francois Ferrand | e56a829 | 2017-06-14 12:29:47 +0000 | [diff] [blame] | 137 | bool isNamespaceDeclaration(const AnnotatedLine *Line) { |
| 138 | const FormatToken *NamespaceTok = Line->First; |
Francois Ferrand | ad72256 | 2017-06-30 20:25:55 +0000 | [diff] [blame] | 139 | return NamespaceTok && NamespaceTok->getNamespaceToken(); |
Francois Ferrand | e56a829 | 2017-06-14 12:29:47 +0000 | [diff] [blame] | 140 | } |
| 141 | |
| 142 | bool isEndOfNamespace(const AnnotatedLine *Line, |
| 143 | const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { |
| 144 | if (!Line->startsWith(tok::r_brace)) |
| 145 | return false; |
| 146 | size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex; |
| 147 | if (StartLineIndex == UnwrappedLine::kInvalidIndex) |
| 148 | return false; |
| 149 | assert(StartLineIndex < AnnotatedLines.size()); |
| 150 | return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]); |
| 151 | } |
| 152 | |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 153 | class LineJoiner { |
| 154 | public: |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 155 | LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords, |
| 156 | const SmallVectorImpl<AnnotatedLine *> &Lines) |
Francois Ferrand | e56a829 | 2017-06-14 12:29:47 +0000 | [diff] [blame] | 157 | : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()), |
| 158 | AnnotatedLines(Lines) {} |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 159 | |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 160 | /// \brief Returns the next line, merging multiple lines into one if possible. |
| 161 | const AnnotatedLine *getNextMergedLine(bool DryRun, |
| 162 | LevelIndentTracker &IndentTracker) { |
| 163 | if (Next == End) |
| 164 | return nullptr; |
| 165 | const AnnotatedLine *Current = *Next; |
| 166 | IndentTracker.nextLine(*Current); |
Manuel Klimek | 89628f6 | 2017-09-20 09:51:03 +0000 | [diff] [blame] | 167 | unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 168 | if (MergedLines > 0 && Style.ColumnLimit == 0) |
| 169 | // Disallow line merging if there is a break at the start of one of the |
| 170 | // input lines. |
| 171 | for (unsigned i = 0; i < MergedLines; ++i) |
| 172 | if (Next[i + 1]->First->NewlinesBefore > 0) |
| 173 | MergedLines = 0; |
| 174 | if (!DryRun) |
| 175 | for (unsigned i = 0; i < MergedLines; ++i) |
Cameron Desrochers | 1991e5d | 2016-11-15 15:07:07 +0000 | [diff] [blame] | 176 | join(*Next[0], *Next[i + 1]); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 177 | Next = Next + MergedLines + 1; |
| 178 | return Current; |
| 179 | } |
| 180 | |
| 181 | private: |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 182 | /// \brief Calculates how many lines can be merged into 1 starting at \p I. |
| 183 | unsigned |
Francois Ferrand | e56a829 | 2017-06-14 12:29:47 +0000 | [diff] [blame] | 184 | tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker, |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 185 | SmallVectorImpl<AnnotatedLine *>::const_iterator I, |
| 186 | SmallVectorImpl<AnnotatedLine *>::const_iterator E) { |
Francois Ferrand | e56a829 | 2017-06-14 12:29:47 +0000 | [diff] [blame] | 187 | const unsigned Indent = IndentTracker.getIndent(); |
| 188 | |
Daniel Jasper | 9ecb0e9 | 2015-03-13 13:32:11 +0000 | [diff] [blame] | 189 | // Can't join the last line with anything. |
| 190 | if (I + 1 == E) |
| 191 | return 0; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 192 | // We can never merge stuff if there are trailing line comments. |
| 193 | const AnnotatedLine *TheLine = *I; |
| 194 | if (TheLine->Last->is(TT_LineComment)) |
| 195 | return 0; |
Daniel Jasper | 9ecb0e9 | 2015-03-13 13:32:11 +0000 | [diff] [blame] | 196 | if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore) |
| 197 | return 0; |
| 198 | if (TheLine->InPPDirective && |
| 199 | (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)) |
| 200 | return 0; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 201 | |
| 202 | if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit) |
| 203 | return 0; |
| 204 | |
| 205 | unsigned Limit = |
| 206 | Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent; |
| 207 | // If we already exceed the column limit, we set 'Limit' to 0. The different |
| 208 | // tryMerge..() functions can then decide whether to still do merging. |
| 209 | Limit = TheLine->Last->TotalLength > Limit |
| 210 | ? 0 |
| 211 | : Limit - TheLine->Last->TotalLength; |
| 212 | |
Francois Ferrand | 2a81ca8 | 2017-06-13 07:02:43 +0000 | [diff] [blame] | 213 | if (TheLine->Last->is(TT_FunctionLBrace) && |
| 214 | TheLine->First == TheLine->Last && |
Francois Ferrand | ad72256 | 2017-06-30 20:25:55 +0000 | [diff] [blame] | 215 | !Style.BraceWrapping.SplitEmptyFunction && |
Francois Ferrand | 2a81ca8 | 2017-06-13 07:02:43 +0000 | [diff] [blame] | 216 | I[1]->First->is(tok::r_brace)) |
| 217 | return tryMergeSimpleBlock(I, E, Limit); |
| 218 | |
Francois Ferrand | ad72256 | 2017-06-30 20:25:55 +0000 | [diff] [blame] | 219 | // Handle empty record blocks where the brace has already been wrapped |
| 220 | if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last && |
| 221 | I != AnnotatedLines.begin()) { |
| 222 | bool EmptyBlock = I[1]->First->is(tok::r_brace); |
| 223 | |
| 224 | const FormatToken *Tok = I[-1]->First; |
| 225 | if (Tok && Tok->is(tok::comment)) |
| 226 | Tok = Tok->getNextNonComment(); |
| 227 | |
| 228 | if (Tok && Tok->getNamespaceToken()) |
| 229 | return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock |
Manuel Klimek | 89628f6 | 2017-09-20 09:51:03 +0000 | [diff] [blame] | 230 | ? tryMergeSimpleBlock(I, E, Limit) |
| 231 | : 0; |
Francois Ferrand | ad72256 | 2017-06-30 20:25:55 +0000 | [diff] [blame] | 232 | |
| 233 | if (Tok && Tok->is(tok::kw_typedef)) |
| 234 | Tok = Tok->getNextNonComment(); |
| 235 | if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union, |
Krasimir Georgiev | d6ce937 | 2017-09-15 11:23:50 +0000 | [diff] [blame] | 236 | tok::kw_extern, Keywords.kw_interface)) |
Francois Ferrand | ad72256 | 2017-06-30 20:25:55 +0000 | [diff] [blame] | 237 | return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock |
Krasimir Georgiev | d6ce937 | 2017-09-15 11:23:50 +0000 | [diff] [blame] | 238 | ? tryMergeSimpleBlock(I, E, Limit) |
| 239 | : 0; |
Francois Ferrand | ad72256 | 2017-06-30 20:25:55 +0000 | [diff] [blame] | 240 | } |
| 241 | |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 242 | // FIXME: TheLine->Level != 0 might or might not be the right check to do. |
| 243 | // If necessary, change to something smarter. |
| 244 | bool MergeShortFunctions = |
| 245 | Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All || |
Daniel Jasper | 20580fd | 2015-06-11 13:31:45 +0000 | [diff] [blame] | 246 | (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 247 | I[1]->First->is(tok::r_brace)) || |
Francois Ferrand | d3f0e3d | 2017-06-21 13:56:02 +0000 | [diff] [blame] | 248 | (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly && |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 249 | TheLine->Level != 0); |
| 250 | |
Francois Ferrand | e56a829 | 2017-06-14 12:29:47 +0000 | [diff] [blame] | 251 | if (Style.CompactNamespaces) { |
| 252 | if (isNamespaceDeclaration(TheLine)) { |
| 253 | int i = 0; |
| 254 | unsigned closingLine = TheLine->MatchingOpeningBlockLineIndex - 1; |
| 255 | for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) && |
| 256 | closingLine == I[i + 1]->MatchingOpeningBlockLineIndex && |
| 257 | I[i + 1]->Last->TotalLength < Limit; |
| 258 | i++, closingLine--) { |
| 259 | // No extra indent for compacted namespaces |
| 260 | IndentTracker.skipLine(*I[i + 1]); |
| 261 | |
| 262 | Limit -= I[i + 1]->Last->TotalLength; |
| 263 | } |
| 264 | return i; |
| 265 | } |
| 266 | |
| 267 | if (isEndOfNamespace(TheLine, AnnotatedLines)) { |
| 268 | int i = 0; |
| 269 | unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1; |
| 270 | for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) && |
| 271 | openingLine == I[i + 1]->MatchingOpeningBlockLineIndex; |
| 272 | i++, openingLine--) { |
| 273 | // No space between consecutive braces |
| 274 | I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace); |
| 275 | |
| 276 | // Indent like the outer-most namespace |
| 277 | IndentTracker.nextLine(*I[i + 1]); |
| 278 | } |
| 279 | return i; |
| 280 | } |
| 281 | } |
| 282 | |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 283 | // Try to merge a function block with left brace unwrapped |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 284 | if (TheLine->Last->is(TT_FunctionLBrace) && |
| 285 | TheLine->First != TheLine->Last) { |
| 286 | return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0; |
| 287 | } |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 288 | // Try to merge a control statement block with left brace unwrapped |
| 289 | if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last && |
| 290 | TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { |
| 291 | return Style.AllowShortBlocksOnASingleLine |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 292 | ? tryMergeSimpleBlock(I, E, Limit) |
| 293 | : 0; |
| 294 | } |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 295 | // Try to merge a control statement block with left brace wrapped |
| 296 | if (I[1]->First->is(tok::l_brace) && |
| 297 | TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { |
| 298 | return Style.BraceWrapping.AfterControlStatement |
| 299 | ? tryMergeSimpleBlock(I, E, Limit) |
| 300 | : 0; |
| 301 | } |
| 302 | // Try to merge either empty or one-line block if is precedeed by control |
| 303 | // statement token |
| 304 | if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last && |
| 305 | I != AnnotatedLines.begin() && |
| 306 | I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { |
| 307 | return Style.AllowShortBlocksOnASingleLine |
| 308 | ? tryMergeSimpleBlock(I - 1, E, Limit) |
| 309 | : 0; |
| 310 | } |
| 311 | // Try to merge a block with left brace wrapped that wasn't yet covered |
| 312 | if (TheLine->Last->is(tok::l_brace)) { |
| 313 | return !Style.BraceWrapping.AfterFunction || |
Manuel Klimek | 89628f6 | 2017-09-20 09:51:03 +0000 | [diff] [blame] | 314 | (I[1]->First->is(tok::r_brace) && |
| 315 | !Style.BraceWrapping.SplitEmptyRecord) |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 316 | ? tryMergeSimpleBlock(I, E, Limit) |
| 317 | : 0; |
| 318 | } |
| 319 | // Try to merge a function block with left brace wrapped |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 320 | if (I[1]->First->is(TT_FunctionLBrace) && |
Daniel Jasper | c1bc38e | 2015-09-29 14:57:55 +0000 | [diff] [blame] | 321 | Style.BraceWrapping.AfterFunction) { |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 322 | if (I[1]->Last->is(TT_LineComment)) |
| 323 | return 0; |
| 324 | |
| 325 | // Check for Limit <= 2 to account for the " {". |
| 326 | if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine))) |
| 327 | return 0; |
| 328 | Limit -= 2; |
| 329 | |
| 330 | unsigned MergedLines = 0; |
Francois Ferrand | 2a81ca8 | 2017-06-13 07:02:43 +0000 | [diff] [blame] | 331 | if (MergeShortFunctions || |
| 332 | (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && |
| 333 | I[1]->First == I[1]->Last && I + 2 != E && |
| 334 | I[2]->First->is(tok::r_brace))) { |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 335 | MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); |
| 336 | // If we managed to merge the block, count the function header, which is |
| 337 | // on a separate line. |
| 338 | if (MergedLines > 0) |
| 339 | ++MergedLines; |
| 340 | } |
| 341 | return MergedLines; |
| 342 | } |
| 343 | if (TheLine->First->is(tok::kw_if)) { |
| 344 | return Style.AllowShortIfStatementsOnASingleLine |
| 345 | ? tryMergeSimpleControlStatement(I, E, Limit) |
| 346 | : 0; |
| 347 | } |
| 348 | if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) { |
| 349 | return Style.AllowShortLoopsOnASingleLine |
| 350 | ? tryMergeSimpleControlStatement(I, E, Limit) |
| 351 | : 0; |
| 352 | } |
| 353 | if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) { |
| 354 | return Style.AllowShortCaseLabelsOnASingleLine |
| 355 | ? tryMergeShortCaseLabels(I, E, Limit) |
| 356 | : 0; |
| 357 | } |
| 358 | if (TheLine->InPPDirective && |
| 359 | (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) { |
| 360 | return tryMergeSimplePPDirective(I, E, Limit); |
| 361 | } |
| 362 | return 0; |
| 363 | } |
| 364 | |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 365 | unsigned |
| 366 | tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I, |
| 367 | SmallVectorImpl<AnnotatedLine *>::const_iterator E, |
| 368 | unsigned Limit) { |
| 369 | if (Limit == 0) |
| 370 | return 0; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 371 | if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline) |
| 372 | return 0; |
| 373 | if (1 + I[1]->Last->TotalLength > Limit) |
| 374 | return 0; |
| 375 | return 1; |
| 376 | } |
| 377 | |
| 378 | unsigned tryMergeSimpleControlStatement( |
| 379 | SmallVectorImpl<AnnotatedLine *>::const_iterator I, |
| 380 | SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) { |
| 381 | if (Limit == 0) |
| 382 | return 0; |
Daniel Jasper | c1bc38e | 2015-09-29 14:57:55 +0000 | [diff] [blame] | 383 | if (Style.BraceWrapping.AfterControlStatement && |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 384 | (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine)) |
| 385 | return 0; |
| 386 | if (I[1]->InPPDirective != (*I)->InPPDirective || |
| 387 | (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) |
| 388 | return 0; |
| 389 | Limit = limitConsideringMacros(I + 1, E, Limit); |
| 390 | AnnotatedLine &Line = **I; |
| 391 | if (Line.Last->isNot(tok::r_paren)) |
| 392 | return 0; |
| 393 | if (1 + I[1]->Last->TotalLength > Limit) |
| 394 | return 0; |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 395 | if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while, |
| 396 | TT_LineComment)) |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 397 | return 0; |
| 398 | // Only inline simple if's (no nested if or else). |
Daniel Jasper | e285b8d | 2015-06-17 09:43:56 +0000 | [diff] [blame] | 399 | if (I + 2 != E && Line.startsWith(tok::kw_if) && |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 400 | I[2]->First->is(tok::kw_else)) |
| 401 | return 0; |
| 402 | return 1; |
| 403 | } |
| 404 | |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 405 | unsigned |
| 406 | tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I, |
| 407 | SmallVectorImpl<AnnotatedLine *>::const_iterator E, |
| 408 | unsigned Limit) { |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 409 | if (Limit == 0 || I + 1 == E || |
| 410 | I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) |
| 411 | return 0; |
| 412 | unsigned NumStmts = 0; |
| 413 | unsigned Length = 0; |
Francois Ferrand | a64ba70 | 2017-07-28 07:56:18 +0000 | [diff] [blame] | 414 | bool EndsWithComment = false; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 415 | bool InPPDirective = I[0]->InPPDirective; |
Francois Ferrand | a64ba70 | 2017-07-28 07:56:18 +0000 | [diff] [blame] | 416 | const unsigned Level = I[0]->Level; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 417 | for (; NumStmts < 3; ++NumStmts) { |
| 418 | if (I + 1 + NumStmts == E) |
| 419 | break; |
| 420 | const AnnotatedLine *Line = I[1 + NumStmts]; |
| 421 | if (Line->InPPDirective != InPPDirective) |
| 422 | break; |
| 423 | if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) |
| 424 | break; |
| 425 | if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch, |
Francois Ferrand | a64ba70 | 2017-07-28 07:56:18 +0000 | [diff] [blame] | 426 | tok::kw_while) || |
| 427 | EndsWithComment) |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 428 | return 0; |
Francois Ferrand | a64ba70 | 2017-07-28 07:56:18 +0000 | [diff] [blame] | 429 | if (Line->First->is(tok::comment)) { |
| 430 | if (Level != Line->Level) |
| 431 | return 0; |
| 432 | SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts; |
| 433 | for (; J != E; ++J) { |
| 434 | Line = *J; |
| 435 | if (Line->InPPDirective != InPPDirective) |
| 436 | break; |
| 437 | if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) |
| 438 | break; |
| 439 | if (Line->First->isNot(tok::comment) || Level != Line->Level) |
| 440 | return 0; |
| 441 | } |
| 442 | break; |
| 443 | } |
| 444 | if (Line->Last->is(tok::comment)) |
| 445 | EndsWithComment = true; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 446 | Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space. |
| 447 | } |
| 448 | if (NumStmts == 0 || NumStmts == 3 || Length > Limit) |
| 449 | return 0; |
| 450 | return NumStmts; |
| 451 | } |
| 452 | |
| 453 | unsigned |
| 454 | tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I, |
| 455 | SmallVectorImpl<AnnotatedLine *>::const_iterator E, |
| 456 | unsigned Limit) { |
| 457 | AnnotatedLine &Line = **I; |
| 458 | |
| 459 | // Don't merge ObjC @ keywords and methods. |
Nico Weber | 33381f5 | 2015-02-07 01:57:32 +0000 | [diff] [blame] | 460 | // FIXME: If an option to allow short exception handling clauses on a single |
| 461 | // line is added, change this to not return for @try and friends. |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 462 | if (Style.Language != FormatStyle::LK_Java && |
| 463 | Line.First->isOneOf(tok::at, tok::minus, tok::plus)) |
| 464 | return 0; |
| 465 | |
| 466 | // Check that the current line allows merging. This depends on whether we |
| 467 | // are in a control flow statements as well as several style flags. |
Daniel Jasper | e9f5357 | 2015-04-30 09:24:17 +0000 | [diff] [blame] | 468 | if (Line.First->isOneOf(tok::kw_else, tok::kw_case) || |
Krasimir Georgiev | 6a1c9d5 | 2017-10-02 15:53:37 +0000 | [diff] [blame] | 469 | (Line.First->Next && Line.First->Next->is(tok::kw_else))) |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 470 | return 0; |
| 471 | if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try, |
Nico Weber | fac2371 | 2015-02-04 15:26:27 +0000 | [diff] [blame] | 472 | tok::kw___try, tok::kw_catch, tok::kw___finally, |
Daniel Jasper | e285b8d | 2015-06-17 09:43:56 +0000 | [diff] [blame] | 473 | tok::kw_for, tok::r_brace, Keywords.kw___except)) { |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 474 | if (!Style.AllowShortBlocksOnASingleLine) |
| 475 | return 0; |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 476 | // Don't merge when we can't except the case when |
| 477 | // the control statement block is empty |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 478 | if (!Style.AllowShortIfStatementsOnASingleLine && |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 479 | Line.startsWith(tok::kw_if) && |
| 480 | !Style.BraceWrapping.AfterControlStatement && |
| 481 | !I[1]->First->is(tok::r_brace)) |
| 482 | return 0; |
| 483 | if (!Style.AllowShortIfStatementsOnASingleLine && |
| 484 | Line.startsWith(tok::kw_if) && |
| 485 | Style.BraceWrapping.AfterControlStatement && I + 2 != E && |
| 486 | !I[2]->First->is(tok::r_brace)) |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 487 | return 0; |
| 488 | if (!Style.AllowShortLoopsOnASingleLine && |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 489 | Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) && |
| 490 | !Style.BraceWrapping.AfterControlStatement && |
| 491 | !I[1]->First->is(tok::r_brace)) |
| 492 | return 0; |
| 493 | if (!Style.AllowShortLoopsOnASingleLine && |
| 494 | Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) && |
| 495 | Style.BraceWrapping.AfterControlStatement && I + 2 != E && |
| 496 | !I[2]->First->is(tok::r_brace)) |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 497 | return 0; |
| 498 | // FIXME: Consider an option to allow short exception handling clauses on |
| 499 | // a single line. |
Nico Weber | fac2371 | 2015-02-04 15:26:27 +0000 | [diff] [blame] | 500 | // FIXME: This isn't covered by tests. |
| 501 | // FIXME: For catch, __except, __finally the first token on the line |
| 502 | // is '}', so this isn't correct here. |
| 503 | if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch, |
| 504 | Keywords.kw___except, tok::kw___finally)) |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 505 | return 0; |
| 506 | } |
| 507 | |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 508 | if (Line.Last->is(tok::l_brace)) { |
| 509 | FormatToken *Tok = I[1]->First; |
| 510 | if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore && |
| 511 | (Tok->getNextNonComment() == nullptr || |
| 512 | Tok->getNextNonComment()->is(tok::semi))) { |
| 513 | // We merge empty blocks even if the line exceeds the column limit. |
| 514 | Tok->SpacesRequiredBefore = 0; |
| 515 | Tok->CanBreakBefore = true; |
| 516 | return 1; |
| 517 | } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) && |
| 518 | !startsExternCBlock(Line)) { |
| 519 | // We don't merge short records. |
Martin Probst | c160cfa | 2017-11-25 09:35:33 +0000 | [diff] [blame^] | 520 | FormatToken *RecordTok = Line.First; |
| 521 | // Skip record modifiers. |
| 522 | while (RecordTok->Next && |
| 523 | RecordTok->isOneOf(tok::kw_typedef, tok::kw_export, |
| 524 | Keywords.kw_declare, Keywords.kw_abstract, |
| 525 | tok::kw_default)) |
| 526 | RecordTok = RecordTok->Next; |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 527 | if (RecordTok && |
| 528 | RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct, |
| 529 | Keywords.kw_interface)) |
| 530 | return 0; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 531 | |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 532 | // Check that we still have three lines and they fit into the limit. |
| 533 | if (I + 2 == E || I[2]->Type == LT_Invalid) |
| 534 | return 0; |
| 535 | Limit = limitConsideringMacros(I + 2, E, Limit); |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 536 | |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 537 | if (!nextTwoLinesFitInto(I, Limit)) |
| 538 | return 0; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 539 | |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 540 | // Second, check that the next line does not contain any braces - if it |
| 541 | // does, readability declines when putting it into a single line. |
| 542 | if (I[1]->Last->is(TT_LineComment)) |
| 543 | return 0; |
| 544 | do { |
| 545 | if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit) |
| 546 | return 0; |
| 547 | Tok = Tok->Next; |
| 548 | } while (Tok); |
| 549 | |
| 550 | // Last, check that the third line starts with a closing brace. |
| 551 | Tok = I[2]->First; |
| 552 | if (Tok->isNot(tok::r_brace)) |
| 553 | return 0; |
| 554 | |
| 555 | // Don't merge "if (a) { .. } else {". |
| 556 | if (Tok->Next && Tok->Next->is(tok::kw_else)) |
| 557 | return 0; |
| 558 | |
| 559 | return 2; |
| 560 | } |
| 561 | } else if (I[1]->First->is(tok::l_brace)) { |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 562 | if (I[1]->Last->is(TT_LineComment)) |
| 563 | return 0; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 564 | |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 565 | // Check for Limit <= 2 to account for the " {". |
| 566 | if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I))) |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 567 | return 0; |
Krasimir Georgiev | 3b0b50b | 2017-09-11 10:12:16 +0000 | [diff] [blame] | 568 | Limit -= 2; |
| 569 | unsigned MergedLines = 0; |
| 570 | if (Style.AllowShortBlocksOnASingleLine || |
| 571 | (I[1]->First == I[1]->Last && I + 2 != E && |
| 572 | I[2]->First->is(tok::r_brace))) { |
| 573 | MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); |
| 574 | // If we managed to merge the block, count the statement header, which |
| 575 | // is on a separate line. |
| 576 | if (MergedLines > 0) |
| 577 | ++MergedLines; |
| 578 | } |
| 579 | return MergedLines; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 580 | } |
| 581 | return 0; |
| 582 | } |
| 583 | |
| 584 | /// Returns the modified column limit for \p I if it is inside a macro and |
| 585 | /// needs a trailing '\'. |
| 586 | unsigned |
| 587 | limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I, |
| 588 | SmallVectorImpl<AnnotatedLine *>::const_iterator E, |
| 589 | unsigned Limit) { |
| 590 | if (I[0]->InPPDirective && I + 1 != E && |
| 591 | !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) { |
| 592 | return Limit < 2 ? 0 : Limit - 2; |
| 593 | } |
| 594 | return Limit; |
| 595 | } |
| 596 | |
| 597 | bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I, |
| 598 | unsigned Limit) { |
| 599 | if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore) |
| 600 | return false; |
| 601 | return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit; |
| 602 | } |
| 603 | |
| 604 | bool containsMustBreak(const AnnotatedLine *Line) { |
| 605 | for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) { |
| 606 | if (Tok->MustBreakBefore) |
| 607 | return true; |
| 608 | } |
| 609 | return false; |
| 610 | } |
| 611 | |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 612 | void join(AnnotatedLine &A, const AnnotatedLine &B) { |
| 613 | assert(!A.Last->Next); |
| 614 | assert(!B.First->Previous); |
| 615 | if (B.Affected) |
| 616 | A.Affected = true; |
| 617 | A.Last->Next = B.First; |
| 618 | B.First->Previous = A.Last; |
| 619 | B.First->CanBreakBefore = true; |
| 620 | unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore; |
| 621 | for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) { |
| 622 | Tok->TotalLength += LengthA; |
| 623 | A.Last = Tok; |
| 624 | } |
| 625 | } |
| 626 | |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 627 | const FormatStyle &Style; |
Nico Weber | fac2371 | 2015-02-04 15:26:27 +0000 | [diff] [blame] | 628 | const AdditionalKeywords &Keywords; |
Daniel Jasper | e6fcf7d | 2015-06-17 13:08:06 +0000 | [diff] [blame] | 629 | const SmallVectorImpl<AnnotatedLine *>::const_iterator End; |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 630 | |
Daniel Jasper | e6fcf7d | 2015-06-17 13:08:06 +0000 | [diff] [blame] | 631 | SmallVectorImpl<AnnotatedLine *>::const_iterator Next; |
Francois Ferrand | e56a829 | 2017-06-14 12:29:47 +0000 | [diff] [blame] | 632 | const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 633 | }; |
| 634 | |
Daniel Jasper | d1c1373 | 2015-01-23 19:37:25 +0000 | [diff] [blame] | 635 | static void markFinalized(FormatToken *Tok) { |
| 636 | for (; Tok; Tok = Tok->Next) { |
| 637 | Tok->Finalized = true; |
| 638 | for (AnnotatedLine *Child : Tok->Children) |
| 639 | markFinalized(Child->First); |
| 640 | } |
| 641 | } |
| 642 | |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 643 | #ifndef NDEBUG |
| 644 | static void printLineState(const LineState &State) { |
| 645 | llvm::dbgs() << "State: "; |
| 646 | for (const ParenState &P : State.Stack) { |
| 647 | llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent |
| 648 | << " "; |
| 649 | } |
| 650 | llvm::dbgs() << State.NextToken->TokenText << "\n"; |
| 651 | } |
| 652 | #endif |
| 653 | |
| 654 | /// \brief Base class for classes that format one \c AnnotatedLine. |
| 655 | class LineFormatter { |
| 656 | public: |
| 657 | LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces, |
| 658 | const FormatStyle &Style, |
| 659 | UnwrappedLineFormatter *BlockFormatter) |
| 660 | : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), |
| 661 | BlockFormatter(BlockFormatter) {} |
Angel Garcia Gomez | 637d1e6 | 2015-10-20 13:23:58 +0000 | [diff] [blame] | 662 | virtual ~LineFormatter() {} |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 663 | |
| 664 | /// \brief Formats an \c AnnotatedLine and returns the penalty. |
| 665 | /// |
| 666 | /// If \p DryRun is \c false, directly applies the changes. |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 667 | virtual unsigned formatLine(const AnnotatedLine &Line, |
| 668 | unsigned FirstIndent, |
| 669 | unsigned FirstStartColumn, |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 670 | bool DryRun) = 0; |
| 671 | |
| 672 | protected: |
| 673 | /// \brief If the \p State's next token is an r_brace closing a nested block, |
| 674 | /// format the nested block before it. |
| 675 | /// |
| 676 | /// Returns \c true if all children could be placed successfully and adapts |
| 677 | /// \p Penalty as well as \p State. If \p DryRun is false, also directly |
| 678 | /// creates changes using \c Whitespaces. |
| 679 | /// |
| 680 | /// The crucial idea here is that children always get formatted upon |
| 681 | /// encountering the closing brace right after the nested block. Now, if we |
| 682 | /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is |
| 683 | /// \c false), the entire block has to be kept on the same line (which is only |
| 684 | /// possible if it fits on the line, only contains a single statement, etc. |
| 685 | /// |
| 686 | /// If \p NewLine is true, we format the nested block on separate lines, i.e. |
| 687 | /// break after the "{", format all lines with correct indentation and the put |
| 688 | /// the closing "}" on yet another new line. |
| 689 | /// |
| 690 | /// This enables us to keep the simple structure of the |
| 691 | /// \c UnwrappedLineFormatter, where we only have two options for each token: |
| 692 | /// break or don't break. |
| 693 | bool formatChildren(LineState &State, bool NewLine, bool DryRun, |
| 694 | unsigned &Penalty) { |
| 695 | const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); |
| 696 | FormatToken &Previous = *State.NextToken->Previous; |
| 697 | if (!LBrace || LBrace->isNot(tok::l_brace) || |
| 698 | LBrace->BlockKind != BK_Block || Previous.Children.size() == 0) |
| 699 | // The previous token does not open a block. Nothing to do. We don't |
| 700 | // assert so that we can simply call this function for all tokens. |
| 701 | return true; |
| 702 | |
| 703 | if (NewLine) { |
| 704 | int AdditionalIndent = State.Stack.back().Indent - |
| 705 | Previous.Children[0]->Level * Style.IndentWidth; |
| 706 | |
| 707 | Penalty += |
| 708 | BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent, |
| 709 | /*FixBadIndentation=*/true); |
| 710 | return true; |
| 711 | } |
| 712 | |
| 713 | if (Previous.Children[0]->First->MustBreakBefore) |
| 714 | return false; |
| 715 | |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 716 | // Cannot merge into one line if this line ends on a comment. |
| 717 | if (Previous.is(tok::comment)) |
| 718 | return false; |
| 719 | |
Daniel Jasper | 7d42f3f | 2017-01-31 11:25:01 +0000 | [diff] [blame] | 720 | // Cannot merge multiple statements into a single line. |
| 721 | if (Previous.Children.size() > 1) |
| 722 | return false; |
| 723 | |
| 724 | const AnnotatedLine *Child = Previous.Children[0]; |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 725 | // We can't put the closing "}" on a line with a trailing comment. |
Daniel Jasper | 7d42f3f | 2017-01-31 11:25:01 +0000 | [diff] [blame] | 726 | if (Child->Last->isTrailingComment()) |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 727 | return false; |
| 728 | |
| 729 | // If the child line exceeds the column limit, we wouldn't want to merge it. |
| 730 | // We add +2 for the trailing " }". |
| 731 | if (Style.ColumnLimit > 0 && |
Daniel Jasper | 7d42f3f | 2017-01-31 11:25:01 +0000 | [diff] [blame] | 732 | Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 733 | return false; |
| 734 | |
| 735 | if (!DryRun) { |
| 736 | Whitespaces->replaceWhitespace( |
Daniel Jasper | 7d42f3f | 2017-01-31 11:25:01 +0000 | [diff] [blame] | 737 | *Child->First, /*Newlines=*/0, /*Spaces=*/1, |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 738 | /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective); |
| 739 | } |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 740 | Penalty += |
| 741 | formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun); |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 742 | |
Daniel Jasper | 7d42f3f | 2017-01-31 11:25:01 +0000 | [diff] [blame] | 743 | State.Column += 1 + Child->Last->TotalLength; |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 744 | return true; |
| 745 | } |
| 746 | |
| 747 | ContinuationIndenter *Indenter; |
| 748 | |
| 749 | private: |
| 750 | WhitespaceManager *Whitespaces; |
| 751 | const FormatStyle &Style; |
| 752 | UnwrappedLineFormatter *BlockFormatter; |
| 753 | }; |
| 754 | |
| 755 | /// \brief Formatter that keeps the existing line breaks. |
| 756 | class NoColumnLimitLineFormatter : public LineFormatter { |
| 757 | public: |
| 758 | NoColumnLimitLineFormatter(ContinuationIndenter *Indenter, |
| 759 | WhitespaceManager *Whitespaces, |
| 760 | const FormatStyle &Style, |
| 761 | UnwrappedLineFormatter *BlockFormatter) |
| 762 | : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} |
| 763 | |
| 764 | /// \brief Formats the line, simply keeping all of the input's line breaking |
| 765 | /// decisions. |
| 766 | unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 767 | unsigned FirstStartColumn, bool DryRun) override { |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 768 | assert(!DryRun); |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 769 | LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn, |
| 770 | &Line, /*DryRun=*/false); |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 771 | while (State.NextToken) { |
| 772 | bool Newline = |
| 773 | Indenter->mustBreak(State) || |
| 774 | (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0); |
| 775 | unsigned Penalty = 0; |
| 776 | formatChildren(State, Newline, /*DryRun=*/false, Penalty); |
| 777 | Indenter->addTokenToState(State, Newline, /*DryRun=*/false); |
| 778 | } |
| 779 | return 0; |
| 780 | } |
| 781 | }; |
| 782 | |
| 783 | /// \brief Formatter that puts all tokens into a single line without breaks. |
| 784 | class NoLineBreakFormatter : public LineFormatter { |
| 785 | public: |
| 786 | NoLineBreakFormatter(ContinuationIndenter *Indenter, |
| 787 | WhitespaceManager *Whitespaces, const FormatStyle &Style, |
| 788 | UnwrappedLineFormatter *BlockFormatter) |
| 789 | : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} |
| 790 | |
| 791 | /// \brief Puts all tokens into a single line. |
| 792 | unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 793 | unsigned FirstStartColumn, bool DryRun) override { |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 794 | unsigned Penalty = 0; |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 795 | LineState State = |
| 796 | Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun); |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 797 | while (State.NextToken) { |
| 798 | formatChildren(State, /*Newline=*/false, DryRun, Penalty); |
Krasimir Georgiev | 994b6c9 | 2017-05-18 08:07:52 +0000 | [diff] [blame] | 799 | Indenter->addTokenToState( |
| 800 | State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun); |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 801 | } |
| 802 | return Penalty; |
| 803 | } |
| 804 | }; |
| 805 | |
| 806 | /// \brief Finds the best way to break lines. |
| 807 | class OptimizingLineFormatter : public LineFormatter { |
| 808 | public: |
| 809 | OptimizingLineFormatter(ContinuationIndenter *Indenter, |
| 810 | WhitespaceManager *Whitespaces, |
| 811 | const FormatStyle &Style, |
| 812 | UnwrappedLineFormatter *BlockFormatter) |
| 813 | : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} |
| 814 | |
| 815 | /// \brief Formats the line by finding the best line breaks with line lengths |
| 816 | /// below the column limit. |
| 817 | unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 818 | unsigned FirstStartColumn, bool DryRun) override { |
| 819 | LineState State = |
| 820 | Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun); |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 821 | |
| 822 | // If the ObjC method declaration does not fit on a line, we should format |
| 823 | // it with one arg per line. |
| 824 | if (State.Line->Type == LT_ObjCMethodDecl) |
| 825 | State.Stack.back().BreakBeforeParameter = true; |
| 826 | |
| 827 | // Find best solution in solution space. |
| 828 | return analyzeSolutionSpace(State, DryRun); |
| 829 | } |
| 830 | |
| 831 | private: |
| 832 | struct CompareLineStatePointers { |
| 833 | bool operator()(LineState *obj1, LineState *obj2) const { |
| 834 | return *obj1 < *obj2; |
| 835 | } |
| 836 | }; |
| 837 | |
| 838 | /// \brief A pair of <penalty, count> that is used to prioritize the BFS on. |
| 839 | /// |
| 840 | /// In case of equal penalties, we want to prefer states that were inserted |
| 841 | /// first. During state generation we make sure that we insert states first |
| 842 | /// that break the line as late as possible. |
| 843 | typedef std::pair<unsigned, unsigned> OrderedPenalty; |
| 844 | |
| 845 | /// \brief An edge in the solution space from \c Previous->State to \c State, |
| 846 | /// inserting a newline dependent on the \c NewLine. |
| 847 | struct StateNode { |
| 848 | StateNode(const LineState &State, bool NewLine, StateNode *Previous) |
| 849 | : State(State), NewLine(NewLine), Previous(Previous) {} |
| 850 | LineState State; |
| 851 | bool NewLine; |
| 852 | StateNode *Previous; |
| 853 | }; |
| 854 | |
| 855 | /// \brief An item in the prioritized BFS search queue. The \c StateNode's |
| 856 | /// \c State has the given \c OrderedPenalty. |
| 857 | typedef std::pair<OrderedPenalty, StateNode *> QueueItem; |
| 858 | |
| 859 | /// \brief The BFS queue type. |
| 860 | typedef std::priority_queue<QueueItem, std::vector<QueueItem>, |
Manuel Klimek | 89628f6 | 2017-09-20 09:51:03 +0000 | [diff] [blame] | 861 | std::greater<QueueItem>> |
| 862 | QueueType; |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 863 | |
| 864 | /// \brief Analyze the entire solution space starting from \p InitialState. |
| 865 | /// |
| 866 | /// This implements a variant of Dijkstra's algorithm on the graph that spans |
| 867 | /// the solution space (\c LineStates are the nodes). The algorithm tries to |
| 868 | /// find the shortest path (the one with lowest penalty) from \p InitialState |
| 869 | /// to a state where all tokens are placed. Returns the penalty. |
| 870 | /// |
| 871 | /// If \p DryRun is \c false, directly applies the changes. |
| 872 | unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) { |
| 873 | std::set<LineState *, CompareLineStatePointers> Seen; |
| 874 | |
| 875 | // Increasing count of \c StateNode items we have created. This is used to |
| 876 | // create a deterministic order independent of the container. |
| 877 | unsigned Count = 0; |
| 878 | QueueType Queue; |
| 879 | |
| 880 | // Insert start element into queue. |
| 881 | StateNode *Node = |
| 882 | new (Allocator.Allocate()) StateNode(InitialState, false, nullptr); |
| 883 | Queue.push(QueueItem(OrderedPenalty(0, Count), Node)); |
| 884 | ++Count; |
| 885 | |
| 886 | unsigned Penalty = 0; |
| 887 | |
| 888 | // While not empty, take first element and follow edges. |
| 889 | while (!Queue.empty()) { |
| 890 | Penalty = Queue.top().first.first; |
| 891 | StateNode *Node = Queue.top().second; |
| 892 | if (!Node->State.NextToken) { |
| 893 | DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n"); |
| 894 | break; |
| 895 | } |
| 896 | Queue.pop(); |
| 897 | |
| 898 | // Cut off the analysis of certain solutions if the analysis gets too |
| 899 | // complex. See description of IgnoreStackForComparison. |
Daniel Jasper | 75bf203 | 2015-10-27 22:55:55 +0000 | [diff] [blame] | 900 | if (Count > 50000) |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 901 | Node->State.IgnoreStackForComparison = true; |
| 902 | |
| 903 | if (!Seen.insert(&Node->State).second) |
| 904 | // State already examined with lower penalty. |
| 905 | continue; |
| 906 | |
| 907 | FormatDecision LastFormat = Node->State.NextToken->Decision; |
| 908 | if (LastFormat == FD_Unformatted || LastFormat == FD_Continue) |
| 909 | addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue); |
| 910 | if (LastFormat == FD_Unformatted || LastFormat == FD_Break) |
| 911 | addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue); |
| 912 | } |
| 913 | |
| 914 | if (Queue.empty()) { |
| 915 | // We were unable to find a solution, do nothing. |
| 916 | // FIXME: Add diagnostic? |
| 917 | DEBUG(llvm::dbgs() << "Could not find a solution.\n"); |
| 918 | return 0; |
| 919 | } |
| 920 | |
| 921 | // Reconstruct the solution. |
| 922 | if (!DryRun) |
| 923 | reconstructPath(InitialState, Queue.top().second); |
| 924 | |
| 925 | DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n"); |
| 926 | DEBUG(llvm::dbgs() << "---\n"); |
| 927 | |
| 928 | return Penalty; |
| 929 | } |
| 930 | |
| 931 | /// \brief Add the following state to the analysis queue \c Queue. |
| 932 | /// |
| 933 | /// Assume the current state is \p PreviousNode and has been reached with a |
| 934 | /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. |
| 935 | void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, |
| 936 | bool NewLine, unsigned *Count, QueueType *Queue) { |
| 937 | if (NewLine && !Indenter->canBreak(PreviousNode->State)) |
| 938 | return; |
| 939 | if (!NewLine && Indenter->mustBreak(PreviousNode->State)) |
| 940 | return; |
| 941 | |
| 942 | StateNode *Node = new (Allocator.Allocate()) |
| 943 | StateNode(PreviousNode->State, NewLine, PreviousNode); |
| 944 | if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty)) |
| 945 | return; |
| 946 | |
| 947 | Penalty += Indenter->addTokenToState(Node->State, NewLine, true); |
| 948 | |
| 949 | Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node)); |
| 950 | ++(*Count); |
| 951 | } |
| 952 | |
| 953 | /// \brief Applies the best formatting by reconstructing the path in the |
| 954 | /// solution space that leads to \c Best. |
| 955 | void reconstructPath(LineState &State, StateNode *Best) { |
| 956 | std::deque<StateNode *> Path; |
| 957 | // We do not need a break before the initial token. |
| 958 | while (Best->Previous) { |
| 959 | Path.push_front(Best); |
| 960 | Best = Best->Previous; |
| 961 | } |
| 962 | for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end(); |
| 963 | I != E; ++I) { |
| 964 | unsigned Penalty = 0; |
| 965 | formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty); |
| 966 | Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false); |
| 967 | |
| 968 | DEBUG({ |
| 969 | printLineState((*I)->Previous->State); |
| 970 | if ((*I)->NewLine) { |
| 971 | llvm::dbgs() << "Penalty for placing " |
| 972 | << (*I)->Previous->State.NextToken->Tok.getName() << ": " |
| 973 | << Penalty << "\n"; |
| 974 | } |
| 975 | }); |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | llvm::SpecificBumpPtrAllocator<StateNode> Allocator; |
| 980 | }; |
| 981 | |
Hans Wennborg | 7eb5464 | 2015-09-10 17:07:54 +0000 | [diff] [blame] | 982 | } // anonymous namespace |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 983 | |
| 984 | unsigned |
| 985 | UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines, |
| 986 | bool DryRun, int AdditionalIndent, |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 987 | bool FixBadIndentation, |
| 988 | unsigned FirstStartColumn, |
| 989 | unsigned NextStartColumn, |
| 990 | unsigned LastStartColumn) { |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 991 | LineJoiner Joiner(Style, Keywords, Lines); |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 992 | |
| 993 | // Try to look up already computed penalty in DryRun-mode. |
| 994 | std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey( |
| 995 | &Lines, AdditionalIndent); |
| 996 | auto CacheIt = PenaltyCache.find(CacheKey); |
| 997 | if (DryRun && CacheIt != PenaltyCache.end()) |
| 998 | return CacheIt->second; |
| 999 | |
| 1000 | assert(!Lines.empty()); |
| 1001 | unsigned Penalty = 0; |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1002 | LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level, |
| 1003 | AdditionalIndent); |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1004 | const AnnotatedLine *PreviousLine = nullptr; |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1005 | const AnnotatedLine *NextLine = nullptr; |
Daniel Jasper | f67c324 | 2015-11-01 00:27:35 +0000 | [diff] [blame] | 1006 | |
| 1007 | // The minimum level of consecutive lines that have been formatted. |
| 1008 | unsigned RangeMinLevel = UINT_MAX; |
Daniel Jasper | f67c324 | 2015-11-01 00:27:35 +0000 | [diff] [blame] | 1009 | |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1010 | bool FirstLine = true; |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1011 | for (const AnnotatedLine *Line = |
| 1012 | Joiner.getNextMergedLine(DryRun, IndentTracker); |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1013 | Line; Line = NextLine, FirstLine = false) { |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1014 | const AnnotatedLine &TheLine = *Line; |
| 1015 | unsigned Indent = IndentTracker.getIndent(); |
Daniel Jasper | f67c324 | 2015-11-01 00:27:35 +0000 | [diff] [blame] | 1016 | |
| 1017 | // We continue formatting unchanged lines to adjust their indent, e.g. if a |
| 1018 | // scope was added. However, we need to carefully stop doing this when we |
| 1019 | // exit the scope of affected lines to prevent indenting a the entire |
| 1020 | // remaining file if it currently missing a closing brace. |
| 1021 | bool ContinueFormatting = |
| 1022 | TheLine.Level > RangeMinLevel || |
Daniel Jasper | f83834f | 2015-11-02 20:02:49 +0000 | [diff] [blame] | 1023 | (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace)); |
Daniel Jasper | f67c324 | 2015-11-01 00:27:35 +0000 | [diff] [blame] | 1024 | |
| 1025 | bool FixIndentation = (FixBadIndentation || ContinueFormatting) && |
Daniel Jasper | a1036e5 | 2015-10-28 01:08:22 +0000 | [diff] [blame] | 1026 | Indent != TheLine.First->OriginalColumn; |
Manuel Klimek | ec5c3db | 2015-05-07 12:26:30 +0000 | [diff] [blame] | 1027 | bool ShouldFormat = TheLine.Affected || FixIndentation; |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1028 | // We cannot format this line; if the reason is that the line had a |
| 1029 | // parsing error, remember that. |
Krasimir Georgiev | bcda54b | 2017-04-21 14:35:20 +0000 | [diff] [blame] | 1030 | if (ShouldFormat && TheLine.Type == LT_Invalid && Status) { |
| 1031 | Status->FormatComplete = false; |
| 1032 | Status->Line = |
| 1033 | SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation()); |
| 1034 | } |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1035 | |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1036 | if (ShouldFormat && TheLine.Type != LT_Invalid) { |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1037 | if (!DryRun) { |
| 1038 | bool LastLine = Line->First->is(tok::eof); |
| 1039 | formatFirstToken(TheLine, PreviousLine, |
| 1040 | Indent, |
| 1041 | LastLine ? LastStartColumn : NextStartColumn + Indent); |
| 1042 | } |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1043 | |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1044 | NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); |
| 1045 | unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine); |
| 1046 | bool FitsIntoOneLine = |
| 1047 | TheLine.Last->TotalLength + Indent <= ColumnLimit || |
Martin Probst | 0cd74ee | 2016-06-13 16:39:50 +0000 | [diff] [blame] | 1048 | (TheLine.Type == LT_ImportStatement && |
| 1049 | (Style.Language != FormatStyle::LK_JavaScript || |
| 1050 | !Style.JavaScriptWrapImports)); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1051 | if (Style.ColumnLimit == 0) |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 1052 | NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this) |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1053 | .formatLine(TheLine, NextStartColumn + Indent, |
| 1054 | FirstLine ? FirstStartColumn : 0, DryRun); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1055 | else if (FitsIntoOneLine) |
| 1056 | Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this) |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1057 | .formatLine(TheLine, NextStartColumn + Indent, |
| 1058 | FirstLine ? FirstStartColumn : 0, DryRun); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1059 | else |
Manuel Klimek | d3585db | 2015-05-11 08:21:35 +0000 | [diff] [blame] | 1060 | Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this) |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1061 | .formatLine(TheLine, NextStartColumn + Indent, |
| 1062 | FirstLine ? FirstStartColumn : 0, DryRun); |
Daniel Jasper | f67c324 | 2015-11-01 00:27:35 +0000 | [diff] [blame] | 1063 | RangeMinLevel = std::min(RangeMinLevel, TheLine.Level); |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1064 | } else { |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1065 | // If no token in the current line is affected, we still need to format |
| 1066 | // affected children. |
| 1067 | if (TheLine.ChildrenAffected) |
Daniel Jasper | 35ca66d | 2016-02-29 12:26:20 +0000 | [diff] [blame] | 1068 | for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) |
| 1069 | if (!Tok->Children.empty()) |
| 1070 | format(Tok->Children, DryRun); |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1071 | |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1072 | // Adapt following lines on the current indent level to the same level |
| 1073 | // unless the current \c AnnotatedLine is not at the beginning of a line. |
| 1074 | bool StartsNewLine = |
| 1075 | TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst; |
| 1076 | if (StartsNewLine) |
| 1077 | IndentTracker.adjustToUnmodifiedLine(TheLine); |
| 1078 | if (!DryRun) { |
| 1079 | bool ReformatLeadingWhitespace = |
| 1080 | StartsNewLine && ((PreviousLine && PreviousLine->Affected) || |
| 1081 | TheLine.LeadingEmptyLinesAffected); |
| 1082 | // Format the first token. |
| 1083 | if (ReformatLeadingWhitespace) |
Daniel Jasper | 7d42f3f | 2017-01-31 11:25:01 +0000 | [diff] [blame] | 1084 | formatFirstToken(TheLine, PreviousLine, |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1085 | TheLine.First->OriginalColumn, |
Daniel Jasper | 7d42f3f | 2017-01-31 11:25:01 +0000 | [diff] [blame] | 1086 | TheLine.First->OriginalColumn); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1087 | else |
| 1088 | Whitespaces->addUntouchableToken(*TheLine.First, |
| 1089 | TheLine.InPPDirective); |
| 1090 | |
| 1091 | // Notify the WhitespaceManager about the unchanged whitespace. |
| 1092 | for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next) |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1093 | Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1094 | } |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1095 | NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); |
Daniel Jasper | f67c324 | 2015-11-01 00:27:35 +0000 | [diff] [blame] | 1096 | RangeMinLevel = UINT_MAX; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1097 | } |
Daniel Jasper | d1c1373 | 2015-01-23 19:37:25 +0000 | [diff] [blame] | 1098 | if (!DryRun) |
| 1099 | markFinalized(TheLine.First); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1100 | PreviousLine = &TheLine; |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1101 | } |
| 1102 | PenaltyCache[CacheKey] = Penalty; |
| 1103 | return Penalty; |
| 1104 | } |
| 1105 | |
Daniel Jasper | 7d42f3f | 2017-01-31 11:25:01 +0000 | [diff] [blame] | 1106 | void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line, |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1107 | const AnnotatedLine *PreviousLine, |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1108 | unsigned Indent, |
| 1109 | unsigned NewlineIndent) { |
Manuel Klimek | 89628f6 | 2017-09-20 09:51:03 +0000 | [diff] [blame] | 1110 | FormatToken &RootToken = *Line.First; |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1111 | if (RootToken.is(tok::eof)) { |
| 1112 | unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u); |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1113 | unsigned TokenIndent = Newlines ? NewlineIndent : 0; |
| 1114 | Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent, |
| 1115 | TokenIndent); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1116 | return; |
| 1117 | } |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1118 | unsigned Newlines = |
| 1119 | std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); |
| 1120 | // Remove empty lines before "}" where applicable. |
| 1121 | if (RootToken.is(tok::r_brace) && |
| 1122 | (!RootToken.Next || |
| 1123 | (RootToken.Next->is(tok::semi) && !RootToken.Next->Next))) |
| 1124 | Newlines = std::min(Newlines, 1u); |
Martin Probst | a004b3f | 2017-11-17 18:06:33 +0000 | [diff] [blame] | 1125 | // Remove empty lines at the start of nested blocks (lambdas/arrow functions) |
| 1126 | if (PreviousLine == nullptr && Line.Level > 0) |
| 1127 | Newlines = std::min(Newlines, 1u); |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1128 | if (Newlines == 0 && !RootToken.IsFirst) |
| 1129 | Newlines = 1; |
| 1130 | if (RootToken.IsFirst && !RootToken.HasUnescapedNewline) |
| 1131 | Newlines = 0; |
| 1132 | |
| 1133 | // Remove empty lines after "{". |
| 1134 | if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine && |
| 1135 | PreviousLine->Last->is(tok::l_brace) && |
| 1136 | PreviousLine->First->isNot(tok::kw_namespace) && |
| 1137 | !startsExternCBlock(*PreviousLine)) |
| 1138 | Newlines = 1; |
| 1139 | |
| 1140 | // Insert extra new line before access specifiers. |
| 1141 | if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && |
| 1142 | RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1) |
| 1143 | ++Newlines; |
| 1144 | |
| 1145 | // Remove empty lines after access specifiers. |
Daniel Jasper | ac5c97e3 | 2015-03-09 08:13:55 +0000 | [diff] [blame] | 1146 | if (PreviousLine && PreviousLine->First->isAccessSpecifier() && |
| 1147 | (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1148 | Newlines = std::min(1u, Newlines); |
| 1149 | |
Krasimir Georgiev | 9ad83fe | 2017-10-30 14:01:50 +0000 | [diff] [blame] | 1150 | if (Newlines) |
| 1151 | Indent = NewlineIndent; |
| 1152 | |
| 1153 | // Preprocessor directives get indented after the hash, if indented. |
| 1154 | if (Line.Type == LT_PreprocessorDirective || Line.Type == LT_ImportStatement) |
| 1155 | Indent = 0; |
| 1156 | |
Daniel Jasper | 7d42f3f | 2017-01-31 11:25:01 +0000 | [diff] [blame] | 1157 | Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent, |
| 1158 | Line.InPPDirective && |
| 1159 | !RootToken.HasUnescapedNewline); |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1160 | } |
| 1161 | |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1162 | unsigned |
| 1163 | UnwrappedLineFormatter::getColumnLimit(bool InPPDirective, |
| 1164 | const AnnotatedLine *NextLine) const { |
| 1165 | // In preprocessor directives reserve two chars for trailing " \" if the |
| 1166 | // next line continues the preprocessor directive. |
| 1167 | bool ContinuesPPDirective = |
Daniel Jasper | 1a02822 | 2015-05-26 07:03:42 +0000 | [diff] [blame] | 1168 | InPPDirective && |
| 1169 | // If there is no next line, this is likely a child line and the parent |
| 1170 | // continues the preprocessor directive. |
| 1171 | (!NextLine || |
| 1172 | (NextLine->InPPDirective && |
| 1173 | // If there is an unescaped newline between this line and the next, the |
| 1174 | // next line starts a new preprocessor directive. |
| 1175 | !NextLine->First->HasUnescapedNewline)); |
Manuel Klimek | 3d3ea84 | 2015-05-12 09:23:57 +0000 | [diff] [blame] | 1176 | return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0); |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1177 | } |
| 1178 | |
Daniel Jasper | 0df5093 | 2014-12-10 19:00:42 +0000 | [diff] [blame] | 1179 | } // namespace format |
| 1180 | } // namespace clang |