rename test
[clang.git] / lib / Lex / Pragma.cpp
blobf0475bc0cb2016df369de237f450c8312a06dea7
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.
13 //===----------------------------------------------------------------------===//
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/MacroInfo.h"
20 #include "clang/Lex/LexDiagnostic.h"
21 #include "clang/Basic/FileManager.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "llvm/Support/CrashRecoveryContext.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include <algorithm>
26 using namespace clang;
28 // Out-of-line destructor to provide a home for the class.
29 PragmaHandler::~PragmaHandler() {
32 //===----------------------------------------------------------------------===//
33 // EmptyPragmaHandler Implementation.
34 //===----------------------------------------------------------------------===//
36 EmptyPragmaHandler::EmptyPragmaHandler() {}
38 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
39 PragmaIntroducerKind Introducer,
40 Token &FirstToken) {}
42 //===----------------------------------------------------------------------===//
43 // PragmaNamespace Implementation.
44 //===----------------------------------------------------------------------===//
47 PragmaNamespace::~PragmaNamespace() {
48 for (llvm::StringMap<PragmaHandler*>::iterator
49 I = Handlers.begin(), E = Handlers.end(); I != E; ++I)
50 delete I->second;
53 /// FindHandler - Check to see if there is already a handler for the
54 /// specified name. If not, return the handler for the null identifier if it
55 /// exists, otherwise return null. If IgnoreNull is true (the default) then
56 /// the null handler isn't returned on failure to match.
57 PragmaHandler *PragmaNamespace::FindHandler(llvm::StringRef Name,
58 bool IgnoreNull) const {
59 if (PragmaHandler *Handler = Handlers.lookup(Name))
60 return Handler;
61 return IgnoreNull ? 0 : Handlers.lookup(llvm::StringRef());
64 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
65 assert(!Handlers.lookup(Handler->getName()) &&
66 "A handler with this name is already registered in this namespace");
67 llvm::StringMapEntry<PragmaHandler *> &Entry =
68 Handlers.GetOrCreateValue(Handler->getName());
69 Entry.setValue(Handler);
72 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
73 assert(Handlers.lookup(Handler->getName()) &&
74 "Handler not registered in this namespace");
75 Handlers.erase(Handler->getName());
78 void PragmaNamespace::HandlePragma(Preprocessor &PP,
79 PragmaIntroducerKind Introducer,
80 Token &Tok) {
81 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
82 // expand it, the user can have a STDC #define, that should not affect this.
83 PP.LexUnexpandedToken(Tok);
85 // Get the handler for this token. If there is no handler, ignore the pragma.
86 PragmaHandler *Handler
87 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
88 : llvm::StringRef(),
89 /*IgnoreNull=*/false);
90 if (Handler == 0) {
91 PP.Diag(Tok, diag::warn_pragma_ignored);
92 return;
95 // Otherwise, pass it down.
96 Handler->HandlePragma(PP, Introducer, Tok);
99 //===----------------------------------------------------------------------===//
100 // Preprocessor Pragma Directive Handling.
101 //===----------------------------------------------------------------------===//
103 /// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
104 /// rest of the pragma, passing it to the registered pragma handlers.
105 void Preprocessor::HandlePragmaDirective(unsigned Introducer) {
106 ++NumPragma;
108 // Invoke the first level of pragma handlers which reads the namespace id.
109 Token Tok;
110 PragmaHandlers->HandlePragma(*this, PragmaIntroducerKind(Introducer), Tok);
112 // If the pragma handler didn't read the rest of the line, consume it now.
113 if (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective)
114 DiscardUntilEndOfDirective();
117 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
118 /// return the first token after the directive. The _Pragma token has just
119 /// been read into 'Tok'.
120 void Preprocessor::Handle_Pragma(Token &Tok) {
121 // Remember the pragma token location.
122 SourceLocation PragmaLoc = Tok.getLocation();
124 // Read the '('.
125 Lex(Tok);
126 if (Tok.isNot(tok::l_paren)) {
127 Diag(PragmaLoc, diag::err__Pragma_malformed);
128 return;
131 // Read the '"..."'.
132 Lex(Tok);
133 if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal)) {
134 Diag(PragmaLoc, diag::err__Pragma_malformed);
135 return;
138 // Remember the string.
139 std::string StrVal = getSpelling(Tok);
141 // Read the ')'.
142 Lex(Tok);
143 if (Tok.isNot(tok::r_paren)) {
144 Diag(PragmaLoc, diag::err__Pragma_malformed);
145 return;
148 SourceLocation RParenLoc = Tok.getLocation();
150 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1:
151 // "The string literal is destringized by deleting the L prefix, if present,
152 // deleting the leading and trailing double-quotes, replacing each escape
153 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
154 // single backslash."
155 if (StrVal[0] == 'L') // Remove L prefix.
156 StrVal.erase(StrVal.begin());
157 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
158 "Invalid string token!");
160 // Remove the front quote, replacing it with a space, so that the pragma
161 // contents appear to have a space before them.
162 StrVal[0] = ' ';
164 // Replace the terminating quote with a \n.
165 StrVal[StrVal.size()-1] = '\n';
167 // Remove escaped quotes and escapes.
168 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
169 if (StrVal[i] == '\\' &&
170 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
171 // \\ -> '\' and \" -> '"'.
172 StrVal.erase(StrVal.begin()+i);
173 --e;
177 Handle_Pragma(PIK__Pragma, StrVal, PragmaLoc, RParenLoc);
179 // Finally, return whatever came after the pragma directive.
180 return Lex(Tok);
183 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
184 /// is not enclosed within a string literal.
185 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
186 // Remember the pragma token location.
187 SourceLocation PragmaLoc = Tok.getLocation();
189 // Read the '('.
190 Lex(Tok);
191 if (Tok.isNot(tok::l_paren)) {
192 Diag(PragmaLoc, diag::err__Pragma_malformed);
193 return;
196 // Get the tokens enclosed within the __pragma().
197 llvm::SmallVector<Token, 32> PragmaToks;
198 int NumParens = 0;
199 Lex(Tok);
200 while (Tok.isNot(tok::eof)) {
201 if (Tok.is(tok::l_paren))
202 NumParens++;
203 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
204 break;
205 PragmaToks.push_back(Tok);
206 Lex(Tok);
209 if (Tok.is(tok::eof)) {
210 Diag(PragmaLoc, diag::err_unterminated___pragma);
211 return;
214 // Build the pragma string.
215 std::string StrVal = " ";
216 for (llvm::SmallVector<Token, 32>::iterator I =
217 PragmaToks.begin(), E = PragmaToks.end(); I != E; ++I) {
218 StrVal += getSpelling(*I);
221 SourceLocation RParenLoc = Tok.getLocation();
223 Handle_Pragma(PIK___pragma, StrVal, PragmaLoc, RParenLoc);
225 // Finally, return whatever came after the pragma directive.
226 return Lex(Tok);
229 void Preprocessor::Handle_Pragma(unsigned Introducer,
230 const std::string &StrVal,
231 SourceLocation PragmaLoc,
232 SourceLocation RParenLoc) {
234 // Plop the string (including the newline and trailing null) into a buffer
235 // where we can lex it.
236 Token TmpTok;
237 TmpTok.startToken();
238 CreateString(&StrVal[0], StrVal.size(), TmpTok);
239 SourceLocation TokLoc = TmpTok.getLocation();
241 // Make and enter a lexer object so that we lex and expand the tokens just
242 // like any others.
243 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
244 StrVal.size(), *this);
246 EnterSourceFileWithLexer(TL, 0);
248 // With everything set up, lex this as a #pragma directive.
249 HandlePragmaDirective(Introducer);
254 /// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
256 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
257 if (isInPrimaryFile()) {
258 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
259 return;
262 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
263 // Mark the file as a once-only file now.
264 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
267 void Preprocessor::HandlePragmaMark() {
268 assert(CurPPLexer && "No current lexer?");
269 if (CurLexer)
270 CurLexer->ReadToEndOfLine();
271 else
272 CurPTHLexer->DiscardToEndOfLine();
276 /// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
278 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
279 Token Tok;
281 while (1) {
282 // Read the next token to poison. While doing this, pretend that we are
283 // skipping while reading the identifier to poison.
284 // This avoids errors on code like:
285 // #pragma GCC poison X
286 // #pragma GCC poison X
287 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
288 LexUnexpandedToken(Tok);
289 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
291 // If we reached the end of line, we're done.
292 if (Tok.is(tok::eom)) return;
294 // Can only poison identifiers.
295 if (Tok.isNot(tok::raw_identifier)) {
296 Diag(Tok, diag::err_pp_invalid_poison);
297 return;
300 // Look up the identifier info for the token. We disabled identifier lookup
301 // by saying we're skipping contents, so we need to do this manually.
302 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
304 // Already poisoned.
305 if (II->isPoisoned()) continue;
307 // If this is a macro identifier, emit a warning.
308 if (II->hasMacroDefinition())
309 Diag(Tok, diag::pp_poisoning_existing_macro);
311 // Finally, poison it!
312 II->setIsPoisoned();
316 /// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
317 /// that the whole directive has been parsed.
318 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
319 if (isInPrimaryFile()) {
320 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
321 return;
324 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
325 PreprocessorLexer *TheLexer = getCurrentFileLexer();
327 // Mark the file as a system header.
328 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
331 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
332 if (PLoc.isInvalid())
333 return;
335 unsigned FilenameLen = strlen(PLoc.getFilename());
336 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename(),
337 FilenameLen);
339 // Emit a line marker. This will change any source locations from this point
340 // forward to realize they are in a system header.
341 // Create a line note with this information.
342 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine(), FilenameID,
343 false, false, true, false);
345 // Notify the client, if desired, that we are in a new source file.
346 if (Callbacks)
347 Callbacks->FileChanged(SysHeaderTok.getLocation(),
348 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
351 /// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
353 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
354 Token FilenameTok;
355 CurPPLexer->LexIncludeFilename(FilenameTok);
357 // If the token kind is EOM, the error has already been diagnosed.
358 if (FilenameTok.is(tok::eom))
359 return;
361 // Reserve a buffer to get the spelling.
362 llvm::SmallString<128> FilenameBuffer;
363 bool Invalid = false;
364 llvm::StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
365 if (Invalid)
366 return;
368 bool isAngled =
369 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
370 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
371 // error.
372 if (Filename.empty())
373 return;
375 // Search include directories for this file.
376 const DirectoryLookup *CurDir;
377 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
378 if (File == 0) {
379 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
380 return;
383 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
385 // If this file is older than the file it depends on, emit a diagnostic.
386 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
387 // Lex tokens at the end of the message and include them in the message.
388 std::string Message;
389 Lex(DependencyTok);
390 while (DependencyTok.isNot(tok::eom)) {
391 Message += getSpelling(DependencyTok) + " ";
392 Lex(DependencyTok);
395 // Remove the trailing ' ' if present.
396 if (!Message.empty())
397 Message.erase(Message.end()-1);
398 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
402 /// HandlePragmaComment - Handle the microsoft #pragma comment extension. The
403 /// syntax is:
404 /// #pragma comment(linker, "foo")
405 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
406 /// "foo" is a string, which is fully macro expanded, and permits string
407 /// concatenation, embedded escape characters etc. See MSDN for more details.
408 void Preprocessor::HandlePragmaComment(Token &Tok) {
409 SourceLocation CommentLoc = Tok.getLocation();
410 Lex(Tok);
411 if (Tok.isNot(tok::l_paren)) {
412 Diag(CommentLoc, diag::err_pragma_comment_malformed);
413 return;
416 // Read the identifier.
417 Lex(Tok);
418 if (Tok.isNot(tok::identifier)) {
419 Diag(CommentLoc, diag::err_pragma_comment_malformed);
420 return;
423 // Verify that this is one of the 5 whitelisted options.
424 // FIXME: warn that 'exestr' is deprecated.
425 const IdentifierInfo *II = Tok.getIdentifierInfo();
426 if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") &&
427 !II->isStr("linker") && !II->isStr("user")) {
428 Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
429 return;
432 // Read the optional string if present.
433 Lex(Tok);
434 std::string ArgumentString;
435 if (Tok.is(tok::comma)) {
436 Lex(Tok); // eat the comma.
438 // We need at least one string.
439 if (Tok.isNot(tok::string_literal)) {
440 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
441 return;
444 // String concatenation allows multiple strings, which can even come from
445 // macro expansion.
446 // "foo " "bar" "Baz"
447 llvm::SmallVector<Token, 4> StrToks;
448 while (Tok.is(tok::string_literal)) {
449 StrToks.push_back(Tok);
450 Lex(Tok);
453 // Concatenate and parse the strings.
454 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
455 assert(!Literal.AnyWide && "Didn't allow wide strings in");
456 if (Literal.hadError)
457 return;
458 if (Literal.Pascal) {
459 Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed);
460 return;
463 ArgumentString = std::string(Literal.GetString(),
464 Literal.GetString()+Literal.GetStringLength());
467 // FIXME: If the kind is "compiler" warn if the string is present (it is
468 // ignored).
469 // FIXME: 'lib' requires a comment string.
470 // FIXME: 'linker' requires a comment string, and has a specific list of
471 // things that are allowable.
473 if (Tok.isNot(tok::r_paren)) {
474 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
475 return;
477 Lex(Tok); // eat the r_paren.
479 if (Tok.isNot(tok::eom)) {
480 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
481 return;
484 // If the pragma is lexically sound, notify any interested PPCallbacks.
485 if (Callbacks)
486 Callbacks->PragmaComment(CommentLoc, II, ArgumentString);
489 /// HandlePragmaMessage - Handle the microsoft and gcc #pragma message
490 /// extension. The syntax is:
491 /// #pragma message(string)
492 /// OR, in GCC mode:
493 /// #pragma message string
494 /// string is a string, which is fully macro expanded, and permits string
495 /// concatenation, embedded escape characters, etc... See MSDN for more details.
496 void Preprocessor::HandlePragmaMessage(Token &Tok) {
497 SourceLocation MessageLoc = Tok.getLocation();
498 Lex(Tok);
499 bool ExpectClosingParen = false;
500 switch (Tok.getKind()) {
501 case tok::l_paren:
502 // We have a MSVC style pragma message.
503 ExpectClosingParen = true;
504 // Read the string.
505 Lex(Tok);
506 break;
507 case tok::string_literal:
508 // We have a GCC style pragma message, and we just read the string.
509 break;
510 default:
511 Diag(MessageLoc, diag::err_pragma_message_malformed);
512 return;
515 // We need at least one string.
516 if (Tok.isNot(tok::string_literal)) {
517 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
518 return;
521 // String concatenation allows multiple strings, which can even come from
522 // macro expansion.
523 // "foo " "bar" "Baz"
524 llvm::SmallVector<Token, 4> StrToks;
525 while (Tok.is(tok::string_literal)) {
526 StrToks.push_back(Tok);
527 Lex(Tok);
530 // Concatenate and parse the strings.
531 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
532 assert(!Literal.AnyWide && "Didn't allow wide strings in");
533 if (Literal.hadError)
534 return;
535 if (Literal.Pascal) {
536 Diag(StrToks[0].getLocation(), diag::err_pragma_message_malformed);
537 return;
540 llvm::StringRef MessageString(Literal.GetString(), Literal.GetStringLength());
542 if (ExpectClosingParen) {
543 if (Tok.isNot(tok::r_paren)) {
544 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
545 return;
547 Lex(Tok); // eat the r_paren.
550 if (Tok.isNot(tok::eom)) {
551 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
552 return;
555 // Output the message.
556 Diag(MessageLoc, diag::warn_pragma_message) << MessageString;
558 // If the pragma is lexically sound, notify any interested PPCallbacks.
559 if (Callbacks)
560 Callbacks->PragmaMessage(MessageLoc, MessageString);
563 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
564 /// Return the IdentifierInfo* associated with the macro to push or pop.
565 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
566 // Remember the pragma token location.
567 Token PragmaTok = Tok;
569 // Read the '('.
570 Lex(Tok);
571 if (Tok.isNot(tok::l_paren)) {
572 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
573 << getSpelling(PragmaTok);
574 return 0;
577 // Read the macro name string.
578 Lex(Tok);
579 if (Tok.isNot(tok::string_literal)) {
580 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
581 << getSpelling(PragmaTok);
582 return 0;
585 // Remember the macro string.
586 std::string StrVal = getSpelling(Tok);
588 // Read the ')'.
589 Lex(Tok);
590 if (Tok.isNot(tok::r_paren)) {
591 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
592 << getSpelling(PragmaTok);
593 return 0;
596 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
597 "Invalid string token!");
599 // Create a Token from the string.
600 Token MacroTok;
601 MacroTok.startToken();
602 MacroTok.setKind(tok::raw_identifier);
603 CreateString(&StrVal[1], StrVal.size() - 2, MacroTok);
605 // Get the IdentifierInfo of MacroToPushTok.
606 return LookUpIdentifierInfo(MacroTok);
609 /// HandlePragmaPushMacro - Handle #pragma push_macro.
610 /// The syntax is:
611 /// #pragma push_macro("macro")
612 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
613 // Parse the pragma directive and get the macro IdentifierInfo*.
614 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
615 if (!IdentInfo) return;
617 // Get the MacroInfo associated with IdentInfo.
618 MacroInfo *MI = getMacroInfo(IdentInfo);
620 MacroInfo *MacroCopyToPush = 0;
621 if (MI) {
622 // Make a clone of MI.
623 MacroCopyToPush = CloneMacroInfo(*MI);
625 // Allow the original MacroInfo to be redefined later.
626 MI->setIsAllowRedefinitionsWithoutWarning(true);
629 // Push the cloned MacroInfo so we can retrieve it later.
630 PragmaPushMacroInfo[IdentInfo].push_back(MacroCopyToPush);
633 /// HandlePragmaPopMacro - Handle #pragma pop_macro.
634 /// The syntax is:
635 /// #pragma pop_macro("macro")
636 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
637 SourceLocation MessageLoc = PopMacroTok.getLocation();
639 // Parse the pragma directive and get the macro IdentifierInfo*.
640 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
641 if (!IdentInfo) return;
643 // Find the vector<MacroInfo*> associated with the macro.
644 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
645 PragmaPushMacroInfo.find(IdentInfo);
646 if (iter != PragmaPushMacroInfo.end()) {
647 // Release the MacroInfo currently associated with IdentInfo.
648 MacroInfo *CurrentMI = getMacroInfo(IdentInfo);
649 if (CurrentMI) {
650 if (CurrentMI->isWarnIfUnused())
651 WarnUnusedMacroLocs.erase(CurrentMI->getDefinitionLoc());
652 ReleaseMacroInfo(CurrentMI);
655 // Get the MacroInfo we want to reinstall.
656 MacroInfo *MacroToReInstall = iter->second.back();
658 // Reinstall the previously pushed macro.
659 setMacroInfo(IdentInfo, MacroToReInstall);
661 // Pop PragmaPushMacroInfo stack.
662 iter->second.pop_back();
663 if (iter->second.size() == 0)
664 PragmaPushMacroInfo.erase(iter);
665 } else {
666 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
667 << IdentInfo->getName();
671 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
672 /// If 'Namespace' is non-null, then it is a token required to exist on the
673 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
674 void Preprocessor::AddPragmaHandler(llvm::StringRef Namespace,
675 PragmaHandler *Handler) {
676 PragmaNamespace *InsertNS = PragmaHandlers;
678 // If this is specified to be in a namespace, step down into it.
679 if (!Namespace.empty()) {
680 // If there is already a pragma handler with the name of this namespace,
681 // we either have an error (directive with the same name as a namespace) or
682 // we already have the namespace to insert into.
683 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
684 InsertNS = Existing->getIfNamespace();
685 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
686 " handler with the same name!");
687 } else {
688 // Otherwise, this namespace doesn't exist yet, create and insert the
689 // handler for it.
690 InsertNS = new PragmaNamespace(Namespace);
691 PragmaHandlers->AddPragma(InsertNS);
695 // Check to make sure we don't already have a pragma for this identifier.
696 assert(!InsertNS->FindHandler(Handler->getName()) &&
697 "Pragma handler already exists for this identifier!");
698 InsertNS->AddPragma(Handler);
701 /// RemovePragmaHandler - Remove the specific pragma handler from the
702 /// preprocessor. If \arg Namespace is non-null, then it should be the
703 /// namespace that \arg Handler was added to. It is an error to remove
704 /// a handler that has not been registered.
705 void Preprocessor::RemovePragmaHandler(llvm::StringRef Namespace,
706 PragmaHandler *Handler) {
707 PragmaNamespace *NS = PragmaHandlers;
709 // If this is specified to be in a namespace, step down into it.
710 if (!Namespace.empty()) {
711 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
712 assert(Existing && "Namespace containing handler does not exist!");
714 NS = Existing->getIfNamespace();
715 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
718 NS->RemovePragmaHandler(Handler);
720 // If this is a non-default namespace and it is now empty, remove
721 // it.
722 if (NS != PragmaHandlers && NS->IsEmpty())
723 PragmaHandlers->RemovePragmaHandler(NS);
726 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
727 Token Tok;
728 LexUnexpandedToken(Tok);
730 if (Tok.isNot(tok::identifier)) {
731 Diag(Tok, diag::ext_on_off_switch_syntax);
732 return true;
734 IdentifierInfo *II = Tok.getIdentifierInfo();
735 if (II->isStr("ON"))
736 Result = tok::OOS_ON;
737 else if (II->isStr("OFF"))
738 Result = tok::OOS_OFF;
739 else if (II->isStr("DEFAULT"))
740 Result = tok::OOS_DEFAULT;
741 else {
742 Diag(Tok, diag::ext_on_off_switch_syntax);
743 return true;
746 // Verify that this is followed by EOM.
747 LexUnexpandedToken(Tok);
748 if (Tok.isNot(tok::eom))
749 Diag(Tok, diag::ext_pragma_syntax_eom);
750 return false;
753 namespace {
754 /// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
755 struct PragmaOnceHandler : public PragmaHandler {
756 PragmaOnceHandler() : PragmaHandler("once") {}
757 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
758 Token &OnceTok) {
759 PP.CheckEndOfDirective("pragma once");
760 PP.HandlePragmaOnce(OnceTok);
764 /// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
765 /// rest of the line is not lexed.
766 struct PragmaMarkHandler : public PragmaHandler {
767 PragmaMarkHandler() : PragmaHandler("mark") {}
768 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
769 Token &MarkTok) {
770 PP.HandlePragmaMark();
774 /// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
775 struct PragmaPoisonHandler : public PragmaHandler {
776 PragmaPoisonHandler() : PragmaHandler("poison") {}
777 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
778 Token &PoisonTok) {
779 PP.HandlePragmaPoison(PoisonTok);
783 /// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
784 /// as a system header, which silences warnings in it.
785 struct PragmaSystemHeaderHandler : public PragmaHandler {
786 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
787 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
788 Token &SHToken) {
789 PP.HandlePragmaSystemHeader(SHToken);
790 PP.CheckEndOfDirective("pragma");
793 struct PragmaDependencyHandler : public PragmaHandler {
794 PragmaDependencyHandler() : PragmaHandler("dependency") {}
795 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
796 Token &DepToken) {
797 PP.HandlePragmaDependency(DepToken);
801 struct PragmaDebugHandler : public PragmaHandler {
802 PragmaDebugHandler() : PragmaHandler("__debug") {}
803 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
804 Token &DepToken) {
805 Token Tok;
806 PP.LexUnexpandedToken(Tok);
807 if (Tok.isNot(tok::identifier)) {
808 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
809 return;
811 IdentifierInfo *II = Tok.getIdentifierInfo();
813 if (II->isStr("assert")) {
814 assert(0 && "This is an assertion!");
815 } else if (II->isStr("crash")) {
816 *(volatile int*) 0x11 = 0;
817 } else if (II->isStr("llvm_fatal_error")) {
818 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
819 } else if (II->isStr("llvm_unreachable")) {
820 llvm_unreachable("#pragma clang __debug llvm_unreachable");
821 } else if (II->isStr("overflow_stack")) {
822 DebugOverflowStack();
823 } else if (II->isStr("handle_crash")) {
824 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
825 if (CRC)
826 CRC->HandleCrash();
827 } else {
828 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
829 << II->getName();
833 void DebugOverflowStack() {
834 DebugOverflowStack();
838 /// PragmaDiagnosticHandler - e.g. '#pragma GCC diagnostic ignored "-Wformat"'
839 struct PragmaDiagnosticHandler : public PragmaHandler {
840 public:
841 explicit PragmaDiagnosticHandler() : PragmaHandler("diagnostic") {}
842 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
843 Token &DiagToken) {
844 SourceLocation DiagLoc = DiagToken.getLocation();
845 Token Tok;
846 PP.LexUnexpandedToken(Tok);
847 if (Tok.isNot(tok::identifier)) {
848 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
849 return;
851 IdentifierInfo *II = Tok.getIdentifierInfo();
853 diag::Mapping Map;
854 if (II->isStr("warning"))
855 Map = diag::MAP_WARNING;
856 else if (II->isStr("error"))
857 Map = diag::MAP_ERROR;
858 else if (II->isStr("ignored"))
859 Map = diag::MAP_IGNORE;
860 else if (II->isStr("fatal"))
861 Map = diag::MAP_FATAL;
862 else if (II->isStr("pop")) {
863 if (!PP.getDiagnostics().popMappings(DiagLoc))
864 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
866 return;
867 } else if (II->isStr("push")) {
868 PP.getDiagnostics().pushMappings(DiagLoc);
869 return;
870 } else {
871 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
872 return;
875 PP.LexUnexpandedToken(Tok);
877 // We need at least one string.
878 if (Tok.isNot(tok::string_literal)) {
879 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
880 return;
883 // String concatenation allows multiple strings, which can even come from
884 // macro expansion.
885 // "foo " "bar" "Baz"
886 llvm::SmallVector<Token, 4> StrToks;
887 while (Tok.is(tok::string_literal)) {
888 StrToks.push_back(Tok);
889 PP.LexUnexpandedToken(Tok);
892 if (Tok.isNot(tok::eom)) {
893 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
894 return;
897 // Concatenate and parse the strings.
898 StringLiteralParser Literal(&StrToks[0], StrToks.size(), PP);
899 assert(!Literal.AnyWide && "Didn't allow wide strings in");
900 if (Literal.hadError)
901 return;
902 if (Literal.Pascal) {
903 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
904 return;
907 std::string WarningName(Literal.GetString(),
908 Literal.GetString()+Literal.GetStringLength());
910 if (WarningName.size() < 3 || WarningName[0] != '-' ||
911 WarningName[1] != 'W') {
912 PP.Diag(StrToks[0].getLocation(),
913 diag::warn_pragma_diagnostic_invalid_option);
914 return;
917 if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.c_str()+2,
918 Map, DiagLoc))
919 PP.Diag(StrToks[0].getLocation(),
920 diag::warn_pragma_diagnostic_unknown_warning) << WarningName;
924 /// PragmaCommentHandler - "#pragma comment ...".
925 struct PragmaCommentHandler : public PragmaHandler {
926 PragmaCommentHandler() : PragmaHandler("comment") {}
927 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
928 Token &CommentTok) {
929 PP.HandlePragmaComment(CommentTok);
933 /// PragmaMessageHandler - "#pragma message("...")".
934 struct PragmaMessageHandler : public PragmaHandler {
935 PragmaMessageHandler() : PragmaHandler("message") {}
936 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
937 Token &CommentTok) {
938 PP.HandlePragmaMessage(CommentTok);
942 /// PragmaPushMacroHandler - "#pragma push_macro" saves the value of the
943 /// macro on the top of the stack.
944 struct PragmaPushMacroHandler : public PragmaHandler {
945 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
946 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
947 Token &PushMacroTok) {
948 PP.HandlePragmaPushMacro(PushMacroTok);
953 /// PragmaPopMacroHandler - "#pragma pop_macro" sets the value of the
954 /// macro to the value on the top of the stack.
955 struct PragmaPopMacroHandler : public PragmaHandler {
956 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
957 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
958 Token &PopMacroTok) {
959 PP.HandlePragmaPopMacro(PopMacroTok);
963 // Pragma STDC implementations.
965 /// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...".
966 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
967 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
968 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
969 Token &Tok) {
970 tok::OnOffSwitch OOS;
971 if (PP.LexOnOffSwitch(OOS))
972 return;
973 if (OOS == tok::OOS_ON)
974 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
978 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...".
979 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
980 PragmaSTDC_CX_LIMITED_RANGEHandler()
981 : PragmaHandler("CX_LIMITED_RANGE") {}
982 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
983 Token &Tok) {
984 tok::OnOffSwitch OOS;
985 PP.LexOnOffSwitch(OOS);
989 /// PragmaSTDC_UnknownHandler - "#pragma STDC ...".
990 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
991 PragmaSTDC_UnknownHandler() {}
992 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
993 Token &UnknownTok) {
994 // C99 6.10.6p2, unknown forms are not allowed.
995 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
999 } // end anonymous namespace
1002 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1003 /// #pragma GCC poison/system_header/dependency and #pragma once.
1004 void Preprocessor::RegisterBuiltinPragmas() {
1005 AddPragmaHandler(new PragmaOnceHandler());
1006 AddPragmaHandler(new PragmaMarkHandler());
1007 AddPragmaHandler(new PragmaPushMacroHandler());
1008 AddPragmaHandler(new PragmaPopMacroHandler());
1009 AddPragmaHandler(new PragmaMessageHandler());
1011 // #pragma GCC ...
1012 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1013 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1014 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1015 AddPragmaHandler("GCC", new PragmaDiagnosticHandler());
1016 // #pragma clang ...
1017 AddPragmaHandler("clang", new PragmaPoisonHandler());
1018 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1019 AddPragmaHandler("clang", new PragmaDebugHandler());
1020 AddPragmaHandler("clang", new PragmaDependencyHandler());
1021 AddPragmaHandler("clang", new PragmaDiagnosticHandler());
1023 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1024 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1025 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1027 // MS extensions.
1028 if (Features.Microsoft) {
1029 AddPragmaHandler(new PragmaCommentHandler());