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