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