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