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