Lexer.h revision 0770dabb1ae81a2a9c2e7199262067103062a0b3
1//===--- Lexer.h - C Language Family Lexer ----------------------*- 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 Lexer interface. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_LEXER_H 15#define LLVM_CLANG_LEXER_H 16 17#include "clang/Lex/PreprocessorLexer.h" 18#include "clang/Basic/LangOptions.h" 19#include "llvm/ADT/SmallVector.h" 20#include <string> 21#include <vector> 22#include <cassert> 23 24namespace clang { 25class Diagnostic; 26class SourceManager; 27class Preprocessor; 28class DiagnosticBuilder; 29 30/// Lexer - This provides a simple interface that turns a text buffer into a 31/// stream of tokens. This provides no support for file reading or buffering, 32/// or buffering/seeking of tokens, only forward lexing is supported. It relies 33/// on the specified Preprocessor object to handle preprocessor directives, etc. 34class Lexer : public PreprocessorLexer { 35 //===--------------------------------------------------------------------===// 36 // Constant configuration values for this lexer. 37 const char *BufferStart; // Start of the buffer. 38 const char *BufferEnd; // End of the buffer. 39 SourceLocation FileLoc; // Location for start of file. 40 LangOptions Features; // Features enabled by this language (cache). 41 bool Is_PragmaLexer; // True if lexer for _Pragma handling. 42 43 //===--------------------------------------------------------------------===// 44 // Context-specific lexing flags set by the preprocessor. 45 // 46 47 /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace 48 /// and return them as tokens. This is used for -C and -CC modes, and 49 /// whitespace preservation can be useful for some clients that want to lex 50 /// the file in raw mode and get every character from the file. 51 /// 52 /// When this is set to 2 it returns comments and whitespace. When set to 1 53 /// it returns comments, when it is set to 0 it returns normal tokens only. 54 unsigned char ExtendedTokenMode; 55 56 //===--------------------------------------------------------------------===// 57 // Context that changes as the file is lexed. 58 // NOTE: any state that mutates when in raw mode must have save/restore code 59 // in Lexer::isNextPPTokenLParen. 60 61 // BufferPtr - Current pointer into the buffer. This is the next character 62 // to be lexed. 63 const char *BufferPtr; 64 65 // IsAtStartOfLine - True if the next lexed token should get the "start of 66 // line" flag set on it. 67 bool IsAtStartOfLine; 68 69 Lexer(const Lexer&); // DO NOT IMPLEMENT 70 void operator=(const Lexer&); // DO NOT IMPLEMENT 71 friend class Preprocessor; 72 73 void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd); 74public: 75 76 /// Lexer constructor - Create a new lexer object for the specified buffer 77 /// with the specified preprocessor managing the lexing process. This lexer 78 /// assumes that the associated file buffer and Preprocessor objects will 79 /// outlive it, so it doesn't take ownership of either of them. 80 Lexer(SourceLocation FileLoc, Preprocessor &PP); 81 Lexer(SourceLocation FileLoc, Preprocessor &PP, 82 const char *BufStart, const char *BufEnd); 83 84 /// Lexer constructor - Create a new raw lexer object. This object is only 85 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text 86 /// range will outlive it, so it doesn't take ownership of it. 87 Lexer(SourceLocation FileLoc, const LangOptions &Features, 88 const char *BufStart, const char *BufPtr, const char *BufEnd); 89 90 /// Lexer constructor - Create a new raw lexer object. This object is only 91 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text 92 /// range will outlive it, so it doesn't take ownership of it. 93 Lexer(FileID FID, const SourceManager &SM, const LangOptions &Features); 94 95 /// getFeatures - Return the language features currently enabled. NOTE: this 96 /// lexer modifies features as a file is parsed! 97 const LangOptions &getFeatures() const { return Features; } 98 99 /// getFileLoc - Return the File Location for the file we are lexing out of. 100 /// The physical location encodes the location where the characters come from, 101 /// the virtual location encodes where we should *claim* the characters came 102 /// from. Currently this is only used by _Pragma handling. 103 SourceLocation getFileLoc() const { return FileLoc; } 104 105 /// Lex - Return the next token in the file. If this is the end of file, it 106 /// return the tok::eof token. Return true if an error occurred and 107 /// compilation should terminate, false if normal. This implicitly involves 108 /// the preprocessor. 109 void Lex(Token &Result) { 110 // Start a new token. 111 Result.startToken(); 112 113 // NOTE, any changes here should also change code after calls to 114 // Preprocessor::HandleDirective 115 if (IsAtStartOfLine) { 116 Result.setFlag(Token::StartOfLine); 117 IsAtStartOfLine = false; 118 } 119 120 // Get a token. Note that this may delete the current lexer if the end of 121 // file is reached. 122 LexTokenInternal(Result); 123 } 124 125 /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma. 126 bool isPragmaLexer() const { return Is_PragmaLexer; } 127 128 /// IndirectLex - An indirect call to 'Lex' that can be invoked via 129 /// the PreprocessorLexer interface. 130 void IndirectLex(Token &Result) { Lex(Result); } 131 132 /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no 133 /// associated preprocessor object. Return true if the 'next character to 134 /// read' pointer points and the end of the lexer buffer, false otherwise. 135 bool LexFromRawLexer(Token &Result) { 136 assert(LexingRawMode && "Not already in raw mode!"); 137 Lex(Result); 138 // Note that lexing to the end of the buffer doesn't implicitly delete the 139 // lexer when in raw mode. 140 return BufferPtr == BufferEnd; 141 } 142 143 /// isKeepWhitespaceMode - Return true if the lexer should return tokens for 144 /// every character in the file, including whitespace and comments. This 145 /// should only be used in raw mode, as the preprocessor is not prepared to 146 /// deal with the excess tokens. 147 bool isKeepWhitespaceMode() const { 148 return ExtendedTokenMode > 1; 149 } 150 151 /// SetKeepWhitespaceMode - This method lets clients enable or disable 152 /// whitespace retention mode. 153 void SetKeepWhitespaceMode(bool Val) { 154 assert((!Val || LexingRawMode) && 155 "Can only enable whitespace retention in raw mode"); 156 ExtendedTokenMode = Val ? 2 : 0; 157 } 158 159 /// inKeepCommentMode - Return true if the lexer should return comments as 160 /// tokens. 161 bool inKeepCommentMode() const { 162 return ExtendedTokenMode > 0; 163 } 164 165 /// SetCommentRetentionMode - Change the comment retention mode of the lexer 166 /// to the specified mode. This is really only useful when lexing in raw 167 /// mode, because otherwise the lexer needs to manage this. 168 void SetCommentRetentionState(bool Mode) { 169 assert(!isKeepWhitespaceMode() && 170 "Can't play with comment retention state when retaining whitespace"); 171 ExtendedTokenMode = Mode ? 1 : 0; 172 } 173 174 const char *getBufferStart() const { return BufferStart; } 175 176 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an 177 /// uninterpreted string. This switches the lexer out of directive mode. 178 std::string ReadToEndOfLine(); 179 180 181 /// Diag - Forwarding function for diagnostics. This translate a source 182 /// position in the current buffer into a SourceLocation object for rendering. 183 DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const; 184 185 /// getSourceLocation - Return a source location identifier for the specified 186 /// offset in the current file. 187 SourceLocation getSourceLocation(const char *Loc) const; 188 189 /// getSourceLocation - Return a source location for the next character in 190 /// the current file. 191 SourceLocation getSourceLocation() { return getSourceLocation(BufferPtr); } 192 193 /// Stringify - Convert the specified string into a C string by escaping '\' 194 /// and " characters. This does not add surrounding ""'s to the string. 195 /// If Charify is true, this escapes the ' character instead of ". 196 static std::string Stringify(const std::string &Str, bool Charify = false); 197 198 /// Stringify - Convert the specified string into a C string by escaping '\' 199 /// and " characters. This does not add surrounding ""'s to the string. 200 static void Stringify(llvm::SmallVectorImpl<char> &Str); 201 202 /// MeasureTokenLength - Relex the token at the specified location and return 203 /// its length in bytes in the input file. If the token needs cleaning (e.g. 204 /// includes a trigraph or an escaped newline) then this count includes bytes 205 /// that are part of that. 206 static unsigned MeasureTokenLength(SourceLocation Loc, 207 const SourceManager &SM); 208 209 //===--------------------------------------------------------------------===// 210 // Internal implementation interfaces. 211private: 212 213 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called 214 /// by Lex. 215 /// 216 void LexTokenInternal(Token &Result); 217 218 /// FormTokenWithChars - When we lex a token, we have identified a span 219 /// starting at BufferPtr, going to TokEnd that forms the token. This method 220 /// takes that range and assigns it to the token as its location and size. In 221 /// addition, since tokens cannot overlap, this also updates BufferPtr to be 222 /// TokEnd. 223 void FormTokenWithChars(Token &Result, const char *TokEnd, 224 tok::TokenKind Kind) { 225 Result.setLocation(getSourceLocation(BufferPtr)); 226 Result.setLength(TokEnd-BufferPtr); 227 Result.setKind(Kind); 228 BufferPtr = TokEnd; 229 } 230 231 /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a 232 /// tok::l_paren token, 0 if it is something else and 2 if there are no more 233 /// tokens in the buffer controlled by this lexer. 234 unsigned isNextPPTokenLParen(); 235 236 //===--------------------------------------------------------------------===// 237 // Lexer character reading interfaces. 238public: 239 240 // This lexer is built on two interfaces for reading characters, both of which 241 // automatically provide phase 1/2 translation. getAndAdvanceChar is used 242 // when we know that we will be reading a character from the input buffer and 243 // that this character will be part of the result token. This occurs in (f.e.) 244 // string processing, because we know we need to read until we find the 245 // closing '"' character. 246 // 247 // The second interface is the combination of PeekCharAndSize with 248 // ConsumeChar. PeekCharAndSize reads a phase 1/2 translated character, 249 // returning it and its size. If the lexer decides that this character is 250 // part of the current token, it calls ConsumeChar on it. This two stage 251 // approach allows us to emit diagnostics for characters (e.g. warnings about 252 // trigraphs), knowing that they only are emitted if the character is 253 // consumed. 254 255 /// isObviouslySimpleCharacter - Return true if the specified character is 256 /// obviously the same in translation phase 1 and translation phase 3. This 257 /// can return false for characters that end up being the same, but it will 258 /// never return true for something that needs to be mapped. 259 static bool isObviouslySimpleCharacter(char C) { 260 return C != '?' && C != '\\'; 261 } 262 263 /// getAndAdvanceChar - Read a single 'character' from the specified buffer, 264 /// advance over it, and return it. This is tricky in several cases. Here we 265 /// just handle the trivial case and fall-back to the non-inlined 266 /// getCharAndSizeSlow method to handle the hard case. 267 inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) { 268 // If this is not a trigraph and not a UCN or escaped newline, return 269 // quickly. 270 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++; 271 272 unsigned Size = 0; 273 char C = getCharAndSizeSlow(Ptr, Size, &Tok); 274 Ptr += Size; 275 return C; 276 } 277 278private: 279 /// ConsumeChar - When a character (identified by PeekCharAndSize) is consumed 280 /// and added to a given token, check to see if there are diagnostics that 281 /// need to be emitted or flags that need to be set on the token. If so, do 282 /// it. 283 const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) { 284 // Normal case, we consumed exactly one token. Just return it. 285 if (Size == 1) 286 return Ptr+Size; 287 288 // Otherwise, re-lex the character with a current token, allowing 289 // diagnostics to be emitted and flags to be set. 290 Size = 0; 291 getCharAndSizeSlow(Ptr, Size, &Tok); 292 return Ptr+Size; 293 } 294 295 /// getCharAndSize - Peek a single 'character' from the specified buffer, 296 /// get its size, and return it. This is tricky in several cases. Here we 297 /// just handle the trivial case and fall-back to the non-inlined 298 /// getCharAndSizeSlow method to handle the hard case. 299 inline char getCharAndSize(const char *Ptr, unsigned &Size) { 300 // If this is not a trigraph and not a UCN or escaped newline, return 301 // quickly. 302 if (isObviouslySimpleCharacter(Ptr[0])) { 303 Size = 1; 304 return *Ptr; 305 } 306 307 Size = 0; 308 return getCharAndSizeSlow(Ptr, Size); 309 } 310 311 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize 312 /// method. 313 char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0); 314public: 315 316 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever 317 /// emit a warning. 318 static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, 319 const LangOptions &Features) { 320 // If this is not a trigraph and not a UCN or escaped newline, return 321 // quickly. 322 if (isObviouslySimpleCharacter(Ptr[0])) { 323 Size = 1; 324 return *Ptr; 325 } 326 327 Size = 0; 328 return getCharAndSizeSlowNoWarn(Ptr, Size, Features); 329 } 330private: 331 332 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a 333 /// diagnostic. 334 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, 335 const LangOptions &Features); 336 337 //===--------------------------------------------------------------------===// 338 // Other lexer functions. 339 340 // Helper functions to lex the remainder of a token of the specific type. 341 void LexIdentifier (Token &Result, const char *CurPtr); 342 void LexNumericConstant (Token &Result, const char *CurPtr); 343 void LexStringLiteral (Token &Result, const char *CurPtr,bool Wide); 344 void LexAngledStringLiteral(Token &Result, const char *CurPtr); 345 void LexCharConstant (Token &Result, const char *CurPtr); 346 bool LexEndOfFile (Token &Result, const char *CurPtr); 347 348 bool SkipWhitespace (Token &Result, const char *CurPtr); 349 bool SkipBCPLComment (Token &Result, const char *CurPtr); 350 bool SkipBlockComment (Token &Result, const char *CurPtr); 351 bool SaveBCPLComment (Token &Result, const char *CurPtr); 352}; 353 354 355} // end namespace clang 356 357#endif 358