Lexer.h revision 678c6358c8d4e368c78629099142397c63c1ee35
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, except for unterminated /*. 64 /// 5. The only callback made into the preprocessor is to report a hard error 65 /// on an unterminated '/*' comment. 66 /// 67 /// Note that in raw mode that the PP pointer may be null. 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 Lexer(const Lexer&); // DO NOT IMPLEMENT 96 void operator=(const Lexer&); // DO NOT IMPLEMENT 97 friend class Preprocessor; 98public: 99 100 /// Lexer constructor - Create a new lexer object for the specified buffer 101 /// with the specified preprocessor managing the lexing process. This lexer 102 /// assumes that the associated file buffer and Preprocessor objects will 103 /// outlive it, so it doesn't take ownership of either of them. 104 Lexer(SourceLocation FileLoc, Preprocessor &PP, 105 const char *BufStart = 0, const char *BufEnd = 0); 106 107 /// Lexer constructor - Create a new raw lexer object. This object is only 108 /// suitable for calls to 'LexRawToken'. This lexer assumes that the 109 /// associated file buffer will outlive it, so it doesn't take ownership of 110 /// either of them. 111 Lexer(SourceLocation FileLoc, const LangOptions &Features, 112 const char *BufStart, const char *BufEnd); 113 114 /// getFeatures - Return the language features currently enabled. NOTE: this 115 /// lexer modifies features as a file is parsed! 116 const LangOptions &getFeatures() const { return Features; } 117 118 /// getFileLoc - Return the File Location for the file we are lexing out of. 119 /// The physical location encodes the location where the characters come from, 120 /// the virtual location encodes where we should *claim* the characters came 121 /// from. Currently this is only used by _Pragma handling. 122 SourceLocation getFileLoc() const { return FileLoc; } 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(Token &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(Token::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(Token &Result) { 148 assert(!(PP && LexingRawMode) && "Already in raw mode!"); 149 LexingRawMode = true; 150 Lex(Result); 151 LexingRawMode = PP == 0; 152 // Note that lexing to the end of the buffer doesn't implicitly delete the 153 // lexer when in raw mode. 154 return BufferPtr == BufferEnd; 155 } 156 157 /// SetCommentRetentionMode - Change the comment retention mode of the lexer 158 /// to the specified mode. This is really only useful when lexing in raw 159 /// mode, because otherwise the lexer needs to manage this. 160 void SetCommentRetentionState(bool Mode) { 161 KeepCommentMode = Mode; 162 } 163 164 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an 165 /// uninterpreted string. This switches the lexer out of directive mode. 166 std::string ReadToEndOfLine(); 167 168 169 /// Diag - Forwarding function for diagnostics. This translate a source 170 /// position in the current buffer into a SourceLocation object for rendering. 171 void Diag(const char *Loc, unsigned DiagID, 172 const std::string &Msg = std::string()) const; 173 void Diag(SourceLocation Loc, unsigned DiagID, 174 const std::string &Msg = std::string()) const; 175 176 /// getSourceLocation - Return a source location identifier for the specified 177 /// offset in the current file. 178 SourceLocation getSourceLocation(const char *Loc) const; 179 180 /// Stringify - Convert the specified string into a C string by escaping '\' 181 /// and " characters. This does not add surrounding ""'s to the string. 182 /// If Charify is true, this escapes the ' character instead of ". 183 static std::string Stringify(const std::string &Str, bool Charify = false); 184 185 /// Stringify - Convert the specified string into a C string by escaping '\' 186 /// and " characters. This does not add surrounding ""'s to the string. 187 static void Stringify(llvm::SmallVectorImpl<char> &Str); 188 189 /// MeasureTokenLength - Relex the token at the specified location and return 190 /// its length in bytes in the input file. If the token needs cleaning (e.g. 191 /// includes a trigraph or an escaped newline) then this count includes bytes 192 /// that are part of that. 193 static unsigned MeasureTokenLength(SourceLocation Loc, 194 const SourceManager &SM); 195 196 //===--------------------------------------------------------------------===// 197 // Internal implementation interfaces. 198private: 199 200 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called 201 /// by Lex. 202 /// 203 void LexTokenInternal(Token &Result); 204 205 /// FormTokenWithChars - When we lex a token, we have identified a span 206 /// starting at BufferPtr, going to TokEnd that forms the token. This method 207 /// takes that range and assigns it to the token as its location and size. In 208 /// addition, since tokens cannot overlap, this also updates BufferPtr to be 209 /// TokEnd. 210 void FormTokenWithChars(Token &Result, const char *TokEnd) { 211 Result.setLocation(getSourceLocation(BufferPtr)); 212 Result.setLength(TokEnd-BufferPtr); 213 BufferPtr = TokEnd; 214 } 215 216 /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a 217 /// tok::l_paren token, 0 if it is something else and 2 if there are no more 218 /// tokens in the buffer controlled by this lexer. 219 unsigned isNextPPTokenLParen(); 220 221 //===--------------------------------------------------------------------===// 222 // Lexer character reading interfaces. 223public: 224 225 // This lexer is built on two interfaces for reading characters, both of which 226 // automatically provide phase 1/2 translation. getAndAdvanceChar is used 227 // when we know that we will be reading a character from the input buffer and 228 // that this character will be part of the result token. This occurs in (f.e.) 229 // string processing, because we know we need to read until we find the 230 // closing '"' character. 231 // 232 // The second interface is the combination of PeekCharAndSize with 233 // ConsumeChar. PeekCharAndSize reads a phase 1/2 translated character, 234 // returning it and its size. If the lexer decides that this character is 235 // part of the current token, it calls ConsumeChar on it. This two stage 236 // approach allows us to emit diagnostics for characters (e.g. warnings about 237 // trigraphs), knowing that they only are emitted if the character is 238 // consumed. 239 240 /// isObviouslySimpleCharacter - Return true if the specified character is 241 /// obviously the same in translation phase 1 and translation phase 3. This 242 /// can return false for characters that end up being the same, but it will 243 /// never return true for something that needs to be mapped. 244 static bool isObviouslySimpleCharacter(char C) { 245 return C != '?' && C != '\\'; 246 } 247 248 /// getAndAdvanceChar - Read a single 'character' from the specified buffer, 249 /// advance over it, and return it. This is tricky in several cases. Here we 250 /// just handle the trivial case and fall-back to the non-inlined 251 /// getCharAndSizeSlow method to handle the hard case. 252 inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) { 253 // If this is not a trigraph and not a UCN or escaped newline, return 254 // quickly. 255 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++; 256 257 unsigned Size = 0; 258 char C = getCharAndSizeSlow(Ptr, Size, &Tok); 259 Ptr += Size; 260 return C; 261 } 262 263private: 264 /// ConsumeChar - When a character (identified by PeekCharAndSize) is consumed 265 /// and added to a given token, check to see if there are diagnostics that 266 /// need to be emitted or flags that need to be set on the token. If so, do 267 /// it. 268 const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) { 269 // Normal case, we consumed exactly one token. Just return it. 270 if (Size == 1) 271 return Ptr+Size; 272 273 // Otherwise, re-lex the character with a current token, allowing 274 // diagnostics to be emitted and flags to be set. 275 Size = 0; 276 getCharAndSizeSlow(Ptr, Size, &Tok); 277 return Ptr+Size; 278 } 279 280 /// getCharAndSize - Peek a single 'character' from the specified buffer, 281 /// get its size, and return it. This is tricky in several cases. Here we 282 /// just handle the trivial case and fall-back to the non-inlined 283 /// getCharAndSizeSlow method to handle the hard case. 284 inline char getCharAndSize(const char *Ptr, unsigned &Size) { 285 // If this is not a trigraph and not a UCN or escaped newline, return 286 // quickly. 287 if (isObviouslySimpleCharacter(Ptr[0])) { 288 Size = 1; 289 return *Ptr; 290 } 291 292 Size = 0; 293 return getCharAndSizeSlow(Ptr, Size); 294 } 295 296 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize 297 /// method. 298 char getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok = 0); 299 300 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever 301 /// emit a warning. 302 static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size, 303 const LangOptions &Features) { 304 // If this is not a trigraph and not a UCN or escaped newline, return 305 // quickly. 306 if (isObviouslySimpleCharacter(Ptr[0])) { 307 Size = 1; 308 return *Ptr; 309 } 310 311 Size = 0; 312 return getCharAndSizeSlowNoWarn(Ptr, Size, Features); 313 } 314 315 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a 316 /// diagnostic. 317 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, 318 const LangOptions &Features); 319 320 //===--------------------------------------------------------------------===// 321 // #if directive handling. 322 323 /// pushConditionalLevel - When we enter a #if directive, this keeps track of 324 /// what we are currently in for diagnostic emission (e.g. #if with missing 325 /// #endif). 326 void pushConditionalLevel(SourceLocation DirectiveStart, bool WasSkipping, 327 bool FoundNonSkip, bool FoundElse) { 328 PPConditionalInfo CI; 329 CI.IfLoc = DirectiveStart; 330 CI.WasSkipping = WasSkipping; 331 CI.FoundNonSkip = FoundNonSkip; 332 CI.FoundElse = FoundElse; 333 ConditionalStack.push_back(CI); 334 } 335 void pushConditionalLevel(const PPConditionalInfo &CI) { 336 ConditionalStack.push_back(CI); 337 } 338 339 /// popConditionalLevel - Remove an entry off the top of the conditional 340 /// stack, returning information about it. If the conditional stack is empty, 341 /// this returns true and does not fill in the arguments. 342 bool popConditionalLevel(PPConditionalInfo &CI) { 343 if (ConditionalStack.empty()) return true; 344 CI = ConditionalStack.back(); 345 ConditionalStack.pop_back(); 346 return false; 347 } 348 349 /// peekConditionalLevel - Return the top of the conditional stack. This 350 /// requires that there be a conditional active. 351 PPConditionalInfo &peekConditionalLevel() { 352 assert(!ConditionalStack.empty() && "No conditionals active!"); 353 return ConditionalStack.back(); 354 } 355 356 unsigned getConditionalStackDepth() const { return ConditionalStack.size(); } 357 358 //===--------------------------------------------------------------------===// 359 // Other lexer functions. 360 361 // Helper functions to lex the remainder of a token of the specific type. 362 void LexIdentifier (Token &Result, const char *CurPtr); 363 void LexNumericConstant (Token &Result, const char *CurPtr); 364 void LexStringLiteral (Token &Result, const char *CurPtr,bool Wide); 365 void LexAngledStringLiteral(Token &Result, const char *CurPtr); 366 void LexCharConstant (Token &Result, const char *CurPtr); 367 bool LexEndOfFile (Token &Result, const char *CurPtr); 368 369 void SkipWhitespace (Token &Result, const char *CurPtr); 370 bool SkipBCPLComment (Token &Result, const char *CurPtr); 371 bool SkipBlockComment (Token &Result, const char *CurPtr); 372 bool SaveBCPLComment (Token &Result, const char *CurPtr); 373 374 /// LexIncludeFilename - After the preprocessor has parsed a #include, lex and 375 /// (potentially) macro expand the filename. If the sequence parsed is not 376 /// lexically legal, emit a diagnostic and return a result EOM token. 377 void LexIncludeFilename(Token &Result); 378}; 379 380 381} // end namespace clang 382 383#endif 384