Pragma.cpp revision 062f23246510393c19b537b68ec88b6a08ee8996
1//===--- Pragma.cpp - Pragma registration and handling --------------------===// 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 implements the PragmaHandler/PragmaTable interfaces and implements 11// pragma related methods of the Preprocessor class. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Lex/Pragma.h" 16#include "clang/Lex/HeaderSearch.h" 17#include "clang/Lex/LiteralSupport.h" 18#include "clang/Lex/Preprocessor.h" 19#include "clang/Lex/LexDiagnostic.h" 20#include "clang/Basic/FileManager.h" 21#include "clang/Basic/SourceManager.h" 22using namespace clang; 23 24// Out-of-line destructor to provide a home for the class. 25PragmaHandler::~PragmaHandler() { 26} 27 28//===----------------------------------------------------------------------===// 29// PragmaNamespace Implementation. 30//===----------------------------------------------------------------------===// 31 32 33PragmaNamespace::~PragmaNamespace() { 34 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) 35 delete Handlers[i]; 36} 37 38/// FindHandler - Check to see if there is already a handler for the 39/// specified name. If not, return the handler for the null identifier if it 40/// exists, otherwise return null. If IgnoreNull is true (the default) then 41/// the null handler isn't returned on failure to match. 42PragmaHandler *PragmaNamespace::FindHandler(const IdentifierInfo *Name, 43 bool IgnoreNull) const { 44 PragmaHandler *NullHandler = 0; 45 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) { 46 if (Handlers[i]->getName() == Name) 47 return Handlers[i]; 48 49 if (Handlers[i]->getName() == 0) 50 NullHandler = Handlers[i]; 51 } 52 return IgnoreNull ? 0 : NullHandler; 53} 54 55void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) { 56 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) { 57 if (Handlers[i] == Handler) { 58 Handlers[i] = Handlers.back(); 59 Handlers.pop_back(); 60 return; 61 } 62 } 63 assert(0 && "Handler not registered in this namespace"); 64} 65 66void PragmaNamespace::HandlePragma(Preprocessor &PP, Token &Tok) { 67 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro 68 // expand it, the user can have a STDC #define, that should not affect this. 69 PP.LexUnexpandedToken(Tok); 70 71 // Get the handler for this token. If there is no handler, ignore the pragma. 72 PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false); 73 if (Handler == 0) { 74 PP.Diag(Tok, diag::warn_pragma_ignored); 75 return; 76 } 77 78 // Otherwise, pass it down. 79 Handler->HandlePragma(PP, Tok); 80} 81 82//===----------------------------------------------------------------------===// 83// Preprocessor Pragma Directive Handling. 84//===----------------------------------------------------------------------===// 85 86/// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the 87/// rest of the pragma, passing it to the registered pragma handlers. 88void Preprocessor::HandlePragmaDirective() { 89 ++NumPragma; 90 91 // Invoke the first level of pragma handlers which reads the namespace id. 92 Token Tok; 93 PragmaHandlers->HandlePragma(*this, Tok); 94 95 // If the pragma handler didn't read the rest of the line, consume it now. 96 if (CurPPLexer->ParsingPreprocessorDirective) 97 DiscardUntilEndOfDirective(); 98} 99 100/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 101/// return the first token after the directive. The _Pragma token has just 102/// been read into 'Tok'. 103void Preprocessor::Handle_Pragma(Token &Tok) { 104 // Remember the pragma token location. 105 SourceLocation PragmaLoc = Tok.getLocation(); 106 107 // Read the '('. 108 Lex(Tok); 109 if (Tok.isNot(tok::l_paren)) { 110 Diag(PragmaLoc, diag::err__Pragma_malformed); 111 return; 112 } 113 114 // Read the '"..."'. 115 Lex(Tok); 116 if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal)) { 117 Diag(PragmaLoc, diag::err__Pragma_malformed); 118 return; 119 } 120 121 // Remember the string. 122 std::string StrVal = getSpelling(Tok); 123 124 // Read the ')'. 125 Lex(Tok); 126 if (Tok.isNot(tok::r_paren)) { 127 Diag(PragmaLoc, diag::err__Pragma_malformed); 128 return; 129 } 130 131 SourceLocation RParenLoc = Tok.getLocation(); 132 133 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1: 134 // "The string literal is destringized by deleting the L prefix, if present, 135 // deleting the leading and trailing double-quotes, replacing each escape 136 // sequence \" by a double-quote, and replacing each escape sequence \\ by a 137 // single backslash." 138 if (StrVal[0] == 'L') // Remove L prefix. 139 StrVal.erase(StrVal.begin()); 140 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && 141 "Invalid string token!"); 142 143 // Remove the front quote, replacing it with a space, so that the pragma 144 // contents appear to have a space before them. 145 StrVal[0] = ' '; 146 147 // Replace the terminating quote with a \n. 148 StrVal[StrVal.size()-1] = '\n'; 149 150 // Remove escaped quotes and escapes. 151 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) { 152 if (StrVal[i] == '\\' && 153 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) { 154 // \\ -> '\' and \" -> '"'. 155 StrVal.erase(StrVal.begin()+i); 156 --e; 157 } 158 } 159 160 // Plop the string (including the newline and trailing null) into a buffer 161 // where we can lex it. 162 Token TmpTok; 163 TmpTok.startToken(); 164 CreateString(&StrVal[0], StrVal.size(), TmpTok); 165 SourceLocation TokLoc = TmpTok.getLocation(); 166 167 // Make and enter a lexer object so that we lex and expand the tokens just 168 // like any others. 169 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc, 170 StrVal.size(), *this); 171 172 EnterSourceFileWithLexer(TL, 0); 173 174 // With everything set up, lex this as a #pragma directive. 175 HandlePragmaDirective(); 176 177 // Finally, return whatever came after the pragma directive. 178 return Lex(Tok); 179} 180 181 182 183/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'. 184/// 185void Preprocessor::HandlePragmaOnce(Token &OnceTok) { 186 if (isInPrimaryFile()) { 187 Diag(OnceTok, diag::pp_pragma_once_in_main_file); 188 return; 189 } 190 191 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. 192 // Mark the file as a once-only file now. 193 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry()); 194} 195 196void Preprocessor::HandlePragmaMark() { 197 assert(CurPPLexer && "No current lexer?"); 198 if (CurLexer) CurLexer->ReadToEndOfLine(); 199 else CurPTHLexer->DiscardToEndOfLine(); 200} 201 202 203/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'. 204/// 205void Preprocessor::HandlePragmaPoison(Token &PoisonTok) { 206 Token Tok; 207 208 while (1) { 209 // Read the next token to poison. While doing this, pretend that we are 210 // skipping while reading the identifier to poison. 211 // This avoids errors on code like: 212 // #pragma GCC poison X 213 // #pragma GCC poison X 214 if (CurPPLexer) CurPPLexer->LexingRawMode = true; 215 LexUnexpandedToken(Tok); 216 if (CurPPLexer) CurPPLexer->LexingRawMode = false; 217 218 // If we reached the end of line, we're done. 219 if (Tok.is(tok::eom)) return; 220 221 // Can only poison identifiers. 222 if (Tok.isNot(tok::identifier)) { 223 Diag(Tok, diag::err_pp_invalid_poison); 224 return; 225 } 226 227 // Look up the identifier info for the token. We disabled identifier lookup 228 // by saying we're skipping contents, so we need to do this manually. 229 IdentifierInfo *II = LookUpIdentifierInfo(Tok); 230 231 // Already poisoned. 232 if (II->isPoisoned()) continue; 233 234 // If this is a macro identifier, emit a warning. 235 if (II->hasMacroDefinition()) 236 Diag(Tok, diag::pp_poisoning_existing_macro); 237 238 // Finally, poison it! 239 II->setIsPoisoned(); 240 } 241} 242 243/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know 244/// that the whole directive has been parsed. 245void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) { 246 if (isInPrimaryFile()) { 247 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file); 248 return; 249 } 250 251 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. 252 PreprocessorLexer *TheLexer = getCurrentFileLexer(); 253 254 // Mark the file as a system header. 255 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry()); 256 257 // Notify the client, if desired, that we are in a new source file. 258 if (Callbacks) 259 Callbacks->FileChanged(SysHeaderTok.getLocation(), 260 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System); 261} 262 263/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah. 264/// 265void Preprocessor::HandlePragmaDependency(Token &DependencyTok) { 266 Token FilenameTok; 267 CurPPLexer->LexIncludeFilename(FilenameTok); 268 269 // If the token kind is EOM, the error has already been diagnosed. 270 if (FilenameTok.is(tok::eom)) 271 return; 272 273 // Reserve a buffer to get the spelling. 274 llvm::SmallVector<char, 128> FilenameBuffer; 275 FilenameBuffer.resize(FilenameTok.getLength()); 276 277 const char *FilenameStart = &FilenameBuffer[0]; 278 unsigned Len = getSpelling(FilenameTok, FilenameStart); 279 const char *FilenameEnd = FilenameStart+Len; 280 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(), 281 FilenameStart, FilenameEnd); 282 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 283 // error. 284 if (FilenameStart == 0) 285 return; 286 287 // Search include directories for this file. 288 const DirectoryLookup *CurDir; 289 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd, 290 isAngled, 0, CurDir); 291 if (File == 0) { 292 Diag(FilenameTok, diag::err_pp_file_not_found) 293 << std::string(FilenameStart, FilenameEnd); 294 return; 295 } 296 297 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry(); 298 299 // If this file is older than the file it depends on, emit a diagnostic. 300 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) { 301 // Lex tokens at the end of the message and include them in the message. 302 std::string Message; 303 Lex(DependencyTok); 304 while (DependencyTok.isNot(tok::eom)) { 305 Message += getSpelling(DependencyTok) + " "; 306 Lex(DependencyTok); 307 } 308 309 Message.erase(Message.end()-1); 310 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message; 311 } 312} 313 314/// HandlePragmaComment - Handle the microsoft #pragma comment extension. The 315/// syntax is: 316/// #pragma comment(linker, "foo") 317/// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user. 318/// "foo" is a string, which is fully macro expanded, and permits string 319/// concatenation, embedded escape characters etc. See MSDN for more details. 320void Preprocessor::HandlePragmaComment(Token &Tok) { 321 SourceLocation CommentLoc = Tok.getLocation(); 322 Lex(Tok); 323 if (Tok.isNot(tok::l_paren)) { 324 Diag(CommentLoc, diag::err_pragma_comment_malformed); 325 return; 326 } 327 328 // Read the identifier. 329 Lex(Tok); 330 if (Tok.isNot(tok::identifier)) { 331 Diag(CommentLoc, diag::err_pragma_comment_malformed); 332 return; 333 } 334 335 // Verify that this is one of the 5 whitelisted options. 336 // FIXME: warn that 'exestr' is deprecated. 337 const IdentifierInfo *II = Tok.getIdentifierInfo(); 338 if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") && 339 !II->isStr("linker") && !II->isStr("user")) { 340 Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind); 341 return; 342 } 343 344 // Read the optional string if present. 345 Lex(Tok); 346 std::string ArgumentString; 347 if (Tok.is(tok::comma)) { 348 Lex(Tok); // eat the comma. 349 350 // We need at least one string. 351 if (Tok.getKind() != tok::string_literal) { 352 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); 353 return; 354 } 355 356 // String concatenation allows multiple strings, which can even come from 357 // macro expansion. 358 // "foo " "bar" "Baz" 359 llvm::SmallVector<Token, 4> StrToks; 360 while (Tok.getKind() == tok::string_literal) { 361 StrToks.push_back(Tok); 362 Lex(Tok); 363 } 364 365 // Concatenate and parse the strings. 366 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this); 367 assert(!Literal.AnyWide && "Didn't allow wide strings in"); 368 if (Literal.hadError) 369 return; 370 if (Literal.Pascal) { 371 Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed); 372 return; 373 } 374 375 ArgumentString = std::string(Literal.GetString(), 376 Literal.GetString()+Literal.GetStringLength()); 377 } 378 379 // FIXME: If the kind is "compiler" warn if the string is present (it is 380 // ignored). 381 // FIXME: 'lib' requires a comment string. 382 // FIXME: 'linker' requires a comment string, and has a specific list of 383 // things that are allowable. 384 385 if (Tok.isNot(tok::r_paren)) { 386 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); 387 return; 388 } 389 Lex(Tok); // eat the r_paren. 390 391 if (Tok.isNot(tok::eom)) { 392 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); 393 return; 394 } 395 396 // If the pragma is lexically sound, notify any interested PPCallbacks. 397 if (Callbacks) 398 Callbacks->PragmaComment(CommentLoc, II, ArgumentString); 399} 400 401 402 403 404/// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 405/// If 'Namespace' is non-null, then it is a token required to exist on the 406/// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 407void Preprocessor::AddPragmaHandler(const char *Namespace, 408 PragmaHandler *Handler) { 409 PragmaNamespace *InsertNS = PragmaHandlers; 410 411 // If this is specified to be in a namespace, step down into it. 412 if (Namespace) { 413 IdentifierInfo *NSID = getIdentifierInfo(Namespace); 414 415 // If there is already a pragma handler with the name of this namespace, 416 // we either have an error (directive with the same name as a namespace) or 417 // we already have the namespace to insert into. 418 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) { 419 InsertNS = Existing->getIfNamespace(); 420 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma" 421 " handler with the same name!"); 422 } else { 423 // Otherwise, this namespace doesn't exist yet, create and insert the 424 // handler for it. 425 InsertNS = new PragmaNamespace(NSID); 426 PragmaHandlers->AddPragma(InsertNS); 427 } 428 } 429 430 // Check to make sure we don't already have a pragma for this identifier. 431 assert(!InsertNS->FindHandler(Handler->getName()) && 432 "Pragma handler already exists for this identifier!"); 433 InsertNS->AddPragma(Handler); 434} 435 436/// RemovePragmaHandler - Remove the specific pragma handler from the 437/// preprocessor. If \arg Namespace is non-null, then it should be the 438/// namespace that \arg Handler was added to. It is an error to remove 439/// a handler that has not been registered. 440void Preprocessor::RemovePragmaHandler(const char *Namespace, 441 PragmaHandler *Handler) { 442 PragmaNamespace *NS = PragmaHandlers; 443 444 // If this is specified to be in a namespace, step down into it. 445 if (Namespace) { 446 IdentifierInfo *NSID = getIdentifierInfo(Namespace); 447 PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID); 448 assert(Existing && "Namespace containing handler does not exist!"); 449 450 NS = Existing->getIfNamespace(); 451 assert(NS && "Invalid namespace, registered as a regular pragma handler!"); 452 } 453 454 NS->RemovePragmaHandler(Handler); 455 456 // If this is a non-default namespace and it is now empty, remove 457 // it. 458 if (NS != PragmaHandlers && NS->IsEmpty()) 459 PragmaHandlers->RemovePragmaHandler(NS); 460} 461 462namespace { 463/// PragmaOnceHandler - "#pragma once" marks the file as atomically included. 464struct PragmaOnceHandler : public PragmaHandler { 465 PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {} 466 virtual void HandlePragma(Preprocessor &PP, Token &OnceTok) { 467 PP.CheckEndOfDirective("pragma once"); 468 PP.HandlePragmaOnce(OnceTok); 469 } 470}; 471 472/// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the 473/// rest of the line is not lexed. 474struct PragmaMarkHandler : public PragmaHandler { 475 PragmaMarkHandler(const IdentifierInfo *MarkID) : PragmaHandler(MarkID) {} 476 virtual void HandlePragma(Preprocessor &PP, Token &MarkTok) { 477 PP.HandlePragmaMark(); 478 } 479}; 480 481/// PragmaPoisonHandler - "#pragma poison x" marks x as not usable. 482struct PragmaPoisonHandler : public PragmaHandler { 483 PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {} 484 virtual void HandlePragma(Preprocessor &PP, Token &PoisonTok) { 485 PP.HandlePragmaPoison(PoisonTok); 486 } 487}; 488 489/// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file 490/// as a system header, which silences warnings in it. 491struct PragmaSystemHeaderHandler : public PragmaHandler { 492 PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {} 493 virtual void HandlePragma(Preprocessor &PP, Token &SHToken) { 494 PP.HandlePragmaSystemHeader(SHToken); 495 PP.CheckEndOfDirective("pragma"); 496 } 497}; 498struct PragmaDependencyHandler : public PragmaHandler { 499 PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {} 500 virtual void HandlePragma(Preprocessor &PP, Token &DepToken) { 501 PP.HandlePragmaDependency(DepToken); 502 } 503}; 504 505/// PragmaCommentHandler - "#pragma comment ...". 506struct PragmaCommentHandler : public PragmaHandler { 507 PragmaCommentHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {} 508 virtual void HandlePragma(Preprocessor &PP, Token &CommentTok) { 509 PP.HandlePragmaComment(CommentTok); 510 } 511}; 512 513// Pragma STDC implementations. 514 515/// PragmaSTDC_FP_CONTRACTHandler - "#pragma STDC FP_CONTRACT ...". 516struct PragmaSTDC_FP_CONTRACTHandler : public PragmaHandler { 517 PragmaSTDC_FP_CONTRACTHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {} 518 virtual void HandlePragma(Preprocessor &PP, Token &CommentTok) { 519 //PP.HandlePragmaComment(CommentTok); 520 } 521}; 522 523/// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...". 524struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler { 525 PragmaSTDC_FENV_ACCESSHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {} 526 virtual void HandlePragma(Preprocessor &PP, Token &CommentTok) { 527 //PP.HandlePragmaComment(CommentTok); 528 } 529}; 530 531/// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...". 532struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler { 533 PragmaSTDC_CX_LIMITED_RANGEHandler(const IdentifierInfo *ID) 534 : PragmaHandler(ID) {} 535 virtual void HandlePragma(Preprocessor &PP, Token &CommentTok) { 536 //PP.HandlePragmaComment(CommentTok); 537 } 538}; 539 540/// PragmaSTDC_UnknownHandler - "#pragma STDC ...". 541struct PragmaSTDC_UnknownHandler : public PragmaHandler { 542 PragmaSTDC_UnknownHandler() : PragmaHandler(0) {} 543 virtual void HandlePragma(Preprocessor &PP, Token &CommentTok) { 544 //PP.HandlePragmaComment(CommentTok); 545 } 546}; 547 548} // end anonymous namespace 549 550 551/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 552/// #pragma GCC poison/system_header/dependency and #pragma once. 553void Preprocessor::RegisterBuiltinPragmas() { 554 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once"))); 555 AddPragmaHandler(0, new PragmaMarkHandler(getIdentifierInfo("mark"))); 556 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison"))); 557 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler( 558 getIdentifierInfo("system_header"))); 559 AddPragmaHandler("GCC", new PragmaDependencyHandler( 560 getIdentifierInfo("dependency"))); 561 562 AddPragmaHandler("STDC", new PragmaSTDC_FP_CONTRACTHandler( 563 getIdentifierInfo("FP_CONTRACT"))); 564 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler( 565 getIdentifierInfo("FENV_ACCESS"))); 566 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler( 567 getIdentifierInfo("CX_LIMITED_RANGE"))); 568 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler()); 569 570 // MS extensions. 571 if (Features.Microsoft) 572 AddPragmaHandler(0, new PragmaCommentHandler(getIdentifierInfo("comment"))); 573} 574