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