Lexer.h revision d217773f106856a11879ec79dc468efefaf2ee75
1//===--- Lexer.h - C Language Family Lexer ----------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source 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/Token.h"
18#include "clang/Lex/MultipleIncludeOpt.h"
19#include "clang/Basic/LangOptions.h"
20#include <string>
21#include <vector>
22#include <cassert>
23
24namespace llvm {
25  class MemoryBuffer;
26}
27
28namespace clang {
29class Diagnostic;
30class Preprocessor;
31
32/// Lexer - This provides a simple interface that turns a text buffer into a
33/// stream of tokens.  This provides no support for file reading or buffering,
34/// or buffering/seeking of tokens, only forward lexing is supported.  It relies
35/// on the specified Preprocessor object to handle preprocessor directives, etc.
36class Lexer {
37  //===--------------------------------------------------------------------===//
38  // Constant configuration values for this lexer.
39  const char *BufferEnd;         // End of the buffer.
40  const llvm::MemoryBuffer *InputFile; // The file we are reading from.
41  SourceLocation FileLoc;        // Location for start of file.
42  Preprocessor &PP;              // Preprocessor object controlling lexing.
43  LangOptions Features;          // Features enabled by this language (cache).
44  bool Is_PragmaLexer;           // True if lexer for _Pragma handling.
45  bool IsMainFile;               // True if top-level file.
46
47  //===--------------------------------------------------------------------===//
48  // Context-specific lexing flags set by the preprocessor.
49  //
50
51  /// ParsingPreprocessorDirective - This is true when parsing #XXX.  This turns
52  /// '\n' into a tok::eom token.
53  bool ParsingPreprocessorDirective;
54
55  /// ParsingFilename - True after #include: this turns <xx> into a
56  /// tok::angle_string_literal token.
57  bool ParsingFilename;
58
59  /// LexingRawMode - True if in raw mode:  This flag disables interpretation of
60  /// tokens and is a far faster mode to lex in than non-raw-mode.  This flag:
61  ///  1. If EOF of the current lexer is found, the include stack isn't popped.
62  ///  2. Identifier information is not looked up for identifier tokens.  As an
63  ///     effect of this, implicit macro expansion is naturally disabled.
64  ///  3. "#" tokens at the start of a line are treated as normal tokens, not
65  ///     implicitly transformed by the lexer.
66  ///  4. All diagnostic messages are disabled, except for unterminated /*.
67  ///  5. The only callback made into the preprocessor is to report a hard error
68  ///     on an unterminated '/*' comment.
69  bool LexingRawMode;
70
71  /// KeepCommentMode - The lexer can optionally keep C & BCPL-style comments,
72  /// and return them as tokens.  This is used for -C and -CC modes.
73  bool KeepCommentMode;
74
75  //===--------------------------------------------------------------------===//
76  // Context that changes as the file is lexed.
77  // NOTE: any state that mutates when in raw mode must have save/restore code
78  // in Lexer::isNextPPTokenLParen.
79
80  // BufferPtr - Current pointer into the buffer.  This is the next character
81  // to be lexed.
82  const char *BufferPtr;
83
84  // IsAtStartOfLine - True if the next lexed token should get the "start of
85  // line" flag set on it.
86  bool IsAtStartOfLine;
87
88  /// MIOpt - This is a state machine that detects the #ifndef-wrapping a file
89  /// idiom for the multiple-include optimization.
90  MultipleIncludeOpt MIOpt;
91
92  /// ConditionalStack - Information about the set of #if/#ifdef/#ifndef blocks
93  /// we are currently in.
94  std::vector<PPConditionalInfo> ConditionalStack;
95
96  Lexer(const Lexer&);          // DO NOT IMPLEMENT
97  void operator=(const Lexer&); // DO NOT IMPLEMENT
98  friend class Preprocessor;
99public:
100
101  /// Lexer constructor - Create a new lexer object for the specified buffer
102  /// with the specified preprocessor managing the lexing process.  This lexer
103  /// assumes that the associated MemoryBuffer and Preprocessor objects will
104  /// outlive it, so it doesn't take ownership of either of them.
105  Lexer(SourceLocation FileLoc, Preprocessor &PP,
106        const char *BufStart = 0, const char *BufEnd = 0);
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  /// setIsMainFile - Mark this lexer as being the lexer for the top-level
119  /// source file.
120  void setIsMainFile() {
121    IsMainFile = true;
122  }
123
124  /// isMainFile - Return true if this is the top-level file.
125  ///
126  bool isMainFile() const { return IsMainFile; }
127
128  /// Lex - Return the next token in the file.  If this is the end of file, it
129  /// return the tok::eof token.  Return true if an error occurred and
130  /// compilation should terminate, false if normal.  This implicitly involves
131  /// the preprocessor.
132  void Lex(Token &Result) {
133    // Start a new token.
134    Result.startToken();
135
136    // NOTE, any changes here should also change code after calls to
137    // Preprocessor::HandleDirective
138    if (IsAtStartOfLine) {
139      Result.setFlag(Token::StartOfLine);
140      IsAtStartOfLine = false;
141    }
142
143    // Get a token.  Note that this may delete the current lexer if the end of
144    // file is reached.
145    LexTokenInternal(Result);
146  }
147
148  /// LexRawToken - Switch the lexer to raw mode, lex a token into Result and
149  /// switch it back.  Return true if the 'next character to read' pointer
150  /// points and the end of the lexer buffer, false otherwise.
151  bool LexRawToken(Token &Result) {
152    assert(!LexingRawMode && "Already in raw mode!");
153    LexingRawMode = true;
154    Lex(Result);
155    LexingRawMode = false;
156    return BufferPtr == BufferEnd;
157  }
158
159  /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
160  /// uninterpreted string.  This switches the lexer out of directive mode.
161  std::string ReadToEndOfLine();
162
163
164  /// Diag - Forwarding function for diagnostics.  This translate a source
165  /// position in the current buffer into a SourceLocation object for rendering.
166  void Diag(const char *Loc, unsigned DiagID,
167            const std::string &Msg = std::string()) const;
168  void Diag(SourceLocation Loc, unsigned DiagID,
169            const std::string &Msg = std::string()) const;
170
171  /// getSourceLocation - Return a source location identifier for the specified
172  /// offset in the current file.
173  SourceLocation getSourceLocation(const char *Loc) const;
174
175  /// Stringify - Convert the specified string into a C string by escaping '\'
176  /// and " characters.  This does not add surrounding ""'s to the string.
177  /// If Charify is true, this escapes the ' character instead of ".
178  static std::string Stringify(const std::string &Str, bool Charify = false);
179
180  //===--------------------------------------------------------------------===//
181  // Internal implementation interfaces.
182private:
183
184  /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
185  /// by Lex.
186  ///
187  void LexTokenInternal(Token &Result);
188
189  /// FormTokenWithChars - When we lex a token, we have identified a span
190  /// starting at BufferPtr, going to TokEnd that forms the token.  This method
191  /// takes that range and assigns it to the token as its location and size.  In
192  /// addition, since tokens cannot overlap, this also updates BufferPtr to be
193  /// TokEnd.
194  void FormTokenWithChars(Token &Result, const char *TokEnd) {
195    Result.setLocation(getSourceLocation(BufferPtr));
196    Result.setLength(TokEnd-BufferPtr);
197    BufferPtr = TokEnd;
198  }
199
200  /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a
201  /// tok::l_paren token, 0 if it is something else and 2 if there are no more
202  /// tokens in the buffer controlled by this lexer.
203  unsigned isNextPPTokenLParen();
204
205  //===--------------------------------------------------------------------===//
206  // Lexer character reading interfaces.
207public:
208
209  // This lexer is built on two interfaces for reading characters, both of which
210  // automatically provide phase 1/2 translation.  getAndAdvanceChar is used
211  // when we know that we will be reading a character from the input buffer and
212  // that this character will be part of the result token. This occurs in (f.e.)
213  // string processing, because we know we need to read until we find the
214  // closing '"' character.
215  //
216  // The second interface is the combination of PeekCharAndSize with
217  // ConsumeChar.  PeekCharAndSize reads a phase 1/2 translated character,
218  // returning it and its size.  If the lexer decides that this character is
219  // part of the current token, it calls ConsumeChar on it.  This two stage
220  // approach allows us to emit diagnostics for characters (e.g. warnings about
221  // trigraphs), knowing that they only are emitted if the character is
222  // consumed.
223
224  /// isObviouslySimpleCharacter - Return true if the specified character is
225  /// obviously the same in translation phase 1 and translation phase 3.  This
226  /// can return false for characters that end up being the same, but it will
227  /// never return true for something that needs to be mapped.
228  static bool isObviouslySimpleCharacter(char C) {
229    return C != '?' && C != '\\';
230  }
231
232  /// getAndAdvanceChar - Read a single 'character' from the specified buffer,
233  /// advance over it, and return it.  This is tricky in several cases.  Here we
234  /// just handle the trivial case and fall-back to the non-inlined
235  /// getCharAndSizeSlow method to handle the hard case.
236  inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) {
237    // If this is not a trigraph and not a UCN or escaped newline, return
238    // quickly.
239    if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
240
241    unsigned Size = 0;
242    char C = getCharAndSizeSlow(Ptr, Size, &Tok);
243    Ptr += Size;
244    return C;
245  }
246
247private:
248  /// ConsumeChar - When a character (identified by PeekCharAndSize) is consumed
249  /// and added to a given token, check to see if there are diagnostics that
250  /// need to be emitted or flags that need to be set on the token.  If so, do
251  /// it.
252  const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
253    // Normal case, we consumed exactly one token.  Just return it.
254    if (Size == 1)
255      return Ptr+Size;
256
257    // Otherwise, re-lex the character with a current token, allowing
258    // diagnostics to be emitted and flags to be set.
259    Size = 0;
260    getCharAndSizeSlow(Ptr, Size, &Tok);
261    return Ptr+Size;
262  }
263
264  /// getCharAndSize - Peek a single 'character' from the specified buffer,
265  /// get its size, and return it.  This is tricky in several cases.  Here we
266  /// just handle the trivial case and fall-back to the non-inlined
267  /// getCharAndSizeSlow method to handle the hard case.
268  inline char getCharAndSize(const char *Ptr, unsigned &Size) {
269    // If this is not a trigraph and not a UCN or escaped newline, return
270    // quickly.
271    if (isObviouslySimpleCharacter(Ptr[0])) {
272      Size = 1;
273      return *Ptr;
274    }
275
276    Size = 0;
277    return getCharAndSizeSlow(Ptr, Size);
278  }
279
280  /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
281  /// method.
282  char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0);
283
284  /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
285  /// emit a warning.
286  static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
287                                          const LangOptions &Features) {
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 getCharAndSizeSlowNoWarn(Ptr, Size, Features);
297  }
298
299  /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
300  /// diagnostic.
301  static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
302                                       const LangOptions &Features);
303
304  //===--------------------------------------------------------------------===//
305  // #if directive handling.
306
307  /// pushConditionalLevel - When we enter a #if directive, this keeps track of
308  /// what we are currently in for diagnostic emission (e.g. #if with missing
309  /// #endif).
310  void pushConditionalLevel(SourceLocation DirectiveStart, bool WasSkipping,
311                            bool FoundNonSkip, bool FoundElse) {
312    PPConditionalInfo CI;
313    CI.IfLoc = DirectiveStart;
314    CI.WasSkipping = WasSkipping;
315    CI.FoundNonSkip = FoundNonSkip;
316    CI.FoundElse = FoundElse;
317    ConditionalStack.push_back(CI);
318  }
319  void pushConditionalLevel(const PPConditionalInfo &CI) {
320    ConditionalStack.push_back(CI);
321  }
322
323  /// popConditionalLevel - Remove an entry off the top of the conditional
324  /// stack, returning information about it.  If the conditional stack is empty,
325  /// this returns true and does not fill in the arguments.
326  bool popConditionalLevel(PPConditionalInfo &CI) {
327    if (ConditionalStack.empty()) return true;
328    CI = ConditionalStack.back();
329    ConditionalStack.pop_back();
330    return false;
331  }
332
333  /// peekConditionalLevel - Return the top of the conditional stack.  This
334  /// requires that there be a conditional active.
335  PPConditionalInfo &peekConditionalLevel() {
336    assert(!ConditionalStack.empty() && "No conditionals active!");
337    return ConditionalStack.back();
338  }
339
340  unsigned getConditionalStackDepth() const { return ConditionalStack.size(); }
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  void 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  /// LexIncludeFilename - After the preprocessor has parsed a #include, lex and
359  /// (potentially) macro expand the filename.  If the sequence parsed is not
360  /// lexically legal, emit a diagnostic and return a result EOM token.
361  void LexIncludeFilename(Token &Result);
362};
363
364
365}  // end namespace clang
366
367#endif
368