blob: ef698a7a5205ea29de4b5d9cf638bc14673b4c4f [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 Kornienkodcc0c5b2013-08-29 17:32:57 +000087 /// \brief Adds a multiline string literal to the \p State.
88 ///
89 /// \returns Extra penalty for the first line of the literal: last line is
90 /// handled in \c addNextStateToQueue, and the penalty for other lines doesn't
91 /// matter, as we don't change them.
92 unsigned addMultilineStringLiteral(const FormatToken &Current,
93 LineState &State);
94
Daniel Jasper4df1ff92013-08-23 11:57:34 +000095 /// \brief Returns \c true if the next token starts a multiline string
96 /// literal.
97 ///
98 /// This includes implicitly concatenated strings, strings that will be broken
99 /// by clang-format and string literals with escaped newlines.
100 bool NextIsMultilineString(const LineState &State);
101
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000102 FormatStyle Style;
103 SourceManager &SourceMgr;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000104 WhitespaceManager &Whitespaces;
105 encoding::Encoding Encoding;
106 bool BinPackInconclusiveFunctions;
107};
108
109struct ParenState {
110 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
111 bool NoLineBreak)
112 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
113 BreakBeforeClosingBrace(false), QuestionColumn(0),
114 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
115 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
116 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000117 CallContinuation(0), VariablePos(0), ContainsLineBreak(false),
118 ContainsUnwrappedBuilder(0) {}
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000119
120 /// \brief The position to which a specific parenthesis level needs to be
121 /// indented.
122 unsigned Indent;
123
124 /// \brief The position of the last space on each level.
125 ///
126 /// Used e.g. to break like:
127 /// functionCall(Parameter, otherCall(
128 /// OtherParameter));
129 unsigned LastSpace;
130
131 /// \brief The position the first "<<" operator encountered on each level.
132 ///
133 /// Used to align "<<" operators. 0 if no such operator has been encountered
134 /// on a level.
135 unsigned FirstLessLess;
136
137 /// \brief Whether a newline needs to be inserted before the block's closing
138 /// brace.
139 ///
140 /// We only want to insert a newline before the closing brace if there also
141 /// was a newline after the beginning left brace.
142 bool BreakBeforeClosingBrace;
143
144 /// \brief The column of a \c ? in a conditional expression;
145 unsigned QuestionColumn;
146
147 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
148 /// lines, in this context.
149 bool AvoidBinPacking;
150
151 /// \brief Break after the next comma (or all the commas in this context if
152 /// \c AvoidBinPacking is \c true).
153 bool BreakBeforeParameter;
154
155 /// \brief Line breaking in this context would break a formatting rule.
156 bool NoLineBreak;
157
158 /// \brief The position of the colon in an ObjC method declaration/call.
159 unsigned ColonPos;
160
161 /// \brief The start of the most recent function in a builder-type call.
162 unsigned StartOfFunctionCall;
163
164 /// \brief Contains the start of array subscript expressions, so that they
165 /// can be aligned.
166 unsigned StartOfArraySubscripts;
167
168 /// \brief If a nested name specifier was broken over multiple lines, this
169 /// contains the start column of the second line. Otherwise 0.
170 unsigned NestedNameSpecifierContinuation;
171
172 /// \brief If a call expression was broken over multiple lines, this
173 /// contains the start column of the second line. Otherwise 0.
174 unsigned CallContinuation;
175
176 /// \brief The column of the first variable name in a variable declaration.
177 ///
178 /// Used to align further variables if necessary.
179 unsigned VariablePos;
180
181 /// \brief \c true if this \c ParenState already contains a line-break.
182 ///
183 /// The first line break in a certain \c ParenState causes extra penalty so
184 /// that clang-format prefers similar breaks, i.e. breaks in the same
185 /// parenthesis.
186 bool ContainsLineBreak;
187
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000188 /// \brief \c true if this \c ParenState contains multiple segments of a
189 /// builder-type call on one line.
190 bool ContainsUnwrappedBuilder;
191
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000192 bool operator<(const ParenState &Other) const {
193 if (Indent != Other.Indent)
194 return Indent < Other.Indent;
195 if (LastSpace != Other.LastSpace)
196 return LastSpace < Other.LastSpace;
197 if (FirstLessLess != Other.FirstLessLess)
198 return FirstLessLess < Other.FirstLessLess;
199 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
200 return BreakBeforeClosingBrace;
201 if (QuestionColumn != Other.QuestionColumn)
202 return QuestionColumn < Other.QuestionColumn;
203 if (AvoidBinPacking != Other.AvoidBinPacking)
204 return AvoidBinPacking;
205 if (BreakBeforeParameter != Other.BreakBeforeParameter)
206 return BreakBeforeParameter;
207 if (NoLineBreak != Other.NoLineBreak)
208 return NoLineBreak;
209 if (ColonPos != Other.ColonPos)
210 return ColonPos < Other.ColonPos;
211 if (StartOfFunctionCall != Other.StartOfFunctionCall)
212 return StartOfFunctionCall < Other.StartOfFunctionCall;
213 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
214 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
215 if (CallContinuation != Other.CallContinuation)
216 return CallContinuation < Other.CallContinuation;
217 if (VariablePos != Other.VariablePos)
218 return VariablePos < Other.VariablePos;
219 if (ContainsLineBreak != Other.ContainsLineBreak)
220 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasperd3fef0f2013-08-27 14:24:43 +0000221 if (ContainsUnwrappedBuilder != Other.ContainsUnwrappedBuilder)
222 return ContainsUnwrappedBuilder < Other.ContainsUnwrappedBuilder;
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000223 return false;
224 }
225};
226
227/// \brief The current state when indenting a unwrapped line.
228///
229/// As the indenting tries different combinations this is copied by value.
230struct LineState {
231 /// \brief The number of used columns in the current line.
232 unsigned Column;
233
234 /// \brief The token that needs to be next formatted.
235 const FormatToken *NextToken;
236
237 /// \brief \c true if this line contains a continued for-loop section.
238 bool LineContainsContinuedForLoopSection;
239
240 /// \brief The level of nesting inside (), [], <> and {}.
241 unsigned ParenLevel;
242
243 /// \brief The \c ParenLevel at the start of this line.
244 unsigned StartOfLineLevel;
245
246 /// \brief The lowest \c ParenLevel on the current line.
247 unsigned LowestLevelOnLine;
248
249 /// \brief The start column of the string literal, if we're in a string
250 /// literal sequence, 0 otherwise.
251 unsigned StartOfStringLiteral;
252
253 /// \brief A stack keeping track of properties applying to parenthesis
254 /// levels.
255 std::vector<ParenState> Stack;
256
257 /// \brief Ignore the stack of \c ParenStates for state comparison.
258 ///
259 /// In long and deeply nested unwrapped lines, the current algorithm can
260 /// be insufficient for finding the best formatting with a reasonable amount
261 /// of time and memory. Setting this flag will effectively lead to the
262 /// algorithm not analyzing some combinations. However, these combinations
263 /// rarely contain the optimal solution: In short, accepting a higher
264 /// penalty early would need to lead to different values in the \c
265 /// ParenState stack (in an otherwise identical state) and these different
266 /// values would need to lead to a significant amount of avoided penalty
267 /// later.
268 ///
269 /// FIXME: Come up with a better algorithm instead.
270 bool IgnoreStackForComparison;
271
Daniel Jasper567dcf92013-09-05 09:29:45 +0000272 /// \brief The indent of the first token.
273 unsigned FirstIndent;
274
275 /// \brief The line that is being formatted.
276 ///
277 /// Does not need to be considered for memoization because it doesn't change.
278 const AnnotatedLine *Line;
279
Daniel Jasper6b2afe42013-08-16 11:20:30 +0000280 /// \brief Comparison operator to be able to used \c LineState in \c map.
281 bool operator<(const LineState &Other) const {
282 if (NextToken != Other.NextToken)
283 return NextToken < Other.NextToken;
284 if (Column != Other.Column)
285 return Column < Other.Column;
286 if (LineContainsContinuedForLoopSection !=
287 Other.LineContainsContinuedForLoopSection)
288 return LineContainsContinuedForLoopSection;
289 if (ParenLevel != Other.ParenLevel)
290 return ParenLevel < Other.ParenLevel;
291 if (StartOfLineLevel != Other.StartOfLineLevel)
292 return StartOfLineLevel < Other.StartOfLineLevel;
293 if (LowestLevelOnLine != Other.LowestLevelOnLine)
294 return LowestLevelOnLine < Other.LowestLevelOnLine;
295 if (StartOfStringLiteral != Other.StartOfStringLiteral)
296 return StartOfStringLiteral < Other.StartOfStringLiteral;
297 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
298 return false;
299 return Stack < Other.Stack;
300 }
301};
302
303} // end namespace format
304} // end namespace clang
305
306#endif // LLVM_CLANG_FORMAT_CONTINUATION_INDENTER_H