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