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