blob: 9a3c118561ede85619789580c0d2ecf1ada59937 [file] [log] [blame]
Daniel Jasperde0328a2013-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"
Alexander Kornienkoce9161a2014-01-02 15:13:14 +000021#include "llvm/Support/Regex.h"
Daniel Jasperde0328a2013-08-16 11:20:30 +000022
23namespace clang {
24class SourceManager;
25
26namespace format {
27
28class AnnotatedLine;
29struct FormatToken;
30struct LineState;
31struct ParenState;
32class WhitespaceManager;
33
34class ContinuationIndenter {
35public:
36 /// \brief Constructs a \c ContinuationIndenter to format \p Line starting in
37 /// column \p FirstIndent.
38 ContinuationIndenter(const FormatStyle &Style, SourceManager &SourceMgr,
Daniel Jasperde0328a2013-08-16 11:20:30 +000039 WhitespaceManager &Whitespaces,
40 encoding::Encoding Encoding,
41 bool BinPackInconclusiveFunctions);
42
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000043 /// \brief Get the initial state, i.e. the state after placing \p Line's
44 /// first token at \p FirstIndent.
Daniel Jasper1c5d9df2013-09-06 07:54:20 +000045 LineState getInitialState(unsigned FirstIndent, const AnnotatedLine *Line,
46 bool DryRun);
Daniel Jasperde0328a2013-08-16 11:20:30 +000047
48 // FIXME: canBreak and mustBreak aren't strictly indentation-related. Find a
49 // better home.
50 /// \brief Returns \c true, if a line break after \p State is allowed.
51 bool canBreak(const LineState &State);
52
53 /// \brief Returns \c true, if a line break after \p State is mandatory.
54 bool mustBreak(const LineState &State);
55
56 /// \brief Appends the next token to \p State and updates information
57 /// necessary for indentation.
58 ///
59 /// Puts the token on the current line if \p Newline is \c false and adds a
60 /// line break and necessary indentation otherwise.
61 ///
62 /// If \p DryRun is \c false, also creates and stores the required
63 /// \c Replacement.
Daniel Jasper8de9ed02013-08-22 15:00:41 +000064 unsigned addTokenToState(LineState &State, bool Newline, bool DryRun,
65 unsigned ExtraSpaces = 0);
Daniel Jasperde0328a2013-08-16 11:20:30 +000066
67 /// \brief Get the column limit for this line. This is the style's column
68 /// limit, potentially reduced for preprocessor definitions.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000069 unsigned getColumnLimit(const LineState &State) const;
Daniel Jasperde0328a2013-08-16 11:20:30 +000070
71private:
72 /// \brief Mark the next token as consumed in \p State and modify its stacks
73 /// accordingly.
74 unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline);
75
76 /// \brief If the current token sticks out over the end of the line, break
77 /// it if possible.
78 ///
79 /// \returns An extra penalty if a token was broken, otherwise 0.
80 ///
81 /// The returned penalty will cover the cost of the additional line breaks and
82 /// column limit violation in all lines except for the last one. The penalty
83 /// for the column limit violation in the last line (and in single line
84 /// tokens) is handled in \c addNextStateToQueue.
85 unsigned breakProtrudingToken(const FormatToken &Current, LineState &State,
86 bool DryRun);
87
Alexander Kornienko1f803962013-10-01 14:41:18 +000088 /// \brief Appends the next token to \p State and updates information
89 /// necessary for indentation.
90 ///
91 /// Puts the token on the current line.
92 ///
93 /// If \p DryRun is \c false, also creates and stores the required
94 /// \c Replacement.
Daniel Jasper48437ce2013-11-20 14:54:39 +000095 void addTokenOnCurrentLine(LineState &State, bool DryRun,
96 unsigned ExtraSpaces);
Alexander Kornienko1f803962013-10-01 14:41:18 +000097
98 /// \brief Appends the next token to \p State and updates information
99 /// necessary for indentation.
100 ///
101 /// Adds a line break and necessary indentation.
102 ///
103 /// If \p DryRun is \c false, also creates and stores the required
104 /// \c Replacement.
105 unsigned addTokenOnNewLine(LineState &State, bool DryRun);
106
Daniel Jasper9f388d02014-03-27 14:33:30 +0000107 /// \brief Calculate the new column for a line wrap before the next token.
108 unsigned getNewLineColumn(const LineState &State);
109
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000110 /// \brief Adds a multiline token to the \p State.
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000111 ///
112 /// \returns Extra penalty for the first line of the literal: last line is
113 /// handled in \c addNextStateToQueue, and the penalty for other lines doesn't
114 /// matter, as we don't change them.
Alexander Kornienko917f9e02013-09-10 12:29:48 +0000115 unsigned addMultilineToken(const FormatToken &Current, LineState &State);
Alexander Kornienkod7b837e2013-08-29 17:32:57 +0000116
Daniel Jasperf438cb72013-08-23 11:57:34 +0000117 /// \brief Returns \c true if the next token starts a multiline string
118 /// literal.
119 ///
120 /// This includes implicitly concatenated strings, strings that will be broken
121 /// by clang-format and string literals with escaped newlines.
Daniel Jasperc39b56f2013-12-16 07:23:08 +0000122 bool nextIsMultilineString(const LineState &State);
Daniel Jasperf438cb72013-08-23 11:57:34 +0000123
Daniel Jasperde0328a2013-08-16 11:20:30 +0000124 FormatStyle Style;
125 SourceManager &SourceMgr;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000126 WhitespaceManager &Whitespaces;
127 encoding::Encoding Encoding;
128 bool BinPackInconclusiveFunctions;
Alexander Kornienkoce9161a2014-01-02 15:13:14 +0000129 llvm::Regex CommentPragmasRegex;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000130};
131
132struct ParenState {
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000133 ParenState(unsigned Indent, unsigned IndentLevel, unsigned LastSpace,
134 bool AvoidBinPacking, bool NoLineBreak)
135 : Indent(Indent), IndentLevel(IndentLevel), LastSpace(LastSpace),
136 FirstLessLess(0), BreakBeforeClosingBrace(false), QuestionColumn(0),
Daniel Jasperde0328a2013-08-16 11:20:30 +0000137 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
138 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
139 StartOfArraySubscripts(0), NestedNameSpecifierContinuation(0),
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000140 CallContinuation(0), VariablePos(0), ContainsLineBreak(false),
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000141 ContainsUnwrappedBuilder(0), AlignColons(true),
142 ObjCSelectorNameFound(false) {}
Daniel Jasperde0328a2013-08-16 11:20:30 +0000143
144 /// \brief The position to which a specific parenthesis level needs to be
145 /// indented.
146 unsigned Indent;
147
Alexander Kornienkoe2e03872013-10-14 00:46:35 +0000148 /// \brief The number of indentation levels of the block.
149 unsigned IndentLevel;
150
Daniel Jasperde0328a2013-08-16 11:20:30 +0000151 /// \brief The position of the last space on each level.
152 ///
153 /// Used e.g. to break like:
154 /// functionCall(Parameter, otherCall(
155 /// OtherParameter));
156 unsigned LastSpace;
157
158 /// \brief The position the first "<<" operator encountered on each level.
159 ///
160 /// Used to align "<<" operators. 0 if no such operator has been encountered
161 /// on a level.
162 unsigned FirstLessLess;
163
164 /// \brief Whether a newline needs to be inserted before the block's closing
165 /// brace.
166 ///
167 /// We only want to insert a newline before the closing brace if there also
168 /// was a newline after the beginning left brace.
169 bool BreakBeforeClosingBrace;
170
171 /// \brief The column of a \c ? in a conditional expression;
172 unsigned QuestionColumn;
173
174 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
175 /// lines, in this context.
176 bool AvoidBinPacking;
177
178 /// \brief Break after the next comma (or all the commas in this context if
179 /// \c AvoidBinPacking is \c true).
180 bool BreakBeforeParameter;
181
182 /// \brief Line breaking in this context would break a formatting rule.
183 bool NoLineBreak;
184
185 /// \brief The position of the colon in an ObjC method declaration/call.
186 unsigned ColonPos;
187
188 /// \brief The start of the most recent function in a builder-type call.
189 unsigned StartOfFunctionCall;
190
191 /// \brief Contains the start of array subscript expressions, so that they
192 /// can be aligned.
193 unsigned StartOfArraySubscripts;
194
195 /// \brief If a nested name specifier was broken over multiple lines, this
196 /// contains the start column of the second line. Otherwise 0.
197 unsigned NestedNameSpecifierContinuation;
198
199 /// \brief If a call expression was broken over multiple lines, this
200 /// contains the start column of the second line. Otherwise 0.
201 unsigned CallContinuation;
202
203 /// \brief The column of the first variable name in a variable declaration.
204 ///
205 /// Used to align further variables if necessary.
206 unsigned VariablePos;
207
208 /// \brief \c true if this \c ParenState already contains a line-break.
209 ///
210 /// The first line break in a certain \c ParenState causes extra penalty so
211 /// that clang-format prefers similar breaks, i.e. breaks in the same
212 /// parenthesis.
213 bool ContainsLineBreak;
214
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000215 /// \brief \c true if this \c ParenState contains multiple segments of a
216 /// builder-type call on one line.
217 bool ContainsUnwrappedBuilder;
218
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000219 /// \brief \c true if the colons of the curren ObjC method expression should
220 /// be aligned.
221 ///
222 /// Not considered for memoization as it will always have the same value at
223 /// the same token.
224 bool AlignColons;
225
226 /// \brief \c true if at least one selector name was found in the current
227 /// ObjC method expression.
228 ///
229 /// Not considered for memoization as it will always have the same value at
230 /// the same token.
231 bool ObjCSelectorNameFound;
232
Daniel Jasperde0328a2013-08-16 11:20:30 +0000233 bool operator<(const ParenState &Other) const {
234 if (Indent != Other.Indent)
235 return Indent < Other.Indent;
236 if (LastSpace != Other.LastSpace)
237 return LastSpace < Other.LastSpace;
238 if (FirstLessLess != Other.FirstLessLess)
239 return FirstLessLess < Other.FirstLessLess;
240 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
241 return BreakBeforeClosingBrace;
242 if (QuestionColumn != Other.QuestionColumn)
243 return QuestionColumn < Other.QuestionColumn;
244 if (AvoidBinPacking != Other.AvoidBinPacking)
245 return AvoidBinPacking;
246 if (BreakBeforeParameter != Other.BreakBeforeParameter)
247 return BreakBeforeParameter;
248 if (NoLineBreak != Other.NoLineBreak)
249 return NoLineBreak;
250 if (ColonPos != Other.ColonPos)
251 return ColonPos < Other.ColonPos;
252 if (StartOfFunctionCall != Other.StartOfFunctionCall)
253 return StartOfFunctionCall < Other.StartOfFunctionCall;
254 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
255 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
256 if (CallContinuation != Other.CallContinuation)
257 return CallContinuation < Other.CallContinuation;
258 if (VariablePos != Other.VariablePos)
259 return VariablePos < Other.VariablePos;
260 if (ContainsLineBreak != Other.ContainsLineBreak)
261 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000262 if (ContainsUnwrappedBuilder != Other.ContainsUnwrappedBuilder)
263 return ContainsUnwrappedBuilder < Other.ContainsUnwrappedBuilder;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000264 return false;
265 }
266};
267
268/// \brief The current state when indenting a unwrapped line.
269///
270/// As the indenting tries different combinations this is copied by value.
271struct LineState {
272 /// \brief The number of used columns in the current line.
273 unsigned Column;
274
275 /// \brief The token that needs to be next formatted.
Manuel Klimek71814b42013-10-11 21:25:45 +0000276 FormatToken *NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000277
278 /// \brief \c true if this line contains a continued for-loop section.
279 bool LineContainsContinuedForLoopSection;
280
281 /// \brief The level of nesting inside (), [], <> and {}.
282 unsigned ParenLevel;
283
284 /// \brief The \c ParenLevel at the start of this line.
285 unsigned StartOfLineLevel;
286
287 /// \brief The lowest \c ParenLevel on the current line.
288 unsigned LowestLevelOnLine;
289
290 /// \brief The start column of the string literal, if we're in a string
291 /// literal sequence, 0 otherwise.
292 unsigned StartOfStringLiteral;
293
294 /// \brief A stack keeping track of properties applying to parenthesis
295 /// levels.
296 std::vector<ParenState> Stack;
297
298 /// \brief Ignore the stack of \c ParenStates for state comparison.
299 ///
300 /// In long and deeply nested unwrapped lines, the current algorithm can
301 /// be insufficient for finding the best formatting with a reasonable amount
302 /// of time and memory. Setting this flag will effectively lead to the
303 /// algorithm not analyzing some combinations. However, these combinations
304 /// rarely contain the optimal solution: In short, accepting a higher
305 /// penalty early would need to lead to different values in the \c
306 /// ParenState stack (in an otherwise identical state) and these different
307 /// values would need to lead to a significant amount of avoided penalty
308 /// later.
309 ///
310 /// FIXME: Come up with a better algorithm instead.
311 bool IgnoreStackForComparison;
312
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000313 /// \brief The indent of the first token.
314 unsigned FirstIndent;
315
316 /// \brief The line that is being formatted.
317 ///
318 /// Does not need to be considered for memoization because it doesn't change.
319 const AnnotatedLine *Line;
320
Daniel Jasperde0328a2013-08-16 11:20:30 +0000321 /// \brief Comparison operator to be able to used \c LineState in \c map.
322 bool operator<(const LineState &Other) const {
323 if (NextToken != Other.NextToken)
324 return NextToken < Other.NextToken;
325 if (Column != Other.Column)
326 return Column < Other.Column;
327 if (LineContainsContinuedForLoopSection !=
328 Other.LineContainsContinuedForLoopSection)
329 return LineContainsContinuedForLoopSection;
330 if (ParenLevel != Other.ParenLevel)
331 return ParenLevel < Other.ParenLevel;
332 if (StartOfLineLevel != Other.StartOfLineLevel)
333 return StartOfLineLevel < Other.StartOfLineLevel;
334 if (LowestLevelOnLine != Other.LowestLevelOnLine)
335 return LowestLevelOnLine < Other.LowestLevelOnLine;
336 if (StartOfStringLiteral != Other.StartOfStringLiteral)
337 return StartOfStringLiteral < Other.StartOfStringLiteral;
338 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
339 return false;
340 return Stack < Other.Stack;
341 }
342};
343
344} // end namespace format
345} // end namespace clang
346
347#endif // LLVM_CLANG_FORMAT_CONTINUATION_INDENTER_H