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