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