Lexer.h revision 9e6293d4dfd688429f77ee3b6edba9dfd7ada3a2
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/Token.h" 18#include "clang/Lex/MultipleIncludeOpt.h" 19#include "clang/Basic/LangOptions.h" 20#include "llvm/ADT/SmallVector.h" 21#include <string> 22#include <vector> 23#include <cassert> 24 25namespace clang { 26class Diagnostic; 27class SourceManager; 28class Preprocessor; 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 { 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 Preprocessor *PP; // Preprocessor object controlling lexing. 41 LangOptions Features; // Features enabled by this language (cache). 42 bool Is_PragmaLexer; // True if lexer for _Pragma handling. 43 44 //===--------------------------------------------------------------------===// 45 // Context-specific lexing flags set by the preprocessor. 46 // 47 48 /// ParsingPreprocessorDirective - This is true when parsing #XXX. This turns 49 /// '\n' into a tok::eom token. 50 bool ParsingPreprocessorDirective; 51 52 /// ParsingFilename - True after #include: this turns <xx> into a 53 /// tok::angle_string_literal token. 54 bool ParsingFilename; 55 56 /// LexingRawMode - True if in raw mode: This flag disables interpretation of 57 /// tokens and is a far faster mode to lex in than non-raw-mode. This flag: 58 /// 1. If EOF of the current lexer is found, the include stack isn't popped. 59 /// 2. Identifier information is not looked up for identifier tokens. As an 60 /// effect of this, implicit macro expansion is naturally disabled. 61 /// 3. "#" tokens at the start of a line are treated as normal tokens, not 62 /// implicitly transformed by the lexer. 63 /// 4. All diagnostic messages are disabled. 64 /// 5. No callbacks are made into the preprocessor. 65 /// 66 /// Note that in raw mode that the PP pointer may be null. 67 bool LexingRawMode; 68 69 /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace 70 /// and return them as tokens. This is used for -C and -CC modes, and 71 /// whitespace preservation can be useful for some clients that want to lex 72 /// the file in raw mode and get every character from the file. 73 /// 74 /// When this is set to 2 it returns comments and whitespace. When set to 1 75 /// it returns comments, when it is set to 0 it returns normal tokens only. 76 unsigned char ExtendedTokenMode; 77 78 //===--------------------------------------------------------------------===// 79 // Context that changes as the file is lexed. 80 // NOTE: any state that mutates when in raw mode must have save/restore code 81 // in Lexer::isNextPPTokenLParen. 82 83 // BufferPtr - Current pointer into the buffer. This is the next character 84 // to be lexed. 85 const char *BufferPtr; 86 87 // IsAtStartOfLine - True if the next lexed token should get the "start of 88 // line" flag set on it. 89 bool IsAtStartOfLine; 90 91 /// MIOpt - This is a state machine that detects the #ifndef-wrapping a file 92 /// idiom for the multiple-include optimization. 93 MultipleIncludeOpt MIOpt; 94 95 /// ConditionalStack - Information about the set of #if/#ifdef/#ifndef blocks 96 /// we are currently in. 97 std::vector<PPConditionalInfo> ConditionalStack; 98 99 Lexer(const Lexer&); // DO NOT IMPLEMENT 100 void operator=(const Lexer&); // DO NOT IMPLEMENT 101 friend class Preprocessor; 102public: 103 104 /// Lexer constructor - Create a new lexer object for the specified buffer 105 /// with the specified preprocessor managing the lexing process. This lexer 106 /// assumes that the associated file buffer and Preprocessor objects will 107 /// outlive it, so it doesn't take ownership of either of them. 108 Lexer(SourceLocation FileLoc, Preprocessor &PP, 109 const char *BufStart = 0, const char *BufEnd = 0); 110 111 /// Lexer constructor - Create a new raw lexer object. This object is only 112 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text 113 /// range will outlive it, so it doesn't take ownership of it. 114 Lexer(SourceLocation FileLoc, const LangOptions &Features, 115 const char *BufStart, const char *BufEnd, 116 const llvm::MemoryBuffer *FromFile = 0); 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 /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no 149 /// associated preprocessor object. Return true if the 'next character to 150 /// read' pointer points and the end of the lexer buffer, false otherwise. 151 bool LexFromRawLexer(Token &Result) { 152 assert(LexingRawMode && "Not already in raw mode!"); 153 Lex(Result); 154 // Note that lexing to the end of the buffer doesn't implicitly delete the 155 // lexer when in raw mode. 156 return BufferPtr == BufferEnd; 157 } 158 159 /// isKeepWhitespaceMode - Return true if the lexer should return tokens for 160 /// every character in the file, including whitespace and comments. This 161 /// should only be used in raw mode, as the preprocessor is not prepared to 162 /// deal with the excess tokens. 163 bool isKeepWhitespaceMode() const { 164 return ExtendedTokenMode > 1; 165 } 166 167 /// SetKeepWhitespaceMode - This method lets clients enable or disable 168 /// whitespace retention mode. 169 void SetKeepWhitespaceMode(bool Val) { 170 assert((!Val || LexingRawMode) && 171 "Can only enable whitespace retention in raw mode"); 172 ExtendedTokenMode = Val ? 2 : 0; 173 } 174 175 /// inKeepCommentMode - Return true if the lexer should return comments as 176 /// tokens. 177 bool inKeepCommentMode() const { 178 return ExtendedTokenMode > 0; 179 } 180 181 /// SetCommentRetentionMode - Change the comment retention mode of the lexer 182 /// to the specified mode. This is really only useful when lexing in raw 183 /// mode, because otherwise the lexer needs to manage this. 184 void SetCommentRetentionState(bool Mode) { 185 assert(!isKeepWhitespaceMode() && 186 "Can't play with comment retention state when retaining whitespace"); 187 ExtendedTokenMode = Mode ? 1 : 0; 188 } 189 190 191 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an 192 /// uninterpreted string. This switches the lexer out of directive mode. 193 std::string ReadToEndOfLine(); 194 195 196 /// Diag - Forwarding function for diagnostics. This translate a source 197 /// position in the current buffer into a SourceLocation object for rendering. 198 void Diag(const char *Loc, unsigned DiagID, 199 const std::string &Msg = std::string()) const; 200 void Diag(SourceLocation Loc, unsigned DiagID, 201 const std::string &Msg = std::string()) const; 202 203 /// getSourceLocation - Return a source location identifier for the specified 204 /// offset in the current file. 205 SourceLocation getSourceLocation(const char *Loc) const; 206 207 /// Stringify - Convert the specified string into a C string by escaping '\' 208 /// and " characters. This does not add surrounding ""'s to the string. 209 /// If Charify is true, this escapes the ' character instead of ". 210 static std::string Stringify(const std::string &Str, bool Charify = false); 211 212 /// Stringify - Convert the specified string into a C string by escaping '\' 213 /// and " characters. This does not add surrounding ""'s to the string. 214 static void Stringify(llvm::SmallVectorImpl<char> &Str); 215 216 /// MeasureTokenLength - Relex the token at the specified location and return 217 /// its length in bytes in the input file. If the token needs cleaning (e.g. 218 /// includes a trigraph or an escaped newline) then this count includes bytes 219 /// that are part of that. 220 static unsigned MeasureTokenLength(SourceLocation Loc, 221 const SourceManager &SM); 222 223 //===--------------------------------------------------------------------===// 224 // Internal implementation interfaces. 225private: 226 227 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called 228 /// by Lex. 229 /// 230 void LexTokenInternal(Token &Result); 231 232 /// FormTokenWithChars - When we lex a token, we have identified a span 233 /// starting at BufferPtr, going to TokEnd that forms the token. This method 234 /// takes that range and assigns it to the token as its location and size. In 235 /// addition, since tokens cannot overlap, this also updates BufferPtr to be 236 /// TokEnd. 237 void FormTokenWithChars(Token &Result, const char *TokEnd, 238 tok::TokenKind Kind) { 239 Result.setLocation(getSourceLocation(BufferPtr)); 240 Result.setLength(TokEnd-BufferPtr); 241 Result.setKind(Kind); 242 BufferPtr = TokEnd; 243 } 244 245 /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a 246 /// tok::l_paren token, 0 if it is something else and 2 if there are no more 247 /// tokens in the buffer controlled by this lexer. 248 unsigned isNextPPTokenLParen(); 249 250 //===--------------------------------------------------------------------===// 251 // Lexer character reading interfaces. 252public: 253 254 // This lexer is built on two interfaces for reading characters, both of which 255 // automatically provide phase 1/2 translation. getAndAdvanceChar is used 256 // when we know that we will be reading a character from the input buffer and 257 // that this character will be part of the result token. This occurs in (f.e.) 258 // string processing, because we know we need to read until we find the 259 // closing '"' character. 260 // 261 // The second interface is the combination of PeekCharAndSize with 262 // ConsumeChar. PeekCharAndSize reads a phase 1/2 translated character, 263 // returning it and its size. If the lexer decides that this character is 264 // part of the current token, it calls ConsumeChar on it. This two stage 265 // approach allows us to emit diagnostics for characters (e.g. warnings about 266 // trigraphs), knowing that they only are emitted if the character is 267 // consumed. 268 269 /// isObviouslySimpleCharacter - Return true if the specified character is 270 /// obviously the same in translation phase 1 and translation phase 3. This 271 /// can return false for characters that end up being the same, but it will 272 /// never return true for something that needs to be mapped. 273 static bool isObviouslySimpleCharacter(char C) { 274 return C != '?' && C != '\\'; 275 } 276 277 /// getAndAdvanceChar - Read a single 'character' from the specified buffer, 278 /// advance over it, and return it. This is tricky in several cases. Here we 279 /// just handle the trivial case and fall-back to the non-inlined 280 /// getCharAndSizeSlow method to handle the hard case. 281 inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) { 282 // If this is not a trigraph and not a UCN or escaped newline, return 283 // quickly. 284 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++; 285 286 unsigned Size = 0; 287 char C = getCharAndSizeSlow(Ptr, Size, &Tok); 288 Ptr += Size; 289 return C; 290 } 291 292private: 293 /// ConsumeChar - When a character (identified by PeekCharAndSize) is consumed 294 /// and added to a given token, check to see if there are diagnostics that 295 /// need to be emitted or flags that need to be set on the token. If so, do 296 /// it. 297 const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) { 298 // Normal case, we consumed exactly one token. Just return it. 299 if (Size == 1) 300 return Ptr+Size; 301 302 // Otherwise, re-lex the character with a current token, allowing 303 // diagnostics to be emitted and flags to be set. 304 Size = 0; 305 getCharAndSizeSlow(Ptr, Size, &Tok); 306 return Ptr+Size; 307 } 308 309 /// getCharAndSize - Peek a single 'character' from the specified buffer, 310 /// get its size, and return it. This is tricky in several cases. Here we 311 /// just handle the trivial case and fall-back to the non-inlined 312 /// getCharAndSizeSlow method to handle the hard case. 313 inline char getCharAndSize(const char *Ptr, unsigned &Size) { 314 // If this is not a trigraph and not a UCN or escaped newline, return 315 // quickly. 316 if (isObviouslySimpleCharacter(Ptr[0])) { 317 Size = 1; 318 return *Ptr; 319 } 320 321 Size = 0; 322 return getCharAndSizeSlow(Ptr, Size); 323 } 324 325 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize 326 /// method. 327 char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0); 328 329 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever 330 /// emit a warning. 331 static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, 332 const LangOptions &Features) { 333 // If this is not a trigraph and not a UCN or escaped newline, return 334 // quickly. 335 if (isObviouslySimpleCharacter(Ptr[0])) { 336 Size = 1; 337 return *Ptr; 338 } 339 340 Size = 0; 341 return getCharAndSizeSlowNoWarn(Ptr, Size, Features); 342 } 343 344 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a 345 /// diagnostic. 346 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, 347 const LangOptions &Features); 348 349 //===--------------------------------------------------------------------===// 350 // #if directive handling. 351 352 /// pushConditionalLevel - When we enter a #if directive, this keeps track of 353 /// what we are currently in for diagnostic emission (e.g. #if with missing 354 /// #endif). 355 void pushConditionalLevel(SourceLocation DirectiveStart, bool WasSkipping, 356 bool FoundNonSkip, bool FoundElse) { 357 PPConditionalInfo CI; 358 CI.IfLoc = DirectiveStart; 359 CI.WasSkipping = WasSkipping; 360 CI.FoundNonSkip = FoundNonSkip; 361 CI.FoundElse = FoundElse; 362 ConditionalStack.push_back(CI); 363 } 364 void pushConditionalLevel(const PPConditionalInfo &CI) { 365 ConditionalStack.push_back(CI); 366 } 367 368 /// popConditionalLevel - Remove an entry off the top of the conditional 369 /// stack, returning information about it. If the conditional stack is empty, 370 /// this returns true and does not fill in the arguments. 371 bool popConditionalLevel(PPConditionalInfo &CI) { 372 if (ConditionalStack.empty()) return true; 373 CI = ConditionalStack.back(); 374 ConditionalStack.pop_back(); 375 return false; 376 } 377 378 /// peekConditionalLevel - Return the top of the conditional stack. This 379 /// requires that there be a conditional active. 380 PPConditionalInfo &peekConditionalLevel() { 381 assert(!ConditionalStack.empty() && "No conditionals active!"); 382 return ConditionalStack.back(); 383 } 384 385 unsigned getConditionalStackDepth() const { return ConditionalStack.size(); } 386 387 //===--------------------------------------------------------------------===// 388 // Other lexer functions. 389 390 // Helper functions to lex the remainder of a token of the specific type. 391 void LexIdentifier (Token &Result, const char *CurPtr); 392 void LexNumericConstant (Token &Result, const char *CurPtr); 393 void LexStringLiteral (Token &Result, const char *CurPtr,bool Wide); 394 void LexAngledStringLiteral(Token &Result, const char *CurPtr); 395 void LexCharConstant (Token &Result, const char *CurPtr); 396 bool LexEndOfFile (Token &Result, const char *CurPtr); 397 398 bool SkipWhitespace (Token &Result, const char *CurPtr); 399 bool SkipBCPLComment (Token &Result, const char *CurPtr); 400 bool SkipBlockComment (Token &Result, const char *CurPtr); 401 bool SaveBCPLComment (Token &Result, const char *CurPtr); 402 403 /// LexIncludeFilename - After the preprocessor has parsed a #include, lex and 404 /// (potentially) macro expand the filename. If the sequence parsed is not 405 /// lexically legal, emit a diagnostic and return a result EOM token. 406 void LexIncludeFilename(Token &Result); 407}; 408 409 410} // end namespace clang 411 412#endif 413