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