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