Lexer.h revision 42e00d19b0dac64732eb5449d52a076282fcbf77
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 <vector>
22#include <cassert>
23
24namespace clang {
25class Diagnostic;
26class SourceManager;
27class Preprocessor;
28class DiagnosticBuilder;
29
30/// Lexer - This provides a simple interface that turns a text buffer into a
31/// stream of tokens.  This provides no support for file reading or buffering,
32/// or buffering/seeking of tokens, only forward lexing is supported.  It relies
33/// on the specified Preprocessor object to handle preprocessor directives, etc.
34class Lexer : public PreprocessorLexer {
35  //===--------------------------------------------------------------------===//
36  // Constant configuration values for this lexer.
37  const char *BufferStart;       // Start of the buffer.
38  const char *BufferEnd;         // End of the buffer.
39  SourceLocation FileLoc;        // Location for start of file.
40  LangOptions Features;          // Features enabled by this language (cache).
41  bool Is_PragmaLexer;           // True if lexer for _Pragma handling.
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, 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 SourceManager &SM, const LangOptions &Features);
92
93  /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
94  /// _Pragma expansion.  This has a variety of magic semantics that this method
95  /// sets up.  It returns a new'd Lexer that must be delete'd when done.
96  static Lexer *Create_PragmaLexer(SourceLocation TokStartLoc, unsigned TokLen,
97                                   Preprocessor &PP);
98
99
100  /// getFeatures - Return the language features currently enabled.  NOTE: this
101  /// lexer modifies features as a file is parsed!
102  const LangOptions &getFeatures() const { return Features; }
103
104  /// getFileLoc - Return the File Location for the file we are lexing out of.
105  /// The physical location encodes the location where the characters come from,
106  /// the virtual location encodes where we should *claim* the characters came
107  /// from.  Currently this is only used by _Pragma handling.
108  SourceLocation getFileLoc() const { return FileLoc; }
109
110  /// Lex - Return the next token in the file.  If this is the end of file, it
111  /// return the tok::eof token.  Return true if an error occurred and
112  /// compilation should terminate, false if normal.  This implicitly involves
113  /// the preprocessor.
114  void Lex(Token &Result) {
115    // Start a new token.
116    Result.startToken();
117
118    // NOTE, any changes here should also change code after calls to
119    // Preprocessor::HandleDirective
120    if (IsAtStartOfLine) {
121      Result.setFlag(Token::StartOfLine);
122      IsAtStartOfLine = false;
123    }
124
125    // Get a token.  Note that this may delete the current lexer if the end of
126    // file is reached.
127    LexTokenInternal(Result);
128  }
129
130  /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
131  bool isPragmaLexer() const { return Is_PragmaLexer; }
132
133  /// IndirectLex - An indirect call to 'Lex' that can be invoked via
134  ///  the PreprocessorLexer interface.
135  void IndirectLex(Token &Result) { Lex(Result); }
136
137  /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no
138  /// associated preprocessor object.  Return true if the 'next character to
139  /// read' pointer points and the end of the lexer buffer, false otherwise.
140  bool LexFromRawLexer(Token &Result) {
141    assert(LexingRawMode && "Not already in raw mode!");
142    Lex(Result);
143    // Note that lexing to the end of the buffer doesn't implicitly delete the
144    // lexer when in raw mode.
145    return BufferPtr == BufferEnd;
146  }
147
148  /// isKeepWhitespaceMode - Return true if the lexer should return tokens for
149  /// every character in the file, including whitespace and comments.  This
150  /// should only be used in raw mode, as the preprocessor is not prepared to
151  /// deal with the excess tokens.
152  bool isKeepWhitespaceMode() const {
153    return ExtendedTokenMode > 1;
154  }
155
156  /// SetKeepWhitespaceMode - This method lets clients enable or disable
157  /// whitespace retention mode.
158  void SetKeepWhitespaceMode(bool Val) {
159    assert((!Val || LexingRawMode) &&
160           "Can only enable whitespace retention in raw mode");
161    ExtendedTokenMode = Val ? 2 : 0;
162  }
163
164  /// inKeepCommentMode - Return true if the lexer should return comments as
165  /// tokens.
166  bool inKeepCommentMode() const {
167    return ExtendedTokenMode > 0;
168  }
169
170  /// SetCommentRetentionMode - Change the comment retention mode of the lexer
171  /// to the specified mode.  This is really only useful when lexing in raw
172  /// mode, because otherwise the lexer needs to manage this.
173  void SetCommentRetentionState(bool Mode) {
174    assert(!isKeepWhitespaceMode() &&
175           "Can't play with comment retention state when retaining whitespace");
176    ExtendedTokenMode = Mode ? 1 : 0;
177  }
178
179  const char *getBufferStart() const { return BufferStart; }
180
181  /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
182  /// uninterpreted string.  This switches the lexer out of directive mode.
183  std::string ReadToEndOfLine();
184
185
186  /// Diag - Forwarding function for diagnostics.  This translate a source
187  /// position in the current buffer into a SourceLocation object for rendering.
188  DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const;
189
190  /// getSourceLocation - Return a source location identifier for the specified
191  /// offset in the current file.
192  SourceLocation getSourceLocation(const char *Loc) const;
193
194  /// getSourceLocation - Return a source location for the next character in
195  /// the current file.
196  SourceLocation getSourceLocation() { return getSourceLocation(BufferPtr); }
197
198  /// Stringify - Convert the specified string into a C string by escaping '\'
199  /// and " characters.  This does not add surrounding ""'s to the string.
200  /// If Charify is true, this escapes the ' character instead of ".
201  static std::string Stringify(const std::string &Str, bool Charify = false);
202
203  /// Stringify - Convert the specified string into a C string by escaping '\'
204  /// and " characters.  This does not add surrounding ""'s to the string.
205  static void Stringify(llvm::SmallVectorImpl<char> &Str);
206
207  /// MeasureTokenLength - Relex the token at the specified location and return
208  /// its length in bytes in the input file.  If the token needs cleaning (e.g.
209  /// includes a trigraph or an escaped newline) then this count includes bytes
210  /// that are part of that.
211  static unsigned MeasureTokenLength(SourceLocation Loc,
212                                     const SourceManager &SM);
213
214  //===--------------------------------------------------------------------===//
215  // Internal implementation interfaces.
216private:
217
218  /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
219  /// by Lex.
220  ///
221  void LexTokenInternal(Token &Result);
222
223  /// FormTokenWithChars - When we lex a token, we have identified a span
224  /// starting at BufferPtr, going to TokEnd that forms the token.  This method
225  /// takes that range and assigns it to the token as its location and size.  In
226  /// addition, since tokens cannot overlap, this also updates BufferPtr to be
227  /// TokEnd.
228  void FormTokenWithChars(Token &Result, const char *TokEnd,
229                          tok::TokenKind Kind) {
230    Result.setLocation(getSourceLocation(BufferPtr));
231    Result.setLength(TokEnd-BufferPtr);
232    Result.setKind(Kind);
233    BufferPtr = TokEnd;
234  }
235
236  /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a
237  /// tok::l_paren token, 0 if it is something else and 2 if there are no more
238  /// tokens in the buffer controlled by this lexer.
239  unsigned isNextPPTokenLParen();
240
241  //===--------------------------------------------------------------------===//
242  // Lexer character reading interfaces.
243public:
244
245  // This lexer is built on two interfaces for reading characters, both of which
246  // automatically provide phase 1/2 translation.  getAndAdvanceChar is used
247  // when we know that we will be reading a character from the input buffer and
248  // that this character will be part of the result token. This occurs in (f.e.)
249  // string processing, because we know we need to read until we find the
250  // closing '"' character.
251  //
252  // The second interface is the combination of PeekCharAndSize with
253  // ConsumeChar.  PeekCharAndSize reads a phase 1/2 translated character,
254  // returning it and its size.  If the lexer decides that this character is
255  // part of the current token, it calls ConsumeChar on it.  This two stage
256  // approach allows us to emit diagnostics for characters (e.g. warnings about
257  // trigraphs), knowing that they only are emitted if the character is
258  // consumed.
259
260  /// isObviouslySimpleCharacter - Return true if the specified character is
261  /// obviously the same in translation phase 1 and translation phase 3.  This
262  /// can return false for characters that end up being the same, but it will
263  /// never return true for something that needs to be mapped.
264  static bool isObviouslySimpleCharacter(char C) {
265    return C != '?' && C != '\\';
266  }
267
268  /// getAndAdvanceChar - Read a single 'character' from the specified buffer,
269  /// advance over it, and return it.  This is tricky in several cases.  Here we
270  /// just handle the trivial case and fall-back to the non-inlined
271  /// getCharAndSizeSlow method to handle the hard case.
272  inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) {
273    // If this is not a trigraph and not a UCN or escaped newline, return
274    // quickly.
275    if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
276
277    unsigned Size = 0;
278    char C = getCharAndSizeSlow(Ptr, Size, &Tok);
279    Ptr += Size;
280    return C;
281  }
282
283private:
284  /// ConsumeChar - When a character (identified by PeekCharAndSize) is consumed
285  /// and added to a given token, check to see if there are diagnostics that
286  /// need to be emitted or flags that need to be set on the token.  If so, do
287  /// it.
288  const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
289    // Normal case, we consumed exactly one token.  Just return it.
290    if (Size == 1)
291      return Ptr+Size;
292
293    // Otherwise, re-lex the character with a current token, allowing
294    // diagnostics to be emitted and flags to be set.
295    Size = 0;
296    getCharAndSizeSlow(Ptr, Size, &Tok);
297    return Ptr+Size;
298  }
299
300  /// getCharAndSize - Peek a single 'character' from the specified buffer,
301  /// get its size, and return it.  This is tricky in several cases.  Here we
302  /// just handle the trivial case and fall-back to the non-inlined
303  /// getCharAndSizeSlow method to handle the hard case.
304  inline char getCharAndSize(const char *Ptr, unsigned &Size) {
305    // If this is not a trigraph and not a UCN or escaped newline, return
306    // quickly.
307    if (isObviouslySimpleCharacter(Ptr[0])) {
308      Size = 1;
309      return *Ptr;
310    }
311
312    Size = 0;
313    return getCharAndSizeSlow(Ptr, Size);
314  }
315
316  /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
317  /// method.
318  char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0);
319public:
320
321  /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
322  /// emit a warning.
323  static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
324                                          const LangOptions &Features) {
325    // If this is not a trigraph and not a UCN or escaped newline, return
326    // quickly.
327    if (isObviouslySimpleCharacter(Ptr[0])) {
328      Size = 1;
329      return *Ptr;
330    }
331
332    Size = 0;
333    return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
334  }
335private:
336
337  /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
338  /// diagnostic.
339  static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
340                                       const LangOptions &Features);
341
342  //===--------------------------------------------------------------------===//
343  // Other lexer functions.
344
345  // Helper functions to lex the remainder of a token of the specific type.
346  void LexIdentifier         (Token &Result, const char *CurPtr);
347  void LexNumericConstant    (Token &Result, const char *CurPtr);
348  void LexStringLiteral      (Token &Result, const char *CurPtr,bool Wide);
349  void LexAngledStringLiteral(Token &Result, const char *CurPtr);
350  void LexCharConstant       (Token &Result, const char *CurPtr);
351  bool LexEndOfFile          (Token &Result, const char *CurPtr);
352
353  bool SkipWhitespace        (Token &Result, const char *CurPtr);
354  bool SkipBCPLComment       (Token &Result, const char *CurPtr);
355  bool SkipBlockComment      (Token &Result, const char *CurPtr);
356  bool SaveBCPLComment       (Token &Result, const char *CurPtr);
357};
358
359
360}  // end namespace clang
361
362#endif
363