1 //===--- FormatToken.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 contains the declaration of the FormatToken, a wrapper
12 /// around Token with additional information related to formatting.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
17 #define LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
18 
19 #include "clang/Basic/OperatorPrecedence.h"
20 #include "clang/Format/Format.h"
21 #include "clang/Lex/Lexer.h"
22 #include <memory>
23 
24 namespace clang {
25 namespace format {
26 
27 enum TokenType {
28   TT_ArrayInitializerLSquare,
29   TT_ArraySubscriptLSquare,
30   TT_AttributeParen,
31   TT_BinaryOperator,
32   TT_BitFieldColon,
33   TT_BlockComment,
34   TT_CastRParen,
35   TT_ConditionalExpr,
36   TT_ConflictAlternative,
37   TT_ConflictEnd,
38   TT_ConflictStart,
39   TT_CtorInitializerColon,
40   TT_CtorInitializerComma,
41   TT_DesignatedInitializerPeriod,
42   TT_DictLiteral,
43   TT_FunctionLBrace,
44   TT_FunctionTypeLParen,
45   TT_ImplicitStringLiteral,
46   TT_InheritanceColon,
47   TT_InlineASMColon,
48   TT_LambdaLSquare,
49   TT_LineComment,
50   TT_ObjCBlockLBrace,
51   TT_ObjCBlockLParen,
52   TT_ObjCDecl,
53   TT_ObjCForIn,
54   TT_ObjCMethodExpr,
55   TT_ObjCMethodSpecifier,
56   TT_ObjCProperty,
57   TT_ObjCSelectorName,
58   TT_OverloadedOperator,
59   TT_OverloadedOperatorLParen,
60   TT_PointerOrReference,
61   TT_PureVirtualSpecifier,
62   TT_RangeBasedForLoopColon,
63   TT_StartOfName,
64   TT_TemplateCloser,
65   TT_TemplateOpener,
66   TT_TrailingAnnotation,
67   TT_TrailingReturnArrow,
68   TT_TrailingUnaryOperator,
69   TT_UnaryOperator,
70   TT_Unknown
71 };
72 
73 // Represents what type of block a set of braces open.
74 enum BraceBlockKind {
75   BK_Unknown,
76   BK_Block,
77   BK_BracedInit
78 };
79 
80 // The packing kind of a function's parameters.
81 enum ParameterPackingKind {
82   PPK_BinPacked,
83   PPK_OnePerLine,
84   PPK_Inconclusive
85 };
86 
87 enum FormatDecision {
88   FD_Unformatted,
89   FD_Continue,
90   FD_Break
91 };
92 
93 class TokenRole;
94 class AnnotatedLine;
95 
96 /// \brief A wrapper around a \c Token storing information about the
97 /// whitespace characters preceding it.
98 struct FormatToken {
99   FormatToken()
100       : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
101         ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false),
102         IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false),
103         BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0),
104         CanBreakBefore(false), ClosesTemplateDeclaration(false),
105         ParameterCount(0), PackingKind(PPK_Inconclusive), TotalLength(0),
106         UnbreakableTailLength(0), BindingStrength(0), NestingLevel(0),
107         SplitPenalty(0), LongestObjCSelectorName(0), FakeRParens(0),
108         StartsBinaryExpression(false), EndsBinaryExpression(false),
109         OperatorIndex(0), LastOperator(false),
110         PartOfMultiVariableDeclStmt(false), IsForEachMacro(false),
111         MatchingParen(NULL), Previous(NULL), Next(NULL),
112         Decision(FD_Unformatted), Finalized(false) {}
113 
114   /// \brief The \c Token.
115   Token Tok;
116 
117   /// \brief The number of newlines immediately before the \c Token.
118   ///
119   /// This can be used to determine what the user wrote in the original code
120   /// and thereby e.g. leave an empty line between two function definitions.
121   unsigned NewlinesBefore;
122 
123   /// \brief Whether there is at least one unescaped newline before the \c
124   /// Token.
125   bool HasUnescapedNewline;
126 
127   /// \brief The range of the whitespace immediately preceding the \c Token.
128   SourceRange WhitespaceRange;
129 
130   /// \brief The offset just past the last '\n' in this token's leading
131   /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
132   unsigned LastNewlineOffset;
133 
134   /// \brief The width of the non-whitespace parts of the token (or its first
135   /// line for multi-line tokens) in columns.
136   /// We need this to correctly measure number of columns a token spans.
137   unsigned ColumnWidth;
138 
139   /// \brief Contains the width in columns of the last line of a multi-line
140   /// token.
141   unsigned LastLineColumnWidth;
142 
143   /// \brief Whether the token text contains newlines (escaped or not).
144   bool IsMultiline;
145 
146   /// \brief Indicates that this is the first token.
147   bool IsFirst;
148 
149   /// \brief Whether there must be a line break before this token.
150   ///
151   /// This happens for example when a preprocessor directive ended directly
152   /// before the token.
153   bool MustBreakBefore;
154 
155   /// \brief Returns actual token start location without leading escaped
156   /// newlines and whitespace.
157   ///
158   /// This can be different to Tok.getLocation(), which includes leading escaped
159   /// newlines.
160   SourceLocation getStartOfNonWhitespace() const {
161     return WhitespaceRange.getEnd();
162   }
163 
164   /// \brief The raw text of the token.
165   ///
166   /// Contains the raw token text without leading whitespace and without leading
167   /// escaped newlines.
168   StringRef TokenText;
169 
170   /// \brief Set to \c true if this token is an unterminated literal.
171   bool IsUnterminatedLiteral;
172 
173   /// \brief Contains the kind of block if this token is a brace.
174   BraceBlockKind BlockKind;
175 
176   TokenType Type;
177 
178   /// \brief The number of spaces that should be inserted before this token.
179   unsigned SpacesRequiredBefore;
180 
181   /// \brief \c true if it is allowed to break before this token.
182   bool CanBreakBefore;
183 
184   bool ClosesTemplateDeclaration;
185 
186   /// \brief Number of parameters, if this is "(", "[" or "<".
187   ///
188   /// This is initialized to 1 as we don't need to distinguish functions with
189   /// 0 parameters from functions with 1 parameter. Thus, we can simply count
190   /// the number of commas.
191   unsigned ParameterCount;
192 
193   /// \brief A token can have a special role that can carry extra information
194   /// about the token's formatting.
195   std::unique_ptr<TokenRole> Role;
196 
197   /// \brief If this is an opening parenthesis, how are the parameters packed?
198   ParameterPackingKind PackingKind;
199 
200   /// \brief The total length of the unwrapped line up to and including this
201   /// token.
202   unsigned TotalLength;
203 
204   /// \brief The original 0-based column of this token, including expanded tabs.
205   /// The configured TabWidth is used as tab width.
206   unsigned OriginalColumn;
207 
208   /// \brief The length of following tokens until the next natural split point,
209   /// or the next token that can be broken.
210   unsigned UnbreakableTailLength;
211 
212   // FIXME: Come up with a 'cleaner' concept.
213   /// \brief The binding strength of a token. This is a combined value of
214   /// operator precedence, parenthesis nesting, etc.
215   unsigned BindingStrength;
216 
217   /// \brief The nesting level of this token, i.e. the number of surrounding (),
218   /// [], {} or <>.
219   unsigned NestingLevel;
220 
221   /// \brief Penalty for inserting a line break before this token.
222   unsigned SplitPenalty;
223 
224   /// \brief If this is the first ObjC selector name in an ObjC method
225   /// definition or call, this contains the length of the longest name.
226   ///
227   /// This being set to 0 means that the selectors should not be colon-aligned,
228   /// e.g. because several of them are block-type.
229   unsigned LongestObjCSelectorName;
230 
231   /// \brief Stores the number of required fake parentheses and the
232   /// corresponding operator precedence.
233   ///
234   /// If multiple fake parentheses start at a token, this vector stores them in
235   /// reverse order, i.e. inner fake parenthesis first.
236   SmallVector<prec::Level, 4> FakeLParens;
237   /// \brief Insert this many fake ) after this token for correct indentation.
238   unsigned FakeRParens;
239 
240   /// \brief \c true if this token starts a binary expression, i.e. has at least
241   /// one fake l_paren with a precedence greater than prec::Unknown.
242   bool StartsBinaryExpression;
243   /// \brief \c true if this token ends a binary expression.
244   bool EndsBinaryExpression;
245 
246   /// \brief Is this is an operator (or "."/"->") in a sequence of operators
247   /// with the same precedence, contains the 0-based operator index.
248   unsigned OperatorIndex;
249 
250   /// \brief Is this the last operator (or "."/"->") in a sequence of operators
251   /// with the same precedence?
252   bool LastOperator;
253 
254   /// \brief Is this token part of a \c DeclStmt defining multiple variables?
255   ///
256   /// Only set if \c Type == \c TT_StartOfName.
257   bool PartOfMultiVariableDeclStmt;
258 
259   /// \brief Is this a foreach macro?
260   bool IsForEachMacro;
261 
262   bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
263 
264   bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
265     return is(K1) || is(K2);
266   }
267 
268   bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
269     return is(K1) || is(K2) || is(K3);
270   }
271 
272   bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
273                tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
274                tok::TokenKind K6 = tok::NUM_TOKENS,
275                tok::TokenKind K7 = tok::NUM_TOKENS,
276                tok::TokenKind K8 = tok::NUM_TOKENS,
277                tok::TokenKind K9 = tok::NUM_TOKENS,
278                tok::TokenKind K10 = tok::NUM_TOKENS,
279                tok::TokenKind K11 = tok::NUM_TOKENS,
280                tok::TokenKind K12 = tok::NUM_TOKENS) const {
281     return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
282            is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
283   }
284 
285   bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
286   bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
287 
288   bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
289     return Tok.isObjCAtKeyword(Kind);
290   }
291 
292   bool isAccessSpecifier(bool ColonRequired = true) const {
293     return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
294            (!ColonRequired || (Next && Next->is(tok::colon)));
295   }
296 
297   /// \brief Determine whether the token is a simple-type-specifier.
298   bool isSimpleTypeSpecifier() const;
299 
300   bool isObjCAccessSpecifier() const {
301     return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
302                                    Next->isObjCAtKeyword(tok::objc_protected) ||
303                                    Next->isObjCAtKeyword(tok::objc_package) ||
304                                    Next->isObjCAtKeyword(tok::objc_private));
305   }
306 
307   /// \brief Returns whether \p Tok is ([{ or a template opening <.
308   bool opensScope() const {
309     return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
310            Type == TT_TemplateOpener;
311   }
312   /// \brief Returns whether \p Tok is )]} or a template closing >.
313   bool closesScope() const {
314     return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
315            Type == TT_TemplateCloser;
316   }
317 
318   /// \brief Returns \c true if this is a "." or "->" accessing a member.
319   bool isMemberAccess() const {
320     return isOneOf(tok::arrow, tok::period) &&
321            Type != TT_DesignatedInitializerPeriod;
322   }
323 
324   bool isUnaryOperator() const {
325     switch (Tok.getKind()) {
326     case tok::plus:
327     case tok::plusplus:
328     case tok::minus:
329     case tok::minusminus:
330     case tok::exclaim:
331     case tok::tilde:
332     case tok::kw_sizeof:
333     case tok::kw_alignof:
334       return true;
335     default:
336       return false;
337     }
338   }
339 
340   bool isBinaryOperator() const {
341     // Comma is a binary operator, but does not behave as such wrt. formatting.
342     return getPrecedence() > prec::Comma;
343   }
344 
345   bool isTrailingComment() const {
346     return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
347   }
348 
349   prec::Level getPrecedence() const {
350     return getBinOpPrecedence(Tok.getKind(), true, true);
351   }
352 
353   /// \brief Returns the previous token ignoring comments.
354   FormatToken *getPreviousNonComment() const {
355     FormatToken *Tok = Previous;
356     while (Tok != NULL && Tok->is(tok::comment))
357       Tok = Tok->Previous;
358     return Tok;
359   }
360 
361   /// \brief Returns the next token ignoring comments.
362   const FormatToken *getNextNonComment() const {
363     const FormatToken *Tok = Next;
364     while (Tok != NULL && Tok->is(tok::comment))
365       Tok = Tok->Next;
366     return Tok;
367   }
368 
369   /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
370   /// list that should be indented with a block indent.
371   bool opensBlockTypeList(const FormatStyle &Style) const {
372     return Type == TT_ArrayInitializerLSquare ||
373            (is(tok::l_brace) &&
374             (BlockKind == BK_Block || Type == TT_DictLiteral ||
375              !Style.Cpp11BracedListStyle));
376   }
377 
378   /// \brief Same as opensBlockTypeList, but for the closing token.
379   bool closesBlockTypeList(const FormatStyle &Style) const {
380     return MatchingParen && MatchingParen->opensBlockTypeList(Style);
381   }
382 
383   FormatToken *MatchingParen;
384 
385   FormatToken *Previous;
386   FormatToken *Next;
387 
388   SmallVector<AnnotatedLine *, 1> Children;
389 
390   /// \brief Stores the formatting decision for the token once it was made.
391   FormatDecision Decision;
392 
393   /// \brief If \c true, this token has been fully formatted (indented and
394   /// potentially re-formatted inside), and we do not allow further formatting
395   /// changes.
396   bool Finalized;
397 
398 private:
399   // Disallow copying.
400   FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
401   void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
402 };
403 
404 class ContinuationIndenter;
405 struct LineState;
406 
407 class TokenRole {
408 public:
409   TokenRole(const FormatStyle &Style) : Style(Style) {}
410   virtual ~TokenRole();
411 
412   /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
413   /// this function precomputes required information for formatting.
414   virtual void precomputeFormattingInfos(const FormatToken *Token);
415 
416   /// \brief Apply the special formatting that the given role demands.
417   ///
418   /// Assumes that the token having this role is already formatted.
419   ///
420   /// Continues formatting from \p State leaving indentation to \p Indenter and
421   /// returns the total penalty that this formatting incurs.
422   virtual unsigned formatFromToken(LineState &State,
423                                    ContinuationIndenter *Indenter,
424                                    bool DryRun) {
425     return 0;
426   }
427 
428   /// \brief Same as \c formatFromToken, but assumes that the first token has
429   /// already been set thereby deciding on the first line break.
430   virtual unsigned formatAfterToken(LineState &State,
431                                     ContinuationIndenter *Indenter,
432                                     bool DryRun) {
433     return 0;
434   }
435 
436   /// \brief Notifies the \c Role that a comma was found.
437   virtual void CommaFound(const FormatToken *Token) {}
438 
439 protected:
440   const FormatStyle &Style;
441 };
442 
443 class CommaSeparatedList : public TokenRole {
444 public:
445   CommaSeparatedList(const FormatStyle &Style)
446       : TokenRole(Style), HasNestedBracedList(false) {}
447 
448   void precomputeFormattingInfos(const FormatToken *Token) override;
449 
450   unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
451                             bool DryRun) override;
452 
453   unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
454                            bool DryRun) override;
455 
456   /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
457   void CommaFound(const FormatToken *Token) override { Commas.push_back(Token);}
458 
459 private:
460   /// \brief A struct that holds information on how to format a given list with
461   /// a specific number of columns.
462   struct ColumnFormat {
463     /// \brief The number of columns to use.
464     unsigned Columns;
465 
466     /// \brief The total width in characters.
467     unsigned TotalWidth;
468 
469     /// \brief The number of lines required for this format.
470     unsigned LineCount;
471 
472     /// \brief The size of each column in characters.
473     SmallVector<unsigned, 8> ColumnSizes;
474   };
475 
476   /// \brief Calculate which \c ColumnFormat fits best into
477   /// \p RemainingCharacters.
478   const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
479 
480   /// \brief The ordered \c FormatTokens making up the commas of this list.
481   SmallVector<const FormatToken *, 8> Commas;
482 
483   /// \brief The length of each of the list's items in characters including the
484   /// trailing comma.
485   SmallVector<unsigned, 8> ItemLengths;
486 
487   /// \brief Precomputed formats that can be used for this list.
488   SmallVector<ColumnFormat, 4> Formats;
489 
490   bool HasNestedBracedList;
491 };
492 
493 } // namespace format
494 } // namespace clang
495 
496 #endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
497