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