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