1 //===--- 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_LIB_FORMAT_CONTINUATIONINDENTER_H
17 #define LLVM_CLANG_LIB_FORMAT_CONTINUATIONINDENTER_H
18 
19 #include "Encoding.h"
20 #include "FormatToken.h"
21 #include "clang/Format/Format.h"
22 #include "llvm/Support/Regex.h"
23 #include <map>
24 #include <tuple>
25 
26 namespace clang {
27 class SourceManager;
28 
29 namespace format {
30 
31 class AnnotatedLine;
32 class BreakableToken;
33 struct FormatToken;
34 struct LineState;
35 struct ParenState;
36 struct RawStringFormatStyleManager;
37 class WhitespaceManager;
38 
39 struct RawStringFormatStyleManager {
40   llvm::StringMap<FormatStyle> DelimiterStyle;
41   llvm::StringMap<FormatStyle> EnclosingFunctionStyle;
42 
43   RawStringFormatStyleManager(const FormatStyle &CodeStyle);
44 
45   llvm::Optional<FormatStyle> getDelimiterStyle(StringRef Delimiter) const;
46 
47   llvm::Optional<FormatStyle>
48   getEnclosingFunctionStyle(StringRef EnclosingFunction) const;
49 };
50 
51 class ContinuationIndenter {
52 public:
53   /// \brief Constructs a \c ContinuationIndenter to format \p Line starting in
54   /// column \p FirstIndent.
55   ContinuationIndenter(const FormatStyle &Style,
56                        const AdditionalKeywords &Keywords,
57                        const SourceManager &SourceMgr,
58                        WhitespaceManager &Whitespaces,
59                        encoding::Encoding Encoding,
60                        bool BinPackInconclusiveFunctions);
61 
62   /// \brief Get the initial state, i.e. the state after placing \p Line's
63   /// first token at \p FirstIndent. When reformatting a fragment of code, as in
64   /// the case of formatting inside raw string literals, \p FirstStartColumn is
65   /// the column at which the state of the parent formatter is.
66   LineState getInitialState(unsigned FirstIndent, unsigned FirstStartColumn,
67                             const AnnotatedLine *Line, bool DryRun);
68 
69   // FIXME: canBreak and mustBreak aren't strictly indentation-related. Find a
70   // better home.
71   /// \brief Returns \c true, if a line break after \p State is allowed.
72   bool canBreak(const LineState &State);
73 
74   /// \brief Returns \c true, if a line break after \p State is mandatory.
75   bool mustBreak(const LineState &State);
76 
77   /// \brief Appends the next token to \p State and updates information
78   /// necessary for indentation.
79   ///
80   /// Puts the token on the current line if \p Newline is \c false and adds a
81   /// line break and necessary indentation otherwise.
82   ///
83   /// If \p DryRun is \c false, also creates and stores the required
84   /// \c Replacement.
85   unsigned addTokenToState(LineState &State, bool Newline, bool DryRun,
86                            unsigned ExtraSpaces = 0);
87 
88   /// \brief Get the column limit for this line. This is the style's column
89   /// limit, potentially reduced for preprocessor definitions.
90   unsigned getColumnLimit(const LineState &State) const;
91 
92 private:
93   /// \brief Mark the next token as consumed in \p State and modify its stacks
94   /// accordingly.
95   unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline);
96 
97   /// \brief Update 'State' according to the next token's fake left parentheses.
98   void moveStatePastFakeLParens(LineState &State, bool Newline);
99   /// \brief Update 'State' according to the next token's fake r_parens.
100   void moveStatePastFakeRParens(LineState &State);
101 
102   /// \brief Update 'State' according to the next token being one of "(<{[".
103   void moveStatePastScopeOpener(LineState &State, bool Newline);
104   /// \brief Update 'State' according to the next token being one of ")>}]".
105   void moveStatePastScopeCloser(LineState &State);
106   /// \brief Update 'State' with the next token opening a nested block.
107   void moveStateToNewBlock(LineState &State);
108 
109   /// \brief Reformats a raw string literal.
110   ///
111   /// \returns An extra penalty induced by reformatting the token.
112   unsigned reformatRawStringLiteral(const FormatToken &Current,
113                                     LineState &State,
114                                     const FormatStyle &RawStringStyle,
115                                     bool DryRun);
116 
117   /// \brief If the current token is at the end of the current line, handle
118   /// the transition to the next line.
119   unsigned handleEndOfLine(const FormatToken &Current, LineState &State,
120                            bool DryRun, bool AllowBreak);
121 
122   /// \brief If \p Current is a raw string that is configured to be reformatted,
123   /// return the style to be used.
124   llvm::Optional<FormatStyle> getRawStringStyle(const FormatToken &Current,
125                                                 const LineState &State);
126 
127   /// \brief If the current token sticks out over the end of the line, break
128   /// it if possible.
129   ///
130   /// \returns A pair (penalty, exceeded), where penalty is the extra penalty
131   /// when tokens are broken or lines exceed the column limit, and exceeded
132   /// indicates whether the algorithm purposefully left lines exceeding the
133   /// column limit.
134   ///
135   /// The returned penalty will cover the cost of the additional line breaks
136   /// and column limit violation in all lines except for the last one. The
137   /// penalty for the column limit violation in the last line (and in single
138   /// line tokens) is handled in \c addNextStateToQueue.
139   ///
140   /// \p Strict indicates whether reflowing is allowed to leave characters
141   /// protruding the column limit; if true, lines will be split strictly within
142   /// the column limit where possible; if false, words are allowed to protrude
143   /// over the column limit as long as the penalty is less than the penalty
144   /// of a break.
145   std::pair<unsigned, bool> breakProtrudingToken(const FormatToken &Current,
146                                                  LineState &State,
147                                                  bool AllowBreak, bool DryRun,
148                                                  bool Strict);
149 
150   /// \brief Returns the \c BreakableToken starting at \p Current, or nullptr
151   /// if the current token cannot be broken.
152   std::unique_ptr<BreakableToken>
153   createBreakableToken(const FormatToken &Current, LineState &State,
154                        bool AllowBreak);
155 
156   /// \brief Appends the next token to \p State and updates information
157   /// necessary for indentation.
158   ///
159   /// Puts the token on the current line.
160   ///
161   /// If \p DryRun is \c false, also creates and stores the required
162   /// \c Replacement.
163   void addTokenOnCurrentLine(LineState &State, bool DryRun,
164                              unsigned ExtraSpaces);
165 
166   /// \brief Appends the next token to \p State and updates information
167   /// necessary for indentation.
168   ///
169   /// Adds a line break and necessary indentation.
170   ///
171   /// If \p DryRun is \c false, also creates and stores the required
172   /// \c Replacement.
173   unsigned addTokenOnNewLine(LineState &State, bool DryRun);
174 
175   /// \brief Calculate the new column for a line wrap before the next token.
176   unsigned getNewLineColumn(const LineState &State);
177 
178   /// \brief Adds a multiline token to the \p State.
179   ///
180   /// \returns Extra penalty for the first line of the literal: last line is
181   /// handled in \c addNextStateToQueue, and the penalty for other lines doesn't
182   /// matter, as we don't change them.
183   unsigned addMultilineToken(const FormatToken &Current, LineState &State);
184 
185   /// \brief Returns \c true if the next token starts a multiline string
186   /// literal.
187   ///
188   /// This includes implicitly concatenated strings, strings that will be broken
189   /// by clang-format and string literals with escaped newlines.
190   bool nextIsMultilineString(const LineState &State);
191 
192   FormatStyle Style;
193   const AdditionalKeywords &Keywords;
194   const SourceManager &SourceMgr;
195   WhitespaceManager &Whitespaces;
196   encoding::Encoding Encoding;
197   bool BinPackInconclusiveFunctions;
198   llvm::Regex CommentPragmasRegex;
199   const RawStringFormatStyleManager RawStringFormats;
200 };
201 
202 struct ParenState {
203   ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
204              bool NoLineBreak)
205       : Indent(Indent), LastSpace(LastSpace), NestedBlockIndent(Indent),
206         BreakBeforeClosingBrace(false), AvoidBinPacking(AvoidBinPacking),
207         BreakBeforeParameter(false), NoLineBreak(NoLineBreak),
208         NoLineBreakInOperand(false), LastOperatorWrapped(true),
209         ContainsLineBreak(false), ContainsUnwrappedBuilder(false),
210         AlignColons(true), ObjCSelectorNameFound(false),
211         HasMultipleNestedBlocks(false), NestedBlockInlined(false),
212         IsInsideObjCArrayLiteral(false) {}
213 
214   /// \brief The position to which a specific parenthesis level needs to be
215   /// indented.
216   unsigned Indent;
217 
218   /// \brief The position of the last space on each level.
219   ///
220   /// Used e.g. to break like:
221   /// functionCall(Parameter, otherCall(
222   ///                             OtherParameter));
223   unsigned LastSpace;
224 
225   /// \brief If a block relative to this parenthesis level gets wrapped, indent
226   /// it this much.
227   unsigned NestedBlockIndent;
228 
229   /// \brief The position the first "<<" operator encountered on each level.
230   ///
231   /// Used to align "<<" operators. 0 if no such operator has been encountered
232   /// on a level.
233   unsigned FirstLessLess = 0;
234 
235   /// \brief The column of a \c ? in a conditional expression;
236   unsigned QuestionColumn = 0;
237 
238   /// \brief The position of the colon in an ObjC method declaration/call.
239   unsigned ColonPos = 0;
240 
241   /// \brief The start of the most recent function in a builder-type call.
242   unsigned StartOfFunctionCall = 0;
243 
244   /// \brief Contains the start of array subscript expressions, so that they
245   /// can be aligned.
246   unsigned StartOfArraySubscripts = 0;
247 
248   /// \brief If a nested name specifier was broken over multiple lines, this
249   /// contains the start column of the second line. Otherwise 0.
250   unsigned NestedNameSpecifierContinuation = 0;
251 
252   /// \brief If a call expression was broken over multiple lines, this
253   /// contains the start column of the second line. Otherwise 0.
254   unsigned CallContinuation = 0;
255 
256   /// \brief The column of the first variable name in a variable declaration.
257   ///
258   /// Used to align further variables if necessary.
259   unsigned VariablePos = 0;
260 
261   /// \brief Whether a newline needs to be inserted before the block's closing
262   /// brace.
263   ///
264   /// We only want to insert a newline before the closing brace if there also
265   /// was a newline after the beginning left brace.
266   bool BreakBeforeClosingBrace : 1;
267 
268   /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
269   /// lines, in this context.
270   bool AvoidBinPacking : 1;
271 
272   /// \brief Break after the next comma (or all the commas in this context if
273   /// \c AvoidBinPacking is \c true).
274   bool BreakBeforeParameter : 1;
275 
276   /// \brief Line breaking in this context would break a formatting rule.
277   bool NoLineBreak : 1;
278 
279   /// \brief Same as \c NoLineBreak, but is restricted until the end of the
280   /// operand (including the next ",").
281   bool NoLineBreakInOperand : 1;
282 
283   /// \brief True if the last binary operator on this level was wrapped to the
284   /// next line.
285   bool LastOperatorWrapped : 1;
286 
287   /// \brief \c true if this \c ParenState already contains a line-break.
288   ///
289   /// The first line break in a certain \c ParenState causes extra penalty so
290   /// that clang-format prefers similar breaks, i.e. breaks in the same
291   /// parenthesis.
292   bool ContainsLineBreak : 1;
293 
294   /// \brief \c true if this \c ParenState contains multiple segments of a
295   /// builder-type call on one line.
296   bool ContainsUnwrappedBuilder : 1;
297 
298   /// \brief \c true if the colons of the curren ObjC method expression should
299   /// be aligned.
300   ///
301   /// Not considered for memoization as it will always have the same value at
302   /// the same token.
303   bool AlignColons : 1;
304 
305   /// \brief \c true if at least one selector name was found in the current
306   /// ObjC method expression.
307   ///
308   /// Not considered for memoization as it will always have the same value at
309   /// the same token.
310   bool ObjCSelectorNameFound : 1;
311 
312   /// \brief \c true if there are multiple nested blocks inside these parens.
313   ///
314   /// Not considered for memoization as it will always have the same value at
315   /// the same token.
316   bool HasMultipleNestedBlocks : 1;
317 
318   /// \brief The start of a nested block (e.g. lambda introducer in C++ or
319   /// "function" in JavaScript) is not wrapped to a new line.
320   bool NestedBlockInlined : 1;
321 
322   /// \brief \c true if the current \c ParenState represents an Objective-C
323   /// array literal.
324   bool IsInsideObjCArrayLiteral : 1;
325 
326   bool operator<(const ParenState &Other) const {
327     if (Indent != Other.Indent)
328       return Indent < Other.Indent;
329     if (LastSpace != Other.LastSpace)
330       return LastSpace < Other.LastSpace;
331     if (NestedBlockIndent != Other.NestedBlockIndent)
332       return NestedBlockIndent < Other.NestedBlockIndent;
333     if (FirstLessLess != Other.FirstLessLess)
334       return FirstLessLess < Other.FirstLessLess;
335     if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
336       return BreakBeforeClosingBrace;
337     if (QuestionColumn != Other.QuestionColumn)
338       return QuestionColumn < Other.QuestionColumn;
339     if (AvoidBinPacking != Other.AvoidBinPacking)
340       return AvoidBinPacking;
341     if (BreakBeforeParameter != Other.BreakBeforeParameter)
342       return BreakBeforeParameter;
343     if (NoLineBreak != Other.NoLineBreak)
344       return NoLineBreak;
345     if (LastOperatorWrapped != Other.LastOperatorWrapped)
346       return LastOperatorWrapped;
347     if (ColonPos != Other.ColonPos)
348       return ColonPos < Other.ColonPos;
349     if (StartOfFunctionCall != Other.StartOfFunctionCall)
350       return StartOfFunctionCall < Other.StartOfFunctionCall;
351     if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
352       return StartOfArraySubscripts < Other.StartOfArraySubscripts;
353     if (CallContinuation != Other.CallContinuation)
354       return CallContinuation < Other.CallContinuation;
355     if (VariablePos != Other.VariablePos)
356       return VariablePos < Other.VariablePos;
357     if (ContainsLineBreak != Other.ContainsLineBreak)
358       return ContainsLineBreak;
359     if (ContainsUnwrappedBuilder != Other.ContainsUnwrappedBuilder)
360       return ContainsUnwrappedBuilder;
361     if (NestedBlockInlined != Other.NestedBlockInlined)
362       return NestedBlockInlined;
363     return false;
364   }
365 };
366 
367 /// \brief The current state when indenting a unwrapped line.
368 ///
369 /// As the indenting tries different combinations this is copied by value.
370 struct LineState {
371   /// \brief The number of used columns in the current line.
372   unsigned Column;
373 
374   /// \brief The token that needs to be next formatted.
375   FormatToken *NextToken;
376 
377   /// \brief \c true if this line contains a continued for-loop section.
378   bool LineContainsContinuedForLoopSection;
379 
380   /// \brief \c true if \p NextToken should not continue this line.
381   bool NoContinuation;
382 
383   /// \brief The \c NestingLevel at the start of this line.
384   unsigned StartOfLineLevel;
385 
386   /// \brief The lowest \c NestingLevel on the current line.
387   unsigned LowestLevelOnLine;
388 
389   /// \brief The start column of the string literal, if we're in a string
390   /// literal sequence, 0 otherwise.
391   unsigned StartOfStringLiteral;
392 
393   /// \brief A stack keeping track of properties applying to parenthesis
394   /// levels.
395   std::vector<ParenState> Stack;
396 
397   /// \brief Ignore the stack of \c ParenStates for state comparison.
398   ///
399   /// In long and deeply nested unwrapped lines, the current algorithm can
400   /// be insufficient for finding the best formatting with a reasonable amount
401   /// of time and memory. Setting this flag will effectively lead to the
402   /// algorithm not analyzing some combinations. However, these combinations
403   /// rarely contain the optimal solution: In short, accepting a higher
404   /// penalty early would need to lead to different values in the \c
405   /// ParenState stack (in an otherwise identical state) and these different
406   /// values would need to lead to a significant amount of avoided penalty
407   /// later.
408   ///
409   /// FIXME: Come up with a better algorithm instead.
410   bool IgnoreStackForComparison;
411 
412   /// \brief The indent of the first token.
413   unsigned FirstIndent;
414 
415   /// \brief The line that is being formatted.
416   ///
417   /// Does not need to be considered for memoization because it doesn't change.
418   const AnnotatedLine *Line;
419 
420   /// \brief Comparison operator to be able to used \c LineState in \c map.
421   bool operator<(const LineState &Other) const {
422     if (NextToken != Other.NextToken)
423       return NextToken < Other.NextToken;
424     if (Column != Other.Column)
425       return Column < Other.Column;
426     if (LineContainsContinuedForLoopSection !=
427         Other.LineContainsContinuedForLoopSection)
428       return LineContainsContinuedForLoopSection;
429     if (NoContinuation != Other.NoContinuation)
430       return NoContinuation;
431     if (StartOfLineLevel != Other.StartOfLineLevel)
432       return StartOfLineLevel < Other.StartOfLineLevel;
433     if (LowestLevelOnLine != Other.LowestLevelOnLine)
434       return LowestLevelOnLine < Other.LowestLevelOnLine;
435     if (StartOfStringLiteral != Other.StartOfStringLiteral)
436       return StartOfStringLiteral < Other.StartOfStringLiteral;
437     if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
438       return false;
439     return Stack < Other.Stack;
440   }
441 };
442 
443 } // end namespace format
444 } // end namespace clang
445 
446 #endif
447