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