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