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