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