blob: 60e0027ec741dc1f51a65aeecec52add51a84ae3 [file] [log] [blame]
Daniel Jasper6b2afe42013-08-16 11:20:30 +00001//===--- ContinuationIndenter.h - Format C++ code ---------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file implements an indenter that manages the indentation of
12/// continuations.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_FORMAT_CONTINUATION_INDENTER_H
17#define LLVM_CLANG_FORMAT_CONTINUATION_INDENTER_H
18
19#include "Encoding.h"
20#include "clang/Format/Format.h"
21
22namespace clang {
23class SourceManager;
24
25namespace format {
26
27class AnnotatedLine;
28struct FormatToken;
29struct LineState;
30struct ParenState;
31class WhitespaceManager;
32
33class ContinuationIndenter {
34public:
35 /// \brief Constructs a \c ContinuationIndenter to format \p Line starting in
36 /// column \p FirstIndent.
37 ContinuationIndenter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasper6b2afe42013-08-16 11:20:30 +000038 WhitespaceManager &Whitespaces,
39 encoding::Encoding Encoding,
40 bool BinPackInconclusiveFunctions);
41
Daniel Jasper567dcf92013-09-05 09:29:45 +000042 /// \brief Get the initial state, i.e. the state after placing \p Line's
43 /// first token at \p FirstIndent.
Daniel Jasperb77d7412013-09-06 07:54:20 +000044 LineState getInitialState(unsigned FirstIndent, const AnnotatedLine *Line,
45 bool DryRun);
Daniel Jasper6b2afe42013-08-16 11:20:30 +000046
47 // FIXME: canBreak and mustBreak aren't strictly indentation-related. Find a
48 // better home.
49 /// \brief Returns \c true, if a line break after \p State is allowed.
50 bool canBreak(const LineState &State);
51
52 /// \brief Returns \c true, if a line break after \p State is mandatory.
53 bool mustBreak(const LineState &State);
54
55 /// \brief Appends the next token to \p State and updates information
56 /// necessary for indentation.
57 ///
58 /// Puts the token on the current line if \p Newline is \c false and adds a
59 /// line break and necessary indentation otherwise.
60 ///
61 /// If \p DryRun is \c false, also creates and stores the required
62 /// \c Replacement.
Daniel Jasperd4a03db2013-08-22 15:00:41 +000063 unsigned addTokenToState(LineState &State, bool Newline, bool DryRun,
64 unsigned ExtraSpaces = 0);
Daniel Jasper6b2afe42013-08-16 11:20:30 +000065
66 /// \brief Get the column limit for this line. This is the style's column
67 /// limit, potentially reduced for preprocessor definitions.
Daniel Jasper567dcf92013-09-05 09:29:45 +000068 unsigned getColumnLimit(const LineState &State) const;
Daniel Jasper6b2afe42013-08-16 11:20:30 +000069
70private:
71 /// \brief Mark the next token as consumed in \p State and modify its stacks
72 /// accordingly.
73 unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline);
74
75 /// \brief If the current token sticks out over the end of the line, break
76 /// it if possible.
77 ///
78 /// \returns An extra penalty if a token was broken, otherwise 0.
79 ///
80 /// The returned penalty will cover the cost of the additional line breaks and
81 /// column limit violation in all lines except for the last one. The penalty
82 /// for the column limit violation in the last line (and in single line
83 /// tokens) is handled in \c addNextStateToQueue.
84 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
85 bool DryRun);
86
Alexander Kornienkoe5321c42013-10-01 14:41:18 +000087 /// \brief Appends the next token to \p State and updates information
88 /// necessary for indentation.
89 ///
90 /// Puts the token on the current line.
91 ///
92 /// If \p DryRun is \c false, also creates and stores the required
93 /// \c Replacement.
94 void addTokenOnCurrentLine(LineState &State, bool DryRun,
95 unsigned ExtraSpaces);
96
97 /// \brief Appends the next token to \p State and updates information
98 /// necessary for indentation.
99 ///
100 /// Adds a line break and necessary indentation.
101 ///
102 /// If \p DryRun is \c false, also creates and stores the required
103 /// \c Replacement.
104 unsigned addTokenOnNewLine(LineState &State, bool DryRun);
105
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000106 /// \brief Adds a multiline token to the \p State.
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000107 ///
108 /// \returns Extra penalty for the first line of the literal: last line is
109 /// handled in \c addNextStateToQueue, and the penalty for other lines doesn't
110 /// matter, as we don't change them.
Alexander Kornienko6f6154c2013-09-10 12:29:48 +0000111 unsigned addMultilineToken(const FormatToken &Current, LineState &State);
Alexander Kornienkodcc0c5b2013-08-29 17:32:57 +0000112
Daniel Jasper4df1ff92013-08-23 11:57:34 +0000113 /// \brief Returns \c true if the next token starts a multiline string
114 /// literal.
115 ///
116 /// This includes implicitly concatenated strings, strings that will be broken
117 /// by clang-format and string literals with escaped newlines.
118 bool NextIsMultilineString(const LineState &State);
119
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000120 FormatStyle Style;
121 SourceManager &SourceMgr;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000122 WhitespaceManager &Whitespaces;
123 encoding::Encoding Encoding;
124 bool BinPackInconclusiveFunctions;
125};
126
127struct ParenState {
128 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
129 bool NoLineBreak)
130 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
131 BreakBeforeClosingBrace(false), QuestionColumn(0),
132 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
133 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
134 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000135 CallContinuation(0), VariablePos(0), ContainsLineBreak(false),
136 ContainsUnwrappedBuilder(0) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000137
138 /// \brief The position to which a specific parenthesis level needs to be
139 /// indented.
140 unsigned Indent;
141
142 /// \brief The position of the last space on each level.
143 ///
144 /// Used e.g. to break like:
145 /// functionCall(Parameter, otherCall(
146 /// OtherParameter));
147 unsigned LastSpace;
148
149 /// \brief The position the first "<<" operator encountered on each level.
150 ///
151 /// Used to align "<<" operators. 0 if no such operator has been encountered
152 /// on a level.
153 unsigned FirstLessLess;
154
155 /// \brief Whether a newline needs to be inserted before the block's closing
156 /// brace.
157 ///
158 /// We only want to insert a newline before the closing brace if there also
159 /// was a newline after the beginning left brace.
160 bool BreakBeforeClosingBrace;
161
162 /// \brief The column of a \c ? in a conditional expression;
163 unsigned QuestionColumn;
164
165 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
166 /// lines, in this context.
167 bool AvoidBinPacking;
168
169 /// \brief Break after the next comma (or all the commas in this context if
170 /// \c AvoidBinPacking is \c true).
171 bool BreakBeforeParameter;
172
173 /// \brief Line breaking in this context would break a formatting rule.
174 bool NoLineBreak;
175
176 /// \brief The position of the colon in an ObjC method declaration/call.
177 unsigned ColonPos;
178
179 /// \brief The start of the most recent function in a builder-type call.
180 unsigned StartOfFunctionCall;
181
182 /// \brief Contains the start of array subscript expressions, so that they
183 /// can be aligned.
184 unsigned StartOfArraySubscripts;
185
186 /// \brief If a nested name specifier was broken over multiple lines, this
187 /// contains the start column of the second line. Otherwise 0.
188 unsigned NestedNameSpecifierContinuation;
189
190 /// \brief If a call expression was broken over multiple lines, this
191 /// contains the start column of the second line. Otherwise 0.
192 unsigned CallContinuation;
193
194 /// \brief The column of the first variable name in a variable declaration.
195 ///
196 /// Used to align further variables if necessary.
197 unsigned VariablePos;
198
199 /// \brief \c true if this \c ParenState already contains a line-break.
200 ///
201 /// The first line break in a certain \c ParenState causes extra penalty so
202 /// that clang-format prefers similar breaks, i.e. breaks in the same
203 /// parenthesis.
204 bool ContainsLineBreak;
205
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000206 /// \brief \c true if this \c ParenState contains multiple segments of a
207 /// builder-type call on one line.
208 bool ContainsUnwrappedBuilder;
209
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000210 bool operator<(const ParenState &Other) const {
211 if (Indent != Other.Indent)
212 return Indent < Other.Indent;
213 if (LastSpace != Other.LastSpace)
214 return LastSpace < Other.LastSpace;
215 if (FirstLessLess != Other.FirstLessLess)
216 return FirstLessLess < Other.FirstLessLess;
217 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
218 return BreakBeforeClosingBrace;
219 if (QuestionColumn != Other.QuestionColumn)
220 return QuestionColumn < Other.QuestionColumn;
221 if (AvoidBinPacking != Other.AvoidBinPacking)
222 return AvoidBinPacking;
223 if (BreakBeforeParameter != Other.BreakBeforeParameter)
224 return BreakBeforeParameter;
225 if (NoLineBreak != Other.NoLineBreak)
226 return NoLineBreak;
227 if (ColonPos != Other.ColonPos)
228 return ColonPos < Other.ColonPos;
229 if (StartOfFunctionCall != Other.StartOfFunctionCall)
230 return StartOfFunctionCall < Other.StartOfFunctionCall;
231 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
232 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
233 if (CallContinuation != Other.CallContinuation)
234 return CallContinuation < Other.CallContinuation;
235 if (VariablePos != Other.VariablePos)
236 return VariablePos < Other.VariablePos;
237 if (ContainsLineBreak != Other.ContainsLineBreak)
238 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000239 if (ContainsUnwrappedBuilder != Other.ContainsUnwrappedBuilder)
240 return ContainsUnwrappedBuilder < Other.ContainsUnwrappedBuilder;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000241 return false;
242 }
243};
244
245/// \brief The current state when indenting a unwrapped line.
246///
247/// As the indenting tries different combinations this is copied by value.
248struct LineState {
249 /// \brief The number of used columns in the current line.
250 unsigned Column;
251
252 /// \brief The token that needs to be next formatted.
Manuel Klimekae76f7f2013-10-11 21:25:45 +0000253 FormatToken *NextToken;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000254
255 /// \brief \c true if this line contains a continued for-loop section.
256 bool LineContainsContinuedForLoopSection;
257
258 /// \brief The level of nesting inside (), [], <> and {}.
259 unsigned ParenLevel;
260
261 /// \brief The \c ParenLevel at the start of this line.
262 unsigned StartOfLineLevel;
263
264 /// \brief The lowest \c ParenLevel on the current line.
265 unsigned LowestLevelOnLine;
266
267 /// \brief The start column of the string literal, if we're in a string
268 /// literal sequence, 0 otherwise.
269 unsigned StartOfStringLiteral;
270
271 /// \brief A stack keeping track of properties applying to parenthesis
272 /// levels.
273 std::vector<ParenState> Stack;
274
275 /// \brief Ignore the stack of \c ParenStates for state comparison.
276 ///
277 /// In long and deeply nested unwrapped lines, the current algorithm can
278 /// be insufficient for finding the best formatting with a reasonable amount
279 /// of time and memory. Setting this flag will effectively lead to the
280 /// algorithm not analyzing some combinations. However, these combinations
281 /// rarely contain the optimal solution: In short, accepting a higher
282 /// penalty early would need to lead to different values in the \c
283 /// ParenState stack (in an otherwise identical state) and these different
284 /// values would need to lead to a significant amount of avoided penalty
285 /// later.
286 ///
287 /// FIXME: Come up with a better algorithm instead.
288 bool IgnoreStackForComparison;
289
Daniel Jasper567dcf92013-09-05 09:29:45 +0000290 /// \brief The indent of the first token.
291 unsigned FirstIndent;
292
293 /// \brief The line that is being formatted.
294 ///
295 /// Does not need to be considered for memoization because it doesn't change.
296 const AnnotatedLine *Line;
297
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000298 /// \brief Comparison operator to be able to used \c LineState in \c map.
299 bool operator<(const LineState &Other) const {
300 if (NextToken != Other.NextToken)
301 return NextToken < Other.NextToken;
302 if (Column != Other.Column)
303 return Column < Other.Column;
304 if (LineContainsContinuedForLoopSection !=
305 Other.LineContainsContinuedForLoopSection)
306 return LineContainsContinuedForLoopSection;
307 if (ParenLevel != Other.ParenLevel)
308 return ParenLevel < Other.ParenLevel;
309 if (StartOfLineLevel != Other.StartOfLineLevel)
310 return StartOfLineLevel < Other.StartOfLineLevel;
311 if (LowestLevelOnLine != Other.LowestLevelOnLine)
312 return LowestLevelOnLine < Other.LowestLevelOnLine;
313 if (StartOfStringLiteral != Other.StartOfStringLiteral)
314 return StartOfStringLiteral < Other.StartOfStringLiteral;
315 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
316 return false;
317 return Stack < Other.Stack;
318 }
319};
320
321} // end namespace format
322} // end namespace clang
323
324#endif // LLVM_CLANG_FORMAT_CONTINUATION_INDENTER_H