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