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