Lexer.h revision 834e3f6c77d9ac03997a3f0c56934edcf406a355
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 : 1; // True if lexer for _Pragma handling. 42 bool IsInConflictMarker : 1; // True if in a VCS conflict marker '<<<<<<<' 43 44 //===--------------------------------------------------------------------===// 45 // Context-specific lexing flags set by the preprocessor. 46 // 47 48 /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace 49 /// and return them as tokens. This is used for -C and -CC modes, and 50 /// whitespace preservation can be useful for some clients that want to lex 51 /// the file in raw mode and get every character from the file. 52 /// 53 /// When this is set to 2 it returns comments and whitespace. When set to 1 54 /// it returns comments, when it is set to 0 it returns normal tokens only. 55 unsigned char ExtendedTokenMode; 56 57 //===--------------------------------------------------------------------===// 58 // Context that changes as the file is lexed. 59 // NOTE: any state that mutates when in raw mode must have save/restore code 60 // in Lexer::isNextPPTokenLParen. 61 62 // BufferPtr - Current pointer into the buffer. This is the next character 63 // to be lexed. 64 const char *BufferPtr; 65 66 // IsAtStartOfLine - True if the next lexed token should get the "start of 67 // line" flag set on it. 68 bool IsAtStartOfLine; 69 70 Lexer(const Lexer&); // DO NOT IMPLEMENT 71 void operator=(const Lexer&); // DO NOT IMPLEMENT 72 friend class Preprocessor; 73 74 void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd); 75public: 76 77 /// Lexer constructor - Create a new lexer object for the specified buffer 78 /// with the specified preprocessor managing the lexing process. This lexer 79 /// assumes that the associated file buffer and Preprocessor objects will 80 /// outlive it, so it doesn't take ownership of either of them. 81 Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer, Preprocessor &PP); 82 83 /// Lexer constructor - Create a new raw lexer object. This object is only 84 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text 85 /// range will outlive it, so it doesn't take ownership of it. 86 Lexer(SourceLocation FileLoc, const LangOptions &Features, 87 const char *BufStart, const char *BufPtr, const char *BufEnd); 88 89 /// Lexer constructor - Create a new raw lexer object. This object is only 90 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text 91 /// range will outlive it, so it doesn't take ownership of it. 92 Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer, 93 const SourceManager &SM, const LangOptions &Features); 94 95 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for 96 /// _Pragma expansion. This has a variety of magic semantics that this method 97 /// sets up. It returns a new'd Lexer that must be delete'd when done. 98 static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc, 99 SourceLocation InstantiationLocStart, 100 SourceLocation InstantiationLocEnd, 101 unsigned TokLen, Preprocessor &PP); 102 103 104 /// getFeatures - Return the language features currently enabled. NOTE: this 105 /// lexer modifies features as a file is parsed! 106 const LangOptions &getFeatures() const { return Features; } 107 108 /// getFileLoc - Return the File Location for the file we are lexing out of. 109 /// The physical location encodes the location where the characters come from, 110 /// the virtual location encodes where we should *claim* the characters came 111 /// from. Currently this is only used by _Pragma handling. 112 SourceLocation getFileLoc() const { return FileLoc; } 113 114 /// Lex - Return the next token in the file. If this is the end of file, it 115 /// return the tok::eof token. Return true if an error occurred and 116 /// compilation should terminate, false if normal. This implicitly involves 117 /// the preprocessor. 118 void Lex(Token &Result) { 119 // Start a new token. 120 Result.startToken(); 121 122 // NOTE, any changes here should also change code after calls to 123 // Preprocessor::HandleDirective 124 if (IsAtStartOfLine) { 125 Result.setFlag(Token::StartOfLine); 126 IsAtStartOfLine = false; 127 } 128 129 // Get a token. Note that this may delete the current lexer if the end of 130 // file is reached. 131 LexTokenInternal(Result); 132 } 133 134 /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma. 135 bool isPragmaLexer() const { return Is_PragmaLexer; } 136 137 /// IndirectLex - An indirect call to 'Lex' that can be invoked via 138 /// the PreprocessorLexer interface. 139 void IndirectLex(Token &Result) { Lex(Result); } 140 141 /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no 142 /// associated preprocessor object. Return true if the 'next character to 143 /// read' pointer points at the end of the lexer buffer, false otherwise. 144 bool LexFromRawLexer(Token &Result) { 145 assert(LexingRawMode && "Not already in raw mode!"); 146 Lex(Result); 147 // Note that lexing to the end of the buffer doesn't implicitly delete the 148 // lexer when in raw mode. 149 return BufferPtr == BufferEnd; 150 } 151 152 /// isKeepWhitespaceMode - Return true if the lexer should return tokens for 153 /// every character in the file, including whitespace and comments. This 154 /// should only be used in raw mode, as the preprocessor is not prepared to 155 /// deal with the excess tokens. 156 bool isKeepWhitespaceMode() const { 157 return ExtendedTokenMode > 1; 158 } 159 160 /// SetKeepWhitespaceMode - This method lets clients enable or disable 161 /// whitespace retention mode. 162 void SetKeepWhitespaceMode(bool Val) { 163 assert((!Val || LexingRawMode) && 164 "Can only enable whitespace retention in raw mode"); 165 ExtendedTokenMode = Val ? 2 : 0; 166 } 167 168 /// inKeepCommentMode - Return true if the lexer should return comments as 169 /// tokens. 170 bool inKeepCommentMode() const { 171 return ExtendedTokenMode > 0; 172 } 173 174 /// SetCommentRetentionMode - Change the comment retention mode of the lexer 175 /// to the specified mode. This is really only useful when lexing in raw 176 /// mode, because otherwise the lexer needs to manage this. 177 void SetCommentRetentionState(bool Mode) { 178 assert(!isKeepWhitespaceMode() && 179 "Can't play with comment retention state when retaining whitespace"); 180 ExtendedTokenMode = Mode ? 1 : 0; 181 } 182 183 const char *getBufferStart() const { return BufferStart; } 184 185 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an 186 /// uninterpreted string. This switches the lexer out of directive mode. 187 std::string ReadToEndOfLine(); 188 189 190 /// Diag - Forwarding function for diagnostics. This translate a source 191 /// position in the current buffer into a SourceLocation object for rendering. 192 DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const; 193 194 /// getSourceLocation - Return a source location identifier for the specified 195 /// offset in the current file. 196 SourceLocation getSourceLocation(const char *Loc, unsigned TokLen = 1) const; 197 198 /// getSourceLocation - Return a source location for the next character in 199 /// the current file. 200 SourceLocation getSourceLocation() { return getSourceLocation(BufferPtr); } 201 202 /// \brief Return the current location in the buffer. 203 const char *getBufferLocation() const { return BufferPtr; } 204 205 /// Stringify - Convert the specified string into a C string by escaping '\' 206 /// and " characters. This does not add surrounding ""'s to the string. 207 /// If Charify is true, this escapes the ' character instead of ". 208 static std::string Stringify(const std::string &Str, bool Charify = false); 209 210 /// Stringify - Convert the specified string into a C string by escaping '\' 211 /// and " characters. This does not add surrounding ""'s to the string. 212 static void Stringify(llvm::SmallVectorImpl<char> &Str); 213 214 215 /// getSpelling - This method is used to get the spelling of a token into a 216 /// preallocated buffer, instead of as an std::string. The caller is required 217 /// to allocate enough space for the token, which is guaranteed to be at least 218 /// Tok.getLength() bytes long. The length of the actual result is returned. 219 /// 220 /// Note that this method may do two possible things: it may either fill in 221 /// the buffer specified with characters, or it may *change the input pointer* 222 /// to point to a constant buffer with the data already in it (avoiding a 223 /// copy). The caller is not allowed to modify the returned buffer pointer 224 /// if an internal buffer is returned. 225 static unsigned getSpelling(const Token &Tok, const char *&Buffer, 226 const SourceManager &SourceMgr, 227 const LangOptions &Features, 228 bool *Invalid = 0); 229 230 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a 231 /// token is the characters used to represent the token in the source file 232 /// after trigraph expansion and escaped-newline folding. In particular, this 233 /// wants to get the true, uncanonicalized, spelling of things like digraphs 234 /// UCNs, etc. 235 static std::string getSpelling(const Token &Tok, 236 const SourceManager &SourceMgr, 237 const LangOptions &Features, 238 bool *Invalid = 0); 239 240 /// getSpelling - This method is used to get the spelling of the 241 /// token at the given source location. If, as is usually true, it 242 /// is not necessary to copy any data, then the returned string may 243 /// not point into the provided buffer. 244 /// 245 /// This method lexes at the instantiation depth of the given 246 /// location and does not jump to the instantiation or spelling 247 /// location. 248 static llvm::StringRef getSpelling(SourceLocation loc, 249 llvm::SmallVectorImpl<char> &buffer, 250 const SourceManager &SourceMgr, 251 const LangOptions &Features, 252 bool *invalid = 0); 253 254 /// MeasureTokenLength - Relex the token at the specified location and return 255 /// its length in bytes in the input file. If the token needs cleaning (e.g. 256 /// includes a trigraph or an escaped newline) then this count includes bytes 257 /// that are part of that. 258 static unsigned MeasureTokenLength(SourceLocation Loc, 259 const SourceManager &SM, 260 const LangOptions &LangOpts); 261 262 /// \brief Given a location any where in a source buffer, find the location 263 /// that corresponds to the beginning of the token in which the original 264 /// source location lands. 265 /// 266 /// \param Loc 267 static SourceLocation GetBeginningOfToken(SourceLocation Loc, 268 const SourceManager &SM, 269 const LangOptions &LangOpts); 270 271 /// AdvanceToTokenCharacter - If the current SourceLocation specifies a 272 /// location at the start of a token, return a new location that specifies a 273 /// character within the token. This handles trigraphs and escaped newlines. 274 static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, 275 unsigned Character, 276 const SourceManager &SM, 277 const LangOptions &Features); 278 279 /// \brief Computes the source location just past the end of the 280 /// token at this source location. 281 /// 282 /// This routine can be used to produce a source location that 283 /// points just past the end of the token referenced by \p Loc, and 284 /// is generally used when a diagnostic needs to point just after a 285 /// token where it expected something different that it received. If 286 /// the returned source location would not be meaningful (e.g., if 287 /// it points into a macro), this routine returns an invalid 288 /// source location. 289 /// 290 /// \param Offset an offset from the end of the token, where the source 291 /// location should refer to. The default offset (0) produces a source 292 /// location pointing just past the end of the token; an offset of 1 produces 293 /// a source location pointing to the last character in the token, etc. 294 static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, 295 const SourceManager &SM, 296 const LangOptions &Features); 297 298 /// \brief Compute the preamble of the given file. 299 /// 300 /// The preamble of a file contains the initial comments, include directives, 301 /// and other preprocessor directives that occur before the code in this 302 /// particular file actually begins. The preamble of the main source file is 303 /// a potential prefix header. 304 /// 305 /// \param Buffer The memory buffer containing the file's contents. 306 /// 307 /// \param MaxLines If non-zero, restrict the length of the preamble 308 /// to fewer than this number of lines. 309 /// 310 /// \returns The offset into the file where the preamble ends and the rest 311 /// of the file begins along with a boolean value indicating whether 312 /// the preamble ends at the beginning of a new line. 313 static std::pair<unsigned, bool> 314 ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines = 0); 315 316 //===--------------------------------------------------------------------===// 317 // Internal implementation interfaces. 318private: 319 320 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called 321 /// by Lex. 322 /// 323 void LexTokenInternal(Token &Result); 324 325 /// FormTokenWithChars - When we lex a token, we have identified a span 326 /// starting at BufferPtr, going to TokEnd that forms the token. This method 327 /// takes that range and assigns it to the token as its location and size. In 328 /// addition, since tokens cannot overlap, this also updates BufferPtr to be 329 /// TokEnd. 330 void FormTokenWithChars(Token &Result, const char *TokEnd, 331 tok::TokenKind Kind) { 332 unsigned TokLen = TokEnd-BufferPtr; 333 Result.setLength(TokLen); 334 Result.setLocation(getSourceLocation(BufferPtr, TokLen)); 335 Result.setKind(Kind); 336 BufferPtr = TokEnd; 337 } 338 339 /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a 340 /// tok::l_paren token, 0 if it is something else and 2 if there are no more 341 /// tokens in the buffer controlled by this lexer. 342 unsigned isNextPPTokenLParen(); 343 344 //===--------------------------------------------------------------------===// 345 // Lexer character reading interfaces. 346public: 347 348 // This lexer is built on two interfaces for reading characters, both of which 349 // automatically provide phase 1/2 translation. getAndAdvanceChar is used 350 // when we know that we will be reading a character from the input buffer and 351 // that this character will be part of the result token. This occurs in (f.e.) 352 // string processing, because we know we need to read until we find the 353 // closing '"' character. 354 // 355 // The second interface is the combination of getCharAndSize with 356 // ConsumeChar. getCharAndSize reads a phase 1/2 translated character, 357 // returning it and its size. If the lexer decides that this character is 358 // part of the current token, it calls ConsumeChar on it. This two stage 359 // approach allows us to emit diagnostics for characters (e.g. warnings about 360 // trigraphs), knowing that they only are emitted if the character is 361 // consumed. 362 363 /// isObviouslySimpleCharacter - Return true if the specified character is 364 /// obviously the same in translation phase 1 and translation phase 3. This 365 /// can return false for characters that end up being the same, but it will 366 /// never return true for something that needs to be mapped. 367 static bool isObviouslySimpleCharacter(char C) { 368 return C != '?' && C != '\\'; 369 } 370 371 /// getAndAdvanceChar - Read a single 'character' from the specified buffer, 372 /// advance over it, and return it. This is tricky in several cases. Here we 373 /// just handle the trivial case and fall-back to the non-inlined 374 /// getCharAndSizeSlow method to handle the hard case. 375 inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) { 376 // If this is not a trigraph and not a UCN or escaped newline, return 377 // quickly. 378 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++; 379 380 unsigned Size = 0; 381 char C = getCharAndSizeSlow(Ptr, Size, &Tok); 382 Ptr += Size; 383 return C; 384 } 385 386private: 387 /// ConsumeChar - When a character (identified by getCharAndSize) is consumed 388 /// and added to a given token, check to see if there are diagnostics that 389 /// need to be emitted or flags that need to be set on the token. If so, do 390 /// it. 391 const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) { 392 // Normal case, we consumed exactly one token. Just return it. 393 if (Size == 1) 394 return Ptr+Size; 395 396 // Otherwise, re-lex the character with a current token, allowing 397 // diagnostics to be emitted and flags to be set. 398 Size = 0; 399 getCharAndSizeSlow(Ptr, Size, &Tok); 400 return Ptr+Size; 401 } 402 403 /// getCharAndSize - Peek a single 'character' from the specified buffer, 404 /// get its size, and return it. This is tricky in several cases. Here we 405 /// just handle the trivial case and fall-back to the non-inlined 406 /// getCharAndSizeSlow method to handle the hard case. 407 inline char getCharAndSize(const char *Ptr, unsigned &Size) { 408 // If this is not a trigraph and not a UCN or escaped newline, return 409 // quickly. 410 if (isObviouslySimpleCharacter(Ptr[0])) { 411 Size = 1; 412 return *Ptr; 413 } 414 415 Size = 0; 416 return getCharAndSizeSlow(Ptr, Size); 417 } 418 419 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize 420 /// method. 421 char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0); 422public: 423 424 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever 425 /// emit a warning. 426 static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, 427 const LangOptions &Features) { 428 // If this is not a trigraph and not a UCN or escaped newline, return 429 // quickly. 430 if (isObviouslySimpleCharacter(Ptr[0])) { 431 Size = 1; 432 return *Ptr; 433 } 434 435 Size = 0; 436 return getCharAndSizeSlowNoWarn(Ptr, Size, Features); 437 } 438 439 /// getEscapedNewLineSize - Return the size of the specified escaped newline, 440 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry 441 /// to this function. 442 static unsigned getEscapedNewLineSize(const char *P); 443 444 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of 445 /// them), skip over them and return the first non-escaped-newline found, 446 /// otherwise return P. 447 static const char *SkipEscapedNewLines(const char *P); 448private: 449 450 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a 451 /// diagnostic. 452 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, 453 const LangOptions &Features); 454 455 //===--------------------------------------------------------------------===// 456 // Other lexer functions. 457 458 void SkipBytes(unsigned Bytes, bool StartOfLine); 459 460 // Helper functions to lex the remainder of a token of the specific type. 461 void LexIdentifier (Token &Result, const char *CurPtr); 462 void LexNumericConstant (Token &Result, const char *CurPtr); 463 void LexStringLiteral (Token &Result, const char *CurPtr,bool Wide); 464 void LexAngledStringLiteral(Token &Result, const char *CurPtr); 465 void LexCharConstant (Token &Result, const char *CurPtr); 466 bool LexEndOfFile (Token &Result, const char *CurPtr); 467 468 bool SkipWhitespace (Token &Result, const char *CurPtr); 469 bool SkipBCPLComment (Token &Result, const char *CurPtr); 470 bool SkipBlockComment (Token &Result, const char *CurPtr); 471 bool SaveBCPLComment (Token &Result, const char *CurPtr); 472 473 bool IsStartOfConflictMarker(const char *CurPtr); 474 bool HandleEndOfConflictMarker(const char *CurPtr); 475}; 476 477 478} // end namespace clang 479 480#endif 481