]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/include/clang/Lex/Lexer.h
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / tools / clang / include / clang / Lex / Lexer.h
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 <cassert>
22
23 namespace clang {
24 class DiagnosticsEngine;
25 class SourceManager;
26 class Preprocessor;
27 class DiagnosticBuilder;
28
29 /// ConflictMarkerKind - Kinds of conflict marker which the lexer might be
30 /// recovering from.
31 enum ConflictMarkerKind {
32   /// Not within a conflict marker.
33   CMK_None,
34   /// A normal or diff3 conflict marker, initiated by at least 7 <s,
35   /// separated by at least 7 =s or |s, and terminated by at least 7 >s.
36   CMK_Normal,
37   /// A Perforce-style conflict marker, initiated by 4 >s, separated by 4 =s,
38   /// and terminated by 4 <s.
39   CMK_Perforce
40 };
41
42 /// Lexer - This provides a simple interface that turns a text buffer into a
43 /// stream of tokens.  This provides no support for file reading or buffering,
44 /// or buffering/seeking of tokens, only forward lexing is supported.  It relies
45 /// on the specified Preprocessor object to handle preprocessor directives, etc.
46 class Lexer : public PreprocessorLexer {
47   //===--------------------------------------------------------------------===//
48   // Constant configuration values for this lexer.
49   const char *BufferStart;       // Start of the buffer.
50   const char *BufferEnd;         // End of the buffer.
51   SourceLocation FileLoc;        // Location for start of file.
52   LangOptions Features;          // Features enabled by this language (cache).
53   bool Is_PragmaLexer;           // True if lexer for _Pragma handling.
54   
55   //===--------------------------------------------------------------------===//
56   // Context-specific lexing flags set by the preprocessor.
57   //
58
59   /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace
60   /// and return them as tokens.  This is used for -C and -CC modes, and
61   /// whitespace preservation can be useful for some clients that want to lex
62   /// the file in raw mode and get every character from the file.
63   ///
64   /// When this is set to 2 it returns comments and whitespace.  When set to 1
65   /// it returns comments, when it is set to 0 it returns normal tokens only.
66   unsigned char ExtendedTokenMode;
67
68   //===--------------------------------------------------------------------===//
69   // Context that changes as the file is lexed.
70   // NOTE: any state that mutates when in raw mode must have save/restore code
71   // in Lexer::isNextPPTokenLParen.
72
73   // BufferPtr - Current pointer into the buffer.  This is the next character
74   // to be lexed.
75   const char *BufferPtr;
76
77   // IsAtStartOfLine - True if the next lexed token should get the "start of
78   // line" flag set on it.
79   bool IsAtStartOfLine;
80
81   // CurrentConflictMarkerState - The kind of conflict marker we are handling.
82   ConflictMarkerKind CurrentConflictMarkerState;
83
84   Lexer(const Lexer&);          // DO NOT IMPLEMENT
85   void operator=(const Lexer&); // DO NOT IMPLEMENT
86   friend class Preprocessor;
87
88   void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd);
89 public:
90
91   /// Lexer constructor - Create a new lexer object for the specified buffer
92   /// with the specified preprocessor managing the lexing process.  This lexer
93   /// assumes that the associated file buffer and Preprocessor objects will
94   /// outlive it, so it doesn't take ownership of either of them.
95   Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer, Preprocessor &PP);
96
97   /// Lexer constructor - Create a new raw lexer object.  This object is only
98   /// suitable for calls to 'LexRawToken'.  This lexer assumes that the text
99   /// range will outlive it, so it doesn't take ownership of it.
100   Lexer(SourceLocation FileLoc, const LangOptions &Features,
101         const char *BufStart, const char *BufPtr, const char *BufEnd);
102
103   /// Lexer constructor - Create a new raw lexer object.  This object is only
104   /// suitable for calls to 'LexRawToken'.  This lexer assumes that the text
105   /// range will outlive it, so it doesn't take ownership of it.
106   Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer,
107         const SourceManager &SM, const LangOptions &Features);
108
109   /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
110   /// _Pragma expansion.  This has a variety of magic semantics that this method
111   /// sets up.  It returns a new'd Lexer that must be delete'd when done.
112   static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc,
113                                    SourceLocation ExpansionLocStart,
114                                    SourceLocation ExpansionLocEnd,
115                                    unsigned TokLen, Preprocessor &PP);
116
117
118   /// getFeatures - Return the language features currently enabled.  NOTE: this
119   /// lexer modifies features as a file is parsed!
120   const LangOptions &getFeatures() const { return Features; }
121
122   /// getFileLoc - Return the File Location for the file we are lexing out of.
123   /// The physical location encodes the location where the characters come from,
124   /// the virtual location encodes where we should *claim* the characters came
125   /// from.  Currently this is only used by _Pragma handling.
126   SourceLocation getFileLoc() const { return FileLoc; }
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   /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
149   bool isPragmaLexer() const { return Is_PragmaLexer; }
150
151   /// IndirectLex - An indirect call to 'Lex' that can be invoked via
152   ///  the PreprocessorLexer interface.
153   void IndirectLex(Token &Result) { Lex(Result); }
154
155   /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no
156   /// associated preprocessor object.  Return true if the 'next character to
157   /// read' pointer points at the end of the lexer buffer, false otherwise.
158   bool LexFromRawLexer(Token &Result) {
159     assert(LexingRawMode && "Not already in raw mode!");
160     Lex(Result);
161     // Note that lexing to the end of the buffer doesn't implicitly delete the
162     // lexer when in raw mode.
163     return BufferPtr == BufferEnd;
164   }
165
166   /// isKeepWhitespaceMode - Return true if the lexer should return tokens for
167   /// every character in the file, including whitespace and comments.  This
168   /// should only be used in raw mode, as the preprocessor is not prepared to
169   /// deal with the excess tokens.
170   bool isKeepWhitespaceMode() const {
171     return ExtendedTokenMode > 1;
172   }
173
174   /// SetKeepWhitespaceMode - This method lets clients enable or disable
175   /// whitespace retention mode.
176   void SetKeepWhitespaceMode(bool Val) {
177     assert((!Val || LexingRawMode) &&
178            "Can only enable whitespace retention in raw mode");
179     ExtendedTokenMode = Val ? 2 : 0;
180   }
181
182   /// inKeepCommentMode - Return true if the lexer should return comments as
183   /// tokens.
184   bool inKeepCommentMode() const {
185     return ExtendedTokenMode > 0;
186   }
187
188   /// SetCommentRetentionMode - Change the comment retention mode of the lexer
189   /// to the specified mode.  This is really only useful when lexing in raw
190   /// mode, because otherwise the lexer needs to manage this.
191   void SetCommentRetentionState(bool Mode) {
192     assert(!isKeepWhitespaceMode() &&
193            "Can't play with comment retention state when retaining whitespace");
194     ExtendedTokenMode = Mode ? 1 : 0;
195   }
196
197   const char *getBufferStart() const { return BufferStart; }
198
199   /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
200   /// uninterpreted string.  This switches the lexer out of directive mode.
201   std::string ReadToEndOfLine();
202
203
204   /// Diag - Forwarding function for diagnostics.  This translate a source
205   /// position in the current buffer into a SourceLocation object for rendering.
206   DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const;
207
208   /// getSourceLocation - Return a source location identifier for the specified
209   /// offset in the current file.
210   SourceLocation getSourceLocation(const char *Loc, unsigned TokLen = 1) const;
211
212   /// getSourceLocation - Return a source location for the next character in
213   /// the current file.
214   SourceLocation getSourceLocation() { return getSourceLocation(BufferPtr); }
215
216   /// \brief Return the current location in the buffer.
217   const char *getBufferLocation() const { return BufferPtr; }
218   
219   /// Stringify - Convert the specified string into a C string by escaping '\'
220   /// and " characters.  This does not add surrounding ""'s to the string.
221   /// If Charify is true, this escapes the ' character instead of ".
222   static std::string Stringify(const std::string &Str, bool Charify = false);
223
224   /// Stringify - Convert the specified string into a C string by escaping '\'
225   /// and " characters.  This does not add surrounding ""'s to the string.
226   static void Stringify(SmallVectorImpl<char> &Str);
227
228   
229   /// getSpelling - This method is used to get the spelling of a token into a
230   /// preallocated buffer, instead of as an std::string.  The caller is required
231   /// to allocate enough space for the token, which is guaranteed to be at least
232   /// Tok.getLength() bytes long.  The length of the actual result is returned.
233   ///
234   /// Note that this method may do two possible things: it may either fill in
235   /// the buffer specified with characters, or it may *change the input pointer*
236   /// to point to a constant buffer with the data already in it (avoiding a
237   /// copy).  The caller is not allowed to modify the returned buffer pointer
238   /// if an internal buffer is returned.
239   static unsigned getSpelling(const Token &Tok, const char *&Buffer, 
240                               const SourceManager &SourceMgr,
241                               const LangOptions &Features,
242                               bool *Invalid = 0);
243   
244   /// getSpelling() - Return the 'spelling' of the Tok token.  The spelling of a
245   /// token is the characters used to represent the token in the source file
246   /// after trigraph expansion and escaped-newline folding.  In particular, this
247   /// wants to get the true, uncanonicalized, spelling of things like digraphs
248   /// UCNs, etc.
249   static std::string getSpelling(const Token &Tok,
250                                  const SourceManager &SourceMgr,
251                                  const LangOptions &Features, 
252                                  bool *Invalid = 0);
253
254   /// getSpelling - This method is used to get the spelling of the
255   /// token at the given source location.  If, as is usually true, it
256   /// is not necessary to copy any data, then the returned string may
257   /// not point into the provided buffer.
258   ///
259   /// This method lexes at the expansion depth of the given
260   /// location and does not jump to the expansion or spelling
261   /// location.
262   static StringRef getSpelling(SourceLocation loc,
263                                      SmallVectorImpl<char> &buffer,
264                                      const SourceManager &SourceMgr,
265                                      const LangOptions &Features,
266                                      bool *invalid = 0);
267   
268   /// MeasureTokenLength - Relex the token at the specified location and return
269   /// its length in bytes in the input file.  If the token needs cleaning (e.g.
270   /// includes a trigraph or an escaped newline) then this count includes bytes
271   /// that are part of that.
272   static unsigned MeasureTokenLength(SourceLocation Loc,
273                                      const SourceManager &SM,
274                                      const LangOptions &LangOpts);
275
276   /// \brief Given a location any where in a source buffer, find the location
277   /// that corresponds to the beginning of the token in which the original
278   /// source location lands.
279   ///
280   /// \param Loc 
281   static SourceLocation GetBeginningOfToken(SourceLocation Loc,
282                                             const SourceManager &SM,
283                                             const LangOptions &LangOpts);
284   
285   /// AdvanceToTokenCharacter - If the current SourceLocation specifies a
286   /// location at the start of a token, return a new location that specifies a
287   /// character within the token.  This handles trigraphs and escaped newlines.
288   static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
289                                                 unsigned Character,
290                                                 const SourceManager &SM,
291                                                 const LangOptions &Features);
292   
293   /// \brief Computes the source location just past the end of the
294   /// token at this source location.
295   ///
296   /// This routine can be used to produce a source location that
297   /// points just past the end of the token referenced by \p Loc, and
298   /// is generally used when a diagnostic needs to point just after a
299   /// token where it expected something different that it received. If
300   /// the returned source location would not be meaningful (e.g., if
301   /// it points into a macro), this routine returns an invalid
302   /// source location.
303   ///
304   /// \param Offset an offset from the end of the token, where the source
305   /// location should refer to. The default offset (0) produces a source
306   /// location pointing just past the end of the token; an offset of 1 produces
307   /// a source location pointing to the last character in the token, etc.
308   static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
309                                             const SourceManager &SM,
310                                             const LangOptions &Features);
311
312   /// \brief Returns true if the given MacroID location points at the first
313   /// token of the macro expansion.
314   static bool isAtStartOfMacroExpansion(SourceLocation loc,
315                                             const SourceManager &SM,
316                                             const LangOptions &LangOpts);
317
318   /// \brief Returns true if the given MacroID location points at the last
319   /// token of the macro expansion.
320   static bool isAtEndOfMacroExpansion(SourceLocation loc,
321                                           const SourceManager &SM,
322                                           const LangOptions &LangOpts);
323
324   /// \brief Compute the preamble of the given file.
325   ///
326   /// The preamble of a file contains the initial comments, include directives,
327   /// and other preprocessor directives that occur before the code in this
328   /// particular file actually begins. The preamble of the main source file is
329   /// a potential prefix header.
330   ///
331   /// \param Buffer The memory buffer containing the file's contents.
332   ///
333   /// \param MaxLines If non-zero, restrict the length of the preamble
334   /// to fewer than this number of lines.
335   ///
336   /// \returns The offset into the file where the preamble ends and the rest
337   /// of the file begins along with a boolean value indicating whether 
338   /// the preamble ends at the beginning of a new line.
339   static std::pair<unsigned, bool>
340   ComputePreamble(const llvm::MemoryBuffer *Buffer, const LangOptions &Features,
341                   unsigned MaxLines = 0);
342                                         
343   //===--------------------------------------------------------------------===//
344   // Internal implementation interfaces.
345 private:
346
347   /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
348   /// by Lex.
349   ///
350   void LexTokenInternal(Token &Result);
351
352   /// FormTokenWithChars - When we lex a token, we have identified a span
353   /// starting at BufferPtr, going to TokEnd that forms the token.  This method
354   /// takes that range and assigns it to the token as its location and size.  In
355   /// addition, since tokens cannot overlap, this also updates BufferPtr to be
356   /// TokEnd.
357   void FormTokenWithChars(Token &Result, const char *TokEnd,
358                           tok::TokenKind Kind) {
359     unsigned TokLen = TokEnd-BufferPtr;
360     Result.setLength(TokLen);
361     Result.setLocation(getSourceLocation(BufferPtr, TokLen));
362     Result.setKind(Kind);
363     BufferPtr = TokEnd;
364   }
365
366   /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a
367   /// tok::l_paren token, 0 if it is something else and 2 if there are no more
368   /// tokens in the buffer controlled by this lexer.
369   unsigned isNextPPTokenLParen();
370
371   //===--------------------------------------------------------------------===//
372   // Lexer character reading interfaces.
373 public:
374
375   // This lexer is built on two interfaces for reading characters, both of which
376   // automatically provide phase 1/2 translation.  getAndAdvanceChar is used
377   // when we know that we will be reading a character from the input buffer and
378   // that this character will be part of the result token. This occurs in (f.e.)
379   // string processing, because we know we need to read until we find the
380   // closing '"' character.
381   //
382   // The second interface is the combination of getCharAndSize with
383   // ConsumeChar.  getCharAndSize reads a phase 1/2 translated character,
384   // returning it and its size.  If the lexer decides that this character is
385   // part of the current token, it calls ConsumeChar on it.  This two stage
386   // approach allows us to emit diagnostics for characters (e.g. warnings about
387   // trigraphs), knowing that they only are emitted if the character is
388   // consumed.
389
390   /// isObviouslySimpleCharacter - Return true if the specified character is
391   /// obviously the same in translation phase 1 and translation phase 3.  This
392   /// can return false for characters that end up being the same, but it will
393   /// never return true for something that needs to be mapped.
394   static bool isObviouslySimpleCharacter(char C) {
395     return C != '?' && C != '\\';
396   }
397
398   /// getAndAdvanceChar - Read a single 'character' from the specified buffer,
399   /// advance over it, and return it.  This is tricky in several cases.  Here we
400   /// just handle the trivial case and fall-back to the non-inlined
401   /// getCharAndSizeSlow method to handle the hard case.
402   inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) {
403     // If this is not a trigraph and not a UCN or escaped newline, return
404     // quickly.
405     if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
406
407     unsigned Size = 0;
408     char C = getCharAndSizeSlow(Ptr, Size, &Tok);
409     Ptr += Size;
410     return C;
411   }
412
413 private:
414   /// ConsumeChar - When a character (identified by getCharAndSize) is consumed
415   /// and added to a given token, check to see if there are diagnostics that
416   /// need to be emitted or flags that need to be set on the token.  If so, do
417   /// it.
418   const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
419     // Normal case, we consumed exactly one token.  Just return it.
420     if (Size == 1)
421       return Ptr+Size;
422
423     // Otherwise, re-lex the character with a current token, allowing
424     // diagnostics to be emitted and flags to be set.
425     Size = 0;
426     getCharAndSizeSlow(Ptr, Size, &Tok);
427     return Ptr+Size;
428   }
429
430   /// getCharAndSize - Peek a single 'character' from the specified buffer,
431   /// get its size, and return it.  This is tricky in several cases.  Here we
432   /// just handle the trivial case and fall-back to the non-inlined
433   /// getCharAndSizeSlow method to handle the hard case.
434   inline char getCharAndSize(const char *Ptr, unsigned &Size) {
435     // If this is not a trigraph and not a UCN or escaped newline, return
436     // quickly.
437     if (isObviouslySimpleCharacter(Ptr[0])) {
438       Size = 1;
439       return *Ptr;
440     }
441
442     Size = 0;
443     return getCharAndSizeSlow(Ptr, Size);
444   }
445
446   /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
447   /// method.
448   char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0);
449 public:
450
451   /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
452   /// emit a warning.
453   static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
454                                           const LangOptions &Features) {
455     // If this is not a trigraph and not a UCN or escaped newline, return
456     // quickly.
457     if (isObviouslySimpleCharacter(Ptr[0])) {
458       Size = 1;
459       return *Ptr;
460     }
461
462     Size = 0;
463     return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
464   }
465
466   /// getEscapedNewLineSize - Return the size of the specified escaped newline,
467   /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry
468   /// to this function.
469   static unsigned getEscapedNewLineSize(const char *P);
470
471   /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
472   /// them), skip over them and return the first non-escaped-newline found,
473   /// otherwise return P.
474   static const char *SkipEscapedNewLines(const char *P);
475
476   /// \brief Checks that the given token is the first token that occurs after
477   /// the given location (this excludes comments and whitespace). Returns the
478   /// location immediately after the specified token. If the token is not found
479   /// or the location is inside a macro, the returned source location will be
480   /// invalid.
481   static SourceLocation findLocationAfterToken(SourceLocation loc,
482                                          tok::TokenKind TKind,
483                                          const SourceManager &SM,
484                                          const LangOptions &LangOpts,
485                                          bool SkipTrailingWhitespaceAndNewLine);
486
487 private:
488
489   /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
490   /// diagnostic.
491   static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
492                                        const LangOptions &Features);
493
494   //===--------------------------------------------------------------------===//
495   // Other lexer functions.
496
497   void SkipBytes(unsigned Bytes, bool StartOfLine);
498   
499   // Helper functions to lex the remainder of a token of the specific type.
500   void LexIdentifier         (Token &Result, const char *CurPtr);
501   void LexNumericConstant    (Token &Result, const char *CurPtr);
502   void LexStringLiteral      (Token &Result, const char *CurPtr,
503                               tok::TokenKind Kind);
504   void LexRawStringLiteral   (Token &Result, const char *CurPtr,
505                               tok::TokenKind Kind);
506   void LexAngledStringLiteral(Token &Result, const char *CurPtr);
507   void LexCharConstant       (Token &Result, const char *CurPtr,
508                               tok::TokenKind Kind);
509   bool LexEndOfFile          (Token &Result, const char *CurPtr);
510
511   bool SkipWhitespace        (Token &Result, const char *CurPtr);
512   bool SkipBCPLComment       (Token &Result, const char *CurPtr);
513   bool SkipBlockComment      (Token &Result, const char *CurPtr);
514   bool SaveBCPLComment       (Token &Result, const char *CurPtr);
515   
516   bool IsStartOfConflictMarker(const char *CurPtr);
517   bool HandleEndOfConflictMarker(const char *CurPtr);
518
519   bool isCodeCompletionPoint(const char *CurPtr) const;
520   void cutOffLexing() { BufferPtr = BufferEnd; }
521 };
522
523
524 }  // end namespace clang
525
526 #endif