clang  6.0.0svn
Lexer.h
Go to the documentation of this file.
1 //===- Lexer.h - C Language Family Lexer ------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the Lexer interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_LEX_LEXER_H
15 #define LLVM_CLANG_LEX_LEXER_H
16 
19 #include "clang/Basic/TokenKinds.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"
25 #include <cassert>
26 #include <cstdint>
27 #include <string>
28 
29 namespace llvm {
30 
31 class MemoryBuffer;
32 
33 } // namespace llvm
34 
35 namespace clang {
36 
37 class DiagnosticBuilder;
38 class Preprocessor;
39 class SourceManager;
40 
41 /// ConflictMarkerKind - Kinds of conflict marker which the lexer might be
42 /// recovering from.
44  /// Not within a conflict marker.
46 
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.
50 
51  /// A Perforce-style conflict marker, initiated by 4 ">"s,
52  /// separated by 4 "="s, and terminated by 4 "<"s.
54 };
55 
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.
60  /// \brief Size of the preamble in bytes.
61  unsigned Size;
62 
63  /// \brief Whether the preamble ends at the start of a new line.
64  ///
65  /// Used to inform the lexer as to whether it's starting at the beginning of
66  /// a line after skipping the preamble.
68 
69  PreambleBounds(unsigned Size, bool PreambleEndsAtStartOfLine)
70  : Size(Size), PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
71 };
72 
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;
79 
80  void anchor() override;
81 
82  //===--------------------------------------------------------------------===//
83  // Constant configuration values for this lexer.
84 
85  // Start of the buffer.
86  const char *BufferStart;
87 
88  // End of the buffer.
89  const char *BufferEnd;
90 
91  // Location for start of file.
92  SourceLocation FileLoc;
93 
94  // LangOpts enabled by this language (cache).
95  LangOptions LangOpts;
96 
97  // True if lexer for _Pragma handling.
98  bool Is_PragmaLexer;
99 
100  //===--------------------------------------------------------------------===//
101  // Context-specific lexing flags set by the preprocessor.
102  //
103 
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.
108  ///
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;
112 
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.
117 
118  // BufferPtr - Current pointer into the buffer. This is the next character
119  // to be lexed.
120  const char *BufferPtr;
121 
122  // IsAtStartOfLine - True if the next lexed token should get the "start of
123  // line" flag set on it.
124  bool IsAtStartOfLine;
125 
126  bool IsAtPhysicalStartOfLine;
127 
128  bool HasLeadingSpace;
129 
130  bool HasLeadingEmptyMacro;
131 
132  // CurrentConflictMarkerState - The kind of conflict marker we are handling.
133  ConflictMarkerKind CurrentConflictMarkerState;
134 
135  void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd);
136 
137 public:
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);
143 
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);
149 
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);
155 
156  Lexer(const Lexer &) = delete;
157  Lexer &operator=(const Lexer &) = delete;
158 
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);
166 
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; }
170 
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; }
176 
177 private:
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);
181 
182 public:
183  /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
184  bool isPragmaLexer() const { return Is_PragmaLexer; }
185 
186 private:
187  /// IndirectLex - An indirect call to 'Lex' that can be invoked via
188  /// the PreprocessorLexer interface.
189  void IndirectLex(Token &Result) override { Lex(Result); }
190 
191 public:
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!");
197  Lex(Result);
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;
201  }
202 
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;
209  }
210 
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;
217  }
218 
219  /// inKeepCommentMode - Return true if the lexer should return comments as
220  /// tokens.
221  bool inKeepCommentMode() const {
222  return ExtendedTokenMode > 0;
223  }
224 
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;
232  }
233 
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.
237  ///
238  /// This requires the lexer to have an associated preprocessor. A standalone
239  /// lexer has nothing to reset to.
240  void resetExtendedTokenMode();
241 
242  /// Gets source code buffer.
243  StringRef getBuffer() const {
244  return StringRef(BufferStart, BufferEnd - BufferStart);
245  }
246 
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);
250 
251 
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;
255 
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;
259 
260  /// getSourceLocation - Return a source location for the next character in
261  /// the current file.
263  return getSourceLocation(BufferPtr);
264  }
265 
266  /// \brief Return the current location in the buffer.
267  const char *getBufferLocation() const { return BufferPtr; }
268 
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);
273 
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);
277 
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.
282  ///
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);
292 
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
297  /// UCNs, etc.
298  static std::string getSpelling(const Token &Tok,
299  const SourceManager &SourceMgr,
300  const LangOptions &LangOpts,
301  bool *Invalid = nullptr);
302 
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.
307  ///
308  /// This method lexes at the expansion depth of the given
309  /// location and does not jump to the expansion or spelling
310  /// location.
311  static StringRef getSpelling(SourceLocation loc,
312  SmallVectorImpl<char> &buffer,
313  const SourceManager &SourceMgr,
314  const LangOptions &LangOpts,
315  bool *invalid = nullptr);
316 
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);
324 
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);
331 
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);
338 
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,
343  unsigned Character,
344  const SourceManager &SM,
345  const LangOptions &LangOpts);
346 
347  /// \brief Computes the source location just past the end of the
348  /// token at this source location.
349  ///
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
356  /// source location.
357  ///
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);
365 
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.
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));
377  }
379  const SourceManager &SM,
380  const LangOptions &LangOpts) {
381  return Range.isTokenRange()
382  ? getAsCharRange(Range.getAsRange(), SM, LangOpts)
383  : Range;
384  }
385 
386  /// \brief Returns true if the given MacroID location points at the first
387  /// token of the macro expansion.
388  ///
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);
395 
396  /// \brief Returns true if the given MacroID location points at the last
397  /// token of the macro expansion.
398  ///
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);
405 
406  /// \brief Accepts a range and returns a character range with file locations.
407  ///
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.
410  ///
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:
413  ///
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:
416  /// \#define M 1 2
417  /// a M
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
422  ///
423  /// -The macro is a function macro and the range can be mapped to the macro
424  /// arguments, e.g:
425  /// \#define M 1 2
426  /// \#define FM(x) x
427  /// FM(a b M)
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);
435 
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);
441 
442  /// \brief Retrieve the name of the immediate macro expansion.
443  ///
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);
452 
453  /// \brief Retrieve the name of the immediate macro expansion.
454  ///
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.
461  ///
462  /// This differs from Lexer::getImmediateMacroName in that any macro argument
463  /// location will result in the topmost function macro that accepted it.
464  /// e.g.
465  /// \code
466  /// MAC1( MAC2(foo) )
467  /// \endcode
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);
472 
473  /// \brief Compute the preamble of the given file.
474  ///
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.
479  ///
480  /// \param Buffer The memory buffer containing the file's contents.
481  ///
482  /// \param MaxLines If non-zero, restrict the length of the preamble
483  /// to fewer than this number of lines.
484  ///
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);
491 
492  /// Finds the token that comes right after the given location.
493  ///
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);
498 
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
503  /// invalid.
504  static SourceLocation findLocationAfterToken(SourceLocation loc,
505  tok::TokenKind TKind,
506  const SourceManager &SM,
507  const LangOptions &LangOpts,
508  bool SkipTrailingWhitespaceAndNewLine);
509 
510  /// \brief Returns true if the given character could appear in an identifier.
511  static bool isIdentifierBodyChar(char c, const LangOptions &LangOpts);
512 
513  /// \brief Checks whether new line pointed by Str is preceded by escape
514  /// sequence.
515  static bool isNewLineEscaped(const char *BufferStart, const char *Str);
516 
517  /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
518  /// emit a warning.
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
522  // quickly.
523  if (isObviouslySimpleCharacter(Ptr[0])) {
524  Size = 1;
525  return *Ptr;
526  }
527 
528  Size = 0;
529  return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
530  }
531 
532  /// Returns the leading whitespace for line that corresponds to the given
533  /// location \p Loc.
534  static StringRef getIndentationForLine(SourceLocation Loc,
535  const SourceManager &SM);
536 
537 private:
538  //===--------------------------------------------------------------------===//
539  // Internal implementation interfaces.
540 
541  /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
542  /// by Lex.
543  ///
544  bool LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine);
545 
546  bool CheckUnicodeWhitespace(Token &Result, uint32_t C, const char *CurPtr);
547 
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
550  /// function.
551  bool LexUnicode(Token &Result, uint32_t C, const char *CurPtr);
552 
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
557  /// TokEnd.
558  void FormTokenWithChars(Token &Result, const char *TokEnd,
560  unsigned TokLen = TokEnd-BufferPtr;
561  Result.setLength(TokLen);
562  Result.setLocation(getSourceLocation(BufferPtr, TokLen));
563  Result.setKind(Kind);
564  BufferPtr = TokEnd;
565  }
566 
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();
571 
572  //===--------------------------------------------------------------------===//
573  // Lexer character reading interfaces.
574 
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.
581  //
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
588  // consumed.
589 
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 != '\\';
596  }
597 
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
604  // quickly.
605  if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
606 
607  unsigned Size = 0;
608  char C = getCharAndSizeSlow(Ptr, Size, &Tok);
609  Ptr += Size;
610  return C;
611  }
612 
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
616  /// it.
617  const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
618  // Normal case, we consumed exactly one token. Just return it.
619  if (Size == 1)
620  return Ptr+Size;
621 
622  // Otherwise, re-lex the character with a current token, allowing
623  // diagnostics to be emitted and flags to be set.
624  Size = 0;
625  getCharAndSizeSlow(Ptr, Size, &Tok);
626  return Ptr+Size;
627  }
628 
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
635  // quickly.
636  if (isObviouslySimpleCharacter(Ptr[0])) {
637  Size = 1;
638  return *Ptr;
639  }
640 
641  Size = 0;
642  return getCharAndSizeSlow(Ptr, Size);
643  }
644 
645  /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
646  /// method.
647  char getCharAndSizeSlow(const char *Ptr, unsigned &Size,
648  Token *Tok = nullptr);
649 
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);
654 
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);
659 
660  /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
661  /// diagnostic.
662  static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
663  const LangOptions &LangOpts);
664 
665  //===--------------------------------------------------------------------===//
666  // Other lexer functions.
667 
668  void SetByteOffset(unsigned Offset, bool StartOfLine);
669 
670  void PropagateLineStartLeadingSpaceInfo(Token &Result);
671 
672  const char *LexUDSuffix(Token &Result, const char *CurPtr,
673  bool IsStringLiteral);
674 
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);
693 
694  bool IsStartOfConflictMarker(const char *CurPtr);
695  bool HandleEndOfConflictMarker(const char *CurPtr);
696 
697  bool lexEditorPlaceholder(Token &Result, const char *CurPtr);
698 
699  bool isCodeCompletionPoint(const char *CurPtr) const;
700  void cutOffLexing() { BufferPtr = BufferEnd; }
701 
702  bool isHexaLiteral(const char *Start, const LangOptions &LangOpts);
703 
704 
705  /// Read a universal character name.
706  ///
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.
714  ///
715  /// \return The Unicode codepoint specified by the UCN, or 0 if the UCN is
716  /// invalid.
717  uint32_t tryReadUCN(const char *&CurPtr, const char *SlashLoc, Token *Tok);
718 
719  /// \brief Try to consume a UCN as part of an identifier at the current
720  /// location.
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
727  /// success.
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,
731  Token &Result);
732 
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);
739 };
740 
741 } // namespace clang
742 
743 #endif // LLVM_CLANG_LEX_LEXER_H
Describes the bounds (start, size) of the preamble and a flag required by PreprocessorOptions::Precom...
Definition: Lexer.h:59
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:77
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
const char * getBufferLocation() const
Return the current location in the buffer.
Definition: Lexer.h:267
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:26
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition: Lexer.h:195
StringRef P
static char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, const LangOptions &LangOpts)
getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever emit a warning.
Definition: Lexer.h:519
ConflictMarkerKind
ConflictMarkerKind - Kinds of conflict marker which the lexer might be recovering from...
Definition: Lexer.h:43
static CharSourceRange getAsCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Definition: Lexer.h:378
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
void setKind(tok::TokenKind K)
Definition: Token.h:91
SourceLocation getFileLoc() const
getFileLoc - Return the File Location for the file we are lexing out of.
Definition: Lexer.h:175
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
bool isPragmaLexer() const
isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
Definition: Lexer.h:184
A Perforce-style conflict marker, initiated by 4 ">"s, separated by 4 "="s, and terminated by 4 "<"s...
Definition: Lexer.h:53
SourceLocation getSourceLocation() override
getSourceLocation - Return a source location for the next character in the current file...
Definition: Lexer.h:262
uint32_t Offset
Definition: CacheTokens.cpp:43
const FormatToken & Tok
StringRef getBuffer() const
Gets source code buffer.
Definition: Lexer.h:243
bool PreambleEndsAtStartOfLine
Whether the preamble ends at the start of a new line.
Definition: Lexer.h:67
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:955
const LangOptions & getLangOpts() const
getLangOpts - Return the language features currently enabled.
Definition: Lexer.h:169
Defines the clang::LangOptions interface.
SourceLocation End
Represents a character-granular source range.
bool isKeepWhitespaceMode() const
isKeepWhitespaceMode - Return true if the lexer should return tokens for every character in the file...
Definition: Lexer.h:207
SourceLocation getEnd() const
const SourceManager & SM
Definition: Format.cpp:1337
Kind
Encodes a location in the source.
void setLength(unsigned Len)
Definition: Token.h:133
PreambleBounds(unsigned Size, bool PreambleEndsAtStartOfLine)
Definition: Lexer.h:69
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
bool inKeepCommentMode() const
inKeepCommentMode - Return true if the lexer should return comments as tokens.
Definition: Lexer.h:221
bool isTokenRange() const
Return true if the end of this range specifies the start of the last token.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
SourceRange getAsRange() const
Dataflow Directional Tag Classes.
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:370
unsigned Size
Size of the preamble in bytes.
Definition: Lexer.h:61
Defines the clang::TokenKind enum and support functions.
Defines the clang::SourceLocation class and associated facilities.
Not within a conflict marker.
Definition: Lexer.h:45
void SetCommentRetentionState(bool Mode)
SetCommentRetentionMode - Change the comment retention mode of the lexer to the specified mode...
Definition: Lexer.h:228
void setLocation(SourceLocation L)
Definition: Token.h:132
A normal or diff3 conflict marker, initiated by at least 7 "<"s, separated by at least 7 "="s or "|"s...
Definition: Lexer.h:49
A trivial tuple used to represent a source range.
Defines the PreprocessorLexer interface.
void SetKeepWhitespaceMode(bool Val)
SetKeepWhitespaceMode - This method lets clients enable or disable whitespace retention mode...
Definition: Lexer.h:213
SourceLocation getBegin() const
This class handles loading and caching of source files into memory.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127