xref: /freebsd/contrib/llvm-project/clang/include/clang/Lex/Token.h (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
1 //===--- Token.h - Token interface ------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the Token interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LEX_TOKEN_H
14 #define LLVM_CLANG_LEX_TOKEN_H
15 
16 #include "clang/Basic/SourceLocation.h"
17 #include "clang/Basic/TokenKinds.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/StringRef.h"
20 #include <cassert>
21 
22 namespace clang {
23 
24 class IdentifierInfo;
25 class LangOptions;
26 
27 /// Token - This structure provides full information about a lexed token.
28 /// It is not intended to be space efficient, it is intended to return as much
29 /// information as possible about each returned token.  This is expected to be
30 /// compressed into a smaller form if memory footprint is important.
31 ///
32 /// The parser can create a special "annotation token" representing a stream of
33 /// tokens that were parsed and semantically resolved, e.g.: "foo::MyClass<int>"
34 /// can be represented by a single typename annotation token that carries
35 /// information about the SourceRange of the tokens and the type object.
36 class Token {
37   /// The location of the token. This is actually a SourceLocation.
38   SourceLocation::UIntTy Loc;
39 
40   // Conceptually these next two fields could be in a union.  However, this
41   // causes gcc 4.2 to pessimize LexTokenInternal, a very performance critical
42   // routine. Keeping as separate members with casts until a more beautiful fix
43   // presents itself.
44 
45   /// UintData - This holds either the length of the token text, when
46   /// a normal token, or the end of the SourceRange when an annotation
47   /// token.
48   SourceLocation::UIntTy UintData;
49 
50   /// PtrData - This is a union of four different pointer types, which depends
51   /// on what type of token this is:
52   ///  Identifiers, keywords, etc:
53   ///    This is an IdentifierInfo*, which contains the uniqued identifier
54   ///    spelling.
55   ///  Literals:  isLiteral() returns true.
56   ///    This is a pointer to the start of the token in a text buffer, which
57   ///    may be dirty (have trigraphs / escaped newlines).
58   ///  Annotations (resolved type names, C++ scopes, etc): isAnnotation().
59   ///    This is a pointer to sema-specific data for the annotation token.
60   ///  Eof:
61   ///    This is a pointer to a Decl.
62   ///  Other:
63   ///    This is null.
64   void *PtrData;
65 
66   /// Kind - The actual flavor of token this is.
67   tok::TokenKind Kind;
68 
69   /// Flags - Bits we track about this token, members of the TokenFlags enum.
70   unsigned short Flags;
71 
72 public:
73   // Various flags set per token:
74   enum TokenFlags {
75     StartOfLine = 0x01,   // At start of line or only after whitespace
76                           // (considering the line after macro expansion).
77     LeadingSpace = 0x02,  // Whitespace exists before this token (considering
78                           // whitespace after macro expansion).
79     DisableExpand = 0x04, // This identifier may never be macro expanded.
80     NeedsCleaning = 0x08, // Contained an escaped newline or trigraph.
81     LeadingEmptyMacro = 0x10, // Empty macro exists before this token.
82     HasUDSuffix = 0x20,  // This string or character literal has a ud-suffix.
83     HasUCN = 0x40,       // This identifier contains a UCN.
84     IgnoredComma = 0x80, // This comma is not a macro argument separator (MS).
85     StringifiedInMacro = 0x100, // This string or character literal is formed by
86                                 // macro stringizing or charizing operator.
87     CommaAfterElided = 0x200, // The comma following this token was elided (MS).
88     IsEditorPlaceholder = 0x400, // This identifier is a placeholder.
89     IsReinjected = 0x800,        // A phase 4 token that was produced before and
90                           // re-added, e.g. via EnterTokenStream. Annotation
91                           // tokens are *not* reinjected.
92     HasSeenNoTrivialPPDirective =
93         0x1000, // Whether we've seen any 'no-trivial' pp-directives before
94                 // current position.
95   };
96 
getKind()97   tok::TokenKind getKind() const { return Kind; }
setKind(tok::TokenKind K)98   void setKind(tok::TokenKind K) { Kind = K; }
99 
100   /// is/isNot - Predicates to check if this token is a specific kind, as in
101   /// "if (Tok.is(tok::l_brace)) {...}".
is(tok::TokenKind K)102   bool is(tok::TokenKind K) const { return Kind == K; }
isNot(tok::TokenKind K)103   bool isNot(tok::TokenKind K) const { return Kind != K; }
isOneOf(Ts...Ks)104   template <typename... Ts> bool isOneOf(Ts... Ks) const {
105     static_assert(sizeof...(Ts) > 0,
106                   "requires at least one tok::TokenKind specified");
107     return (is(Ks) || ...);
108   }
109 
110   /// Return true if this is a raw identifier (when lexing
111   /// in raw mode) or a non-keyword identifier (when lexing in non-raw mode).
isAnyIdentifier()112   bool isAnyIdentifier() const {
113     return tok::isAnyIdentifier(getKind());
114   }
115 
116   /// Return true if this is a "literal", like a numeric
117   /// constant, string, etc.
isLiteral()118   bool isLiteral() const {
119     return tok::isLiteral(getKind());
120   }
121 
122   /// Return true if this is any of tok::annot_* kind tokens.
isAnnotation()123   bool isAnnotation() const { return tok::isAnnotation(getKind()); }
124 
125   /// Return true if the token is a keyword that is parsed in the same
126   /// position as a standard attribute, but that has semantic meaning
127   /// and so cannot be a true attribute.
isRegularKeywordAttribute()128   bool isRegularKeywordAttribute() const {
129     return tok::isRegularKeywordAttribute(getKind());
130   }
131 
132   /// Return a source location identifier for the specified
133   /// offset in the current file.
getLocation()134   SourceLocation getLocation() const {
135     return SourceLocation::getFromRawEncoding(Loc);
136   }
getLength()137   unsigned getLength() const {
138     assert(!isAnnotation() && "Annotation tokens have no length field");
139     return UintData;
140   }
141 
setLocation(SourceLocation L)142   void setLocation(SourceLocation L) { Loc = L.getRawEncoding(); }
setLength(unsigned Len)143   void setLength(unsigned Len) {
144     assert(!isAnnotation() && "Annotation tokens have no length field");
145     UintData = Len;
146   }
147 
getAnnotationEndLoc()148   SourceLocation getAnnotationEndLoc() const {
149     assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token");
150     return SourceLocation::getFromRawEncoding(UintData ? UintData : Loc);
151   }
setAnnotationEndLoc(SourceLocation L)152   void setAnnotationEndLoc(SourceLocation L) {
153     assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token");
154     UintData = L.getRawEncoding();
155   }
156 
getLastLoc()157   SourceLocation getLastLoc() const {
158     return isAnnotation() ? getAnnotationEndLoc() : getLocation();
159   }
160 
getEndLoc()161   SourceLocation getEndLoc() const {
162     return isAnnotation() ? getAnnotationEndLoc()
163                           : getLocation().getLocWithOffset(getLength());
164   }
165 
166   /// SourceRange of the group of tokens that this annotation token
167   /// represents.
getAnnotationRange()168   SourceRange getAnnotationRange() const {
169     return SourceRange(getLocation(), getAnnotationEndLoc());
170   }
setAnnotationRange(SourceRange R)171   void setAnnotationRange(SourceRange R) {
172     setLocation(R.getBegin());
173     setAnnotationEndLoc(R.getEnd());
174   }
175 
getName()176   const char *getName() const { return tok::getTokenName(Kind); }
177 
178   /// Reset all flags to cleared.
startToken()179   void startToken() {
180     Kind = tok::unknown;
181     Flags = 0;
182     PtrData = nullptr;
183     UintData = 0;
184     Loc = SourceLocation().getRawEncoding();
185   }
186 
hasPtrData()187   bool hasPtrData() const { return PtrData != nullptr; }
188 
getIdentifierInfo()189   IdentifierInfo *getIdentifierInfo() const {
190     assert(isNot(tok::raw_identifier) &&
191            "getIdentifierInfo() on a tok::raw_identifier token!");
192     assert(!isAnnotation() &&
193            "getIdentifierInfo() on an annotation token!");
194     if (isLiteral()) return nullptr;
195     if (is(tok::eof)) return nullptr;
196     return (IdentifierInfo*) PtrData;
197   }
setIdentifierInfo(IdentifierInfo * II)198   void setIdentifierInfo(IdentifierInfo *II) {
199     PtrData = (void*) II;
200   }
201 
getEofData()202   const void *getEofData() const {
203     assert(is(tok::eof));
204     return reinterpret_cast<const void *>(PtrData);
205   }
setEofData(const void * D)206   void setEofData(const void *D) {
207     assert(is(tok::eof));
208     assert(!PtrData);
209     PtrData = const_cast<void *>(D);
210   }
211 
212   /// getRawIdentifier - For a raw identifier token (i.e., an identifier
213   /// lexed in raw mode), returns a reference to the text substring in the
214   /// buffer if known.
getRawIdentifier()215   StringRef getRawIdentifier() const {
216     assert(is(tok::raw_identifier));
217     return StringRef(reinterpret_cast<const char *>(PtrData), getLength());
218   }
setRawIdentifierData(const char * Ptr)219   void setRawIdentifierData(const char *Ptr) {
220     assert(is(tok::raw_identifier));
221     PtrData = const_cast<char*>(Ptr);
222   }
223 
224   /// getLiteralData - For a literal token (numeric constant, string, etc), this
225   /// returns a pointer to the start of it in the text buffer if known, null
226   /// otherwise.
getLiteralData()227   const char *getLiteralData() const {
228     assert(isLiteral() && "Cannot get literal data of non-literal");
229     return reinterpret_cast<const char*>(PtrData);
230   }
setLiteralData(const char * Ptr)231   void setLiteralData(const char *Ptr) {
232     assert(isLiteral() && "Cannot set literal data of non-literal");
233     PtrData = const_cast<char*>(Ptr);
234   }
235 
getAnnotationValue()236   void *getAnnotationValue() const {
237     assert(isAnnotation() && "Used AnnotVal on non-annotation token");
238     return PtrData;
239   }
setAnnotationValue(void * val)240   void setAnnotationValue(void *val) {
241     assert(isAnnotation() && "Used AnnotVal on non-annotation token");
242     PtrData = val;
243   }
244 
245   /// Set the specified flag.
setFlag(TokenFlags Flag)246   void setFlag(TokenFlags Flag) {
247     Flags |= Flag;
248   }
249 
250   /// Get the specified flag.
getFlag(TokenFlags Flag)251   bool getFlag(TokenFlags Flag) const {
252     return (Flags & Flag) != 0;
253   }
254 
255   /// Unset the specified flag.
clearFlag(TokenFlags Flag)256   void clearFlag(TokenFlags Flag) {
257     Flags &= ~Flag;
258   }
259 
260   /// Return the internal represtation of the flags.
261   ///
262   /// This is only intended for low-level operations such as writing tokens to
263   /// disk.
getFlags()264   unsigned getFlags() const {
265     return Flags;
266   }
267 
268   /// Set a flag to either true or false.
setFlagValue(TokenFlags Flag,bool Val)269   void setFlagValue(TokenFlags Flag, bool Val) {
270     if (Val)
271       setFlag(Flag);
272     else
273       clearFlag(Flag);
274   }
275 
276   /// isAtStartOfLine - Return true if this token is at the start of a line.
277   ///
isAtStartOfLine()278   bool isAtStartOfLine() const { return getFlag(StartOfLine); }
279 
280   /// Return true if this token has whitespace before it.
281   ///
hasLeadingSpace()282   bool hasLeadingSpace() const { return getFlag(LeadingSpace); }
283 
284   /// Return true if this identifier token should never
285   /// be expanded in the future, due to C99 6.10.3.4p2.
isExpandDisabled()286   bool isExpandDisabled() const { return getFlag(DisableExpand); }
287 
288   /// Return true if we have an ObjC keyword identifier.
289   bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const;
290 
291   /// Return the ObjC keyword kind.
292   tok::ObjCKeywordKind getObjCKeywordID() const;
293 
294   bool isSimpleTypeSpecifier(const LangOptions &LangOpts) const;
295 
296   /// Return true if this token has trigraphs or escaped newlines in it.
needsCleaning()297   bool needsCleaning() const { return getFlag(NeedsCleaning); }
298 
299   /// Return true if this token has an empty macro before it.
300   ///
hasLeadingEmptyMacro()301   bool hasLeadingEmptyMacro() const { return getFlag(LeadingEmptyMacro); }
302 
303   /// Return true if this token is a string or character literal which
304   /// has a ud-suffix.
hasUDSuffix()305   bool hasUDSuffix() const { return getFlag(HasUDSuffix); }
306 
307   /// Returns true if this token contains a universal character name.
hasUCN()308   bool hasUCN() const { return getFlag(HasUCN); }
309 
310   /// Returns true if this token is formed by macro by stringizing or charizing
311   /// operator.
stringifiedInMacro()312   bool stringifiedInMacro() const { return getFlag(StringifiedInMacro); }
313 
314   /// Returns true if the comma after this token was elided.
commaAfterElided()315   bool commaAfterElided() const { return getFlag(CommaAfterElided); }
316 
317   /// Returns true if this token is an editor placeholder.
318   ///
319   /// Editor placeholders are produced by the code-completion engine and are
320   /// represented as characters between '<#' and '#>' in the source code. The
321   /// lexer uses identifier tokens to represent placeholders.
isEditorPlaceholder()322   bool isEditorPlaceholder() const { return getFlag(IsEditorPlaceholder); }
323 
hasSeenNoTrivialPPDirective()324   bool hasSeenNoTrivialPPDirective() const {
325     return getFlag(HasSeenNoTrivialPPDirective);
326   }
327 };
328 
329 /// Information about the conditional stack (\#if directives)
330 /// currently active.
331 struct PPConditionalInfo {
332   /// Location where the conditional started.
333   SourceLocation IfLoc;
334 
335   /// True if this was contained in a skipping directive, e.g.,
336   /// in a "\#if 0" block.
337   bool WasSkipping;
338 
339   /// True if we have emitted tokens already, and now we're in
340   /// an \#else block or something.  Only useful in Skipping blocks.
341   bool FoundNonSkip;
342 
343   /// True if we've seen a \#else in this block.  If so,
344   /// \#elif/\#else directives are not allowed.
345   bool FoundElse;
346 };
347 
348 // Extra information needed for annonation tokens.
349 struct PragmaLoopHintInfo {
350   Token PragmaName;
351   Token Option;
352   ArrayRef<Token> Toks;
353 };
354 } // end namespace clang
355 
356 #endif // LLVM_CLANG_LEX_TOKEN_H
357