Preprocessor.h revision 53b0dabbe52219a8057659b90539837394ef0fa1
1//===--- Preprocessor.h - C Language Family Preprocessor --------*- 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 Preprocessor interface. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_LEX_PREPROCESSOR_H 15#define LLVM_CLANG_LEX_PREPROCESSOR_H 16 17#include "clang/Lex/Lexer.h" 18#include "clang/Lex/MacroExpander.h" 19#include "clang/Basic/IdentifierTable.h" 20#include "clang/Basic/SourceLocation.h" 21#include "llvm/ADT/DenseMap.h" 22 23namespace clang { 24 25class SourceManager; 26class FileManager; 27class FileEntry; 28class HeaderSearch; 29class PragmaNamespace; 30class PragmaHandler; 31class ScratchBuffer; 32class TargetInfo; 33class PPCallbacks; 34class DirectoryLookup; 35 36/// Preprocessor - This object forms engages in a tight little dance to 37/// efficiently preprocess tokens. Lexers know only about tokens within a 38/// single source file, and don't know anything about preprocessor-level issues 39/// like the #include stack, token expansion, etc. 40/// 41class Preprocessor { 42 Diagnostic &Diags; 43 const LangOptions &Features; 44 TargetInfo &Target; 45 FileManager &FileMgr; 46 SourceManager &SourceMgr; 47 ScratchBuffer *ScratchBuf; 48 HeaderSearch &HeaderInfo; 49 50 /// Identifiers for builtin macros and other builtins. 51 IdentifierInfo *Ident__LINE__, *Ident__FILE__; // __LINE__, __FILE__ 52 IdentifierInfo *Ident__DATE__, *Ident__TIME__; // __DATE__, __TIME__ 53 IdentifierInfo *Ident__INCLUDE_LEVEL__; // __INCLUDE_LEVEL__ 54 IdentifierInfo *Ident__BASE_FILE__; // __BASE_FILE__ 55 IdentifierInfo *Ident__TIMESTAMP__; // __TIMESTAMP__ 56 IdentifierInfo *Ident_Pragma, *Ident__VA_ARGS__; // _Pragma, __VA_ARGS__ 57 58 SourceLocation DATELoc, TIMELoc; 59 60 enum { 61 /// MaxIncludeStackDepth - Maximum depth of #includes. 62 MaxAllowedIncludeStackDepth = 200 63 }; 64 65 // State that is set before the preprocessor begins. 66 bool KeepComments : 1; 67 bool KeepMacroComments : 1; 68 69 // State that changes while the preprocessor runs: 70 bool DisableMacroExpansion : 1; // True if macro expansion is disabled. 71 bool InMacroArgs : 1; // True if parsing fn macro invocation args. 72 73 /// Identifiers - This is mapping/lookup information for all identifiers in 74 /// the program, including program keywords. 75 IdentifierTable Identifiers; 76 77 /// Selectors - This table contains all the selectors in the program. Unlike 78 /// IdentifierTable above, this table *isn't* populated by the preprocessor. 79 /// It is declared/instantiated here because it's role/lifetime is 80 /// conceptually similar the IdentifierTable. In addition, the current control 81 /// flow (in clang::ParseAST()), make it convenient to put here. 82 /// FIXME: Make sure the lifetime of Identifiers/Selectors *isn't* tied to 83 /// the lifetime fo the preprocessor. 84 SelectorTable Selectors; 85 86 /// PragmaHandlers - This tracks all of the pragmas that the client registered 87 /// with this preprocessor. 88 PragmaNamespace *PragmaHandlers; 89 90 /// CurLexer - This is the current top of the stack that we're lexing from if 91 /// not expanding a macro. One of CurLexer and CurMacroExpander must be null. 92 Lexer *CurLexer; 93 94 /// CurLookup - The DirectoryLookup structure used to find the current 95 /// FileEntry, if CurLexer is non-null and if applicable. This allows us to 96 /// implement #include_next and find directory-specific properties. 97 const DirectoryLookup *CurDirLookup; 98 99 /// CurMacroExpander - This is the current macro we are expanding, if we are 100 /// expanding a macro. One of CurLexer and CurMacroExpander must be null. 101 MacroExpander *CurMacroExpander; 102 103 /// IncludeMacroStack - This keeps track of the stack of files currently 104 /// #included, and macros currently being expanded from, not counting 105 /// CurLexer/CurMacroExpander. 106 struct IncludeStackInfo { 107 Lexer *TheLexer; 108 const DirectoryLookup *TheDirLookup; 109 MacroExpander *TheMacroExpander; 110 IncludeStackInfo(Lexer *L, const DirectoryLookup *D, MacroExpander *M) 111 : TheLexer(L), TheDirLookup(D), TheMacroExpander(M) { 112 } 113 }; 114 std::vector<IncludeStackInfo> IncludeMacroStack; 115 116 /// Callbacks - These are actions invoked when some preprocessor activity is 117 /// encountered (e.g. a file is #included, etc). 118 PPCallbacks *Callbacks; 119 120 /// Macros - For each IdentifierInfo with 'HasMacro' set, we keep a mapping 121 /// to the actual definition of the macro. 122 llvm::DenseMap<IdentifierInfo*, MacroInfo*> Macros; 123 124 // Various statistics we track for performance analysis. 125 unsigned NumDirectives, NumIncluded, NumDefined, NumUndefined, NumPragma; 126 unsigned NumIf, NumElse, NumEndif; 127 unsigned NumEnteredSourceFiles, MaxIncludeStackDepth; 128 unsigned NumMacroExpanded, NumFnMacroExpanded, NumBuiltinMacroExpanded; 129 unsigned NumFastMacroExpanded, NumTokenPaste, NumFastTokenPaste; 130 unsigned NumSkipped; 131 132 /// Predefines - This pointer, if non-null, are the predefined macros that 133 /// preprocessor should use from the command line etc. 134 const char *Predefines; 135 136 /// MacroExpanderCache - Cache macro expanders to reduce malloc traffic. 137 enum { MacroExpanderCacheSize = 8 }; 138 unsigned NumCachedMacroExpanders; 139 MacroExpander *MacroExpanderCache[MacroExpanderCacheSize]; 140public: 141 Preprocessor(Diagnostic &diags, const LangOptions &opts, TargetInfo &target, 142 SourceManager &SM, HeaderSearch &Headers); 143 ~Preprocessor(); 144 145 Diagnostic &getDiagnostics() const { return Diags; } 146 const LangOptions &getLangOptions() const { return Features; } 147 TargetInfo &getTargetInfo() const { return Target; } 148 FileManager &getFileManager() const { return FileMgr; } 149 SourceManager &getSourceManager() const { return SourceMgr; } 150 HeaderSearch &getHeaderSearchInfo() const { return HeaderInfo; } 151 152 IdentifierTable &getIdentifierTable() { return Identifiers; } 153 SelectorTable &getSelectorTable() { return Selectors; } 154 155 /// SetCommentRetentionState - Control whether or not the preprocessor retains 156 /// comments in output. 157 void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments) { 158 this->KeepComments = KeepComments | KeepMacroComments; 159 this->KeepMacroComments = KeepMacroComments; 160 } 161 162 bool getCommentRetentionState() const { return KeepComments; } 163 164 /// isCurrentLexer - Return true if we are lexing directly from the specified 165 /// lexer. 166 bool isCurrentLexer(const Lexer *L) const { 167 return CurLexer == L; 168 } 169 170 /// getCurrentLexer - Return the current file lexer being lexed from. Note 171 /// that this ignores any potentially active macro expansions and _Pragma 172 /// expansions going on at the time. 173 Lexer *getCurrentFileLexer() const; 174 175 /// getPPCallbacks/SetPPCallbacks - Accessors for preprocessor callbacks. 176 /// 177 PPCallbacks *getPPCallbacks() const { return Callbacks; } 178 void setPPCallbacks(PPCallbacks *C) { 179 Callbacks = C; 180 } 181 182 /// getMacroInfo - Given an identifier, return the MacroInfo it is #defined to 183 /// or null if it isn't #define'd. 184 MacroInfo *getMacroInfo(IdentifierInfo *II) const { 185 return II->hasMacroDefinition() ? Macros.find(II)->second : 0; 186 } 187 188 /// setMacroInfo - Specify a macro for this identifier. 189 /// 190 void setMacroInfo(IdentifierInfo *II, MacroInfo *MI); 191 192 void setPredefines(const char *P) { 193 Predefines = P; 194 } 195 196 /// getIdentifierInfo - Return information about the specified preprocessor 197 /// identifier token. The version of this method that takes two character 198 /// pointers is preferred unless the identifier is already available as a 199 /// string (this avoids allocation and copying of memory to construct an 200 /// std::string). 201 IdentifierInfo *getIdentifierInfo(const char *NameStart, 202 const char *NameEnd) { 203 return &Identifiers.get(NameStart, NameEnd); 204 } 205 IdentifierInfo *getIdentifierInfo(const char *NameStr) { 206 return getIdentifierInfo(NameStr, NameStr+strlen(NameStr)); 207 } 208 209 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 210 /// If 'Namespace' is non-null, then it is a token required to exist on the 211 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 212 void AddPragmaHandler(const char *Namespace, PragmaHandler *Handler); 213 214 /// EnterMainSourceFile - Enter the specified FileID as the main source file, 215 /// which implicitly adds the builting defines etc. 216 void EnterMainSourceFile(unsigned CurFileID); 217 218 219 /// EnterSourceFile - Add a source file to the top of the include stack and 220 /// start lexing tokens from it instead of the current buffer. If isMainFile 221 /// is true, this is the main file for the translation unit. 222 void EnterSourceFile(unsigned CurFileID, const DirectoryLookup *Dir); 223 224 /// EnterMacro - Add a Macro to the top of the include stack and start lexing 225 /// tokens from it instead of the current buffer. Args specifies the 226 /// tokens input to a function-like macro. 227 void EnterMacro(Token &Identifier, MacroArgs *Args); 228 229 /// EnterTokenStream - Add a "macro" context to the top of the include stack, 230 /// which will cause the lexer to start returning the specified tokens. Note 231 /// that these tokens will be re-macro-expanded when/if expansion is enabled. 232 /// This method assumes that the specified stream of tokens has a permanent 233 /// owner somewhere, so they do not need to be copied. 234 void EnterTokenStream(const Token *Toks, unsigned NumToks); 235 236 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the 237 /// lexer stack. This should only be used in situations where the current 238 /// state of the top-of-stack lexer is known. 239 void RemoveTopOfLexerStack(); 240 241 /// Lex - To lex a token from the preprocessor, just pull a token from the 242 /// current lexer or macro object. 243 void Lex(Token &Result) { 244 if (CurLexer) 245 CurLexer->Lex(Result); 246 else 247 CurMacroExpander->Lex(Result); 248 } 249 250 /// LexNonComment - Lex a token. If it's a comment, keep lexing until we get 251 /// something not a comment. This is useful in -E -C mode where comments 252 /// would foul up preprocessor directive handling. 253 void LexNonComment(Token &Result) { 254 do 255 Lex(Result); 256 while (Result.getKind() == tok::comment); 257 } 258 259 /// LexUnexpandedToken - This is just like Lex, but this disables macro 260 /// expansion of identifier tokens. 261 void LexUnexpandedToken(Token &Result) { 262 // Disable macro expansion. 263 bool OldVal = DisableMacroExpansion; 264 DisableMacroExpansion = true; 265 // Lex the token. 266 Lex(Result); 267 268 // Reenable it. 269 DisableMacroExpansion = OldVal; 270 } 271 272 /// Diag - Forwarding function for diagnostics. This emits a diagnostic at 273 /// the specified Token's location, translating the token's start 274 /// position in the current buffer into a SourcePosition object for rendering. 275 void Diag(SourceLocation Loc, unsigned DiagID); 276 void Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg); 277 void Diag(const Token &Tok, unsigned DiagID) { 278 Diag(Tok.getLocation(), DiagID); 279 } 280 void Diag(const Token &Tok, unsigned DiagID, const std::string &Msg) { 281 Diag(Tok.getLocation(), DiagID, Msg); 282 } 283 284 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a 285 /// token is the characters used to represent the token in the source file 286 /// after trigraph expansion and escaped-newline folding. In particular, this 287 /// wants to get the true, uncanonicalized, spelling of things like digraphs 288 /// UCNs, etc. 289 std::string getSpelling(const Token &Tok) const; 290 291 /// getSpelling - This method is used to get the spelling of a token into a 292 /// preallocated buffer, instead of as an std::string. The caller is required 293 /// to allocate enough space for the token, which is guaranteed to be at least 294 /// Tok.getLength() bytes long. The length of the actual result is returned. 295 /// 296 /// Note that this method may do two possible things: it may either fill in 297 /// the buffer specified with characters, or it may *change the input pointer* 298 /// to point to a constant buffer with the data already in it (avoiding a 299 /// copy). The caller is not allowed to modify the returned buffer pointer 300 /// if an internal buffer is returned. 301 unsigned getSpelling(const Token &Tok, const char *&Buffer) const; 302 303 304 /// CreateString - Plop the specified string into a scratch buffer and return 305 /// a location for it. If specified, the source location provides a source 306 /// location for the token. 307 SourceLocation CreateString(const char *Buf, unsigned Len, 308 SourceLocation SourceLoc = SourceLocation()); 309 310 /// DumpToken - Print the token to stderr, used for debugging. 311 /// 312 void DumpToken(const Token &Tok, bool DumpFlags = false) const; 313 void DumpMacro(const MacroInfo &MI) const; 314 315 /// AdvanceToTokenCharacter - Given a location that specifies the start of a 316 /// token, return a new location that specifies a character within the token. 317 SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,unsigned Char); 318 319 /// IncrementPasteCounter - Increment the counters for the number of token 320 /// paste operations performed. If fast was specified, this is a 'fast paste' 321 /// case we handled. 322 /// 323 void IncrementPasteCounter(bool isFast) { 324 if (isFast) 325 ++NumFastTokenPaste; 326 else 327 ++NumTokenPaste; 328 } 329 330 void PrintStats(); 331 332 //===--------------------------------------------------------------------===// 333 // Preprocessor callback methods. These are invoked by a lexer as various 334 // directives and events are found. 335 336 /// LookUpIdentifierInfo - Given a tok::identifier token, look up the 337 /// identifier information for the token and install it into the token. 338 IdentifierInfo *LookUpIdentifierInfo(Token &Identifier, 339 const char *BufPtr = 0); 340 341 /// HandleIdentifier - This callback is invoked when the lexer reads an 342 /// identifier and has filled in the tokens IdentifierInfo member. This 343 /// callback potentially macro expands it or turns it into a named token (like 344 /// 'for'). 345 void HandleIdentifier(Token &Identifier); 346 347 348 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of 349 /// the current file. This either returns the EOF token and returns true, or 350 /// pops a level off the include stack and returns false, at which point the 351 /// client should call lex again. 352 bool HandleEndOfFile(Token &Result, bool isEndOfMacro = false); 353 354 /// HandleEndOfMacro - This callback is invoked when the lexer hits the end of 355 /// the current macro line. It returns true if Result is filled in with a 356 /// token, or false if Lex should be called again. 357 bool HandleEndOfMacro(Token &Result); 358 359 /// HandleDirective - This callback is invoked when the lexer sees a # token 360 /// at the start of a line. This consumes the directive, modifies the 361 /// lexer/preprocessor state, and advances the lexer(s) so that the next token 362 /// read is the correct one. 363 void HandleDirective(Token &Result); 364 365 /// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If 366 /// not, emit a diagnostic and consume up until the eom. 367 void CheckEndOfDirective(const char *Directive); 368private: 369 /// isInPrimaryFile - Return true if we're in the top-level file, not in a 370 /// #include. 371 bool isInPrimaryFile() const; 372 373 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the 374 /// current line until the tok::eom token is found. 375 void DiscardUntilEndOfDirective(); 376 377 /// ReadMacroName - Lex and validate a macro name, which occurs after a 378 /// #define or #undef. This emits a diagnostic, sets the token kind to eom, 379 /// and discards the rest of the macro line if the macro name is invalid. 380 void ReadMacroName(Token &MacroNameTok, char isDefineUndef = 0); 381 382 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 383 /// definition has just been read. Lex the rest of the arguments and the 384 /// closing ), updating MI with what we learn. Return true if an error occurs 385 /// parsing the arg list. 386 bool ReadMacroDefinitionArgList(MacroInfo *MI); 387 388 /// SkipExcludedConditionalBlock - We just read a #if or related directive and 389 /// decided that the subsequent tokens are in the #if'd out portion of the 390 /// file. Lex the rest of the file, until we see an #endif. If 391 /// FoundNonSkipPortion is true, then we have already emitted code for part of 392 /// this #if directive, so #else/#elif blocks should never be entered. If 393 /// FoundElse is false, then #else directives are ok, if not, then we have 394 /// already seen one so a #else directive is a duplicate. When this returns, 395 /// the caller can lex the first valid token. 396 void SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 397 bool FoundNonSkipPortion, bool FoundElse); 398 399 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that 400 /// may occur after a #if or #elif directive and return it as a bool. If the 401 /// expression is equivalent to "!defined(X)" return X in IfNDefMacro. 402 bool EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro); 403 404 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 405 /// #pragma GCC poison/system_header/dependency and #pragma once. 406 void RegisterBuiltinPragmas(); 407 408 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 409 /// identifier table. 410 void RegisterBuiltinMacros(); 411 IdentifierInfo *RegisterBuiltinMacro(const char *Name); 412 413 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to 414 /// be expanded as a macro, handle it and return the next token as 'Tok'. If 415 /// the macro should not be expanded return true, otherwise return false. 416 bool HandleMacroExpandedIdentifier(Token &Tok, MacroInfo *MI); 417 418 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 419 /// lexed is a '('. If so, consume the token and return true, if not, this 420 /// method should have no observable side-effect on the lexed tokens. 421 bool isNextPPTokenLParen(); 422 423 /// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is 424 /// invoked to read all of the formal arguments specified for the macro 425 /// invocation. This returns null on error. 426 MacroArgs *ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI); 427 428 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 429 /// as a builtin macro, handle it and return the next token as 'Tok'. 430 void ExpandBuiltinMacro(Token &Tok); 431 432 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 433 /// return the first token after the directive. The _Pragma token has just 434 /// been read into 'Tok'. 435 void Handle_Pragma(Token &Tok); 436 437 438 /// EnterSourceFileWithLexer - Add a lexer to the top of the include stack and 439 /// start lexing tokens from it instead of the current buffer. 440 void EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *Dir); 441 442 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 443 /// checked and spelled filename, e.g. as an operand of #include. This returns 444 /// true if the input filename was in <>'s or false if it were in ""'s. The 445 /// caller is expected to provide a buffer that is large enough to hold the 446 /// spelling of the filename, but is also expected to handle the case when 447 /// this method decides to use a different buffer. 448 bool GetIncludeFilenameSpelling(SourceLocation Loc, 449 const char *&BufStart, const char *&BufEnd); 450 451 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 452 /// return null on failure. isAngled indicates whether the file reference is 453 /// for system #include's or not (i.e. using <> instead of ""). 454 const FileEntry *LookupFile(const char *FilenameStart,const char *FilenameEnd, 455 bool isAngled, const DirectoryLookup *FromDir, 456 const DirectoryLookup *&CurDir); 457 458 //===--------------------------------------------------------------------===// 459 /// Handle*Directive - implement the various preprocessor directives. These 460 /// should side-effect the current preprocessor object so that the next call 461 /// to Lex() will return the appropriate token next. 462 463 void HandleUserDiagnosticDirective(Token &Tok, bool isWarning); 464 void HandleIdentSCCSDirective(Token &Tok); 465 466 // File inclusion. 467 void HandleIncludeDirective(Token &Tok, 468 const DirectoryLookup *LookupFrom = 0, 469 bool isImport = false); 470 void HandleIncludeNextDirective(Token &Tok); 471 void HandleImportDirective(Token &Tok); 472 473 // Macro handling. 474 void HandleDefineDirective(Token &Tok, bool isTargetSpecific); 475 void HandleUndefDirective(Token &Tok); 476 void HandleDefineOtherTargetDirective(Token &Tok); 477 // HandleAssertDirective(Token &Tok); 478 // HandleUnassertDirective(Token &Tok); 479 480 // Conditional Inclusion. 481 void HandleIfdefDirective(Token &Tok, bool isIfndef, 482 bool ReadAnyTokensBeforeDirective); 483 void HandleIfDirective(Token &Tok, bool ReadAnyTokensBeforeDirective); 484 void HandleEndifDirective(Token &Tok); 485 void HandleElseDirective(Token &Tok); 486 void HandleElifDirective(Token &Tok); 487 488 // Pragmas. 489 void HandlePragmaDirective(); 490public: 491 void HandlePragmaOnce(Token &OnceTok); 492 void HandlePragmaPoison(Token &PoisonTok); 493 void HandlePragmaSystemHeader(Token &SysHeaderTok); 494 void HandlePragmaDependency(Token &DependencyTok); 495}; 496 497} // end namespace clang 498 499#endif 500