Lexer.h revision 7d100872341f233c81e1d7b72b40457e62c36862
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_LEXER_H
15#define LLVM_CLANG_LEXER_H
16
17#include "clang/Lex/PreprocessorLexer.h"
18#include "clang/Basic/LangOptions.h"
19#include "llvm/ADT/SmallVector.h"
20#include <string>
21#include <cassert>
22
23namespace clang {
24class Diagnostic;
25class SourceManager;
26class Preprocessor;
27class DiagnosticBuilder;
28
29/// Lexer - This provides a simple interface that turns a text buffer into a
30/// stream of tokens.  This provides no support for file reading or buffering,
31/// or buffering/seeking of tokens, only forward lexing is supported.  It relies
32/// on the specified Preprocessor object to handle preprocessor directives, etc.
33class Lexer : public PreprocessorLexer {
34  //===--------------------------------------------------------------------===//
35  // Constant configuration values for this lexer.
36  const char *BufferStart;       // Start of the buffer.
37  const char *BufferEnd;         // End of the buffer.
38  SourceLocation FileLoc;        // Location for start of file.
39  LangOptions Features;          // Features enabled by this language (cache).
40  bool Is_PragmaLexer : 1;       // True if lexer for _Pragma handling.
41  bool IsInConflictMarker : 1;   // True if in a VCS conflict marker '<<<<<<<'
42
43  //===--------------------------------------------------------------------===//
44  // Context-specific lexing flags set by the preprocessor.
45  //
46
47  /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace
48  /// and return them as tokens.  This is used for -C and -CC modes, and
49  /// whitespace preservation can be useful for some clients that want to lex
50  /// the file in raw mode and get every character from the file.
51  ///
52  /// When this is set to 2 it returns comments and whitespace.  When set to 1
53  /// it returns comments, when it is set to 0 it returns normal tokens only.
54  unsigned char ExtendedTokenMode;
55
56  //===--------------------------------------------------------------------===//
57  // Context that changes as the file is lexed.
58  // NOTE: any state that mutates when in raw mode must have save/restore code
59  // in Lexer::isNextPPTokenLParen.
60
61  // BufferPtr - Current pointer into the buffer.  This is the next character
62  // to be lexed.
63  const char *BufferPtr;
64
65  // IsAtStartOfLine - True if the next lexed token should get the "start of
66  // line" flag set on it.
67  bool IsAtStartOfLine;
68
69  Lexer(const Lexer&);          // DO NOT IMPLEMENT
70  void operator=(const Lexer&); // DO NOT IMPLEMENT
71  friend class Preprocessor;
72
73  void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd);
74public:
75
76  /// Lexer constructor - Create a new lexer object for the specified buffer
77  /// with the specified preprocessor managing the lexing process.  This lexer
78  /// assumes that the associated file buffer and Preprocessor objects will
79  /// outlive it, so it doesn't take ownership of either of them.
80  Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer, Preprocessor &PP);
81
82  /// Lexer constructor - Create a new raw lexer object.  This object is only
83  /// suitable for calls to 'LexRawToken'.  This lexer assumes that the text
84  /// range will outlive it, so it doesn't take ownership of it.
85  Lexer(SourceLocation FileLoc, const LangOptions &Features,
86        const char *BufStart, const char *BufPtr, const char *BufEnd);
87
88  /// Lexer constructor - Create a new raw lexer object.  This object is only
89  /// suitable for calls to 'LexRawToken'.  This lexer assumes that the text
90  /// range will outlive it, so it doesn't take ownership of it.
91  Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer,
92        const SourceManager &SM, const LangOptions &Features);
93
94  /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
95  /// _Pragma expansion.  This has a variety of magic semantics that this method
96  /// sets up.  It returns a new'd Lexer that must be delete'd when done.
97  static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc,
98                                   SourceLocation ExpansionLocStart,
99                                   SourceLocation ExpansionLocEnd,
100                                   unsigned TokLen, Preprocessor &PP);
101
102
103  /// getFeatures - Return the language features currently enabled.  NOTE: this
104  /// lexer modifies features as a file is parsed!
105  const LangOptions &getFeatures() const { return Features; }
106
107  /// getFileLoc - Return the File Location for the file we are lexing out of.
108  /// The physical location encodes the location where the characters come from,
109  /// the virtual location encodes where we should *claim* the characters came
110  /// from.  Currently this is only used by _Pragma handling.
111  SourceLocation getFileLoc() const { return FileLoc; }
112
113  /// Lex - Return the next token in the file.  If this is the end of file, it
114  /// return the tok::eof token.  Return true if an error occurred and
115  /// compilation should terminate, false if normal.  This implicitly involves
116  /// the preprocessor.
117  void Lex(Token &Result) {
118    // Start a new token.
119    Result.startToken();
120
121    // NOTE, any changes here should also change code after calls to
122    // Preprocessor::HandleDirective
123    if (IsAtStartOfLine) {
124      Result.setFlag(Token::StartOfLine);
125      IsAtStartOfLine = false;
126    }
127
128    // Get a token.  Note that this may delete the current lexer if the end of
129    // file is reached.
130    LexTokenInternal(Result);
131  }
132
133  /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
134  bool isPragmaLexer() const { return Is_PragmaLexer; }
135
136  /// IndirectLex - An indirect call to 'Lex' that can be invoked via
137  ///  the PreprocessorLexer interface.
138  void IndirectLex(Token &Result) { Lex(Result); }
139
140  /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no
141  /// associated preprocessor object.  Return true if the 'next character to
142  /// read' pointer points at the end of the lexer buffer, false otherwise.
143  bool LexFromRawLexer(Token &Result) {
144    assert(LexingRawMode && "Not already in raw mode!");
145    Lex(Result);
146    // Note that lexing to the end of the buffer doesn't implicitly delete the
147    // lexer when in raw mode.
148    return BufferPtr == BufferEnd;
149  }
150
151  /// isKeepWhitespaceMode - Return true if the lexer should return tokens for
152  /// every character in the file, including whitespace and comments.  This
153  /// should only be used in raw mode, as the preprocessor is not prepared to
154  /// deal with the excess tokens.
155  bool isKeepWhitespaceMode() const {
156    return ExtendedTokenMode > 1;
157  }
158
159  /// SetKeepWhitespaceMode - This method lets clients enable or disable
160  /// whitespace retention mode.
161  void SetKeepWhitespaceMode(bool Val) {
162    assert((!Val || LexingRawMode) &&
163           "Can only enable whitespace retention in raw mode");
164    ExtendedTokenMode = Val ? 2 : 0;
165  }
166
167  /// inKeepCommentMode - Return true if the lexer should return comments as
168  /// tokens.
169  bool inKeepCommentMode() const {
170    return ExtendedTokenMode > 0;
171  }
172
173  /// SetCommentRetentionMode - Change the comment retention mode of the lexer
174  /// to the specified mode.  This is really only useful when lexing in raw
175  /// mode, because otherwise the lexer needs to manage this.
176  void SetCommentRetentionState(bool Mode) {
177    assert(!isKeepWhitespaceMode() &&
178           "Can't play with comment retention state when retaining whitespace");
179    ExtendedTokenMode = Mode ? 1 : 0;
180  }
181
182  const char *getBufferStart() const { return BufferStart; }
183
184  /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
185  /// uninterpreted string.  This switches the lexer out of directive mode.
186  std::string ReadToEndOfLine();
187
188
189  /// Diag - Forwarding function for diagnostics.  This translate a source
190  /// position in the current buffer into a SourceLocation object for rendering.
191  DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const;
192
193  /// getSourceLocation - Return a source location identifier for the specified
194  /// offset in the current file.
195  SourceLocation getSourceLocation(const char *Loc, unsigned TokLen = 1) const;
196
197  /// getSourceLocation - Return a source location for the next character in
198  /// the current file.
199  SourceLocation getSourceLocation() { return getSourceLocation(BufferPtr); }
200
201  /// \brief Return the current location in the buffer.
202  const char *getBufferLocation() const { return BufferPtr; }
203
204  /// Stringify - Convert the specified string into a C string by escaping '\'
205  /// and " characters.  This does not add surrounding ""'s to the string.
206  /// If Charify is true, this escapes the ' character instead of ".
207  static std::string Stringify(const std::string &Str, bool Charify = false);
208
209  /// Stringify - Convert the specified string into a C string by escaping '\'
210  /// and " characters.  This does not add surrounding ""'s to the string.
211  static void Stringify(SmallVectorImpl<char> &Str);
212
213
214  /// getSpelling - This method is used to get the spelling of a token into a
215  /// preallocated buffer, instead of as an std::string.  The caller is required
216  /// to allocate enough space for the token, which is guaranteed to be at least
217  /// Tok.getLength() bytes long.  The length of the actual result is returned.
218  ///
219  /// Note that this method may do two possible things: it may either fill in
220  /// the buffer specified with characters, or it may *change the input pointer*
221  /// to point to a constant buffer with the data already in it (avoiding a
222  /// copy).  The caller is not allowed to modify the returned buffer pointer
223  /// if an internal buffer is returned.
224  static unsigned getSpelling(const Token &Tok, const char *&Buffer,
225                              const SourceManager &SourceMgr,
226                              const LangOptions &Features,
227                              bool *Invalid = 0);
228
229  /// getSpelling() - Return the 'spelling' of the Tok token.  The spelling of a
230  /// token is the characters used to represent the token in the source file
231  /// after trigraph expansion and escaped-newline folding.  In particular, this
232  /// wants to get the true, uncanonicalized, spelling of things like digraphs
233  /// UCNs, etc.
234  static std::string getSpelling(const Token &Tok,
235                                 const SourceManager &SourceMgr,
236                                 const LangOptions &Features,
237                                 bool *Invalid = 0);
238
239  /// getSpelling - This method is used to get the spelling of the
240  /// token at the given source location.  If, as is usually true, it
241  /// is not necessary to copy any data, then the returned string may
242  /// not point into the provided buffer.
243  ///
244  /// This method lexes at the expansion depth of the given
245  /// location and does not jump to the expansion or spelling
246  /// location.
247  static StringRef getSpelling(SourceLocation loc,
248                                     SmallVectorImpl<char> &buffer,
249                                     const SourceManager &SourceMgr,
250                                     const LangOptions &Features,
251                                     bool *invalid = 0);
252
253  /// MeasureTokenLength - Relex the token at the specified location and return
254  /// its length in bytes in the input file.  If the token needs cleaning (e.g.
255  /// includes a trigraph or an escaped newline) then this count includes bytes
256  /// that are part of that.
257  static unsigned MeasureTokenLength(SourceLocation Loc,
258                                     const SourceManager &SM,
259                                     const LangOptions &LangOpts);
260
261  /// \brief Given a location any where in a source buffer, find the location
262  /// that corresponds to the beginning of the token in which the original
263  /// source location lands.
264  ///
265  /// \param Loc
266  static SourceLocation GetBeginningOfToken(SourceLocation Loc,
267                                            const SourceManager &SM,
268                                            const LangOptions &LangOpts);
269
270  /// AdvanceToTokenCharacter - If the current SourceLocation specifies a
271  /// location at the start of a token, return a new location that specifies a
272  /// character within the token.  This handles trigraphs and escaped newlines.
273  static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
274                                                unsigned Character,
275                                                const SourceManager &SM,
276                                                const LangOptions &Features);
277
278  /// \brief Computes the source location just past the end of the
279  /// token at this source location.
280  ///
281  /// This routine can be used to produce a source location that
282  /// points just past the end of the token referenced by \p Loc, and
283  /// is generally used when a diagnostic needs to point just after a
284  /// token where it expected something different that it received. If
285  /// the returned source location would not be meaningful (e.g., if
286  /// it points into a macro), this routine returns an invalid
287  /// source location.
288  ///
289  /// \param Offset an offset from the end of the token, where the source
290  /// location should refer to. The default offset (0) produces a source
291  /// location pointing just past the end of the token; an offset of 1 produces
292  /// a source location pointing to the last character in the token, etc.
293  static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
294                                            const SourceManager &SM,
295                                            const LangOptions &Features);
296
297  /// \brief Returns true if the given MacroID location points at the first
298  /// token of the macro expansion.
299  static bool isAtStartOfMacroExpansion(SourceLocation loc,
300                                            const SourceManager &SM,
301                                            const LangOptions &LangOpts);
302
303  /// \brief Returns true if the given MacroID location points at the last
304  /// token of the macro expansion.
305  static bool isAtEndOfMacroExpansion(SourceLocation loc,
306                                          const SourceManager &SM,
307                                          const LangOptions &LangOpts);
308
309  /// \brief Compute the preamble of the given file.
310  ///
311  /// The preamble of a file contains the initial comments, include directives,
312  /// and other preprocessor directives that occur before the code in this
313  /// particular file actually begins. The preamble of the main source file is
314  /// a potential prefix header.
315  ///
316  /// \param Buffer The memory buffer containing the file's contents.
317  ///
318  /// \param MaxLines If non-zero, restrict the length of the preamble
319  /// to fewer than this number of lines.
320  ///
321  /// \returns The offset into the file where the preamble ends and the rest
322  /// of the file begins along with a boolean value indicating whether
323  /// the preamble ends at the beginning of a new line.
324  static std::pair<unsigned, bool>
325  ComputePreamble(const llvm::MemoryBuffer *Buffer, const LangOptions &Features,
326                  unsigned MaxLines = 0);
327
328  //===--------------------------------------------------------------------===//
329  // Internal implementation interfaces.
330private:
331
332  /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
333  /// by Lex.
334  ///
335  void LexTokenInternal(Token &Result);
336
337  /// FormTokenWithChars - When we lex a token, we have identified a span
338  /// starting at BufferPtr, going to TokEnd that forms the token.  This method
339  /// takes that range and assigns it to the token as its location and size.  In
340  /// addition, since tokens cannot overlap, this also updates BufferPtr to be
341  /// TokEnd.
342  void FormTokenWithChars(Token &Result, const char *TokEnd,
343                          tok::TokenKind Kind) {
344    unsigned TokLen = TokEnd-BufferPtr;
345    Result.setLength(TokLen);
346    Result.setLocation(getSourceLocation(BufferPtr, TokLen));
347    Result.setKind(Kind);
348    BufferPtr = TokEnd;
349  }
350
351  /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a
352  /// tok::l_paren token, 0 if it is something else and 2 if there are no more
353  /// tokens in the buffer controlled by this lexer.
354  unsigned isNextPPTokenLParen();
355
356  //===--------------------------------------------------------------------===//
357  // Lexer character reading interfaces.
358public:
359
360  // This lexer is built on two interfaces for reading characters, both of which
361  // automatically provide phase 1/2 translation.  getAndAdvanceChar is used
362  // when we know that we will be reading a character from the input buffer and
363  // that this character will be part of the result token. This occurs in (f.e.)
364  // string processing, because we know we need to read until we find the
365  // closing '"' character.
366  //
367  // The second interface is the combination of getCharAndSize with
368  // ConsumeChar.  getCharAndSize reads a phase 1/2 translated character,
369  // returning it and its size.  If the lexer decides that this character is
370  // part of the current token, it calls ConsumeChar on it.  This two stage
371  // approach allows us to emit diagnostics for characters (e.g. warnings about
372  // trigraphs), knowing that they only are emitted if the character is
373  // consumed.
374
375  /// isObviouslySimpleCharacter - Return true if the specified character is
376  /// obviously the same in translation phase 1 and translation phase 3.  This
377  /// can return false for characters that end up being the same, but it will
378  /// never return true for something that needs to be mapped.
379  static bool isObviouslySimpleCharacter(char C) {
380    return C != '?' && C != '\\';
381  }
382
383  /// getAndAdvanceChar - Read a single 'character' from the specified buffer,
384  /// advance over it, and return it.  This is tricky in several cases.  Here we
385  /// just handle the trivial case and fall-back to the non-inlined
386  /// getCharAndSizeSlow method to handle the hard case.
387  inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) {
388    // If this is not a trigraph and not a UCN or escaped newline, return
389    // quickly.
390    if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
391
392    unsigned Size = 0;
393    char C = getCharAndSizeSlow(Ptr, Size, &Tok);
394    Ptr += Size;
395    return C;
396  }
397
398private:
399  /// ConsumeChar - When a character (identified by getCharAndSize) is consumed
400  /// and added to a given token, check to see if there are diagnostics that
401  /// need to be emitted or flags that need to be set on the token.  If so, do
402  /// it.
403  const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
404    // Normal case, we consumed exactly one token.  Just return it.
405    if (Size == 1)
406      return Ptr+Size;
407
408    // Otherwise, re-lex the character with a current token, allowing
409    // diagnostics to be emitted and flags to be set.
410    Size = 0;
411    getCharAndSizeSlow(Ptr, Size, &Tok);
412    return Ptr+Size;
413  }
414
415  /// getCharAndSize - Peek a single 'character' from the specified buffer,
416  /// get its size, and return it.  This is tricky in several cases.  Here we
417  /// just handle the trivial case and fall-back to the non-inlined
418  /// getCharAndSizeSlow method to handle the hard case.
419  inline char getCharAndSize(const char *Ptr, unsigned &Size) {
420    // If this is not a trigraph and not a UCN or escaped newline, return
421    // quickly.
422    if (isObviouslySimpleCharacter(Ptr[0])) {
423      Size = 1;
424      return *Ptr;
425    }
426
427    Size = 0;
428    return getCharAndSizeSlow(Ptr, Size);
429  }
430
431  /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
432  /// method.
433  char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0);
434public:
435
436  /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
437  /// emit a warning.
438  static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
439                                          const LangOptions &Features) {
440    // If this is not a trigraph and not a UCN or escaped newline, return
441    // quickly.
442    if (isObviouslySimpleCharacter(Ptr[0])) {
443      Size = 1;
444      return *Ptr;
445    }
446
447    Size = 0;
448    return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
449  }
450
451  /// getEscapedNewLineSize - Return the size of the specified escaped newline,
452  /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry
453  /// to this function.
454  static unsigned getEscapedNewLineSize(const char *P);
455
456  /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
457  /// them), skip over them and return the first non-escaped-newline found,
458  /// otherwise return P.
459  static const char *SkipEscapedNewLines(const char *P);
460
461  /// \brief Checks that the given token is the first token that occurs after
462  /// the given location (this excludes comments and whitespace). Returns the
463  /// location immediately after the specified token. If the token is not found
464  /// or the location is inside a macro, the returned source location will be
465  /// invalid.
466  static SourceLocation findLocationAfterToken(SourceLocation loc,
467                                         tok::TokenKind TKind,
468                                         const SourceManager &SM,
469                                         const LangOptions &LangOpts,
470                                         bool SkipTrailingWhitespaceAndNewLine);
471
472private:
473
474  /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
475  /// diagnostic.
476  static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
477                                       const LangOptions &Features);
478
479  //===--------------------------------------------------------------------===//
480  // Other lexer functions.
481
482  void SkipBytes(unsigned Bytes, bool StartOfLine);
483
484  // Helper functions to lex the remainder of a token of the specific type.
485  void LexIdentifier         (Token &Result, const char *CurPtr);
486  void LexNumericConstant    (Token &Result, const char *CurPtr);
487  void LexStringLiteral      (Token &Result, const char *CurPtr,
488                              tok::TokenKind Kind);
489  void LexRawStringLiteral   (Token &Result, const char *CurPtr,
490                              tok::TokenKind Kind);
491  void LexAngledStringLiteral(Token &Result, const char *CurPtr);
492  void LexCharConstant       (Token &Result, const char *CurPtr,
493                              tok::TokenKind Kind);
494  bool LexEndOfFile          (Token &Result, const char *CurPtr);
495
496  bool SkipWhitespace        (Token &Result, const char *CurPtr);
497  bool SkipBCPLComment       (Token &Result, const char *CurPtr);
498  bool SkipBlockComment      (Token &Result, const char *CurPtr);
499  bool SaveBCPLComment       (Token &Result, const char *CurPtr);
500
501  bool IsStartOfConflictMarker(const char *CurPtr);
502  bool HandleEndOfConflictMarker(const char *CurPtr);
503
504  bool isCodeCompletionPoint(const char *CurPtr) const;
505  void cutOffLexing() { BufferPtr = BufferEnd; }
506};
507
508
509}  // end namespace clang
510
511#endif
512