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