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