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