1 //===- Lexer.h - C Language Family Lexer ------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the Lexer interface.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_LEX_LEXER_H
14 #define LLVM_CLANG_LEX_LEXER_H
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"
36 class DiagnosticBuilder;
40 /// ConflictMarkerKind - Kinds of conflict marker which the lexer might be
42 enum ConflictMarkerKind {
43 /// Not within a conflict marker.
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.
50 /// A Perforce-style conflict marker, initiated by 4 ">"s,
51 /// separated by 4 "="s, and terminated by 4 "<"s.
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.
62 /// Whether the preamble ends at the start of a new line.
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;
68 PreambleBounds(unsigned Size, bool PreambleEndsAtStartOfLine)
69 : Size(Size), PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
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;
79 void anchor() override;
81 //===--------------------------------------------------------------------===//
82 // Constant configuration values for this lexer.
84 // Start of the buffer.
85 const char *BufferStart;
88 const char *BufferEnd;
90 // Location for start of file.
91 SourceLocation FileLoc;
93 // LangOpts enabled by this language (cache).
96 // True if lexer for _Pragma handling.
99 //===--------------------------------------------------------------------===//
100 // Context-specific lexing flags set by the preprocessor.
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.
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;
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.
117 // BufferPtr - Current pointer into the buffer. This is the next character
119 const char *BufferPtr;
121 // IsAtStartOfLine - True if the next lexed token should get the "start of
122 // line" flag set on it.
123 bool IsAtStartOfLine;
125 bool IsAtPhysicalStartOfLine;
127 bool HasLeadingSpace;
129 bool HasLeadingEmptyMacro;
131 // CurrentConflictMarkerState - The kind of conflict marker we are handling.
132 ConflictMarkerKind CurrentConflictMarkerState;
134 void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd);
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);
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);
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);
155 Lexer(const Lexer &) = delete;
156 Lexer &operator=(const Lexer &) = delete;
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);
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; }
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; }
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);
182 /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
183 bool isPragmaLexer() const { return Is_PragmaLexer; }
186 /// IndirectLex - An indirect call to 'Lex' that can be invoked via
187 /// the PreprocessorLexer interface.
188 void IndirectLex(Token &Result) override { Lex(Result); }
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!");
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;
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;
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;
218 /// inKeepCommentMode - Return true if the lexer should return comments as
220 bool inKeepCommentMode() const {
221 return ExtendedTokenMode > 0;
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;
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.
237 /// This requires the lexer to have an associated preprocessor. A standalone
238 /// lexer has nothing to reset to.
239 void resetExtendedTokenMode();
241 /// Gets source code buffer.
242 StringRef getBuffer() const {
243 return StringRef(BufferStart, BufferEnd - BufferStart);
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);
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;
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;
259 /// getSourceLocation - Return a source location for the next character in
260 /// the current file.
261 SourceLocation getSourceLocation() override {
262 return getSourceLocation(BufferPtr);
265 /// Return the current location in the buffer.
266 const char *getBufferLocation() const { return BufferPtr; }
268 /// Returns the current lexing offset.
269 unsigned getCurrentBufferOffset() {
270 assert(BufferPtr >= BufferStart && "Invalid buffer state");
271 return BufferPtr - BufferStart;
274 /// Skip over \p NumBytes bytes.
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.
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);
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);
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);
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.
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);
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
312 static std::string getSpelling(const Token &Tok,
313 const SourceManager &SourceMgr,
314 const LangOptions &LangOpts,
315 bool *Invalid = nullptr);
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.
322 /// This method lexes at the expansion depth of the given
323 /// location and does not jump to the expansion or spelling
325 static StringRef getSpelling(SourceLocation loc,
326 SmallVectorImpl<char> &buffer,
327 const SourceManager &SM,
328 const LangOptions &options,
329 bool *invalid = nullptr);
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);
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);
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);
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,
357 const SourceManager &SM,
358 const LangOptions &LangOpts);
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,
365 const SourceManager &SM,
366 const LangOptions &LangOpts) {
367 return TokStart.getLocWithOffset(
368 getTokenPrefixLength(TokStart, Characters, SM, LangOpts));
371 /// Computes the source location just past the end of the
372 /// token at this source location.
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
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);
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);
402 static CharSourceRange getAsCharRange(CharSourceRange Range,
403 const SourceManager &SM,
404 const LangOptions &LangOpts) {
405 return Range.isTokenRange()
406 ? getAsCharRange(Range.getAsRange(), SM, LangOpts)
410 /// Returns true if the given MacroID location points at the first
411 /// token of the macro expansion.
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);
420 /// Returns true if the given MacroID location points at the last
421 /// token of the macro expansion.
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);
430 /// Accepts a range and returns a character range with file locations.
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.
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:
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:
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
447 /// -The macro is a function macro and the range can be mapped to the macro
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);
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);
466 /// Retrieve the name of the immediate macro expansion.
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);
477 /// Retrieve the name of the immediate macro expansion.
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.
486 /// This differs from Lexer::getImmediateMacroName in that any macro argument
487 /// location will result in the topmost function macro that accepted it.
490 /// MAC1( MAC2(foo) )
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);
497 /// Compute the preamble of the given file.
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.
504 /// \param Buffer The memory buffer containing the file's contents.
506 /// \param MaxLines If non-zero, restrict the length of the preamble
507 /// to fewer than this number of lines.
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);
516 /// Finds the token that comes right after the given location.
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);
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
528 static SourceLocation findLocationAfterToken(SourceLocation loc,
529 tok::TokenKind TKind,
530 const SourceManager &SM,
531 const LangOptions &LangOpts,
532 bool SkipTrailingWhitespaceAndNewLine);
534 /// Returns true if the given character could appear in an identifier.
535 static bool isIdentifierBodyChar(char c, const LangOptions &LangOpts);
537 /// Checks whether new line pointed by Str is preceded by escape
539 static bool isNewLineEscaped(const char *BufferStart, const char *Str);
541 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
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
547 if (isObviouslySimpleCharacter(Ptr[0])) {
553 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
556 /// Returns the leading whitespace for line that corresponds to the given
558 static StringRef getIndentationForLine(SourceLocation Loc,
559 const SourceManager &SM);
562 //===--------------------------------------------------------------------===//
563 // Internal implementation interfaces.
565 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
568 bool LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine);
570 bool CheckUnicodeWhitespace(Token &Result, uint32_t C, const char *CurPtr);
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
575 bool LexUnicode(Token &Result, uint32_t C, const char *CurPtr);
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
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);
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();
596 //===--------------------------------------------------------------------===//
597 // Lexer character reading interfaces.
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.
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
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 != '\\';
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
629 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
632 char C = getCharAndSizeSlow(Ptr, Size, &Tok);
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
641 const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
642 // Normal case, we consumed exactly one token. Just return it.
646 // Otherwise, re-lex the character with a current token, allowing
647 // diagnostics to be emitted and flags to be set.
649 getCharAndSizeSlow(Ptr, Size, &Tok);
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
660 if (isObviouslySimpleCharacter(Ptr[0])) {
666 return getCharAndSizeSlow(Ptr, Size);
669 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
671 char getCharAndSizeSlow(const char *Ptr, unsigned &Size,
672 Token *Tok = nullptr);
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);
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);
684 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
686 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
687 const LangOptions &LangOpts);
689 //===--------------------------------------------------------------------===//
690 // Other lexer functions.
692 void SetByteOffset(unsigned Offset, bool StartOfLine);
694 void PropagateLineStartLeadingSpaceInfo(Token &Result);
696 const char *LexUDSuffix(Token &Result, const char *CurPtr,
697 bool IsStringLiteral);
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);
718 bool IsStartOfConflictMarker(const char *CurPtr);
719 bool HandleEndOfConflictMarker(const char *CurPtr);
721 bool lexEditorPlaceholder(Token &Result, const char *CurPtr);
723 bool isCodeCompletionPoint(const char *CurPtr) const;
724 void cutOffLexing() { BufferPtr = BufferEnd; }
726 bool isHexaLiteral(const char *Start, const LangOptions &LangOpts);
728 void codeCompleteIncludedFile(const char *PathStart,
729 const char *CompletionPoint, bool IsAngled);
731 /// Read a universal character name.
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.
741 /// \return The Unicode codepoint specified by the UCN, or 0 if the UCN is
743 uint32_t tryReadUCN(const char *&StartPtr, const char *SlashLoc, Token *Result);
745 /// Try to consume a UCN as part of an identifier at the current
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
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,
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);
769 #endif // LLVM_CLANG_LEX_LEXER_H