1 //===- Lexer.h - C Language Family Lexer ------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the Lexer interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_LEX_LEXER_H 14 #define LLVM_CLANG_LEX_LEXER_H 15 16 #include "clang/Basic/LangOptions.h" 17 #include "clang/Basic/SourceLocation.h" 18 #include "clang/Basic/TokenKinds.h" 19 #include "clang/Lex/PreprocessorLexer.h" 20 #include "clang/Lex/Token.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/StringRef.h" 24 #include <cassert> 25 #include <cstdint> 26 #include <string> 27 28 namespace llvm { 29 30 class MemoryBuffer; 31 32 } // namespace llvm 33 34 namespace clang { 35 36 class DiagnosticBuilder; 37 class Preprocessor; 38 class SourceManager; 39 40 /// ConflictMarkerKind - Kinds of conflict marker which the lexer might be 41 /// recovering from. 42 enum ConflictMarkerKind { 43 /// Not within a conflict marker. 44 CMK_None, 45 46 /// A normal or diff3 conflict marker, initiated by at least 7 "<"s, 47 /// separated by at least 7 "="s or "|"s, and terminated by at least 7 ">"s. 48 CMK_Normal, 49 50 /// A Perforce-style conflict marker, initiated by 4 ">"s, 51 /// separated by 4 "="s, and terminated by 4 "<"s. 52 CMK_Perforce 53 }; 54 55 /// Describes the bounds (start, size) of the preamble and a flag required by 56 /// PreprocessorOptions::PrecompiledPreambleBytes. 57 /// The preamble includes the BOM, if any. 58 struct PreambleBounds { 59 /// Size of the preamble in bytes. 60 unsigned Size; 61 62 /// Whether the preamble ends at the start of a new line. 63 /// 64 /// Used to inform the lexer as to whether it's starting at the beginning of 65 /// a line after skipping the preamble. 66 bool PreambleEndsAtStartOfLine; 67 68 PreambleBounds(unsigned Size, bool PreambleEndsAtStartOfLine) 69 : Size(Size), PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {} 70 }; 71 72 /// Lexer - This provides a simple interface that turns a text buffer into a 73 /// stream of tokens. This provides no support for file reading or buffering, 74 /// or buffering/seeking of tokens, only forward lexing is supported. It relies 75 /// on the specified Preprocessor object to handle preprocessor directives, etc. 76 class Lexer : public PreprocessorLexer { 77 friend class Preprocessor; 78 79 void anchor() override; 80 81 //===--------------------------------------------------------------------===// 82 // Constant configuration values for this lexer. 83 84 // Start of the buffer. 85 const char *BufferStart; 86 87 // End of the buffer. 88 const char *BufferEnd; 89 90 // Location for start of file. 91 SourceLocation FileLoc; 92 93 // LangOpts enabled by this language (cache). 94 LangOptions LangOpts; 95 96 // True if lexer for _Pragma handling. 97 bool Is_PragmaLexer; 98 99 //===--------------------------------------------------------------------===// 100 // Context-specific lexing flags set by the preprocessor. 101 // 102 103 /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace 104 /// and return them as tokens. This is used for -C and -CC modes, and 105 /// whitespace preservation can be useful for some clients that want to lex 106 /// the file in raw mode and get every character from the file. 107 /// 108 /// When this is set to 2 it returns comments and whitespace. When set to 1 109 /// it returns comments, when it is set to 0 it returns normal tokens only. 110 unsigned char ExtendedTokenMode; 111 112 //===--------------------------------------------------------------------===// 113 // Context that changes as the file is lexed. 114 // NOTE: any state that mutates when in raw mode must have save/restore code 115 // in Lexer::isNextPPTokenLParen. 116 117 // BufferPtr - Current pointer into the buffer. This is the next character 118 // to be lexed. 119 const char *BufferPtr; 120 121 // IsAtStartOfLine - True if the next lexed token should get the "start of 122 // line" flag set on it. 123 bool IsAtStartOfLine; 124 125 bool IsAtPhysicalStartOfLine; 126 127 bool HasLeadingSpace; 128 129 bool HasLeadingEmptyMacro; 130 131 // CurrentConflictMarkerState - The kind of conflict marker we are handling. 132 ConflictMarkerKind CurrentConflictMarkerState; 133 134 void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd); 135 136 public: 137 /// Lexer constructor - Create a new lexer object for the specified buffer 138 /// with the specified preprocessor managing the lexing process. This lexer 139 /// assumes that the associated file buffer and Preprocessor objects will 140 /// outlive it, so it doesn't take ownership of either of them. 141 Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP); 142 143 /// Lexer constructor - Create a new raw lexer object. This object is only 144 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the 145 /// text range will outlive it, so it doesn't take ownership of it. 146 Lexer(SourceLocation FileLoc, const LangOptions &LangOpts, 147 const char *BufStart, const char *BufPtr, const char *BufEnd); 148 149 /// Lexer constructor - Create a new raw lexer object. This object is only 150 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the 151 /// text range will outlive it, so it doesn't take ownership of it. 152 Lexer(FileID FID, const llvm::MemoryBuffer *FromFile, 153 const SourceManager &SM, const LangOptions &LangOpts); 154 155 Lexer(const Lexer &) = delete; 156 Lexer &operator=(const Lexer &) = delete; 157 158 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for 159 /// _Pragma expansion. This has a variety of magic semantics that this method 160 /// sets up. It returns a new'd Lexer that must be delete'd when done. 161 static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc, 162 SourceLocation ExpansionLocStart, 163 SourceLocation ExpansionLocEnd, 164 unsigned TokLen, Preprocessor &PP); 165 166 /// getLangOpts - Return the language features currently enabled. 167 /// NOTE: this lexer modifies features as a file is parsed! 168 const LangOptions &getLangOpts() const { return LangOpts; } 169 170 /// getFileLoc - Return the File Location for the file we are lexing out of. 171 /// The physical location encodes the location where the characters come from, 172 /// the virtual location encodes where we should *claim* the characters came 173 /// from. Currently this is only used by _Pragma handling. 174 SourceLocation getFileLoc() const { return FileLoc; } 175 176 private: 177 /// Lex - Return the next token in the file. If this is the end of file, it 178 /// return the tok::eof token. This implicitly involves the preprocessor. 179 bool Lex(Token &Result); 180 181 public: 182 /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma. 183 bool isPragmaLexer() const { return Is_PragmaLexer; } 184 185 private: 186 /// IndirectLex - An indirect call to 'Lex' that can be invoked via 187 /// the PreprocessorLexer interface. 188 void IndirectLex(Token &Result) override { Lex(Result); } 189 190 public: 191 /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no 192 /// associated preprocessor object. Return true if the 'next character to 193 /// read' pointer points at the end of the lexer buffer, false otherwise. 194 bool LexFromRawLexer(Token &Result) { 195 assert(LexingRawMode && "Not already in raw mode!"); 196 Lex(Result); 197 // Note that lexing to the end of the buffer doesn't implicitly delete the 198 // lexer when in raw mode. 199 return BufferPtr == BufferEnd; 200 } 201 202 /// isKeepWhitespaceMode - Return true if the lexer should return tokens for 203 /// every character in the file, including whitespace and comments. This 204 /// should only be used in raw mode, as the preprocessor is not prepared to 205 /// deal with the excess tokens. 206 bool isKeepWhitespaceMode() const { 207 return ExtendedTokenMode > 1; 208 } 209 210 /// SetKeepWhitespaceMode - This method lets clients enable or disable 211 /// whitespace retention mode. 212 void SetKeepWhitespaceMode(bool Val) { 213 assert((!Val || LexingRawMode || LangOpts.TraditionalCPP) && 214 "Can only retain whitespace in raw mode or -traditional-cpp"); 215 ExtendedTokenMode = Val ? 2 : 0; 216 } 217 218 /// inKeepCommentMode - Return true if the lexer should return comments as 219 /// tokens. 220 bool inKeepCommentMode() const { 221 return ExtendedTokenMode > 0; 222 } 223 224 /// SetCommentRetentionMode - Change the comment retention mode of the lexer 225 /// to the specified mode. This is really only useful when lexing in raw 226 /// mode, because otherwise the lexer needs to manage this. 227 void SetCommentRetentionState(bool Mode) { 228 assert(!isKeepWhitespaceMode() && 229 "Can't play with comment retention state when retaining whitespace"); 230 ExtendedTokenMode = Mode ? 1 : 0; 231 } 232 233 /// Sets the extended token mode back to its initial value, according to the 234 /// language options and preprocessor. This controls whether the lexer 235 /// produces comment and whitespace tokens. 236 /// 237 /// This requires the lexer to have an associated preprocessor. A standalone 238 /// lexer has nothing to reset to. 239 void resetExtendedTokenMode(); 240 241 /// Gets source code buffer. 242 StringRef getBuffer() const { 243 return StringRef(BufferStart, BufferEnd - BufferStart); 244 } 245 246 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an 247 /// uninterpreted string. This switches the lexer out of directive mode. 248 void ReadToEndOfLine(SmallVectorImpl<char> *Result = nullptr); 249 250 251 /// Diag - Forwarding function for diagnostics. This translate a source 252 /// position in the current buffer into a SourceLocation object for rendering. 253 DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const; 254 255 /// getSourceLocation - Return a source location identifier for the specified 256 /// offset in the current file. 257 SourceLocation getSourceLocation(const char *Loc, unsigned TokLen = 1) const; 258 259 /// getSourceLocation - Return a source location for the next character in 260 /// the current file. 261 SourceLocation getSourceLocation() override { 262 return getSourceLocation(BufferPtr); 263 } 264 265 /// Return the current location in the buffer. 266 const char *getBufferLocation() const { return BufferPtr; } 267 268 /// Returns the current lexing offset. 269 unsigned getCurrentBufferOffset() { 270 assert(BufferPtr >= BufferStart && "Invalid buffer state"); 271 return BufferPtr - BufferStart; 272 } 273 274 /// Skip over \p NumBytes bytes. 275 /// 276 /// If the skip is successful, the next token will be lexed from the new 277 /// offset. The lexer also assumes that we skipped to the start of the line. 278 /// 279 /// \returns true if the skip failed (new offset would have been past the 280 /// end of the buffer), false otherwise. 281 bool skipOver(unsigned NumBytes); 282 283 /// Stringify - Convert the specified string into a C string by i) escaping 284 /// '\\' and " characters and ii) replacing newline character(s) with "\\n". 285 /// If Charify is true, this escapes the ' character instead of ". 286 static std::string Stringify(StringRef Str, bool Charify = false); 287 288 /// Stringify - Convert the specified string into a C string by i) escaping 289 /// '\\' and " characters and ii) replacing newline character(s) with "\\n". 290 static void Stringify(SmallVectorImpl<char> &Str); 291 292 /// getSpelling - This method is used to get the spelling of a token into a 293 /// preallocated buffer, instead of as an std::string. The caller is required 294 /// to allocate enough space for the token, which is guaranteed to be at least 295 /// Tok.getLength() bytes long. The length of the actual result is returned. 296 /// 297 /// Note that this method may do two possible things: it may either fill in 298 /// the buffer specified with characters, or it may *change the input pointer* 299 /// to point to a constant buffer with the data already in it (avoiding a 300 /// copy). The caller is not allowed to modify the returned buffer pointer 301 /// if an internal buffer is returned. 302 static unsigned getSpelling(const Token &Tok, const char *&Buffer, 303 const SourceManager &SourceMgr, 304 const LangOptions &LangOpts, 305 bool *Invalid = nullptr); 306 307 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a 308 /// token is the characters used to represent the token in the source file 309 /// after trigraph expansion and escaped-newline folding. In particular, this 310 /// wants to get the true, uncanonicalized, spelling of things like digraphs 311 /// UCNs, etc. 312 static std::string getSpelling(const Token &Tok, 313 const SourceManager &SourceMgr, 314 const LangOptions &LangOpts, 315 bool *Invalid = nullptr); 316 317 /// getSpelling - This method is used to get the spelling of the 318 /// token at the given source location. If, as is usually true, it 319 /// is not necessary to copy any data, then the returned string may 320 /// not point into the provided buffer. 321 /// 322 /// This method lexes at the expansion depth of the given 323 /// location and does not jump to the expansion or spelling 324 /// location. 325 static StringRef getSpelling(SourceLocation loc, 326 SmallVectorImpl<char> &buffer, 327 const SourceManager &SM, 328 const LangOptions &options, 329 bool *invalid = nullptr); 330 331 /// MeasureTokenLength - Relex the token at the specified location and return 332 /// its length in bytes in the input file. If the token needs cleaning (e.g. 333 /// includes a trigraph or an escaped newline) then this count includes bytes 334 /// that are part of that. 335 static unsigned MeasureTokenLength(SourceLocation Loc, 336 const SourceManager &SM, 337 const LangOptions &LangOpts); 338 339 /// Relex the token at the specified location. 340 /// \returns true if there was a failure, false on success. 341 static bool getRawToken(SourceLocation Loc, Token &Result, 342 const SourceManager &SM, 343 const LangOptions &LangOpts, 344 bool IgnoreWhiteSpace = false); 345 346 /// Given a location any where in a source buffer, find the location 347 /// that corresponds to the beginning of the token in which the original 348 /// source location lands. 349 static SourceLocation GetBeginningOfToken(SourceLocation Loc, 350 const SourceManager &SM, 351 const LangOptions &LangOpts); 352 353 /// Get the physical length (including trigraphs and escaped newlines) of the 354 /// first \p Characters characters of the token starting at TokStart. 355 static unsigned getTokenPrefixLength(SourceLocation TokStart, 356 unsigned CharNo, 357 const SourceManager &SM, 358 const LangOptions &LangOpts); 359 360 /// AdvanceToTokenCharacter - If the current SourceLocation specifies a 361 /// location at the start of a token, return a new location that specifies a 362 /// character within the token. This handles trigraphs and escaped newlines. 363 static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, 364 unsigned Characters, 365 const SourceManager &SM, 366 const LangOptions &LangOpts) { 367 return TokStart.getLocWithOffset( 368 getTokenPrefixLength(TokStart, Characters, SM, LangOpts)); 369 } 370 371 /// Computes the source location just past the end of the 372 /// token at this source location. 373 /// 374 /// This routine can be used to produce a source location that 375 /// points just past the end of the token referenced by \p Loc, and 376 /// is generally used when a diagnostic needs to point just after a 377 /// token where it expected something different that it received. If 378 /// the returned source location would not be meaningful (e.g., if 379 /// it points into a macro), this routine returns an invalid 380 /// source location. 381 /// 382 /// \param Offset an offset from the end of the token, where the source 383 /// location should refer to. The default offset (0) produces a source 384 /// location pointing just past the end of the token; an offset of 1 produces 385 /// a source location pointing to the last character in the token, etc. 386 static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, 387 const SourceManager &SM, 388 const LangOptions &LangOpts); 389 390 /// Given a token range, produce a corresponding CharSourceRange that 391 /// is not a token range. This allows the source range to be used by 392 /// components that don't have access to the lexer and thus can't find the 393 /// end of the range for themselves. 394 static CharSourceRange getAsCharRange(SourceRange Range, 395 const SourceManager &SM, 396 const LangOptions &LangOpts) { 397 SourceLocation End = getLocForEndOfToken(Range.getEnd(), 0, SM, LangOpts); 398 return End.isInvalid() ? CharSourceRange() 399 : CharSourceRange::getCharRange( 400 Range.getBegin(), End); 401 } 402 static CharSourceRange getAsCharRange(CharSourceRange Range, 403 const SourceManager &SM, 404 const LangOptions &LangOpts) { 405 return Range.isTokenRange() 406 ? getAsCharRange(Range.getAsRange(), SM, LangOpts) 407 : Range; 408 } 409 410 /// Returns true if the given MacroID location points at the first 411 /// token of the macro expansion. 412 /// 413 /// \param MacroBegin If non-null and function returns true, it is set to 414 /// begin location of the macro. 415 static bool isAtStartOfMacroExpansion(SourceLocation loc, 416 const SourceManager &SM, 417 const LangOptions &LangOpts, 418 SourceLocation *MacroBegin = nullptr); 419 420 /// Returns true if the given MacroID location points at the last 421 /// token of the macro expansion. 422 /// 423 /// \param MacroEnd If non-null and function returns true, it is set to 424 /// end location of the macro. 425 static bool isAtEndOfMacroExpansion(SourceLocation loc, 426 const SourceManager &SM, 427 const LangOptions &LangOpts, 428 SourceLocation *MacroEnd = nullptr); 429 430 /// Accepts a range and returns a character range with file locations. 431 /// 432 /// Returns a null range if a part of the range resides inside a macro 433 /// expansion or the range does not reside on the same FileID. 434 /// 435 /// This function is trying to deal with macros and return a range based on 436 /// file locations. The cases where it can successfully handle macros are: 437 /// 438 /// -begin or end range lies at the start or end of a macro expansion, in 439 /// which case the location will be set to the expansion point, e.g: 440 /// \#define M 1 2 441 /// a M 442 /// If you have a range [a, 2] (where 2 came from the macro), the function 443 /// will return a range for "a M" 444 /// if you have range [a, 1], the function will fail because the range 445 /// overlaps with only a part of the macro 446 /// 447 /// -The macro is a function macro and the range can be mapped to the macro 448 /// arguments, e.g: 449 /// \#define M 1 2 450 /// \#define FM(x) x 451 /// FM(a b M) 452 /// if you have range [b, 2], the function will return the file range "b M" 453 /// inside the macro arguments. 454 /// if you have range [a, 2], the function will return the file range 455 /// "FM(a b M)" since the range includes all of the macro expansion. 456 static CharSourceRange makeFileCharRange(CharSourceRange Range, 457 const SourceManager &SM, 458 const LangOptions &LangOpts); 459 460 /// Returns a string for the source that the range encompasses. 461 static StringRef getSourceText(CharSourceRange Range, 462 const SourceManager &SM, 463 const LangOptions &LangOpts, 464 bool *Invalid = nullptr); 465 466 /// Retrieve the name of the immediate macro expansion. 467 /// 468 /// This routine starts from a source location, and finds the name of the macro 469 /// responsible for its immediate expansion. It looks through any intervening 470 /// macro argument expansions to compute this. It returns a StringRef which 471 /// refers to the SourceManager-owned buffer of the source where that macro 472 /// name is spelled. Thus, the result shouldn't out-live that SourceManager. 473 static StringRef getImmediateMacroName(SourceLocation Loc, 474 const SourceManager &SM, 475 const LangOptions &LangOpts); 476 477 /// Retrieve the name of the immediate macro expansion. 478 /// 479 /// This routine starts from a source location, and finds the name of the 480 /// macro responsible for its immediate expansion. It looks through any 481 /// intervening macro argument expansions to compute this. It returns a 482 /// StringRef which refers to the SourceManager-owned buffer of the source 483 /// where that macro name is spelled. Thus, the result shouldn't out-live 484 /// that SourceManager. 485 /// 486 /// This differs from Lexer::getImmediateMacroName in that any macro argument 487 /// location will result in the topmost function macro that accepted it. 488 /// e.g. 489 /// \code 490 /// MAC1( MAC2(foo) ) 491 /// \endcode 492 /// for location of 'foo' token, this function will return "MAC1" while 493 /// Lexer::getImmediateMacroName will return "MAC2". 494 static StringRef getImmediateMacroNameForDiagnostics( 495 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts); 496 497 /// Compute the preamble of the given file. 498 /// 499 /// The preamble of a file contains the initial comments, include directives, 500 /// and other preprocessor directives that occur before the code in this 501 /// particular file actually begins. The preamble of the main source file is 502 /// a potential prefix header. 503 /// 504 /// \param Buffer The memory buffer containing the file's contents. 505 /// 506 /// \param MaxLines If non-zero, restrict the length of the preamble 507 /// to fewer than this number of lines. 508 /// 509 /// \returns The offset into the file where the preamble ends and the rest 510 /// of the file begins along with a boolean value indicating whether 511 /// the preamble ends at the beginning of a new line. 512 static PreambleBounds ComputePreamble(StringRef Buffer, 513 const LangOptions &LangOpts, 514 unsigned MaxLines = 0); 515 516 /// Finds the token that comes right after the given location. 517 /// 518 /// Returns the next token, or none if the location is inside a macro. 519 static Optional<Token> findNextToken(SourceLocation Loc, 520 const SourceManager &SM, 521 const LangOptions &LangOpts); 522 523 /// Checks that the given token is the first token that occurs after 524 /// the given location (this excludes comments and whitespace). Returns the 525 /// location immediately after the specified token. If the token is not found 526 /// or the location is inside a macro, the returned source location will be 527 /// invalid. 528 static SourceLocation findLocationAfterToken(SourceLocation loc, 529 tok::TokenKind TKind, 530 const SourceManager &SM, 531 const LangOptions &LangOpts, 532 bool SkipTrailingWhitespaceAndNewLine); 533 534 /// Returns true if the given character could appear in an identifier. 535 static bool isIdentifierBodyChar(char c, const LangOptions &LangOpts); 536 537 /// Checks whether new line pointed by Str is preceded by escape 538 /// sequence. 539 static bool isNewLineEscaped(const char *BufferStart, const char *Str); 540 541 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever 542 /// emit a warning. 543 static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, 544 const LangOptions &LangOpts) { 545 // If this is not a trigraph and not a UCN or escaped newline, return 546 // quickly. 547 if (isObviouslySimpleCharacter(Ptr[0])) { 548 Size = 1; 549 return *Ptr; 550 } 551 552 Size = 0; 553 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts); 554 } 555 556 /// Returns the leading whitespace for line that corresponds to the given 557 /// location \p Loc. 558 static StringRef getIndentationForLine(SourceLocation Loc, 559 const SourceManager &SM); 560 561 private: 562 //===--------------------------------------------------------------------===// 563 // Internal implementation interfaces. 564 565 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called 566 /// by Lex. 567 /// 568 bool LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine); 569 570 bool CheckUnicodeWhitespace(Token &Result, uint32_t C, const char *CurPtr); 571 572 /// Given that a token begins with the Unicode character \p C, figure out 573 /// what kind of token it is and dispatch to the appropriate lexing helper 574 /// function. 575 bool LexUnicode(Token &Result, uint32_t C, const char *CurPtr); 576 577 /// FormTokenWithChars - When we lex a token, we have identified a span 578 /// starting at BufferPtr, going to TokEnd that forms the token. This method 579 /// takes that range and assigns it to the token as its location and size. In 580 /// addition, since tokens cannot overlap, this also updates BufferPtr to be 581 /// TokEnd. 582 void FormTokenWithChars(Token &Result, const char *TokEnd, 583 tok::TokenKind Kind) { 584 unsigned TokLen = TokEnd-BufferPtr; 585 Result.setLength(TokLen); 586 Result.setLocation(getSourceLocation(BufferPtr, TokLen)); 587 Result.setKind(Kind); 588 BufferPtr = TokEnd; 589 } 590 591 /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a 592 /// tok::l_paren token, 0 if it is something else and 2 if there are no more 593 /// tokens in the buffer controlled by this lexer. 594 unsigned isNextPPTokenLParen(); 595 596 //===--------------------------------------------------------------------===// 597 // Lexer character reading interfaces. 598 599 // This lexer is built on two interfaces for reading characters, both of which 600 // automatically provide phase 1/2 translation. getAndAdvanceChar is used 601 // when we know that we will be reading a character from the input buffer and 602 // that this character will be part of the result token. This occurs in (f.e.) 603 // string processing, because we know we need to read until we find the 604 // closing '"' character. 605 // 606 // The second interface is the combination of getCharAndSize with 607 // ConsumeChar. getCharAndSize reads a phase 1/2 translated character, 608 // returning it and its size. If the lexer decides that this character is 609 // part of the current token, it calls ConsumeChar on it. This two stage 610 // approach allows us to emit diagnostics for characters (e.g. warnings about 611 // trigraphs), knowing that they only are emitted if the character is 612 // consumed. 613 614 /// isObviouslySimpleCharacter - Return true if the specified character is 615 /// obviously the same in translation phase 1 and translation phase 3. This 616 /// can return false for characters that end up being the same, but it will 617 /// never return true for something that needs to be mapped. 618 static bool isObviouslySimpleCharacter(char C) { 619 return C != '?' && C != '\\'; 620 } 621 622 /// getAndAdvanceChar - Read a single 'character' from the specified buffer, 623 /// advance over it, and return it. This is tricky in several cases. Here we 624 /// just handle the trivial case and fall-back to the non-inlined 625 /// getCharAndSizeSlow method to handle the hard case. 626 inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) { 627 // If this is not a trigraph and not a UCN or escaped newline, return 628 // quickly. 629 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++; 630 631 unsigned Size = 0; 632 char C = getCharAndSizeSlow(Ptr, Size, &Tok); 633 Ptr += Size; 634 return C; 635 } 636 637 /// ConsumeChar - When a character (identified by getCharAndSize) is consumed 638 /// and added to a given token, check to see if there are diagnostics that 639 /// need to be emitted or flags that need to be set on the token. If so, do 640 /// it. 641 const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) { 642 // Normal case, we consumed exactly one token. Just return it. 643 if (Size == 1) 644 return Ptr+Size; 645 646 // Otherwise, re-lex the character with a current token, allowing 647 // diagnostics to be emitted and flags to be set. 648 Size = 0; 649 getCharAndSizeSlow(Ptr, Size, &Tok); 650 return Ptr+Size; 651 } 652 653 /// getCharAndSize - Peek a single 'character' from the specified buffer, 654 /// get its size, and return it. This is tricky in several cases. Here we 655 /// just handle the trivial case and fall-back to the non-inlined 656 /// getCharAndSizeSlow method to handle the hard case. 657 inline char getCharAndSize(const char *Ptr, unsigned &Size) { 658 // If this is not a trigraph and not a UCN or escaped newline, return 659 // quickly. 660 if (isObviouslySimpleCharacter(Ptr[0])) { 661 Size = 1; 662 return *Ptr; 663 } 664 665 Size = 0; 666 return getCharAndSizeSlow(Ptr, Size); 667 } 668 669 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize 670 /// method. 671 char getCharAndSizeSlow(const char *Ptr, unsigned &Size, 672 Token *Tok = nullptr); 673 674 /// getEscapedNewLineSize - Return the size of the specified escaped newline, 675 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry 676 /// to this function. 677 static unsigned getEscapedNewLineSize(const char *P); 678 679 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of 680 /// them), skip over them and return the first non-escaped-newline found, 681 /// otherwise return P. 682 static const char *SkipEscapedNewLines(const char *P); 683 684 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a 685 /// diagnostic. 686 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, 687 const LangOptions &LangOpts); 688 689 //===--------------------------------------------------------------------===// 690 // Other lexer functions. 691 692 void SetByteOffset(unsigned Offset, bool StartOfLine); 693 694 void PropagateLineStartLeadingSpaceInfo(Token &Result); 695 696 const char *LexUDSuffix(Token &Result, const char *CurPtr, 697 bool IsStringLiteral); 698 699 // Helper functions to lex the remainder of a token of the specific type. 700 bool LexIdentifier (Token &Result, const char *CurPtr); 701 bool LexNumericConstant (Token &Result, const char *CurPtr); 702 bool LexStringLiteral (Token &Result, const char *CurPtr, 703 tok::TokenKind Kind); 704 bool LexRawStringLiteral (Token &Result, const char *CurPtr, 705 tok::TokenKind Kind); 706 bool LexAngledStringLiteral(Token &Result, const char *CurPtr); 707 bool LexCharConstant (Token &Result, const char *CurPtr, 708 tok::TokenKind Kind); 709 bool LexEndOfFile (Token &Result, const char *CurPtr); 710 bool SkipWhitespace (Token &Result, const char *CurPtr, 711 bool &TokAtPhysicalStartOfLine); 712 bool SkipLineComment (Token &Result, const char *CurPtr, 713 bool &TokAtPhysicalStartOfLine); 714 bool SkipBlockComment (Token &Result, const char *CurPtr, 715 bool &TokAtPhysicalStartOfLine); 716 bool SaveLineComment (Token &Result, const char *CurPtr); 717 718 bool IsStartOfConflictMarker(const char *CurPtr); 719 bool HandleEndOfConflictMarker(const char *CurPtr); 720 721 bool lexEditorPlaceholder(Token &Result, const char *CurPtr); 722 723 bool isCodeCompletionPoint(const char *CurPtr) const; 724 void cutOffLexing() { BufferPtr = BufferEnd; } 725 726 bool isHexaLiteral(const char *Start, const LangOptions &LangOpts); 727 728 void codeCompleteIncludedFile(const char *PathStart, 729 const char *CompletionPoint, bool IsAngled); 730 731 /// Read a universal character name. 732 /// 733 /// \param StartPtr The position in the source buffer after the initial '\'. 734 /// If the UCN is syntactically well-formed (but not 735 /// necessarily valid), this parameter will be updated to 736 /// point to the character after the UCN. 737 /// \param SlashLoc The position in the source buffer of the '\'. 738 /// \param Result The token being formed. Pass \c nullptr to suppress 739 /// diagnostics and handle token formation in the caller. 740 /// 741 /// \return The Unicode codepoint specified by the UCN, or 0 if the UCN is 742 /// invalid. 743 uint32_t tryReadUCN(const char *&StartPtr, const char *SlashLoc, Token *Result); 744 745 /// Try to consume a UCN as part of an identifier at the current 746 /// location. 747 /// \param CurPtr Initially points to the range of characters in the source 748 /// buffer containing the '\'. Updated to point past the end of 749 /// the UCN on success. 750 /// \param Size The number of characters occupied by the '\' (including 751 /// trigraphs and escaped newlines). 752 /// \param Result The token being produced. Marked as containing a UCN on 753 /// success. 754 /// \return \c true if a UCN was lexed and it produced an acceptable 755 /// identifier character, \c false otherwise. 756 bool tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size, 757 Token &Result); 758 759 /// Try to consume an identifier character encoded in UTF-8. 760 /// \param CurPtr Points to the start of the (potential) UTF-8 code unit 761 /// sequence. On success, updated to point past the end of it. 762 /// \return \c true if a UTF-8 sequence mapping to an acceptable identifier 763 /// character was lexed, \c false otherwise. 764 bool tryConsumeIdentifierUTF8Char(const char *&CurPtr); 765 }; 766 767 } // namespace clang 768 769 #endif // LLVM_CLANG_LEX_LEXER_H 770