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 #define LIST_TOKEN_TYPES \
29   TYPE(ArrayInitializerLSquare) \
30   TYPE(ArraySubscriptLSquare) \
31   TYPE(AttributeParen) \
32   TYPE(BinaryOperator) \
33   TYPE(BitFieldColon) \
34   TYPE(BlockComment) \
35   TYPE(CastRParen) \
36   TYPE(ConditionalExpr) \
37   TYPE(ConflictAlternative) \
38   TYPE(ConflictEnd) \
39   TYPE(ConflictStart) \
40   TYPE(CtorInitializerColon) \
41   TYPE(CtorInitializerComma) \
42   TYPE(DesignatedInitializerPeriod) \
43   TYPE(DictLiteral) \
44   TYPE(ForEachMacro) \
45   TYPE(FunctionAnnotationRParen) \
46   TYPE(FunctionDeclarationName) \
47   TYPE(FunctionLBrace) \
48   TYPE(FunctionTypeLParen) \
49   TYPE(ImplicitStringLiteral) \
50   TYPE(InheritanceColon) \
51   TYPE(InlineASMBrace) \
52   TYPE(InlineASMColon) \
53   TYPE(JavaAnnotation) \
54   TYPE(JsComputedPropertyName) \
55   TYPE(JsFatArrow) \
56   TYPE(JsTypeColon) \
57   TYPE(JsTypeOperator) \
58   TYPE(JsTypeOptionalQuestion) \
59   TYPE(LambdaArrow) \
60   TYPE(LambdaLSquare) \
61   TYPE(LeadingJavaAnnotation) \
62   TYPE(LineComment) \
63   TYPE(MacroBlockBegin) \
64   TYPE(MacroBlockEnd) \
65   TYPE(ObjCBlockLBrace) \
66   TYPE(ObjCBlockLParen) \
67   TYPE(ObjCDecl) \
68   TYPE(ObjCForIn) \
69   TYPE(ObjCMethodExpr) \
70   TYPE(ObjCMethodSpecifier) \
71   TYPE(ObjCProperty) \
72   TYPE(ObjCStringLiteral) \
73   TYPE(OverloadedOperator) \
74   TYPE(OverloadedOperatorLParen) \
75   TYPE(PointerOrReference) \
76   TYPE(PureVirtualSpecifier) \
77   TYPE(RangeBasedForLoopColon) \
78   TYPE(RegexLiteral) \
79   TYPE(SelectorName) \
80   TYPE(StartOfName) \
81   TYPE(TemplateCloser) \
82   TYPE(TemplateOpener) \
83   TYPE(TemplateString) \
84   TYPE(TrailingAnnotation) \
85   TYPE(TrailingReturnArrow) \
86   TYPE(TrailingUnaryOperator) \
87   TYPE(UnaryOperator) \
88   TYPE(Unknown)
89 
90 enum TokenType {
91 #define TYPE(X) TT_##X,
92 LIST_TOKEN_TYPES
93 #undef TYPE
94   NUM_TOKEN_TYPES
95 };
96 
97 /// \brief Determines the name of a token type.
98 const char *getTokenTypeName(TokenType Type);
99 
100 // Represents what type of block a set of braces open.
101 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
102 
103 // The packing kind of a function's parameters.
104 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
105 
106 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
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 If this is an operator (or "."/"->") in a sequence of operators
253   /// with the same precedence, points to the next operator.
254   FormatToken *NextOperator = nullptr;
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   bool is(tok::PPKeywordKind Kind) const {
288     return Tok.getIdentifierInfo() &&
289            Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
290   }
291   template <typename A, typename B> bool isOneOf(A K1, B K2) const {
292     return is(K1) || is(K2);
293   }
294   template <typename A, typename B, typename... Ts>
295   bool isOneOf(A K1, B K2, Ts... Ks) const {
296     return is(K1) || isOneOf(K2, Ks...);
297   }
298   template <typename T> bool isNot(T Kind) const { return !is(Kind); }
299 
300   bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
301 
302   bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
303     return Tok.isObjCAtKeyword(Kind);
304   }
305 
306   bool isAccessSpecifier(bool ColonRequired = true) const {
307     return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
308            (!ColonRequired || (Next && Next->is(tok::colon)));
309   }
310 
311   /// \brief Determine whether the token is a simple-type-specifier.
312   bool isSimpleTypeSpecifier() const;
313 
314   bool isObjCAccessSpecifier() const {
315     return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
316                                    Next->isObjCAtKeyword(tok::objc_protected) ||
317                                    Next->isObjCAtKeyword(tok::objc_package) ||
318                                    Next->isObjCAtKeyword(tok::objc_private));
319   }
320 
321   /// \brief Returns whether \p Tok is ([{ or a template opening <.
322   bool opensScope() const {
323     return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
324                    TT_TemplateOpener);
325   }
326   /// \brief Returns whether \p Tok is )]} or a template closing >.
327   bool closesScope() const {
328     return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
329                    TT_TemplateCloser);
330   }
331 
332   /// \brief Returns \c true if this is a "." or "->" accessing a member.
333   bool isMemberAccess() const {
334     return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
335            !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
336                     TT_LambdaArrow);
337   }
338 
339   bool isUnaryOperator() const {
340     switch (Tok.getKind()) {
341     case tok::plus:
342     case tok::plusplus:
343     case tok::minus:
344     case tok::minusminus:
345     case tok::exclaim:
346     case tok::tilde:
347     case tok::kw_sizeof:
348     case tok::kw_alignof:
349       return true;
350     default:
351       return false;
352     }
353   }
354 
355   bool isBinaryOperator() const {
356     // Comma is a binary operator, but does not behave as such wrt. formatting.
357     return getPrecedence() > prec::Comma;
358   }
359 
360   bool isTrailingComment() const {
361     return is(tok::comment) &&
362            (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
363   }
364 
365   /// \brief Returns \c true if this is a keyword that can be used
366   /// like a function call (e.g. sizeof, typeid, ...).
367   bool isFunctionLikeKeyword() const {
368     switch (Tok.getKind()) {
369     case tok::kw_throw:
370     case tok::kw_typeid:
371     case tok::kw_return:
372     case tok::kw_sizeof:
373     case tok::kw_alignof:
374     case tok::kw_alignas:
375     case tok::kw_decltype:
376     case tok::kw_noexcept:
377     case tok::kw_static_assert:
378     case tok::kw___attribute:
379       return true;
380     default:
381       return false;
382     }
383   }
384 
385   /// \brief Returns actual token start location without leading escaped
386   /// newlines and whitespace.
387   ///
388   /// This can be different to Tok.getLocation(), which includes leading escaped
389   /// newlines.
390   SourceLocation getStartOfNonWhitespace() const {
391     return WhitespaceRange.getEnd();
392   }
393 
394   prec::Level getPrecedence() const {
395     return getBinOpPrecedence(Tok.getKind(), true, true);
396   }
397 
398   /// \brief Returns the previous token ignoring comments.
399   FormatToken *getPreviousNonComment() const {
400     FormatToken *Tok = Previous;
401     while (Tok && Tok->is(tok::comment))
402       Tok = Tok->Previous;
403     return Tok;
404   }
405 
406   /// \brief Returns the next token ignoring comments.
407   const FormatToken *getNextNonComment() const {
408     const FormatToken *Tok = Next;
409     while (Tok && Tok->is(tok::comment))
410       Tok = Tok->Next;
411     return Tok;
412   }
413 
414   /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
415   /// list that should be indented with a block indent.
416   bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
417     return is(TT_ArrayInitializerLSquare) ||
418            (is(tok::l_brace) &&
419             (BlockKind == BK_Block || is(TT_DictLiteral) ||
420              (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
421   }
422 
423   /// \brief Same as opensBlockOrBlockTypeList, but for the closing token.
424   bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
425     return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
426   }
427 
428 private:
429   // Disallow copying.
430   FormatToken(const FormatToken &) = delete;
431   void operator=(const FormatToken &) = delete;
432 };
433 
434 class ContinuationIndenter;
435 struct LineState;
436 
437 class TokenRole {
438 public:
439   TokenRole(const FormatStyle &Style) : Style(Style) {}
440   virtual ~TokenRole();
441 
442   /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
443   /// this function precomputes required information for formatting.
444   virtual void precomputeFormattingInfos(const FormatToken *Token);
445 
446   /// \brief Apply the special formatting that the given role demands.
447   ///
448   /// Assumes that the token having this role is already formatted.
449   ///
450   /// Continues formatting from \p State leaving indentation to \p Indenter and
451   /// returns the total penalty that this formatting incurs.
452   virtual unsigned formatFromToken(LineState &State,
453                                    ContinuationIndenter *Indenter,
454                                    bool DryRun) {
455     return 0;
456   }
457 
458   /// \brief Same as \c formatFromToken, but assumes that the first token has
459   /// already been set thereby deciding on the first line break.
460   virtual unsigned formatAfterToken(LineState &State,
461                                     ContinuationIndenter *Indenter,
462                                     bool DryRun) {
463     return 0;
464   }
465 
466   /// \brief Notifies the \c Role that a comma was found.
467   virtual void CommaFound(const FormatToken *Token) {}
468 
469 protected:
470   const FormatStyle &Style;
471 };
472 
473 class CommaSeparatedList : public TokenRole {
474 public:
475   CommaSeparatedList(const FormatStyle &Style)
476       : TokenRole(Style), HasNestedBracedList(false) {}
477 
478   void precomputeFormattingInfos(const FormatToken *Token) override;
479 
480   unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
481                             bool DryRun) override;
482 
483   unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
484                            bool DryRun) override;
485 
486   /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
487   void CommaFound(const FormatToken *Token) override {
488     Commas.push_back(Token);
489   }
490 
491 private:
492   /// \brief A struct that holds information on how to format a given list with
493   /// a specific number of columns.
494   struct ColumnFormat {
495     /// \brief The number of columns to use.
496     unsigned Columns;
497 
498     /// \brief The total width in characters.
499     unsigned TotalWidth;
500 
501     /// \brief The number of lines required for this format.
502     unsigned LineCount;
503 
504     /// \brief The size of each column in characters.
505     SmallVector<unsigned, 8> ColumnSizes;
506   };
507 
508   /// \brief Calculate which \c ColumnFormat fits best into
509   /// \p RemainingCharacters.
510   const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
511 
512   /// \brief The ordered \c FormatTokens making up the commas of this list.
513   SmallVector<const FormatToken *, 8> Commas;
514 
515   /// \brief The length of each of the list's items in characters including the
516   /// trailing comma.
517   SmallVector<unsigned, 8> ItemLengths;
518 
519   /// \brief Precomputed formats that can be used for this list.
520   SmallVector<ColumnFormat, 4> Formats;
521 
522   bool HasNestedBracedList;
523 };
524 
525 /// \brief Encapsulates keywords that are context sensitive or for languages not
526 /// properly supported by Clang's lexer.
527 struct AdditionalKeywords {
528   AdditionalKeywords(IdentifierTable &IdentTable) {
529     kw_final = &IdentTable.get("final");
530     kw_override = &IdentTable.get("override");
531     kw_in = &IdentTable.get("in");
532     kw_of = &IdentTable.get("of");
533     kw_CF_ENUM = &IdentTable.get("CF_ENUM");
534     kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
535     kw_NS_ENUM = &IdentTable.get("NS_ENUM");
536     kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
537 
538     kw_finally = &IdentTable.get("finally");
539     kw_function = &IdentTable.get("function");
540     kw_from = &IdentTable.get("from");
541     kw_import = &IdentTable.get("import");
542     kw_is = &IdentTable.get("is");
543     kw_let = &IdentTable.get("let");
544     kw_var = &IdentTable.get("var");
545 
546     kw_abstract = &IdentTable.get("abstract");
547     kw_assert = &IdentTable.get("assert");
548     kw_extends = &IdentTable.get("extends");
549     kw_implements = &IdentTable.get("implements");
550     kw_instanceof = &IdentTable.get("instanceof");
551     kw_interface = &IdentTable.get("interface");
552     kw_native = &IdentTable.get("native");
553     kw_package = &IdentTable.get("package");
554     kw_synchronized = &IdentTable.get("synchronized");
555     kw_throws = &IdentTable.get("throws");
556     kw___except = &IdentTable.get("__except");
557 
558     kw_mark = &IdentTable.get("mark");
559 
560     kw_extend = &IdentTable.get("extend");
561     kw_option = &IdentTable.get("option");
562     kw_optional = &IdentTable.get("optional");
563     kw_repeated = &IdentTable.get("repeated");
564     kw_required = &IdentTable.get("required");
565     kw_returns = &IdentTable.get("returns");
566 
567     kw_signals = &IdentTable.get("signals");
568     kw_qsignals = &IdentTable.get("Q_SIGNALS");
569     kw_slots = &IdentTable.get("slots");
570     kw_qslots = &IdentTable.get("Q_SLOTS");
571   }
572 
573   // Context sensitive keywords.
574   IdentifierInfo *kw_final;
575   IdentifierInfo *kw_override;
576   IdentifierInfo *kw_in;
577   IdentifierInfo *kw_of;
578   IdentifierInfo *kw_CF_ENUM;
579   IdentifierInfo *kw_CF_OPTIONS;
580   IdentifierInfo *kw_NS_ENUM;
581   IdentifierInfo *kw_NS_OPTIONS;
582   IdentifierInfo *kw___except;
583 
584   // JavaScript keywords.
585   IdentifierInfo *kw_finally;
586   IdentifierInfo *kw_function;
587   IdentifierInfo *kw_from;
588   IdentifierInfo *kw_import;
589   IdentifierInfo *kw_is;
590   IdentifierInfo *kw_let;
591   IdentifierInfo *kw_var;
592 
593   // Java keywords.
594   IdentifierInfo *kw_abstract;
595   IdentifierInfo *kw_assert;
596   IdentifierInfo *kw_extends;
597   IdentifierInfo *kw_implements;
598   IdentifierInfo *kw_instanceof;
599   IdentifierInfo *kw_interface;
600   IdentifierInfo *kw_native;
601   IdentifierInfo *kw_package;
602   IdentifierInfo *kw_synchronized;
603   IdentifierInfo *kw_throws;
604 
605   // Pragma keywords.
606   IdentifierInfo *kw_mark;
607 
608   // Proto keywords.
609   IdentifierInfo *kw_extend;
610   IdentifierInfo *kw_option;
611   IdentifierInfo *kw_optional;
612   IdentifierInfo *kw_repeated;
613   IdentifierInfo *kw_required;
614   IdentifierInfo *kw_returns;
615 
616   // QT keywords.
617   IdentifierInfo *kw_signals;
618   IdentifierInfo *kw_qsignals;
619   IdentifierInfo *kw_slots;
620   IdentifierInfo *kw_qslots;
621 };
622 
623 } // namespace format
624 } // namespace clang
625 
626 #endif
627