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