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