1 //===--- Lexer.h - C Language Family Lexer ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Lexer interface.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LEXER_H
15 #define LLVM_CLANG_LEXER_H
17 #include "clang/Lex/PreprocessorLexer.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "llvm/ADT/SmallVector.h"
27 class DiagnosticBuilder;
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.
33 class 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 : 1; // True if lexer for _Pragma handling.
41 bool IsInConflictMarker : 1; // True if in a VCS conflict marker '<<<<<<<'
43 //===--------------------------------------------------------------------===//
44 // Context-specific lexing flags set by the preprocessor.
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.
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;
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.
61 // BufferPtr - Current pointer into the buffer. This is the next character
63 const char *BufferPtr;
65 // IsAtStartOfLine - True if the next lexed token should get the "start of
66 // line" flag set on it.
69 Lexer(const Lexer&); // DO NOT IMPLEMENT
70 void operator=(const Lexer&); // DO NOT IMPLEMENT
71 friend class Preprocessor;
73 void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd);
76 /// Lexer constructor - Create a new lexer object for the specified buffer
77 /// with the specified preprocessor managing the lexing process. This lexer
78 /// assumes that the associated file buffer and Preprocessor objects will
79 /// outlive it, so it doesn't take ownership of either of them.
80 Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer, Preprocessor &PP);
82 /// Lexer constructor - Create a new raw lexer object. This object is only
83 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text
84 /// range will outlive it, so it doesn't take ownership of it.
85 Lexer(SourceLocation FileLoc, const LangOptions &Features,
86 const char *BufStart, const char *BufPtr, const char *BufEnd);
88 /// Lexer constructor - Create a new raw lexer object. This object is only
89 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text
90 /// range will outlive it, so it doesn't take ownership of it.
91 Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer,
92 const SourceManager &SM, const LangOptions &Features);
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 ExpansionLocStart,
99 SourceLocation ExpansionLocEnd,
100 unsigned TokLen, Preprocessor &PP);
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; }
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; }
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.
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;
128 // Get a token. Note that this may delete the current lexer if the end of
130 LexTokenInternal(Result);
133 /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
134 bool isPragmaLexer() const { return Is_PragmaLexer; }
136 /// IndirectLex - An indirect call to 'Lex' that can be invoked via
137 /// the PreprocessorLexer interface.
138 void IndirectLex(Token &Result) { Lex(Result); }
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!");
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;
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;
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;
167 /// inKeepCommentMode - Return true if the lexer should return comments as
169 bool inKeepCommentMode() const {
170 return ExtendedTokenMode > 0;
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;
182 const char *getBufferStart() const { return BufferStart; }
184 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
185 /// uninterpreted string. This switches the lexer out of directive mode.
186 std::string ReadToEndOfLine();
189 /// Diag - Forwarding function for diagnostics. This translate a source
190 /// position in the current buffer into a SourceLocation object for rendering.
191 DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const;
193 /// getSourceLocation - Return a source location identifier for the specified
194 /// offset in the current file.
195 SourceLocation getSourceLocation(const char *Loc, unsigned TokLen = 1) const;
197 /// getSourceLocation - Return a source location for the next character in
198 /// the current file.
199 SourceLocation getSourceLocation() { return getSourceLocation(BufferPtr); }
201 /// \brief Return the current location in the buffer.
202 const char *getBufferLocation() const { return BufferPtr; }
204 /// Stringify - Convert the specified string into a C string by escaping '\'
205 /// and " characters. This does not add surrounding ""'s to the string.
206 /// If Charify is true, this escapes the ' character instead of ".
207 static std::string Stringify(const std::string &Str, bool Charify = false);
209 /// Stringify - Convert the specified string into a C string by escaping '\'
210 /// and " characters. This does not add surrounding ""'s to the string.
211 static void Stringify(llvm::SmallVectorImpl<char> &Str);
214 /// getSpelling - This method is used to get the spelling of a token into a
215 /// preallocated buffer, instead of as an std::string. The caller is required
216 /// to allocate enough space for the token, which is guaranteed to be at least
217 /// Tok.getLength() bytes long. The length of the actual result is returned.
219 /// Note that this method may do two possible things: it may either fill in
220 /// the buffer specified with characters, or it may *change the input pointer*
221 /// to point to a constant buffer with the data already in it (avoiding a
222 /// copy). The caller is not allowed to modify the returned buffer pointer
223 /// if an internal buffer is returned.
224 static unsigned getSpelling(const Token &Tok, const char *&Buffer,
225 const SourceManager &SourceMgr,
226 const LangOptions &Features,
229 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a
230 /// token is the characters used to represent the token in the source file
231 /// after trigraph expansion and escaped-newline folding. In particular, this
232 /// wants to get the true, uncanonicalized, spelling of things like digraphs
234 static std::string getSpelling(const Token &Tok,
235 const SourceManager &SourceMgr,
236 const LangOptions &Features,
239 /// getSpelling - This method is used to get the spelling of the
240 /// token at the given source location. If, as is usually true, it
241 /// is not necessary to copy any data, then the returned string may
242 /// not point into the provided buffer.
244 /// This method lexes at the expansion depth of the given
245 /// location and does not jump to the expansion or spelling
247 static llvm::StringRef getSpelling(SourceLocation loc,
248 llvm::SmallVectorImpl<char> &buffer,
249 const SourceManager &SourceMgr,
250 const LangOptions &Features,
253 /// MeasureTokenLength - Relex the token at the specified location and return
254 /// its length in bytes in the input file. If the token needs cleaning (e.g.
255 /// includes a trigraph or an escaped newline) then this count includes bytes
256 /// that are part of that.
257 static unsigned MeasureTokenLength(SourceLocation Loc,
258 const SourceManager &SM,
259 const LangOptions &LangOpts);
261 /// \brief Given a location any where in a source buffer, find the location
262 /// that corresponds to the beginning of the token in which the original
263 /// source location lands.
266 static SourceLocation GetBeginningOfToken(SourceLocation Loc,
267 const SourceManager &SM,
268 const LangOptions &LangOpts);
270 /// AdvanceToTokenCharacter - If the current SourceLocation specifies a
271 /// location at the start of a token, return a new location that specifies a
272 /// character within the token. This handles trigraphs and escaped newlines.
273 static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
275 const SourceManager &SM,
276 const LangOptions &Features);
278 /// \brief Computes the source location just past the end of the
279 /// token at this source location.
281 /// This routine can be used to produce a source location that
282 /// points just past the end of the token referenced by \p Loc, and
283 /// is generally used when a diagnostic needs to point just after a
284 /// token where it expected something different that it received. If
285 /// the returned source location would not be meaningful (e.g., if
286 /// it points into a macro), this routine returns an invalid
289 /// \param Offset an offset from the end of the token, where the source
290 /// location should refer to. The default offset (0) produces a source
291 /// location pointing just past the end of the token; an offset of 1 produces
292 /// a source location pointing to the last character in the token, etc.
293 static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
294 const SourceManager &SM,
295 const LangOptions &Features);
297 /// \brief Returns true if the given MacroID location points at the first
298 /// token of the macro expansion.
299 static bool isAtStartOfMacroExpansion(SourceLocation loc,
300 const SourceManager &SM,
301 const LangOptions &LangOpts);
303 /// \brief Returns true if the given MacroID location points at the last
304 /// token of the macro expansion.
305 static bool isAtEndOfMacroExpansion(SourceLocation loc,
306 const SourceManager &SM,
307 const LangOptions &LangOpts);
309 /// \brief Compute the preamble of the given file.
311 /// The preamble of a file contains the initial comments, include directives,
312 /// and other preprocessor directives that occur before the code in this
313 /// particular file actually begins. The preamble of the main source file is
314 /// a potential prefix header.
316 /// \param Buffer The memory buffer containing the file's contents.
318 /// \param MaxLines If non-zero, restrict the length of the preamble
319 /// to fewer than this number of lines.
321 /// \returns The offset into the file where the preamble ends and the rest
322 /// of the file begins along with a boolean value indicating whether
323 /// the preamble ends at the beginning of a new line.
324 static std::pair<unsigned, bool>
325 ComputePreamble(const llvm::MemoryBuffer *Buffer, unsigned MaxLines = 0);
327 //===--------------------------------------------------------------------===//
328 // Internal implementation interfaces.
331 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
334 void LexTokenInternal(Token &Result);
336 /// FormTokenWithChars - When we lex a token, we have identified a span
337 /// starting at BufferPtr, going to TokEnd that forms the token. This method
338 /// takes that range and assigns it to the token as its location and size. In
339 /// addition, since tokens cannot overlap, this also updates BufferPtr to be
341 void FormTokenWithChars(Token &Result, const char *TokEnd,
342 tok::TokenKind Kind) {
343 unsigned TokLen = TokEnd-BufferPtr;
344 Result.setLength(TokLen);
345 Result.setLocation(getSourceLocation(BufferPtr, TokLen));
346 Result.setKind(Kind);
350 /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a
351 /// tok::l_paren token, 0 if it is something else and 2 if there are no more
352 /// tokens in the buffer controlled by this lexer.
353 unsigned isNextPPTokenLParen();
355 //===--------------------------------------------------------------------===//
356 // Lexer character reading interfaces.
359 // This lexer is built on two interfaces for reading characters, both of which
360 // automatically provide phase 1/2 translation. getAndAdvanceChar is used
361 // when we know that we will be reading a character from the input buffer and
362 // that this character will be part of the result token. This occurs in (f.e.)
363 // string processing, because we know we need to read until we find the
364 // closing '"' character.
366 // The second interface is the combination of getCharAndSize with
367 // ConsumeChar. getCharAndSize reads a phase 1/2 translated character,
368 // returning it and its size. If the lexer decides that this character is
369 // part of the current token, it calls ConsumeChar on it. This two stage
370 // approach allows us to emit diagnostics for characters (e.g. warnings about
371 // trigraphs), knowing that they only are emitted if the character is
374 /// isObviouslySimpleCharacter - Return true if the specified character is
375 /// obviously the same in translation phase 1 and translation phase 3. This
376 /// can return false for characters that end up being the same, but it will
377 /// never return true for something that needs to be mapped.
378 static bool isObviouslySimpleCharacter(char C) {
379 return C != '?' && C != '\\';
382 /// getAndAdvanceChar - Read a single 'character' from the specified buffer,
383 /// advance over it, and return it. This is tricky in several cases. Here we
384 /// just handle the trivial case and fall-back to the non-inlined
385 /// getCharAndSizeSlow method to handle the hard case.
386 inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) {
387 // If this is not a trigraph and not a UCN or escaped newline, return
389 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
392 char C = getCharAndSizeSlow(Ptr, Size, &Tok);
398 /// ConsumeChar - When a character (identified by getCharAndSize) is consumed
399 /// and added to a given token, check to see if there are diagnostics that
400 /// need to be emitted or flags that need to be set on the token. If so, do
402 const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
403 // Normal case, we consumed exactly one token. Just return it.
407 // Otherwise, re-lex the character with a current token, allowing
408 // diagnostics to be emitted and flags to be set.
410 getCharAndSizeSlow(Ptr, Size, &Tok);
414 /// getCharAndSize - Peek a single 'character' from the specified buffer,
415 /// get its size, and return it. This is tricky in several cases. Here we
416 /// just handle the trivial case and fall-back to the non-inlined
417 /// getCharAndSizeSlow method to handle the hard case.
418 inline char getCharAndSize(const char *Ptr, unsigned &Size) {
419 // If this is not a trigraph and not a UCN or escaped newline, return
421 if (isObviouslySimpleCharacter(Ptr[0])) {
427 return getCharAndSizeSlow(Ptr, Size);
430 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
432 char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0);
435 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
437 static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
438 const LangOptions &Features) {
439 // If this is not a trigraph and not a UCN or escaped newline, return
441 if (isObviouslySimpleCharacter(Ptr[0])) {
447 return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
450 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
451 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry
452 /// to this function.
453 static unsigned getEscapedNewLineSize(const char *P);
455 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
456 /// them), skip over them and return the first non-escaped-newline found,
457 /// otherwise return P.
458 static const char *SkipEscapedNewLines(const char *P);
461 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
463 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
464 const LangOptions &Features);
466 //===--------------------------------------------------------------------===//
467 // Other lexer functions.
469 void SkipBytes(unsigned Bytes, bool StartOfLine);
471 // Helper functions to lex the remainder of a token of the specific type.
472 void LexIdentifier (Token &Result, const char *CurPtr);
473 void LexNumericConstant (Token &Result, const char *CurPtr);
474 void LexStringLiteral (Token &Result, const char *CurPtr,bool Wide);
475 void LexAngledStringLiteral(Token &Result, const char *CurPtr);
476 void LexCharConstant (Token &Result, const char *CurPtr);
477 bool LexEndOfFile (Token &Result, const char *CurPtr);
479 bool SkipWhitespace (Token &Result, const char *CurPtr);
480 bool SkipBCPLComment (Token &Result, const char *CurPtr);
481 bool SkipBlockComment (Token &Result, const char *CurPtr);
482 bool SaveBCPLComment (Token &Result, const char *CurPtr);
484 bool IsStartOfConflictMarker(const char *CurPtr);
485 bool HandleEndOfConflictMarker(const char *CurPtr);
489 } // end namespace clang