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