]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Format/FormatToken.h
Merge clang trunk r238337 from ^/vendor/clang/dist, resolve conflicts,
[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_JsFatArrow,
55   TT_JsTypeColon,
56   TT_JsTypeOptionalQuestion,
57   TT_LambdaArrow,
58   TT_LambdaLSquare,
59   TT_LeadingJavaAnnotation,
60   TT_LineComment,
61   TT_ObjCBlockLBrace,
62   TT_ObjCBlockLParen,
63   TT_ObjCDecl,
64   TT_ObjCForIn,
65   TT_ObjCMethodExpr,
66   TT_ObjCMethodSpecifier,
67   TT_ObjCProperty,
68   TT_ObjCStringLiteral,
69   TT_OverloadedOperator,
70   TT_OverloadedOperatorLParen,
71   TT_PointerOrReference,
72   TT_PureVirtualSpecifier,
73   TT_RangeBasedForLoopColon,
74   TT_RegexLiteral,
75   TT_SelectorName,
76   TT_StartOfName,
77   TT_TemplateCloser,
78   TT_TemplateOpener,
79   TT_TemplateString,
80   TT_TrailingAnnotation,
81   TT_TrailingReturnArrow,
82   TT_TrailingUnaryOperator,
83   TT_UnaryOperator,
84   TT_Unknown
85 };
86
87 // Represents what type of block a set of braces open.
88 enum BraceBlockKind {
89   BK_Unknown,
90   BK_Block,
91   BK_BracedInit
92 };
93
94 // The packing kind of a function's parameters.
95 enum ParameterPackingKind {
96   PPK_BinPacked,
97   PPK_OnePerLine,
98   PPK_Inconclusive
99 };
100
101 enum FormatDecision {
102   FD_Unformatted,
103   FD_Continue,
104   FD_Break
105 };
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 Is this the last operator (or "."/"->") in a sequence of operators
252   /// with the same precedence?
253   bool LastOperator = false;
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   template <typename A, typename B> bool isOneOf(A K1, B K2) const {
287     return is(K1) || is(K2);
288   }
289   template <typename A, typename B, typename... Ts>
290   bool isOneOf(A K1, B K2, Ts... Ks) const {
291     return is(K1) || isOneOf(K2, Ks...);
292   }
293   template <typename T> bool isNot(T Kind) const { return !is(Kind); }
294
295   bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
296
297   bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
298     return Tok.isObjCAtKeyword(Kind);
299   }
300
301   bool isAccessSpecifier(bool ColonRequired = true) const {
302     return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
303            (!ColonRequired || (Next && Next->is(tok::colon)));
304   }
305
306   /// \brief Determine whether the token is a simple-type-specifier.
307   bool isSimpleTypeSpecifier() const;
308
309   bool isObjCAccessSpecifier() const {
310     return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
311                                    Next->isObjCAtKeyword(tok::objc_protected) ||
312                                    Next->isObjCAtKeyword(tok::objc_package) ||
313                                    Next->isObjCAtKeyword(tok::objc_private));
314   }
315
316   /// \brief Returns whether \p Tok is ([{ or a template opening <.
317   bool opensScope() const {
318     return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
319                    TT_TemplateOpener);
320   }
321   /// \brief Returns whether \p Tok is )]} or a template closing >.
322   bool closesScope() const {
323     return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
324                    TT_TemplateCloser);
325   }
326
327   /// \brief Returns \c true if this is a "." or "->" accessing a member.
328   bool isMemberAccess() const {
329     return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
330            !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
331                     TT_LambdaArrow);
332   }
333
334   bool isUnaryOperator() const {
335     switch (Tok.getKind()) {
336     case tok::plus:
337     case tok::plusplus:
338     case tok::minus:
339     case tok::minusminus:
340     case tok::exclaim:
341     case tok::tilde:
342     case tok::kw_sizeof:
343     case tok::kw_alignof:
344       return true;
345     default:
346       return false;
347     }
348   }
349
350   bool isBinaryOperator() const {
351     // Comma is a binary operator, but does not behave as such wrt. formatting.
352     return getPrecedence() > prec::Comma;
353   }
354
355   bool isTrailingComment() const {
356     return is(tok::comment) &&
357            (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
358   }
359
360   /// \brief Returns \c true if this is a keyword that can be used
361   /// like a function call (e.g. sizeof, typeid, ...).
362   bool isFunctionLikeKeyword() const {
363     switch (Tok.getKind()) {
364     case tok::kw_throw:
365     case tok::kw_typeid:
366     case tok::kw_return:
367     case tok::kw_sizeof:
368     case tok::kw_alignof:
369     case tok::kw_alignas:
370     case tok::kw_decltype:
371     case tok::kw_noexcept:
372     case tok::kw_static_assert:
373     case tok::kw___attribute:
374       return true;
375     default:
376       return false;
377     }
378   }
379
380   /// \brief Returns actual token start location without leading escaped
381   /// newlines and whitespace.
382   ///
383   /// This can be different to Tok.getLocation(), which includes leading escaped
384   /// newlines.
385   SourceLocation getStartOfNonWhitespace() const {
386     return WhitespaceRange.getEnd();
387   }
388
389   prec::Level getPrecedence() const {
390     return getBinOpPrecedence(Tok.getKind(), true, true);
391   }
392
393   /// \brief Returns the previous token ignoring comments.
394   FormatToken *getPreviousNonComment() const {
395     FormatToken *Tok = Previous;
396     while (Tok && Tok->is(tok::comment))
397       Tok = Tok->Previous;
398     return Tok;
399   }
400
401   /// \brief Returns the next token ignoring comments.
402   const FormatToken *getNextNonComment() const {
403     const FormatToken *Tok = Next;
404     while (Tok && Tok->is(tok::comment))
405       Tok = Tok->Next;
406     return Tok;
407   }
408
409   /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
410   /// list that should be indented with a block indent.
411   bool opensBlockTypeList(const FormatStyle &Style) const {
412     return is(TT_ArrayInitializerLSquare) ||
413            (is(tok::l_brace) &&
414             (BlockKind == BK_Block || is(TT_DictLiteral) ||
415              (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
416   }
417
418   /// \brief Same as opensBlockTypeList, but for the closing token.
419   bool closesBlockTypeList(const FormatStyle &Style) const {
420     return MatchingParen && MatchingParen->opensBlockTypeList(Style);
421   }
422
423 private:
424   // Disallow copying.
425   FormatToken(const FormatToken &) = delete;
426   void operator=(const FormatToken &) = delete;
427 };
428
429 class ContinuationIndenter;
430 struct LineState;
431
432 class TokenRole {
433 public:
434   TokenRole(const FormatStyle &Style) : Style(Style) {}
435   virtual ~TokenRole();
436
437   /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
438   /// this function precomputes required information for formatting.
439   virtual void precomputeFormattingInfos(const FormatToken *Token);
440
441   /// \brief Apply the special formatting that the given role demands.
442   ///
443   /// Assumes that the token having this role is already formatted.
444   ///
445   /// Continues formatting from \p State leaving indentation to \p Indenter and
446   /// returns the total penalty that this formatting incurs.
447   virtual unsigned formatFromToken(LineState &State,
448                                    ContinuationIndenter *Indenter,
449                                    bool DryRun) {
450     return 0;
451   }
452
453   /// \brief Same as \c formatFromToken, but assumes that the first token has
454   /// already been set thereby deciding on the first line break.
455   virtual unsigned formatAfterToken(LineState &State,
456                                     ContinuationIndenter *Indenter,
457                                     bool DryRun) {
458     return 0;
459   }
460
461   /// \brief Notifies the \c Role that a comma was found.
462   virtual void CommaFound(const FormatToken *Token) {}
463
464 protected:
465   const FormatStyle &Style;
466 };
467
468 class CommaSeparatedList : public TokenRole {
469 public:
470   CommaSeparatedList(const FormatStyle &Style)
471       : TokenRole(Style), HasNestedBracedList(false) {}
472
473   void precomputeFormattingInfos(const FormatToken *Token) override;
474
475   unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
476                             bool DryRun) override;
477
478   unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
479                            bool DryRun) override;
480
481   /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
482   void CommaFound(const FormatToken *Token) override {
483     Commas.push_back(Token);
484   }
485
486 private:
487   /// \brief A struct that holds information on how to format a given list with
488   /// a specific number of columns.
489   struct ColumnFormat {
490     /// \brief The number of columns to use.
491     unsigned Columns;
492
493     /// \brief The total width in characters.
494     unsigned TotalWidth;
495
496     /// \brief The number of lines required for this format.
497     unsigned LineCount;
498
499     /// \brief The size of each column in characters.
500     SmallVector<unsigned, 8> ColumnSizes;
501   };
502
503   /// \brief Calculate which \c ColumnFormat fits best into
504   /// \p RemainingCharacters.
505   const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
506
507   /// \brief The ordered \c FormatTokens making up the commas of this list.
508   SmallVector<const FormatToken *, 8> Commas;
509
510   /// \brief The length of each of the list's items in characters including the
511   /// trailing comma.
512   SmallVector<unsigned, 8> ItemLengths;
513
514   /// \brief Precomputed formats that can be used for this list.
515   SmallVector<ColumnFormat, 4> Formats;
516
517   bool HasNestedBracedList;
518 };
519
520 /// \brief Encapsulates keywords that are context sensitive or for languages not
521 /// properly supported by Clang's lexer.
522 struct AdditionalKeywords {
523   AdditionalKeywords(IdentifierTable &IdentTable) {
524     kw_in = &IdentTable.get("in");
525     kw_CF_ENUM = &IdentTable.get("CF_ENUM");
526     kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
527     kw_NS_ENUM = &IdentTable.get("NS_ENUM");
528     kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
529
530     kw_finally = &IdentTable.get("finally");
531     kw_function = &IdentTable.get("function");
532     kw_import = &IdentTable.get("import");
533     kw_var = &IdentTable.get("var");
534
535     kw_abstract = &IdentTable.get("abstract");
536     kw_extends = &IdentTable.get("extends");
537     kw_final = &IdentTable.get("final");
538     kw_implements = &IdentTable.get("implements");
539     kw_instanceof = &IdentTable.get("instanceof");
540     kw_interface = &IdentTable.get("interface");
541     kw_native = &IdentTable.get("native");
542     kw_package = &IdentTable.get("package");
543     kw_synchronized = &IdentTable.get("synchronized");
544     kw_throws = &IdentTable.get("throws");
545     kw___except = &IdentTable.get("__except");
546
547     kw_mark = &IdentTable.get("mark");
548
549     kw_option = &IdentTable.get("option");
550     kw_optional = &IdentTable.get("optional");
551     kw_repeated = &IdentTable.get("repeated");
552     kw_required = &IdentTable.get("required");
553     kw_returns = &IdentTable.get("returns");
554
555     kw_signals = &IdentTable.get("signals");
556     kw_slots = &IdentTable.get("slots");
557     kw_qslots = &IdentTable.get("Q_SLOTS");
558   }
559
560   // Context sensitive keywords.
561   IdentifierInfo *kw_in;
562   IdentifierInfo *kw_CF_ENUM;
563   IdentifierInfo *kw_CF_OPTIONS;
564   IdentifierInfo *kw_NS_ENUM;
565   IdentifierInfo *kw_NS_OPTIONS;
566   IdentifierInfo *kw___except;
567
568   // JavaScript keywords.
569   IdentifierInfo *kw_finally;
570   IdentifierInfo *kw_function;
571   IdentifierInfo *kw_import;
572   IdentifierInfo *kw_var;
573
574   // Java keywords.
575   IdentifierInfo *kw_abstract;
576   IdentifierInfo *kw_extends;
577   IdentifierInfo *kw_final;
578   IdentifierInfo *kw_implements;
579   IdentifierInfo *kw_instanceof;
580   IdentifierInfo *kw_interface;
581   IdentifierInfo *kw_native;
582   IdentifierInfo *kw_package;
583   IdentifierInfo *kw_synchronized;
584   IdentifierInfo *kw_throws;
585
586   // Pragma keywords.
587   IdentifierInfo *kw_mark;
588
589   // Proto keywords.
590   IdentifierInfo *kw_option;
591   IdentifierInfo *kw_optional;
592   IdentifierInfo *kw_repeated;
593   IdentifierInfo *kw_required;
594   IdentifierInfo *kw_returns;
595
596   // QT keywords.
597   IdentifierInfo *kw_signals;
598   IdentifierInfo *kw_slots;
599   IdentifierInfo *kw_qslots;
600 };
601
602 } // namespace format
603 } // namespace clang
604
605 #endif