Token.h revision 651f13cea278ec967336033dd032faef0e9fc2ec
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_TOKEN_H
15#define LLVM_CLANG_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 <cstdlib>
22
23namespace clang {
24
25class IdentifierInfo;
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.
36class Token {
37  /// The location of the token.
38  SourceLocation 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  unsigned 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  ///  Other:
61  ///    This is null.
62  void *PtrData;
63
64  /// Kind - The actual flavor of token this is.
65  tok::TokenKind Kind;
66
67  /// Flags - Bits we track about this token, members of the TokenFlags enum.
68  unsigned char Flags;
69public:
70
71  // Various flags set per token:
72  enum TokenFlags {
73    StartOfLine   = 0x01,  // At start of line or only after whitespace
74                           // (considering the line after macro expansion).
75    LeadingSpace  = 0x02,  // Whitespace exists before this token (considering
76                           // whitespace after macro expansion).
77    DisableExpand = 0x04,  // This identifier may never be macro expanded.
78    NeedsCleaning = 0x08,  // Contained an escaped newline or trigraph.
79    LeadingEmptyMacro = 0x10, // Empty macro exists before this token.
80    HasUDSuffix = 0x20,    // This string or character literal has a ud-suffix.
81    HasUCN = 0x40,         // This identifier contains a UCN.
82    IgnoredComma = 0x80    // This comma is not a macro argument separator (MS).
83  };
84
85  tok::TokenKind getKind() const { return Kind; }
86  void setKind(tok::TokenKind K) { Kind = K; }
87
88  /// is/isNot - Predicates to check if this token is a specific kind, as in
89  /// "if (Tok.is(tok::l_brace)) {...}".
90  bool is(tok::TokenKind K) const { return Kind == K; }
91  bool isNot(tok::TokenKind K) const { return Kind != K; }
92
93  /// \brief Return true if this is a raw identifier (when lexing
94  /// in raw mode) or a non-keyword identifier (when lexing in non-raw mode).
95  bool isAnyIdentifier() const {
96    return tok::isAnyIdentifier(getKind());
97  }
98
99  /// \brief Return true if this is a "literal", like a numeric
100  /// constant, string, etc.
101  bool isLiteral() const {
102    return tok::isLiteral(getKind());
103  }
104
105  /// \brief Return true if this is any of tok::annot_* kind tokens.
106  bool isAnnotation() const {
107    return tok::isAnnotation(getKind());
108  }
109
110  /// \brief Return a source location identifier for the specified
111  /// offset in the current file.
112  SourceLocation getLocation() const { return Loc; }
113  unsigned getLength() const {
114    assert(!isAnnotation() && "Annotation tokens have no length field");
115    return UintData;
116  }
117
118  void setLocation(SourceLocation L) { Loc = L; }
119  void setLength(unsigned Len) {
120    assert(!isAnnotation() && "Annotation tokens have no length field");
121    UintData = Len;
122  }
123
124  SourceLocation getAnnotationEndLoc() const {
125    assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token");
126    return SourceLocation::getFromRawEncoding(UintData);
127  }
128  void setAnnotationEndLoc(SourceLocation L) {
129    assert(isAnnotation() && "Used AnnotEndLocID on non-annotation token");
130    UintData = L.getRawEncoding();
131  }
132
133  SourceLocation getLastLoc() const {
134    return isAnnotation() ? getAnnotationEndLoc() : getLocation();
135  }
136
137  /// \brief SourceRange of the group of tokens that this annotation token
138  /// represents.
139  SourceRange getAnnotationRange() const {
140    return SourceRange(getLocation(), getAnnotationEndLoc());
141  }
142  void setAnnotationRange(SourceRange R) {
143    setLocation(R.getBegin());
144    setAnnotationEndLoc(R.getEnd());
145  }
146
147  const char *getName() const { return tok::getTokenName(Kind); }
148
149  /// \brief Reset all flags to cleared.
150  void startToken() {
151    Kind = tok::unknown;
152    Flags = 0;
153    PtrData = 0;
154    UintData = 0;
155    Loc = SourceLocation();
156  }
157
158  IdentifierInfo *getIdentifierInfo() const {
159    assert(isNot(tok::raw_identifier) &&
160           "getIdentifierInfo() on a tok::raw_identifier token!");
161    assert(!isAnnotation() &&
162           "getIdentifierInfo() on an annotation token!");
163    if (isLiteral()) return 0;
164    return (IdentifierInfo*) PtrData;
165  }
166  void setIdentifierInfo(IdentifierInfo *II) {
167    PtrData = (void*) II;
168  }
169
170  /// getRawIdentifierData - For a raw identifier token (i.e., an identifier
171  /// lexed in raw mode), returns a pointer to the start of it in the text
172  /// buffer if known, null otherwise.
173  const char *getRawIdentifierData() const {
174    assert(is(tok::raw_identifier));
175    return reinterpret_cast<const char*>(PtrData);
176  }
177  void setRawIdentifierData(const char *Ptr) {
178    assert(is(tok::raw_identifier));
179    PtrData = const_cast<char*>(Ptr);
180  }
181
182  /// getLiteralData - For a literal token (numeric constant, string, etc), this
183  /// returns a pointer to the start of it in the text buffer if known, null
184  /// otherwise.
185  const char *getLiteralData() const {
186    assert(isLiteral() && "Cannot get literal data of non-literal");
187    return reinterpret_cast<const char*>(PtrData);
188  }
189  void setLiteralData(const char *Ptr) {
190    assert(isLiteral() && "Cannot set literal data of non-literal");
191    PtrData = const_cast<char*>(Ptr);
192  }
193
194  void *getAnnotationValue() const {
195    assert(isAnnotation() && "Used AnnotVal on non-annotation token");
196    return PtrData;
197  }
198  void setAnnotationValue(void *val) {
199    assert(isAnnotation() && "Used AnnotVal on non-annotation token");
200    PtrData = val;
201  }
202
203  /// \brief Set the specified flag.
204  void setFlag(TokenFlags Flag) {
205    Flags |= Flag;
206  }
207
208  /// \brief Unset the specified flag.
209  void clearFlag(TokenFlags Flag) {
210    Flags &= ~Flag;
211  }
212
213  /// \brief Return the internal represtation of the flags.
214  ///
215  /// This is only intended for low-level operations such as writing tokens to
216  /// disk.
217  unsigned getFlags() const {
218    return Flags;
219  }
220
221  /// \brief Set a flag to either true or false.
222  void setFlagValue(TokenFlags Flag, bool Val) {
223    if (Val)
224      setFlag(Flag);
225    else
226      clearFlag(Flag);
227  }
228
229  /// isAtStartOfLine - Return true if this token is at the start of a line.
230  ///
231  bool isAtStartOfLine() const { return (Flags & StartOfLine) ? true : false; }
232
233  /// \brief Return true if this token has whitespace before it.
234  ///
235  bool hasLeadingSpace() const { return (Flags & LeadingSpace) ? true : false; }
236
237  /// \brief Return true if this identifier token should never
238  /// be expanded in the future, due to C99 6.10.3.4p2.
239  bool isExpandDisabled() const {
240    return (Flags & DisableExpand) ? true : false;
241  }
242
243  /// \brief Return true if we have an ObjC keyword identifier.
244  bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const;
245
246  /// \brief Return the ObjC keyword kind.
247  tok::ObjCKeywordKind getObjCKeywordID() const;
248
249  /// \brief Return true if this token has trigraphs or escaped newlines in it.
250  bool needsCleaning() const { return (Flags & NeedsCleaning) ? true : false; }
251
252  /// \brief Return true if this token has an empty macro before it.
253  ///
254  bool hasLeadingEmptyMacro() const {
255    return (Flags & LeadingEmptyMacro) ? true : false;
256  }
257
258  /// \brief Return true if this token is a string or character literal which
259  /// has a ud-suffix.
260  bool hasUDSuffix() const { return (Flags & HasUDSuffix) ? true : false; }
261
262  /// Returns true if this token contains a universal character name.
263  bool hasUCN() const { return (Flags & HasUCN) ? true : false; }
264};
265
266/// \brief Information about the conditional stack (\#if directives)
267/// currently active.
268struct PPConditionalInfo {
269  /// \brief Location where the conditional started.
270  SourceLocation IfLoc;
271
272  /// \brief True if this was contained in a skipping directive, e.g.,
273  /// in a "\#if 0" block.
274  bool WasSkipping;
275
276  /// \brief True if we have emitted tokens already, and now we're in
277  /// an \#else block or something.  Only useful in Skipping blocks.
278  bool FoundNonSkip;
279
280  /// \brief True if we've seen a \#else in this block.  If so,
281  /// \#elif/\#else directives are not allowed.
282  bool FoundElse;
283};
284
285}  // end namespace clang
286
287namespace llvm {
288  template <>
289  struct isPodLike<clang::Token> { static const bool value = true; };
290}  // end namespace llvm
291
292#endif
293