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