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"
24 class DiagnosticsEngine;
27 class DiagnosticBuilder;
29 /// ConflictMarkerKind - Kinds of conflict marker which the lexer might be
31 enum ConflictMarkerKind {
32 /// Not within a conflict marker.
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.
37 /// A Perforce-style conflict marker, initiated by 4 ">"s,
38 /// separated by 4 "="s, and terminated by 4 "<"s.
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 virtual void anchor();
49 //===--------------------------------------------------------------------===//
50 // Constant configuration values for this lexer.
51 const char *BufferStart; // Start of the buffer.
52 const char *BufferEnd; // End of the buffer.
53 SourceLocation FileLoc; // Location for start of file.
54 LangOptions LangOpts; // LangOpts enabled by this language (cache).
55 bool Is_PragmaLexer; // True if lexer for _Pragma handling.
57 //===--------------------------------------------------------------------===//
58 // Context-specific lexing flags set by the preprocessor.
61 /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace
62 /// and return them as tokens. This is used for -C and -CC modes, and
63 /// whitespace preservation can be useful for some clients that want to lex
64 /// the file in raw mode and get every character from the file.
66 /// When this is set to 2 it returns comments and whitespace. When set to 1
67 /// it returns comments, when it is set to 0 it returns normal tokens only.
68 unsigned char ExtendedTokenMode;
70 //===--------------------------------------------------------------------===//
71 // Context that changes as the file is lexed.
72 // NOTE: any state that mutates when in raw mode must have save/restore code
73 // in Lexer::isNextPPTokenLParen.
75 // BufferPtr - Current pointer into the buffer. This is the next character
77 const char *BufferPtr;
79 // IsAtStartOfLine - True if the next lexed token should get the "start of
80 // line" flag set on it.
83 // CurrentConflictMarkerState - The kind of conflict marker we are handling.
84 ConflictMarkerKind CurrentConflictMarkerState;
86 Lexer(const Lexer &) LLVM_DELETED_FUNCTION;
87 void operator=(const Lexer &) LLVM_DELETED_FUNCTION;
88 friend class Preprocessor;
90 void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd);
93 /// Lexer constructor - Create a new lexer object for the specified buffer
94 /// with the specified preprocessor managing the lexing process. This lexer
95 /// assumes that the associated file buffer and Preprocessor objects will
96 /// outlive it, so it doesn't take ownership of either of them.
97 Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer, Preprocessor &PP);
99 /// Lexer constructor - Create a new raw lexer object. This object is only
100 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the
101 /// text range will outlive it, so it doesn't take ownership of it.
102 Lexer(SourceLocation FileLoc, const LangOptions &LangOpts,
103 const char *BufStart, const char *BufPtr, const char *BufEnd);
105 /// Lexer constructor - Create a new raw lexer object. This object is only
106 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the
107 /// text range will outlive it, so it doesn't take ownership of it.
108 Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer,
109 const SourceManager &SM, const LangOptions &LangOpts);
111 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
112 /// _Pragma expansion. This has a variety of magic semantics that this method
113 /// sets up. It returns a new'd Lexer that must be delete'd when done.
114 static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc,
115 SourceLocation ExpansionLocStart,
116 SourceLocation ExpansionLocEnd,
117 unsigned TokLen, Preprocessor &PP);
120 /// getLangOpts - Return the language features currently enabled.
121 /// NOTE: this lexer modifies features as a file is parsed!
122 const LangOptions &getLangOpts() const { return LangOpts; }
124 /// getFileLoc - Return the File Location for the file we are lexing out of.
125 /// The physical location encodes the location where the characters come from,
126 /// the virtual location encodes where we should *claim* the characters came
127 /// from. Currently this is only used by _Pragma handling.
128 SourceLocation getFileLoc() const { return FileLoc; }
130 /// Lex - Return the next token in the file. If this is the end of file, it
131 /// return the tok::eof token. This implicitly involves the preprocessor.
132 void Lex(Token &Result) {
133 // Start a new token.
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;
143 // Get a token. Note that this may delete the current lexer if the end of
145 LexTokenInternal(Result);
148 /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
149 bool isPragmaLexer() const { return Is_PragmaLexer; }
151 /// IndirectLex - An indirect call to 'Lex' that can be invoked via
152 /// the PreprocessorLexer interface.
153 void IndirectLex(Token &Result) { Lex(Result); }
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!");
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;
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;
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;
182 /// inKeepCommentMode - Return true if the lexer should return comments as
184 bool inKeepCommentMode() const {
185 return ExtendedTokenMode > 0;
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;
197 const char *getBufferStart() const { return BufferStart; }
199 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
200 /// uninterpreted string. This switches the lexer out of directive mode.
201 void ReadToEndOfLine(SmallVectorImpl<char> *Result = 0);
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;
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;
212 /// getSourceLocation - Return a source location for the next character in
213 /// the current file.
214 SourceLocation getSourceLocation() { return getSourceLocation(BufferPtr); }
216 /// \brief Return the current location in the buffer.
217 const char *getBufferLocation() const { return BufferPtr; }
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);
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);
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.
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 &LangOpts,
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
249 static std::string getSpelling(const Token &Tok,
250 const SourceManager &SourceMgr,
251 const LangOptions &LangOpts,
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.
259 /// This method lexes at the expansion depth of the given
260 /// location and does not jump to the expansion or spelling
262 static StringRef getSpelling(SourceLocation loc,
263 SmallVectorImpl<char> &buffer,
264 const SourceManager &SourceMgr,
265 const LangOptions &LangOpts,
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);
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 static SourceLocation GetBeginningOfToken(SourceLocation Loc,
280 const SourceManager &SM,
281 const LangOptions &LangOpts);
283 /// AdvanceToTokenCharacter - If the current SourceLocation specifies a
284 /// location at the start of a token, return a new location that specifies a
285 /// character within the token. This handles trigraphs and escaped newlines.
286 static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
288 const SourceManager &SM,
289 const LangOptions &LangOpts);
291 /// \brief Computes the source location just past the end of the
292 /// token at this source location.
294 /// This routine can be used to produce a source location that
295 /// points just past the end of the token referenced by \p Loc, and
296 /// is generally used when a diagnostic needs to point just after a
297 /// token where it expected something different that it received. If
298 /// the returned source location would not be meaningful (e.g., if
299 /// it points into a macro), this routine returns an invalid
302 /// \param Offset an offset from the end of the token, where the source
303 /// location should refer to. The default offset (0) produces a source
304 /// location pointing just past the end of the token; an offset of 1 produces
305 /// a source location pointing to the last character in the token, etc.
306 static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
307 const SourceManager &SM,
308 const LangOptions &LangOpts);
310 /// \brief Returns true if the given MacroID location points at the first
311 /// token of the macro expansion.
313 /// \param MacroBegin If non-null and function returns true, it is set to
314 /// begin location of the macro.
315 static bool isAtStartOfMacroExpansion(SourceLocation loc,
316 const SourceManager &SM,
317 const LangOptions &LangOpts,
318 SourceLocation *MacroBegin = 0);
320 /// \brief Returns true if the given MacroID location points at the last
321 /// token of the macro expansion.
323 /// \param MacroEnd If non-null and function returns true, it is set to
324 /// end location of the macro.
325 static bool isAtEndOfMacroExpansion(SourceLocation loc,
326 const SourceManager &SM,
327 const LangOptions &LangOpts,
328 SourceLocation *MacroEnd = 0);
330 /// \brief Accepts a range and returns a character range with file locations.
332 /// Returns a null range if a part of the range resides inside a macro
333 /// expansion or the range does not reside on the same FileID.
335 /// This function is trying to deal with macros and return a range based on
336 /// file locations. The cases where it can successfully handle macros are:
338 /// -begin or end range lies at the start or end of a macro expansion, in
339 /// which case the location will be set to the expansion point, e.g:
342 /// If you have a range [a, 2] (where 2 came from the macro), the function
343 /// will return a range for "a M"
344 /// if you have range [a, 1], the function will fail because the range
345 /// overlaps with only a part of the macro
347 /// -The macro is a function macro and the range can be mapped to the macro
352 /// if you have range [b, 2], the function will return the file range "b M"
353 /// inside the macro arguments.
354 /// if you have range [a, 2], the function will return the file range
355 /// "FM(a b M)" since the range includes all of the macro expansion.
356 static CharSourceRange makeFileCharRange(CharSourceRange Range,
357 const SourceManager &SM,
358 const LangOptions &LangOpts);
360 /// \brief Returns a string for the source that the range encompasses.
361 static StringRef getSourceText(CharSourceRange Range,
362 const SourceManager &SM,
363 const LangOptions &LangOpts,
366 /// \brief Retrieve the name of the immediate macro expansion.
368 /// This routine starts from a source location, and finds the name of the macro
369 /// responsible for its immediate expansion. It looks through any intervening
370 /// macro argument expansions to compute this. It returns a StringRef which
371 /// refers to the SourceManager-owned buffer of the source where that macro
372 /// name is spelled. Thus, the result shouldn't out-live that SourceManager.
373 static StringRef getImmediateMacroName(SourceLocation Loc,
374 const SourceManager &SM,
375 const LangOptions &LangOpts);
377 /// \brief Compute the preamble of the given file.
379 /// The preamble of a file contains the initial comments, include directives,
380 /// and other preprocessor directives that occur before the code in this
381 /// particular file actually begins. The preamble of the main source file is
382 /// a potential prefix header.
384 /// \param Buffer The memory buffer containing the file's contents.
386 /// \param MaxLines If non-zero, restrict the length of the preamble
387 /// to fewer than this number of lines.
389 /// \returns The offset into the file where the preamble ends and the rest
390 /// of the file begins along with a boolean value indicating whether
391 /// the preamble ends at the beginning of a new line.
392 static std::pair<unsigned, bool>
393 ComputePreamble(const llvm::MemoryBuffer *Buffer, const LangOptions &LangOpts,
394 unsigned MaxLines = 0);
396 /// \brief Checks that the given token is the first token that occurs after
397 /// the given location (this excludes comments and whitespace). Returns the
398 /// location immediately after the specified token. If the token is not found
399 /// or the location is inside a macro, the returned source location will be
401 static SourceLocation findLocationAfterToken(SourceLocation loc,
402 tok::TokenKind TKind,
403 const SourceManager &SM,
404 const LangOptions &LangOpts,
405 bool SkipTrailingWhitespaceAndNewLine);
407 /// \brief Returns true if the given character could appear in an identifier.
408 static bool isIdentifierBodyChar(char c, const LangOptions &LangOpts);
410 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
412 static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
413 const LangOptions &LangOpts) {
414 // If this is not a trigraph and not a UCN or escaped newline, return
416 if (isObviouslySimpleCharacter(Ptr[0])) {
422 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
425 //===--------------------------------------------------------------------===//
426 // Internal implementation interfaces.
429 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
432 void LexTokenInternal(Token &Result);
434 /// FormTokenWithChars - When we lex a token, we have identified a span
435 /// starting at BufferPtr, going to TokEnd that forms the token. This method
436 /// takes that range and assigns it to the token as its location and size. In
437 /// addition, since tokens cannot overlap, this also updates BufferPtr to be
439 void FormTokenWithChars(Token &Result, const char *TokEnd,
440 tok::TokenKind Kind) {
441 unsigned TokLen = TokEnd-BufferPtr;
442 Result.setLength(TokLen);
443 Result.setLocation(getSourceLocation(BufferPtr, TokLen));
444 Result.setKind(Kind);
448 /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a
449 /// tok::l_paren token, 0 if it is something else and 2 if there are no more
450 /// tokens in the buffer controlled by this lexer.
451 unsigned isNextPPTokenLParen();
453 //===--------------------------------------------------------------------===//
454 // Lexer character reading interfaces.
456 // This lexer is built on two interfaces for reading characters, both of which
457 // automatically provide phase 1/2 translation. getAndAdvanceChar is used
458 // when we know that we will be reading a character from the input buffer and
459 // that this character will be part of the result token. This occurs in (f.e.)
460 // string processing, because we know we need to read until we find the
461 // closing '"' character.
463 // The second interface is the combination of getCharAndSize with
464 // ConsumeChar. getCharAndSize reads a phase 1/2 translated character,
465 // returning it and its size. If the lexer decides that this character is
466 // part of the current token, it calls ConsumeChar on it. This two stage
467 // approach allows us to emit diagnostics for characters (e.g. warnings about
468 // trigraphs), knowing that they only are emitted if the character is
471 /// isObviouslySimpleCharacter - Return true if the specified character is
472 /// obviously the same in translation phase 1 and translation phase 3. This
473 /// can return false for characters that end up being the same, but it will
474 /// never return true for something that needs to be mapped.
475 static bool isObviouslySimpleCharacter(char C) {
476 return C != '?' && C != '\\';
479 /// getAndAdvanceChar - Read a single 'character' from the specified buffer,
480 /// advance over it, and return it. This is tricky in several cases. Here we
481 /// just handle the trivial case and fall-back to the non-inlined
482 /// getCharAndSizeSlow method to handle the hard case.
483 inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) {
484 // If this is not a trigraph and not a UCN or escaped newline, return
486 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
489 char C = getCharAndSizeSlow(Ptr, Size, &Tok);
494 /// ConsumeChar - When a character (identified by getCharAndSize) is consumed
495 /// and added to a given token, check to see if there are diagnostics that
496 /// need to be emitted or flags that need to be set on the token. If so, do
498 const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
499 // Normal case, we consumed exactly one token. Just return it.
503 // Otherwise, re-lex the character with a current token, allowing
504 // diagnostics to be emitted and flags to be set.
506 getCharAndSizeSlow(Ptr, Size, &Tok);
510 /// getCharAndSize - Peek a single 'character' from the specified buffer,
511 /// get its size, and return it. This is tricky in several cases. Here we
512 /// just handle the trivial case and fall-back to the non-inlined
513 /// getCharAndSizeSlow method to handle the hard case.
514 inline char getCharAndSize(const char *Ptr, unsigned &Size) {
515 // If this is not a trigraph and not a UCN or escaped newline, return
517 if (isObviouslySimpleCharacter(Ptr[0])) {
523 return getCharAndSizeSlow(Ptr, Size);
526 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
528 char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0);
530 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
531 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry
532 /// to this function.
533 static unsigned getEscapedNewLineSize(const char *P);
535 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
536 /// them), skip over them and return the first non-escaped-newline found,
537 /// otherwise return P.
538 static const char *SkipEscapedNewLines(const char *P);
540 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
542 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
543 const LangOptions &LangOpts);
545 //===--------------------------------------------------------------------===//
546 // Other lexer functions.
548 void SkipBytes(unsigned Bytes, bool StartOfLine);
550 const char *LexUDSuffix(Token &Result, const char *CurPtr);
552 // Helper functions to lex the remainder of a token of the specific type.
553 void LexIdentifier (Token &Result, const char *CurPtr);
554 void LexNumericConstant (Token &Result, const char *CurPtr);
555 void LexStringLiteral (Token &Result, const char *CurPtr,
556 tok::TokenKind Kind);
557 void LexRawStringLiteral (Token &Result, const char *CurPtr,
558 tok::TokenKind Kind);
559 void LexAngledStringLiteral(Token &Result, const char *CurPtr);
560 void LexCharConstant (Token &Result, const char *CurPtr,
561 tok::TokenKind Kind);
562 bool LexEndOfFile (Token &Result, const char *CurPtr);
564 bool SkipWhitespace (Token &Result, const char *CurPtr);
565 bool SkipLineComment (Token &Result, const char *CurPtr);
566 bool SkipBlockComment (Token &Result, const char *CurPtr);
567 bool SaveLineComment (Token &Result, const char *CurPtr);
569 bool IsStartOfConflictMarker(const char *CurPtr);
570 bool HandleEndOfConflictMarker(const char *CurPtr);
572 bool isCodeCompletionPoint(const char *CurPtr) const;
573 void cutOffLexing() { BufferPtr = BufferEnd; }
575 bool isHexaLiteral(const char *Start, const LangOptions &LangOpts);
579 } // end namespace clang