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