blob: 04e31e68b1de7b1293cd9df6af68b21a63b73cc8 [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),
Daniel Jasper3ae6f5a2014-04-09 12:08:39 +0000142 ObjCSelectorNameFound(false), LambdasFound(0) {}
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 Jasper3ae6f5a2014-04-09 12:08:39 +0000233 /// \brief Counts the number of lambda introducers found on this level.
234 ///
235 /// Not considered for memoization as it will always have the same value at
236 /// the same token.
237 unsigned LambdasFound;
238
Daniel Jasperde0328a2013-08-16 11:20:30 +0000239 bool operator<(const ParenState &Other) const {
240 if (Indent != Other.Indent)
241 return Indent < Other.Indent;
242 if (LastSpace != Other.LastSpace)
243 return LastSpace < Other.LastSpace;
244 if (FirstLessLess != Other.FirstLessLess)
245 return FirstLessLess < Other.FirstLessLess;
246 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
247 return BreakBeforeClosingBrace;
248 if (QuestionColumn != Other.QuestionColumn)
249 return QuestionColumn < Other.QuestionColumn;
250 if (AvoidBinPacking != Other.AvoidBinPacking)
251 return AvoidBinPacking;
252 if (BreakBeforeParameter != Other.BreakBeforeParameter)
253 return BreakBeforeParameter;
254 if (NoLineBreak != Other.NoLineBreak)
255 return NoLineBreak;
256 if (ColonPos != Other.ColonPos)
257 return ColonPos < Other.ColonPos;
258 if (StartOfFunctionCall != Other.StartOfFunctionCall)
259 return StartOfFunctionCall < Other.StartOfFunctionCall;
260 if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
261 return StartOfArraySubscripts < Other.StartOfArraySubscripts;
262 if (CallContinuation != Other.CallContinuation)
263 return CallContinuation < Other.CallContinuation;
264 if (VariablePos != Other.VariablePos)
265 return VariablePos < Other.VariablePos;
266 if (ContainsLineBreak != Other.ContainsLineBreak)
267 return ContainsLineBreak < Other.ContainsLineBreak;
Daniel Jasper4c6e0052013-08-27 14:24:43 +0000268 if (ContainsUnwrappedBuilder != Other.ContainsUnwrappedBuilder)
269 return ContainsUnwrappedBuilder < Other.ContainsUnwrappedBuilder;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000270 return false;
271 }
272};
273
274/// \brief The current state when indenting a unwrapped line.
275///
276/// As the indenting tries different combinations this is copied by value.
277struct LineState {
278 /// \brief The number of used columns in the current line.
279 unsigned Column;
280
281 /// \brief The token that needs to be next formatted.
Manuel Klimek71814b42013-10-11 21:25:45 +0000282 FormatToken *NextToken;
Daniel Jasperde0328a2013-08-16 11:20:30 +0000283
284 /// \brief \c true if this line contains a continued for-loop section.
285 bool LineContainsContinuedForLoopSection;
286
287 /// \brief The level of nesting inside (), [], <> and {}.
288 unsigned ParenLevel;
289
290 /// \brief The \c ParenLevel at the start of this line.
291 unsigned StartOfLineLevel;
292
293 /// \brief The lowest \c ParenLevel on the current line.
294 unsigned LowestLevelOnLine;
295
296 /// \brief The start column of the string literal, if we're in a string
297 /// literal sequence, 0 otherwise.
298 unsigned StartOfStringLiteral;
299
300 /// \brief A stack keeping track of properties applying to parenthesis
301 /// levels.
302 std::vector<ParenState> Stack;
303
304 /// \brief Ignore the stack of \c ParenStates for state comparison.
305 ///
306 /// In long and deeply nested unwrapped lines, the current algorithm can
307 /// be insufficient for finding the best formatting with a reasonable amount
308 /// of time and memory. Setting this flag will effectively lead to the
309 /// algorithm not analyzing some combinations. However, these combinations
310 /// rarely contain the optimal solution: In short, accepting a higher
311 /// penalty early would need to lead to different values in the \c
312 /// ParenState stack (in an otherwise identical state) and these different
313 /// values would need to lead to a significant amount of avoided penalty
314 /// later.
315 ///
316 /// FIXME: Come up with a better algorithm instead.
317 bool IgnoreStackForComparison;
318
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000319 /// \brief The indent of the first token.
320 unsigned FirstIndent;
321
322 /// \brief The line that is being formatted.
323 ///
324 /// Does not need to be considered for memoization because it doesn't change.
325 const AnnotatedLine *Line;
326
Daniel Jasperde0328a2013-08-16 11:20:30 +0000327 /// \brief Comparison operator to be able to used \c LineState in \c map.
328 bool operator<(const LineState &Other) const {
329 if (NextToken != Other.NextToken)
330 return NextToken < Other.NextToken;
331 if (Column != Other.Column)
332 return Column < Other.Column;
333 if (LineContainsContinuedForLoopSection !=
334 Other.LineContainsContinuedForLoopSection)
335 return LineContainsContinuedForLoopSection;
336 if (ParenLevel != Other.ParenLevel)
337 return ParenLevel < Other.ParenLevel;
338 if (StartOfLineLevel != Other.StartOfLineLevel)
339 return StartOfLineLevel < Other.StartOfLineLevel;
340 if (LowestLevelOnLine != Other.LowestLevelOnLine)
341 return LowestLevelOnLine < Other.LowestLevelOnLine;
342 if (StartOfStringLiteral != Other.StartOfStringLiteral)
343 return StartOfStringLiteral < Other.StartOfStringLiteral;
344 if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
345 return false;
346 return Stack < Other.Stack;
347 }
348};
349
350} // end namespace format
351} // end namespace clang
352
353#endif // LLVM_CLANG_FORMAT_CONTINUATION_INDENTER_H