Lexer.h revision 5f016e2cb5d11daeb237544de1c5d59f20fe1a6e
1//===--- Lexer.h - C Language Family Lexer ----------------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by Chris Lattner and is distributed under 6// the University of Illinois Open Source 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/LexerToken.h" 18#include "clang/Lex/MultipleIncludeOpt.h" 19#include "clang/Basic/LangOptions.h" 20#include <string> 21#include <vector> 22 23namespace llvm { 24 class MemoryBuffer; 25} 26 27namespace clang { 28class Diagnostic; 29class Preprocessor; 30 31/// Lexer - This provides a simple interface that turns a text buffer into a 32/// stream of tokens. This provides no support for file reading or buffering, 33/// or buffering/seeking of tokens, only forward lexing is supported. It relies 34/// on the specified Preprocessor object to handle preprocessor directives, etc. 35class Lexer { 36 //===--------------------------------------------------------------------===// 37 // Constant configuration values for this lexer. 38 const char * const BufferEnd; // End of the buffer. 39 const llvm::MemoryBuffer *InputFile; // The file we are reading from. 40 unsigned CurFileID; // FileID for the current input file. 41 Preprocessor &PP; // Preprocessor object controlling lexing. 42 LangOptions Features; // Features enabled by this language (cache). 43 bool Is_PragmaLexer; // True if lexer for _Pragma handling. 44 bool IsMainFile; // True if top-level file. 45 46 //===--------------------------------------------------------------------===// 47 // Context-specific lexing flags set by the preprocessor. 48 // 49 50 /// ParsingPreprocessorDirective - This is true when parsing #XXX. This turns 51 /// '\n' into a tok::eom token. 52 bool ParsingPreprocessorDirective; 53 54 /// ParsingFilename - True after #include: this turns <xx> into a 55 /// tok::angle_string_literal token. 56 bool ParsingFilename; 57 58 /// LexingRawMode - True if in raw mode: This flag disables interpretation of 59 /// tokens and is a far faster mode to lex in than non-raw-mode. This flag: 60 /// 1. If EOF of the current lexer is found, the include stack isn't popped. 61 /// 2. Identifier information is not looked up for identifier tokens. As an 62 /// effect of this, implicit macro expansion is naturally disabled. 63 /// 3. "#" tokens at the start of a line are treated as normal tokens, not 64 /// implicitly transformed by the lexer. 65 /// 4. All diagnostic messages are disabled, except for unterminated /*. 66 /// 5. The only callback made into the preprocessor is to report a hard error 67 /// on an unterminated '/*' comment. 68 bool LexingRawMode; 69 70 /// KeepCommentMode - The lexer can optionally keep C & BCPL-style comments, 71 /// and return them as tokens. This is used for -C and -CC modes. 72 bool KeepCommentMode; 73 74 //===--------------------------------------------------------------------===// 75 // Context that changes as the file is lexed. 76 // NOTE: any state that mutates when in raw mode must have save/restore code 77 // in Lexer::isNextPPTokenLParen. 78 79 // BufferPtr - Current pointer into the buffer. This is the next character 80 // to be lexed. 81 const char *BufferPtr; 82 83 // IsAtStartOfLine - True if the next lexed token should get the "start of 84 // line" flag set on it. 85 bool IsAtStartOfLine; 86 87 /// MIOpt - This is a state machine that detects the #ifndef-wrapping a file 88 /// idiom for the multiple-include optimization. 89 MultipleIncludeOpt MIOpt; 90 91 /// ConditionalStack - Information about the set of #if/#ifdef/#ifndef blocks 92 /// we are currently in. 93 std::vector<PPConditionalInfo> ConditionalStack; 94 95 friend class Preprocessor; 96public: 97 98 /// Lexer constructor - Create a new lexer object for the specified buffer 99 /// with the specified preprocessor managing the lexing process. This lexer 100 /// assumes that the specified MemoryBuffer and Preprocessor objects will 101 /// outlive it, but doesn't take ownership of either pointer. 102 Lexer(const llvm::MemoryBuffer *InBuffer, unsigned CurFileID, 103 Preprocessor &PP, const char *BufStart = 0, const char *BufEnd = 0); 104 105 /// getFeatures - Return the language features currently enabled. NOTE: this 106 /// lexer modifies features as a file is parsed! 107 const LangOptions &getFeatures() const { return Features; } 108 109 /// getCurFileID - Return the FileID for the file we are lexing out of. This 110 /// implicitly encodes the include path to get to the file. 111 unsigned getCurFileID() const { return CurFileID; } 112 113 /// setIsMainFile - Mark this lexer as being the lexer for the top-level 114 /// source file. 115 void setIsMainFile() { 116 IsMainFile = true; 117 } 118 119 /// isMainFile - Return true if this is the top-level file. 120 /// 121 bool isMainFile() const { return IsMainFile; } 122 123 /// Lex - Return the next token in the file. If this is the end of file, it 124 /// return the tok::eof token. Return true if an error occurred and 125 /// compilation should terminate, false if normal. This implicitly involves 126 /// the preprocessor. 127 void Lex(LexerToken &Result) { 128 // Start a new token. 129 Result.startToken(); 130 131 // NOTE, any changes here should also change code after calls to 132 // Preprocessor::HandleDirective 133 if (IsAtStartOfLine) { 134 Result.setFlag(LexerToken::StartOfLine); 135 IsAtStartOfLine = false; 136 } 137 138 // Get a token. Note that this may delete the current lexer if the end of 139 // file is reached. 140 LexTokenInternal(Result); 141 } 142 143 /// LexRawToken - Switch the lexer to raw mode, lex a token into Result and 144 /// switch it back. Return true if the 'next character to read' pointer 145 /// points and the end of the lexer buffer, false otherwise. 146 bool LexRawToken(LexerToken &Result) { 147 assert(!LexingRawMode && "Already in raw mode!"); 148 LexingRawMode = true; 149 Lex(Result); 150 LexingRawMode = false; 151 return BufferPtr == BufferEnd; 152 } 153 154 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an 155 /// uninterpreted string. This switches the lexer out of directive mode. 156 std::string ReadToEndOfLine(); 157 158 159 /// Diag - Forwarding function for diagnostics. This translate a source 160 /// position in the current buffer into a SourceLocation object for rendering. 161 void Diag(const char *Loc, unsigned DiagID, 162 const std::string &Msg = std::string()) const; 163 void Diag(SourceLocation Loc, unsigned DiagID, 164 const std::string &Msg = std::string()) const; 165 166 /// getSourceLocation - Return a source location identifier for the specified 167 /// offset in the current file. 168 SourceLocation getSourceLocation(const char *Loc) const; 169 170 /// Stringify - Convert the specified string into a C string by escaping '\' 171 /// and " characters. This does not add surrounding ""'s to the string. 172 /// If Charify is true, this escapes the ' character instead of ". 173 static std::string Stringify(const std::string &Str, bool Charify = false); 174 175 //===--------------------------------------------------------------------===// 176 // Internal implementation interfaces. 177private: 178 179 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called 180 /// by Lex. 181 /// 182 void LexTokenInternal(LexerToken &Result); 183 184 /// FormTokenWithChars - When we lex a token, we have identified a span 185 /// starting at BufferPtr, going to TokEnd that forms the token. This method 186 /// takes that range and assigns it to the token as its location and size. In 187 /// addition, since tokens cannot overlap, this also updates BufferPtr to be 188 /// TokEnd. 189 void FormTokenWithChars(LexerToken &Result, const char *TokEnd) { 190 Result.setLocation(getSourceLocation(BufferPtr)); 191 Result.setLength(TokEnd-BufferPtr); 192 BufferPtr = TokEnd; 193 } 194 195 /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a 196 /// tok::l_paren token, 0 if it is something else and 2 if there are no more 197 /// tokens in the buffer controlled by this lexer. 198 unsigned isNextPPTokenLParen(); 199 200 //===--------------------------------------------------------------------===// 201 // Lexer character reading interfaces. 202 203 // This lexer is built on two interfaces for reading characters, both of which 204 // automatically provide phase 1/2 translation. getAndAdvanceChar is used 205 // when we know that we will be reading a character from the input buffer and 206 // that this character will be part of the result token. This occurs in (f.e.) 207 // string processing, because we know we need to read until we find the 208 // closing '"' character. 209 // 210 // The second interface is the combination of PeekCharAndSize with 211 // ConsumeChar. PeekCharAndSize reads a phase 1/2 translated character, 212 // returning it and its size. If the lexer decides that this character is 213 // part of the current token, it calls ConsumeChar on it. This two stage 214 // approach allows us to emit diagnostics for characters (e.g. warnings about 215 // trigraphs), knowing that they only are emitted if the character is 216 // consumed. 217 218 219 /// getAndAdvanceChar - Read a single 'character' from the specified buffer, 220 /// advance over it, and return it. This is tricky in several cases. Here we 221 /// just handle the trivial case and fall-back to the non-inlined 222 /// getCharAndSizeSlow method to handle the hard case. 223 inline char getAndAdvanceChar(const char *&Ptr, LexerToken &Tok) { 224 // If this is not a trigraph and not a UCN or escaped newline, return 225 // quickly. 226 if (Ptr[0] != '?' && Ptr[0] != '\\') return *Ptr++; 227 228 unsigned Size = 0; 229 char C = getCharAndSizeSlow(Ptr, Size, &Tok); 230 Ptr += Size; 231 return C; 232 } 233 234 /// ConsumeChar - When a character (identified by PeekCharAndSize) is consumed 235 /// and added to a given token, check to see if there are diagnostics that 236 /// need to be emitted or flags that need to be set on the token. If so, do 237 /// it. 238 const char *ConsumeChar(const char *Ptr, unsigned Size, LexerToken &Tok) { 239 // Normal case, we consumed exactly one token. Just return it. 240 if (Size == 1) 241 return Ptr+Size; 242 243 // Otherwise, re-lex the character with a current token, allowing 244 // diagnostics to be emitted and flags to be set. 245 Size = 0; 246 getCharAndSizeSlow(Ptr, Size, &Tok); 247 return Ptr+Size; 248 } 249 250 /// getCharAndSize - Peek a single 'character' from the specified buffer, 251 /// get its size, and return it. This is tricky in several cases. Here we 252 /// just handle the trivial case and fall-back to the non-inlined 253 /// getCharAndSizeSlow method to handle the hard case. 254 inline char getCharAndSize(const char *Ptr, unsigned &Size) { 255 // If this is not a trigraph and not a UCN or escaped newline, return 256 // quickly. 257 if (Ptr[0] != '?' && Ptr[0] != '\\') { 258 Size = 1; 259 return *Ptr; 260 } 261 262 Size = 0; 263 return getCharAndSizeSlow(Ptr, Size); 264 } 265 266 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize 267 /// method. 268 char getCharAndSizeSlow(const char *Ptr, unsigned &Size, LexerToken *Tok = 0); 269 270 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever 271 /// emit a warning. 272 static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, 273 const LangOptions &Features) { 274 // If this is not a trigraph and not a UCN or escaped newline, return 275 // quickly. 276 if (Ptr[0] != '?' && Ptr[0] != '\\') { 277 Size = 1; 278 return *Ptr; 279 } 280 281 Size = 0; 282 return getCharAndSizeSlowNoWarn(Ptr, Size, Features); 283 } 284 285 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a 286 /// diagnostic. 287 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, 288 const LangOptions &Features); 289 290 //===--------------------------------------------------------------------===// 291 // #if directive handling. 292 293 /// pushConditionalLevel - When we enter a #if directive, this keeps track of 294 /// what we are currently in for diagnostic emission (e.g. #if with missing 295 /// #endif). 296 void pushConditionalLevel(SourceLocation DirectiveStart, bool WasSkipping, 297 bool FoundNonSkip, bool FoundElse) { 298 PPConditionalInfo CI; 299 CI.IfLoc = DirectiveStart; 300 CI.WasSkipping = WasSkipping; 301 CI.FoundNonSkip = FoundNonSkip; 302 CI.FoundElse = FoundElse; 303 ConditionalStack.push_back(CI); 304 } 305 void pushConditionalLevel(const PPConditionalInfo &CI) { 306 ConditionalStack.push_back(CI); 307 } 308 309 /// popConditionalLevel - Remove an entry off the top of the conditional 310 /// stack, returning information about it. If the conditional stack is empty, 311 /// this returns true and does not fill in the arguments. 312 bool popConditionalLevel(PPConditionalInfo &CI) { 313 if (ConditionalStack.empty()) return true; 314 CI = ConditionalStack.back(); 315 ConditionalStack.pop_back(); 316 return false; 317 } 318 319 /// peekConditionalLevel - Return the top of the conditional stack. This 320 /// requires that there be a conditional active. 321 PPConditionalInfo &peekConditionalLevel() { 322 assert(!ConditionalStack.empty() && "No conditionals active!"); 323 return ConditionalStack.back(); 324 } 325 326 unsigned getConditionalStackDepth() const { return ConditionalStack.size(); } 327 328 //===--------------------------------------------------------------------===// 329 // Other lexer functions. 330 331 // Helper functions to lex the remainder of a token of the specific type. 332 void LexIdentifier (LexerToken &Result, const char *CurPtr); 333 void LexNumericConstant (LexerToken &Result, const char *CurPtr); 334 void LexStringLiteral (LexerToken &Result, const char *CurPtr,bool Wide); 335 void LexAngledStringLiteral(LexerToken &Result, const char *CurPtr); 336 void LexCharConstant (LexerToken &Result, const char *CurPtr); 337 bool LexEndOfFile (LexerToken &Result, const char *CurPtr); 338 339 void SkipWhitespace (LexerToken &Result, const char *CurPtr); 340 bool SkipBCPLComment (LexerToken &Result, const char *CurPtr); 341 bool SkipBlockComment (LexerToken &Result, const char *CurPtr); 342 bool SaveBCPLComment (LexerToken &Result, const char *CurPtr); 343 344 /// LexIncludeFilename - After the preprocessor has parsed a #include, lex and 345 /// (potentially) macro expand the filename. If the sequence parsed is not 346 /// lexically legal, emit a diagnostic and return a result EOM token. 347 void LexIncludeFilename(LexerToken &Result); 348}; 349 350 351} // end namespace clang 352 353#endif 354