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