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