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