llvm-project
2202 строки · 74.4 Кб
1//===- Pragma.cpp - Pragma registration and handling ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the PragmaHandler/PragmaTable interfaces and implements
10// pragma related methods of the Preprocessor class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Pragma.h"
15#include "clang/Basic/CLWarnings.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/IdentifierTable.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Basic/Module.h"
22#include "clang/Basic/SourceLocation.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/TokenKinds.h"
25#include "clang/Lex/HeaderSearch.h"
26#include "clang/Lex/LexDiagnostic.h"
27#include "clang/Lex/Lexer.h"
28#include "clang/Lex/LiteralSupport.h"
29#include "clang/Lex/MacroInfo.h"
30#include "clang/Lex/ModuleLoader.h"
31#include "clang/Lex/PPCallbacks.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Lex/PreprocessorLexer.h"
34#include "clang/Lex/PreprocessorOptions.h"
35#include "clang/Lex/Token.h"
36#include "clang/Lex/TokenLexer.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallString.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/Timer.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstdint>
50#include <limits>
51#include <optional>
52#include <string>
53#include <utility>
54#include <vector>
55
56using namespace clang;
57
58// Out-of-line destructor to provide a home for the class.
59PragmaHandler::~PragmaHandler() = default;
60
61//===----------------------------------------------------------------------===//
62// EmptyPragmaHandler Implementation.
63//===----------------------------------------------------------------------===//
64
65EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
66
67void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
68PragmaIntroducer Introducer,
69Token &FirstToken) {}
70
71//===----------------------------------------------------------------------===//
72// PragmaNamespace Implementation.
73//===----------------------------------------------------------------------===//
74
75/// FindHandler - Check to see if there is already a handler for the
76/// specified name. If not, return the handler for the null identifier if it
77/// exists, otherwise return null. If IgnoreNull is true (the default) then
78/// the null handler isn't returned on failure to match.
79PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
80bool IgnoreNull) const {
81auto I = Handlers.find(Name);
82if (I != Handlers.end())
83return I->getValue().get();
84if (IgnoreNull)
85return nullptr;
86I = Handlers.find(StringRef());
87if (I != Handlers.end())
88return I->getValue().get();
89return nullptr;
90}
91
92void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
93assert(!Handlers.count(Handler->getName()) &&
94"A handler with this name is already registered in this namespace");
95Handlers[Handler->getName()].reset(Handler);
96}
97
98void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
99auto I = Handlers.find(Handler->getName());
100assert(I != Handlers.end() &&
101"Handler not registered in this namespace");
102// Release ownership back to the caller.
103I->getValue().release();
104Handlers.erase(I);
105}
106
107void PragmaNamespace::HandlePragma(Preprocessor &PP,
108PragmaIntroducer Introducer, Token &Tok) {
109// Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
110// expand it, the user can have a STDC #define, that should not affect this.
111PP.LexUnexpandedToken(Tok);
112
113// Get the handler for this token. If there is no handler, ignore the pragma.
114PragmaHandler *Handler
115= FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
116: StringRef(),
117/*IgnoreNull=*/false);
118if (!Handler) {
119PP.Diag(Tok, diag::warn_pragma_ignored);
120return;
121}
122
123// Otherwise, pass it down.
124Handler->HandlePragma(PP, Introducer, Tok);
125}
126
127//===----------------------------------------------------------------------===//
128// Preprocessor Pragma Directive Handling.
129//===----------------------------------------------------------------------===//
130
131namespace {
132// TokenCollector provides the option to collect tokens that were "read"
133// and return them to the stream to be read later.
134// Currently used when reading _Pragma/__pragma directives.
135struct TokenCollector {
136Preprocessor &Self;
137bool Collect;
138SmallVector<Token, 3> Tokens;
139Token &Tok;
140
141void lex() {
142if (Collect)
143Tokens.push_back(Tok);
144Self.Lex(Tok);
145}
146
147void revert() {
148assert(Collect && "did not collect tokens");
149assert(!Tokens.empty() && "collected unexpected number of tokens");
150
151// Push the ( "string" ) tokens into the token stream.
152auto Toks = std::make_unique<Token[]>(Tokens.size());
153std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get());
154Toks[Tokens.size() - 1] = Tok;
155Self.EnterTokenStream(std::move(Toks), Tokens.size(),
156/*DisableMacroExpansion*/ true,
157/*IsReinject*/ true);
158
159// ... and return the pragma token unchanged.
160Tok = *Tokens.begin();
161}
162};
163} // namespace
164
165/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
166/// rest of the pragma, passing it to the registered pragma handlers.
167void Preprocessor::HandlePragmaDirective(PragmaIntroducer Introducer) {
168if (Callbacks)
169Callbacks->PragmaDirective(Introducer.Loc, Introducer.Kind);
170
171if (!PragmasEnabled)
172return;
173
174++NumPragma;
175
176// Invoke the first level of pragma handlers which reads the namespace id.
177Token Tok;
178PragmaHandlers->HandlePragma(*this, Introducer, Tok);
179
180// If the pragma handler didn't read the rest of the line, consume it now.
181if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
182|| (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
183DiscardUntilEndOfDirective();
184}
185
186/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
187/// return the first token after the directive. The _Pragma token has just
188/// been read into 'Tok'.
189void Preprocessor::Handle_Pragma(Token &Tok) {
190// C11 6.10.3.4/3:
191// all pragma unary operator expressions within [a completely
192// macro-replaced preprocessing token sequence] are [...] processed [after
193// rescanning is complete]
194//
195// This means that we execute _Pragma operators in two cases:
196//
197// 1) on token sequences that would otherwise be produced as the output of
198// phase 4 of preprocessing, and
199// 2) on token sequences formed as the macro-replaced token sequence of a
200// macro argument
201//
202// Case #2 appears to be a wording bug: only _Pragmas that would survive to
203// the end of phase 4 should actually be executed. Discussion on the WG14
204// mailing list suggests that a _Pragma operator is notionally checked early,
205// but only pragmas that survive to the end of phase 4 should be executed.
206//
207// In Case #2, we check the syntax now, but then put the tokens back into the
208// token stream for later consumption.
209
210TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
211
212// Remember the pragma token location.
213SourceLocation PragmaLoc = Tok.getLocation();
214
215// Read the '('.
216Toks.lex();
217if (Tok.isNot(tok::l_paren)) {
218Diag(PragmaLoc, diag::err__Pragma_malformed);
219return;
220}
221
222// Read the '"..."'.
223Toks.lex();
224if (!tok::isStringLiteral(Tok.getKind())) {
225Diag(PragmaLoc, diag::err__Pragma_malformed);
226// Skip bad tokens, and the ')', if present.
227if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
228Lex(Tok);
229while (Tok.isNot(tok::r_paren) &&
230!Tok.isAtStartOfLine() &&
231Tok.isNot(tok::eof))
232Lex(Tok);
233if (Tok.is(tok::r_paren))
234Lex(Tok);
235return;
236}
237
238if (Tok.hasUDSuffix()) {
239Diag(Tok, diag::err_invalid_string_udl);
240// Skip this token, and the ')', if present.
241Lex(Tok);
242if (Tok.is(tok::r_paren))
243Lex(Tok);
244return;
245}
246
247// Remember the string.
248Token StrTok = Tok;
249
250// Read the ')'.
251Toks.lex();
252if (Tok.isNot(tok::r_paren)) {
253Diag(PragmaLoc, diag::err__Pragma_malformed);
254return;
255}
256
257// If we're expanding a macro argument, put the tokens back.
258if (InMacroArgPreExpansion) {
259Toks.revert();
260return;
261}
262
263SourceLocation RParenLoc = Tok.getLocation();
264bool Invalid = false;
265SmallString<64> StrVal;
266StrVal.resize(StrTok.getLength());
267StringRef StrValRef = getSpelling(StrTok, StrVal, &Invalid);
268if (Invalid) {
269Diag(PragmaLoc, diag::err__Pragma_malformed);
270return;
271}
272
273assert(StrValRef.size() <= StrVal.size());
274
275// If the token was spelled somewhere else, copy it.
276if (StrValRef.begin() != StrVal.begin())
277StrVal.assign(StrValRef);
278// Truncate if necessary.
279else if (StrValRef.size() != StrVal.size())
280StrVal.resize(StrValRef.size());
281
282// The _Pragma is lexically sound. Destringize according to C11 6.10.9.1.
283prepare_PragmaString(StrVal);
284
285// Plop the string (including the newline and trailing null) into a buffer
286// where we can lex it.
287Token TmpTok;
288TmpTok.startToken();
289CreateString(StrVal, TmpTok);
290SourceLocation TokLoc = TmpTok.getLocation();
291
292// Make and enter a lexer object so that we lex and expand the tokens just
293// like any others.
294Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
295StrVal.size(), *this);
296
297EnterSourceFileWithLexer(TL, nullptr);
298
299// With everything set up, lex this as a #pragma directive.
300HandlePragmaDirective({PIK__Pragma, PragmaLoc});
301
302// Finally, return whatever came after the pragma directive.
303return Lex(Tok);
304}
305
306void clang::prepare_PragmaString(SmallVectorImpl<char> &StrVal) {
307if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
308(StrVal[0] == 'u' && StrVal[1] != '8'))
309StrVal.erase(StrVal.begin());
310else if (StrVal[0] == 'u')
311StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
312
313if (StrVal[0] == 'R') {
314// FIXME: C++11 does not specify how to handle raw-string-literals here.
315// We strip off the 'R', the quotes, the d-char-sequences, and the parens.
316assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
317"Invalid raw string token!");
318
319// Measure the length of the d-char-sequence.
320unsigned NumDChars = 0;
321while (StrVal[2 + NumDChars] != '(') {
322assert(NumDChars < (StrVal.size() - 5) / 2 &&
323"Invalid raw string token!");
324++NumDChars;
325}
326assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
327
328// Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
329// parens below.
330StrVal.erase(StrVal.begin(), StrVal.begin() + 2 + NumDChars);
331StrVal.erase(StrVal.end() - 1 - NumDChars, StrVal.end());
332} else {
333assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
334"Invalid string token!");
335
336// Remove escaped quotes and escapes.
337unsigned ResultPos = 1;
338for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
339// Skip escapes. \\ -> '\' and \" -> '"'.
340if (StrVal[i] == '\\' && i + 1 < e &&
341(StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
342++i;
343StrVal[ResultPos++] = StrVal[i];
344}
345StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
346}
347
348// Remove the front quote, replacing it with a space, so that the pragma
349// contents appear to have a space before them.
350StrVal[0] = ' ';
351
352// Replace the terminating quote with a \n.
353StrVal[StrVal.size() - 1] = '\n';
354}
355
356/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
357/// is not enclosed within a string literal.
358void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
359// During macro pre-expansion, check the syntax now but put the tokens back
360// into the token stream for later consumption. Same as Handle_Pragma.
361TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
362
363// Remember the pragma token location.
364SourceLocation PragmaLoc = Tok.getLocation();
365
366// Read the '('.
367Toks.lex();
368if (Tok.isNot(tok::l_paren)) {
369Diag(PragmaLoc, diag::err__Pragma_malformed);
370return;
371}
372
373// Get the tokens enclosed within the __pragma(), as well as the final ')'.
374SmallVector<Token, 32> PragmaToks;
375int NumParens = 0;
376Toks.lex();
377while (Tok.isNot(tok::eof)) {
378PragmaToks.push_back(Tok);
379if (Tok.is(tok::l_paren))
380NumParens++;
381else if (Tok.is(tok::r_paren) && NumParens-- == 0)
382break;
383Toks.lex();
384}
385
386if (Tok.is(tok::eof)) {
387Diag(PragmaLoc, diag::err_unterminated___pragma);
388return;
389}
390
391// If we're expanding a macro argument, put the tokens back.
392if (InMacroArgPreExpansion) {
393Toks.revert();
394return;
395}
396
397PragmaToks.front().setFlag(Token::LeadingSpace);
398
399// Replace the ')' with an EOD to mark the end of the pragma.
400PragmaToks.back().setKind(tok::eod);
401
402Token *TokArray = new Token[PragmaToks.size()];
403std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
404
405// Push the tokens onto the stack.
406EnterTokenStream(TokArray, PragmaToks.size(), true, true,
407/*IsReinject*/ false);
408
409// With everything set up, lex this as a #pragma directive.
410HandlePragmaDirective({PIK___pragma, PragmaLoc});
411
412// Finally, return whatever came after the pragma directive.
413return Lex(Tok);
414}
415
416/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
417void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
418// Don't honor the 'once' when handling the primary source file, unless
419// this is a prefix to a TU, which indicates we're generating a PCH file, or
420// when the main file is a header (e.g. when -xc-header is provided on the
421// commandline).
422if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
423Diag(OnceTok, diag::pp_pragma_once_in_main_file);
424return;
425}
426
427// Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
428// Mark the file as a once-only file now.
429HeaderInfo.MarkFileIncludeOnce(*getCurrentFileLexer()->getFileEntry());
430}
431
432void Preprocessor::HandlePragmaMark(Token &MarkTok) {
433assert(CurPPLexer && "No current lexer?");
434
435SmallString<64> Buffer;
436CurLexer->ReadToEndOfLine(&Buffer);
437if (Callbacks)
438Callbacks->PragmaMark(MarkTok.getLocation(), Buffer);
439}
440
441/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
442void Preprocessor::HandlePragmaPoison() {
443Token Tok;
444
445while (true) {
446// Read the next token to poison. While doing this, pretend that we are
447// skipping while reading the identifier to poison.
448// This avoids errors on code like:
449// #pragma GCC poison X
450// #pragma GCC poison X
451if (CurPPLexer) CurPPLexer->LexingRawMode = true;
452LexUnexpandedToken(Tok);
453if (CurPPLexer) CurPPLexer->LexingRawMode = false;
454
455// If we reached the end of line, we're done.
456if (Tok.is(tok::eod)) return;
457
458// Can only poison identifiers.
459if (Tok.isNot(tok::raw_identifier)) {
460Diag(Tok, diag::err_pp_invalid_poison);
461return;
462}
463
464// Look up the identifier info for the token. We disabled identifier lookup
465// by saying we're skipping contents, so we need to do this manually.
466IdentifierInfo *II = LookUpIdentifierInfo(Tok);
467
468// Already poisoned.
469if (II->isPoisoned()) continue;
470
471// If this is a macro identifier, emit a warning.
472if (isMacroDefined(II))
473Diag(Tok, diag::pp_poisoning_existing_macro);
474
475// Finally, poison it!
476II->setIsPoisoned();
477if (II->isFromAST())
478II->setChangedSinceDeserialization();
479}
480}
481
482/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
483/// that the whole directive has been parsed.
484void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
485if (isInPrimaryFile()) {
486Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
487return;
488}
489
490// Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
491PreprocessorLexer *TheLexer = getCurrentFileLexer();
492
493// Mark the file as a system header.
494HeaderInfo.MarkFileSystemHeader(*TheLexer->getFileEntry());
495
496PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
497if (PLoc.isInvalid())
498return;
499
500unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
501
502// Notify the client, if desired, that we are in a new source file.
503if (Callbacks)
504Callbacks->FileChanged(SysHeaderTok.getLocation(),
505PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
506
507// Emit a line marker. This will change any source locations from this point
508// forward to realize they are in a system header.
509// Create a line note with this information.
510SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
511FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
512SrcMgr::C_System);
513}
514
515/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
516void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
517Token FilenameTok;
518if (LexHeaderName(FilenameTok, /*AllowConcatenation*/false))
519return;
520
521// If the next token wasn't a header-name, diagnose the error.
522if (FilenameTok.isNot(tok::header_name)) {
523Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
524return;
525}
526
527// Reserve a buffer to get the spelling.
528SmallString<128> FilenameBuffer;
529bool Invalid = false;
530StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
531if (Invalid)
532return;
533
534bool isAngled =
535GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
536// If GetIncludeFilenameSpelling set the start ptr to null, there was an
537// error.
538if (Filename.empty())
539return;
540
541// Search include directories for this file.
542OptionalFileEntryRef File =
543LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
544nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
545if (!File) {
546if (!SuppressIncludeNotFoundError)
547Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
548return;
549}
550
551OptionalFileEntryRef CurFile = getCurrentFileLexer()->getFileEntry();
552
553// If this file is older than the file it depends on, emit a diagnostic.
554if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
555// Lex tokens at the end of the message and include them in the message.
556std::string Message;
557Lex(DependencyTok);
558while (DependencyTok.isNot(tok::eod)) {
559Message += getSpelling(DependencyTok) + " ";
560Lex(DependencyTok);
561}
562
563// Remove the trailing ' ' if present.
564if (!Message.empty())
565Message.erase(Message.end()-1);
566Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
567}
568}
569
570/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
571/// Return the IdentifierInfo* associated with the macro to push or pop.
572IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
573// Remember the pragma token location.
574Token PragmaTok = Tok;
575
576// Read the '('.
577Lex(Tok);
578if (Tok.isNot(tok::l_paren)) {
579Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
580<< getSpelling(PragmaTok);
581return nullptr;
582}
583
584// Read the macro name string.
585Lex(Tok);
586if (Tok.isNot(tok::string_literal)) {
587Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
588<< getSpelling(PragmaTok);
589return nullptr;
590}
591
592if (Tok.hasUDSuffix()) {
593Diag(Tok, diag::err_invalid_string_udl);
594return nullptr;
595}
596
597// Remember the macro string.
598std::string StrVal = getSpelling(Tok);
599
600// Read the ')'.
601Lex(Tok);
602if (Tok.isNot(tok::r_paren)) {
603Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
604<< getSpelling(PragmaTok);
605return nullptr;
606}
607
608assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
609"Invalid string token!");
610
611// Create a Token from the string.
612Token MacroTok;
613MacroTok.startToken();
614MacroTok.setKind(tok::raw_identifier);
615CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
616
617// Get the IdentifierInfo of MacroToPushTok.
618return LookUpIdentifierInfo(MacroTok);
619}
620
621/// Handle \#pragma push_macro.
622///
623/// The syntax is:
624/// \code
625/// #pragma push_macro("macro")
626/// \endcode
627void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
628// Parse the pragma directive and get the macro IdentifierInfo*.
629IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
630if (!IdentInfo) return;
631
632// Get the MacroInfo associated with IdentInfo.
633MacroInfo *MI = getMacroInfo(IdentInfo);
634
635if (MI) {
636// Allow the original MacroInfo to be redefined later.
637MI->setIsAllowRedefinitionsWithoutWarning(true);
638}
639
640// Push the cloned MacroInfo so we can retrieve it later.
641PragmaPushMacroInfo[IdentInfo].push_back(MI);
642}
643
644/// Handle \#pragma pop_macro.
645///
646/// The syntax is:
647/// \code
648/// #pragma pop_macro("macro")
649/// \endcode
650void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
651SourceLocation MessageLoc = PopMacroTok.getLocation();
652
653// Parse the pragma directive and get the macro IdentifierInfo*.
654IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
655if (!IdentInfo) return;
656
657// Find the vector<MacroInfo*> associated with the macro.
658llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
659PragmaPushMacroInfo.find(IdentInfo);
660if (iter != PragmaPushMacroInfo.end()) {
661// Forget the MacroInfo currently associated with IdentInfo.
662if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
663if (MI->isWarnIfUnused())
664WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
665appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
666}
667
668// Get the MacroInfo we want to reinstall.
669MacroInfo *MacroToReInstall = iter->second.back();
670
671if (MacroToReInstall)
672// Reinstall the previously pushed macro.
673appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
674
675// Pop PragmaPushMacroInfo stack.
676iter->second.pop_back();
677if (iter->second.empty())
678PragmaPushMacroInfo.erase(iter);
679} else {
680Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
681<< IdentInfo->getName();
682}
683}
684
685void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
686// We will either get a quoted filename or a bracketed filename, and we
687// have to track which we got. The first filename is the source name,
688// and the second name is the mapped filename. If the first is quoted,
689// the second must be as well (cannot mix and match quotes and brackets).
690
691// Get the open paren
692Lex(Tok);
693if (Tok.isNot(tok::l_paren)) {
694Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
695return;
696}
697
698// We expect either a quoted string literal, or a bracketed name
699Token SourceFilenameTok;
700if (LexHeaderName(SourceFilenameTok))
701return;
702
703StringRef SourceFileName;
704SmallString<128> FileNameBuffer;
705if (SourceFilenameTok.is(tok::header_name)) {
706SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
707} else {
708Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
709return;
710}
711FileNameBuffer.clear();
712
713// Now we expect a comma, followed by another include name
714Lex(Tok);
715if (Tok.isNot(tok::comma)) {
716Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
717return;
718}
719
720Token ReplaceFilenameTok;
721if (LexHeaderName(ReplaceFilenameTok))
722return;
723
724StringRef ReplaceFileName;
725if (ReplaceFilenameTok.is(tok::header_name)) {
726ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
727} else {
728Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
729return;
730}
731
732// Finally, we expect the closing paren
733Lex(Tok);
734if (Tok.isNot(tok::r_paren)) {
735Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
736return;
737}
738
739// Now that we have the source and target filenames, we need to make sure
740// they're both of the same type (angled vs non-angled)
741StringRef OriginalSource = SourceFileName;
742
743bool SourceIsAngled =
744GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
745SourceFileName);
746bool ReplaceIsAngled =
747GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
748ReplaceFileName);
749if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
750(SourceIsAngled != ReplaceIsAngled)) {
751unsigned int DiagID;
752if (SourceIsAngled)
753DiagID = diag::warn_pragma_include_alias_mismatch_angle;
754else
755DiagID = diag::warn_pragma_include_alias_mismatch_quote;
756
757Diag(SourceFilenameTok.getLocation(), DiagID)
758<< SourceFileName
759<< ReplaceFileName;
760
761return;
762}
763
764// Now we can let the include handler know about this mapping
765getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
766}
767
768// Lex a component of a module name: either an identifier or a string literal;
769// for components that can be expressed both ways, the two forms are equivalent.
770static bool LexModuleNameComponent(
771Preprocessor &PP, Token &Tok,
772std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
773bool First) {
774PP.LexUnexpandedToken(Tok);
775if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
776StringLiteralParser Literal(Tok, PP);
777if (Literal.hadError)
778return true;
779ModuleNameComponent = std::make_pair(
780PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
781} else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
782ModuleNameComponent =
783std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
784} else {
785PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
786return true;
787}
788return false;
789}
790
791static bool LexModuleName(
792Preprocessor &PP, Token &Tok,
793llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
794&ModuleName) {
795while (true) {
796std::pair<IdentifierInfo*, SourceLocation> NameComponent;
797if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
798return true;
799ModuleName.push_back(NameComponent);
800
801PP.LexUnexpandedToken(Tok);
802if (Tok.isNot(tok::period))
803return false;
804}
805}
806
807void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
808SourceLocation Loc = Tok.getLocation();
809
810std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
811if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
812return;
813IdentifierInfo *ModuleName = ModuleNameLoc.first;
814
815LexUnexpandedToken(Tok);
816if (Tok.isNot(tok::eod)) {
817Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
818DiscardUntilEndOfDirective();
819}
820
821CurLexer->LexingRawMode = true;
822
823auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
824if (Tok.getKind() != tok::raw_identifier ||
825Tok.getRawIdentifier() != Ident)
826return false;
827CurLexer->Lex(Tok);
828return true;
829};
830
831// Scan forward looking for the end of the module.
832const char *Start = CurLexer->getBufferLocation();
833const char *End = nullptr;
834unsigned NestingLevel = 1;
835while (true) {
836End = CurLexer->getBufferLocation();
837CurLexer->Lex(Tok);
838
839if (Tok.is(tok::eof)) {
840Diag(Loc, diag::err_pp_module_build_missing_end);
841break;
842}
843
844if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
845// Token was part of module; keep going.
846continue;
847}
848
849// We hit something directive-shaped; check to see if this is the end
850// of the module build.
851CurLexer->ParsingPreprocessorDirective = true;
852CurLexer->Lex(Tok);
853if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
854TryConsumeIdentifier("module")) {
855if (TryConsumeIdentifier("build"))
856// #pragma clang module build -> entering a nested module build.
857++NestingLevel;
858else if (TryConsumeIdentifier("endbuild")) {
859// #pragma clang module endbuild -> leaving a module build.
860if (--NestingLevel == 0)
861break;
862}
863// We should either be looking at the EOD or more of the current directive
864// preceding the EOD. Either way we can ignore this token and keep going.
865assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
866}
867}
868
869CurLexer->LexingRawMode = false;
870
871// Load the extracted text as a preprocessed module.
872assert(CurLexer->getBuffer().begin() <= Start &&
873Start <= CurLexer->getBuffer().end() &&
874CurLexer->getBuffer().begin() <= End &&
875End <= CurLexer->getBuffer().end() &&
876"module source range not contained within same file buffer");
877TheModuleLoader.createModuleFromSource(Loc, ModuleName->getName(),
878StringRef(Start, End - Start));
879}
880
881void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
882Lex(Tok);
883if (Tok.is(tok::l_paren)) {
884Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
885
886std::string FileName;
887if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
888return;
889
890if (Tok.isNot(tok::r_paren)) {
891Diag(Tok, diag::err_expected) << tok::r_paren;
892return;
893}
894Lex(Tok);
895}
896if (Tok.isNot(tok::eod))
897Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
898<< "pragma hdrstop";
899
900if (creatingPCHWithPragmaHdrStop() &&
901SourceMgr.isInMainFile(Tok.getLocation())) {
902assert(CurLexer && "no lexer for #pragma hdrstop processing");
903Token &Result = Tok;
904Result.startToken();
905CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
906CurLexer->cutOffLexing();
907}
908if (usingPCHWithPragmaHdrStop())
909SkippingUntilPragmaHdrStop = false;
910}
911
912/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
913/// If 'Namespace' is non-null, then it is a token required to exist on the
914/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
915void Preprocessor::AddPragmaHandler(StringRef Namespace,
916PragmaHandler *Handler) {
917PragmaNamespace *InsertNS = PragmaHandlers.get();
918
919// If this is specified to be in a namespace, step down into it.
920if (!Namespace.empty()) {
921// If there is already a pragma handler with the name of this namespace,
922// we either have an error (directive with the same name as a namespace) or
923// we already have the namespace to insert into.
924if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
925InsertNS = Existing->getIfNamespace();
926assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
927" handler with the same name!");
928} else {
929// Otherwise, this namespace doesn't exist yet, create and insert the
930// handler for it.
931InsertNS = new PragmaNamespace(Namespace);
932PragmaHandlers->AddPragma(InsertNS);
933}
934}
935
936// Check to make sure we don't already have a pragma for this identifier.
937assert(!InsertNS->FindHandler(Handler->getName()) &&
938"Pragma handler already exists for this identifier!");
939InsertNS->AddPragma(Handler);
940}
941
942/// RemovePragmaHandler - Remove the specific pragma handler from the
943/// preprocessor. If \arg Namespace is non-null, then it should be the
944/// namespace that \arg Handler was added to. It is an error to remove
945/// a handler that has not been registered.
946void Preprocessor::RemovePragmaHandler(StringRef Namespace,
947PragmaHandler *Handler) {
948PragmaNamespace *NS = PragmaHandlers.get();
949
950// If this is specified to be in a namespace, step down into it.
951if (!Namespace.empty()) {
952PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
953assert(Existing && "Namespace containing handler does not exist!");
954
955NS = Existing->getIfNamespace();
956assert(NS && "Invalid namespace, registered as a regular pragma handler!");
957}
958
959NS->RemovePragmaHandler(Handler);
960
961// If this is a non-default namespace and it is now empty, remove it.
962if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
963PragmaHandlers->RemovePragmaHandler(NS);
964delete NS;
965}
966}
967
968bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
969Token Tok;
970LexUnexpandedToken(Tok);
971
972if (Tok.isNot(tok::identifier)) {
973Diag(Tok, diag::ext_on_off_switch_syntax);
974return true;
975}
976IdentifierInfo *II = Tok.getIdentifierInfo();
977if (II->isStr("ON"))
978Result = tok::OOS_ON;
979else if (II->isStr("OFF"))
980Result = tok::OOS_OFF;
981else if (II->isStr("DEFAULT"))
982Result = tok::OOS_DEFAULT;
983else {
984Diag(Tok, diag::ext_on_off_switch_syntax);
985return true;
986}
987
988// Verify that this is followed by EOD.
989LexUnexpandedToken(Tok);
990if (Tok.isNot(tok::eod))
991Diag(Tok, diag::ext_pragma_syntax_eod);
992return false;
993}
994
995namespace {
996
997/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
998struct PragmaOnceHandler : public PragmaHandler {
999PragmaOnceHandler() : PragmaHandler("once") {}
1000
1001void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1002Token &OnceTok) override {
1003PP.CheckEndOfDirective("pragma once");
1004PP.HandlePragmaOnce(OnceTok);
1005}
1006};
1007
1008/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
1009/// rest of the line is not lexed.
1010struct PragmaMarkHandler : public PragmaHandler {
1011PragmaMarkHandler() : PragmaHandler("mark") {}
1012
1013void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1014Token &MarkTok) override {
1015PP.HandlePragmaMark(MarkTok);
1016}
1017};
1018
1019/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
1020struct PragmaPoisonHandler : public PragmaHandler {
1021PragmaPoisonHandler() : PragmaHandler("poison") {}
1022
1023void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1024Token &PoisonTok) override {
1025PP.HandlePragmaPoison();
1026}
1027};
1028
1029/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
1030/// as a system header, which silences warnings in it.
1031struct PragmaSystemHeaderHandler : public PragmaHandler {
1032PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
1033
1034void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1035Token &SHToken) override {
1036PP.HandlePragmaSystemHeader(SHToken);
1037PP.CheckEndOfDirective("pragma");
1038}
1039};
1040
1041struct PragmaDependencyHandler : public PragmaHandler {
1042PragmaDependencyHandler() : PragmaHandler("dependency") {}
1043
1044void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1045Token &DepToken) override {
1046PP.HandlePragmaDependency(DepToken);
1047}
1048};
1049
1050struct PragmaDebugHandler : public PragmaHandler {
1051PragmaDebugHandler() : PragmaHandler("__debug") {}
1052
1053void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1054Token &DebugToken) override {
1055Token Tok;
1056PP.LexUnexpandedToken(Tok);
1057if (Tok.isNot(tok::identifier)) {
1058PP.Diag(Tok, diag::warn_pragma_debug_missing_command);
1059return;
1060}
1061IdentifierInfo *II = Tok.getIdentifierInfo();
1062
1063if (II->isStr("assert")) {
1064if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1065llvm_unreachable("This is an assertion!");
1066} else if (II->isStr("crash")) {
1067llvm::Timer T("crash", "pragma crash");
1068llvm::TimeRegion R(&T);
1069if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1070LLVM_BUILTIN_TRAP;
1071} else if (II->isStr("parser_crash")) {
1072if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash) {
1073Token Crasher;
1074Crasher.startToken();
1075Crasher.setKind(tok::annot_pragma_parser_crash);
1076Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
1077PP.EnterToken(Crasher, /*IsReinject*/ false);
1078}
1079} else if (II->isStr("dump")) {
1080Token DumpAnnot;
1081DumpAnnot.startToken();
1082DumpAnnot.setKind(tok::annot_pragma_dump);
1083DumpAnnot.setAnnotationRange(SourceRange(Tok.getLocation()));
1084PP.EnterToken(DumpAnnot, /*IsReinject*/false);
1085} else if (II->isStr("diag_mapping")) {
1086Token DiagName;
1087PP.LexUnexpandedToken(DiagName);
1088if (DiagName.is(tok::eod))
1089PP.getDiagnostics().dump();
1090else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1091StringLiteralParser Literal(DiagName, PP,
1092StringLiteralEvalMethod::Unevaluated);
1093if (Literal.hadError)
1094return;
1095PP.getDiagnostics().dump(Literal.GetString());
1096} else {
1097PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1098<< II->getName();
1099}
1100} else if (II->isStr("llvm_fatal_error")) {
1101if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1102llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1103} else if (II->isStr("llvm_unreachable")) {
1104if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1105llvm_unreachable("#pragma clang __debug llvm_unreachable");
1106} else if (II->isStr("macro")) {
1107Token MacroName;
1108PP.LexUnexpandedToken(MacroName);
1109auto *MacroII = MacroName.getIdentifierInfo();
1110if (MacroII)
1111PP.dumpMacroInfo(MacroII);
1112else
1113PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1114<< II->getName();
1115} else if (II->isStr("module_map")) {
1116llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1117ModuleName;
1118if (LexModuleName(PP, Tok, ModuleName))
1119return;
1120ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
1121Module *M = nullptr;
1122for (auto IIAndLoc : ModuleName) {
1123M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
1124if (!M) {
1125PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module)
1126<< IIAndLoc.first;
1127return;
1128}
1129}
1130M->dump();
1131} else if (II->isStr("overflow_stack")) {
1132if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1133DebugOverflowStack();
1134} else if (II->isStr("captured")) {
1135HandleCaptured(PP);
1136} else if (II->isStr("modules")) {
1137struct ModuleVisitor {
1138Preprocessor &PP;
1139void visit(Module *M, bool VisibleOnly) {
1140SourceLocation ImportLoc = PP.getModuleImportLoc(M);
1141if (!VisibleOnly || ImportLoc.isValid()) {
1142llvm::errs() << M->getFullModuleName() << " ";
1143if (ImportLoc.isValid()) {
1144llvm::errs() << M << " visible ";
1145ImportLoc.print(llvm::errs(), PP.getSourceManager());
1146}
1147llvm::errs() << "\n";
1148}
1149for (Module *Sub : M->submodules()) {
1150if (!VisibleOnly || ImportLoc.isInvalid() || Sub->IsExplicit)
1151visit(Sub, VisibleOnly);
1152}
1153}
1154void visitAll(bool VisibleOnly) {
1155for (auto &NameAndMod :
1156PP.getHeaderSearchInfo().getModuleMap().modules())
1157visit(NameAndMod.second, VisibleOnly);
1158}
1159} Visitor{PP};
1160
1161Token Kind;
1162PP.LexUnexpandedToken(Kind);
1163auto *DumpII = Kind.getIdentifierInfo();
1164if (!DumpII) {
1165PP.Diag(Kind, diag::warn_pragma_debug_missing_argument)
1166<< II->getName();
1167} else if (DumpII->isStr("all")) {
1168Visitor.visitAll(false);
1169} else if (DumpII->isStr("visible")) {
1170Visitor.visitAll(true);
1171} else if (DumpII->isStr("building")) {
1172for (auto &Building : PP.getBuildingSubmodules()) {
1173llvm::errs() << "in " << Building.M->getFullModuleName();
1174if (Building.ImportLoc.isValid()) {
1175llvm::errs() << " imported ";
1176if (Building.IsPragma)
1177llvm::errs() << "via pragma ";
1178llvm::errs() << "at ";
1179Building.ImportLoc.print(llvm::errs(), PP.getSourceManager());
1180llvm::errs() << "\n";
1181}
1182}
1183} else {
1184PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1185<< DumpII->getName();
1186}
1187} else if (II->isStr("sloc_usage")) {
1188// An optional integer literal argument specifies the number of files to
1189// specifically report information about.
1190std::optional<unsigned> MaxNotes;
1191Token ArgToken;
1192PP.Lex(ArgToken);
1193uint64_t Value;
1194if (ArgToken.is(tok::numeric_constant) &&
1195PP.parseSimpleIntegerLiteral(ArgToken, Value)) {
1196MaxNotes = Value;
1197} else if (ArgToken.isNot(tok::eod)) {
1198PP.Diag(ArgToken, diag::warn_pragma_debug_unexpected_argument);
1199}
1200
1201PP.Diag(Tok, diag::remark_sloc_usage);
1202PP.getSourceManager().noteSLocAddressSpaceUsage(PP.getDiagnostics(),
1203MaxNotes);
1204} else {
1205PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1206<< II->getName();
1207}
1208
1209PPCallbacks *Callbacks = PP.getPPCallbacks();
1210if (Callbacks)
1211Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1212}
1213
1214void HandleCaptured(Preprocessor &PP) {
1215Token Tok;
1216PP.LexUnexpandedToken(Tok);
1217
1218if (Tok.isNot(tok::eod)) {
1219PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1220<< "pragma clang __debug captured";
1221return;
1222}
1223
1224SourceLocation NameLoc = Tok.getLocation();
1225MutableArrayRef<Token> Toks(
1226PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1227Toks[0].startToken();
1228Toks[0].setKind(tok::annot_pragma_captured);
1229Toks[0].setLocation(NameLoc);
1230
1231PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1232/*IsReinject=*/false);
1233}
1234
1235// Disable MSVC warning about runtime stack overflow.
1236#ifdef _MSC_VER
1237#pragma warning(disable : 4717)
1238#endif
1239static void DebugOverflowStack(void (*P)() = nullptr) {
1240void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1241Self(reinterpret_cast<void(*)()>(Self));
1242}
1243#ifdef _MSC_VER
1244#pragma warning(default : 4717)
1245#endif
1246};
1247
1248struct PragmaUnsafeBufferUsageHandler : public PragmaHandler {
1249PragmaUnsafeBufferUsageHandler() : PragmaHandler("unsafe_buffer_usage") {}
1250void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1251Token &FirstToken) override {
1252Token Tok;
1253
1254PP.LexUnexpandedToken(Tok);
1255if (Tok.isNot(tok::identifier)) {
1256PP.Diag(Tok, diag::err_pp_pragma_unsafe_buffer_usage_syntax);
1257return;
1258}
1259
1260IdentifierInfo *II = Tok.getIdentifierInfo();
1261SourceLocation Loc = Tok.getLocation();
1262
1263if (II->isStr("begin")) {
1264if (PP.enterOrExitSafeBufferOptOutRegion(true, Loc))
1265PP.Diag(Loc, diag::err_pp_double_begin_pragma_unsafe_buffer_usage);
1266} else if (II->isStr("end")) {
1267if (PP.enterOrExitSafeBufferOptOutRegion(false, Loc))
1268PP.Diag(Loc, diag::err_pp_unmatched_end_begin_pragma_unsafe_buffer_usage);
1269} else
1270PP.Diag(Tok, diag::err_pp_pragma_unsafe_buffer_usage_syntax);
1271}
1272};
1273
1274/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
1275struct PragmaDiagnosticHandler : public PragmaHandler {
1276private:
1277const char *Namespace;
1278
1279public:
1280explicit PragmaDiagnosticHandler(const char *NS)
1281: PragmaHandler("diagnostic"), Namespace(NS) {}
1282
1283void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1284Token &DiagToken) override {
1285SourceLocation DiagLoc = DiagToken.getLocation();
1286Token Tok;
1287PP.LexUnexpandedToken(Tok);
1288if (Tok.isNot(tok::identifier)) {
1289PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1290return;
1291}
1292IdentifierInfo *II = Tok.getIdentifierInfo();
1293PPCallbacks *Callbacks = PP.getPPCallbacks();
1294
1295// Get the next token, which is either an EOD or a string literal. We lex
1296// it now so that we can early return if the previous token was push or pop.
1297PP.LexUnexpandedToken(Tok);
1298
1299if (II->isStr("pop")) {
1300if (!PP.getDiagnostics().popMappings(DiagLoc))
1301PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1302else if (Callbacks)
1303Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1304
1305if (Tok.isNot(tok::eod))
1306PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1307return;
1308} else if (II->isStr("push")) {
1309PP.getDiagnostics().pushMappings(DiagLoc);
1310if (Callbacks)
1311Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1312
1313if (Tok.isNot(tok::eod))
1314PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1315return;
1316}
1317
1318diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1319.Case("ignored", diag::Severity::Ignored)
1320.Case("warning", diag::Severity::Warning)
1321.Case("error", diag::Severity::Error)
1322.Case("fatal", diag::Severity::Fatal)
1323.Default(diag::Severity());
1324
1325if (SV == diag::Severity()) {
1326PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1327return;
1328}
1329
1330// At this point, we expect a string literal.
1331SourceLocation StringLoc = Tok.getLocation();
1332std::string WarningName;
1333if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1334/*AllowMacroExpansion=*/false))
1335return;
1336
1337if (Tok.isNot(tok::eod)) {
1338PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1339return;
1340}
1341
1342if (WarningName.size() < 3 || WarningName[0] != '-' ||
1343(WarningName[1] != 'W' && WarningName[1] != 'R')) {
1344PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1345return;
1346}
1347
1348diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1349: diag::Flavor::Remark;
1350StringRef Group = StringRef(WarningName).substr(2);
1351bool unknownDiag = false;
1352if (Group == "everything") {
1353// Special handling for pragma clang diagnostic ... "-Weverything".
1354// There is no formal group named "everything", so there has to be a
1355// special case for it.
1356PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1357} else
1358unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1359DiagLoc);
1360if (unknownDiag)
1361PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1362<< WarningName;
1363else if (Callbacks)
1364Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1365}
1366};
1367
1368/// "\#pragma hdrstop [<header-name-string>]"
1369struct PragmaHdrstopHandler : public PragmaHandler {
1370PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1371void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1372Token &DepToken) override {
1373PP.HandlePragmaHdrstop(DepToken);
1374}
1375};
1376
1377/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1378/// diagnostics, so we don't really implement this pragma. We parse it and
1379/// ignore it to avoid -Wunknown-pragma warnings.
1380struct PragmaWarningHandler : public PragmaHandler {
1381PragmaWarningHandler() : PragmaHandler("warning") {}
1382
1383void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1384Token &Tok) override {
1385// Parse things like:
1386// warning(push, 1)
1387// warning(pop)
1388// warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1389SourceLocation DiagLoc = Tok.getLocation();
1390PPCallbacks *Callbacks = PP.getPPCallbacks();
1391
1392PP.Lex(Tok);
1393if (Tok.isNot(tok::l_paren)) {
1394PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1395return;
1396}
1397
1398PP.Lex(Tok);
1399IdentifierInfo *II = Tok.getIdentifierInfo();
1400
1401if (II && II->isStr("push")) {
1402// #pragma warning( push[ ,n ] )
1403int Level = -1;
1404PP.Lex(Tok);
1405if (Tok.is(tok::comma)) {
1406PP.Lex(Tok);
1407uint64_t Value;
1408if (Tok.is(tok::numeric_constant) &&
1409PP.parseSimpleIntegerLiteral(Tok, Value))
1410Level = int(Value);
1411if (Level < 0 || Level > 4) {
1412PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1413return;
1414}
1415}
1416PP.getDiagnostics().pushMappings(DiagLoc);
1417if (Callbacks)
1418Callbacks->PragmaWarningPush(DiagLoc, Level);
1419} else if (II && II->isStr("pop")) {
1420// #pragma warning( pop )
1421PP.Lex(Tok);
1422if (!PP.getDiagnostics().popMappings(DiagLoc))
1423PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1424else if (Callbacks)
1425Callbacks->PragmaWarningPop(DiagLoc);
1426} else {
1427// #pragma warning( warning-specifier : warning-number-list
1428// [; warning-specifier : warning-number-list...] )
1429while (true) {
1430II = Tok.getIdentifierInfo();
1431if (!II && !Tok.is(tok::numeric_constant)) {
1432PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1433return;
1434}
1435
1436// Figure out which warning specifier this is.
1437bool SpecifierValid;
1438PPCallbacks::PragmaWarningSpecifier Specifier;
1439if (II) {
1440int SpecifierInt = llvm::StringSwitch<int>(II->getName())
1441.Case("default", PPCallbacks::PWS_Default)
1442.Case("disable", PPCallbacks::PWS_Disable)
1443.Case("error", PPCallbacks::PWS_Error)
1444.Case("once", PPCallbacks::PWS_Once)
1445.Case("suppress", PPCallbacks::PWS_Suppress)
1446.Default(-1);
1447SpecifierValid = SpecifierInt != -1;
1448if (SpecifierValid)
1449Specifier =
1450static_cast<PPCallbacks::PragmaWarningSpecifier>(SpecifierInt);
1451
1452// If we read a correct specifier, snatch next token (that should be
1453// ":", checked later).
1454if (SpecifierValid)
1455PP.Lex(Tok);
1456} else {
1457// Token is a numeric constant. It should be either 1, 2, 3 or 4.
1458uint64_t Value;
1459if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1460if ((SpecifierValid = (Value >= 1) && (Value <= 4)))
1461Specifier = static_cast<PPCallbacks::PragmaWarningSpecifier>(
1462PPCallbacks::PWS_Level1 + Value - 1);
1463} else
1464SpecifierValid = false;
1465// Next token already snatched by parseSimpleIntegerLiteral.
1466}
1467
1468if (!SpecifierValid) {
1469PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1470return;
1471}
1472if (Tok.isNot(tok::colon)) {
1473PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1474return;
1475}
1476
1477// Collect the warning ids.
1478SmallVector<int, 4> Ids;
1479PP.Lex(Tok);
1480while (Tok.is(tok::numeric_constant)) {
1481uint64_t Value;
1482if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1483Value > INT_MAX) {
1484PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1485return;
1486}
1487Ids.push_back(int(Value));
1488}
1489
1490// Only act on disable for now.
1491diag::Severity SV = diag::Severity();
1492if (Specifier == PPCallbacks::PWS_Disable)
1493SV = diag::Severity::Ignored;
1494if (SV != diag::Severity())
1495for (int Id : Ids) {
1496if (auto Group = diagGroupFromCLWarningID(Id)) {
1497bool unknownDiag = PP.getDiagnostics().setSeverityForGroup(
1498diag::Flavor::WarningOrError, *Group, SV, DiagLoc);
1499assert(!unknownDiag &&
1500"wd table should only contain known diags");
1501(void)unknownDiag;
1502}
1503}
1504
1505if (Callbacks)
1506Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1507
1508// Parse the next specifier if there is a semicolon.
1509if (Tok.isNot(tok::semi))
1510break;
1511PP.Lex(Tok);
1512}
1513}
1514
1515if (Tok.isNot(tok::r_paren)) {
1516PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1517return;
1518}
1519
1520PP.Lex(Tok);
1521if (Tok.isNot(tok::eod))
1522PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1523}
1524};
1525
1526/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1527/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1528/// otherwise to avoid -Wunknown-pragma warnings.
1529struct PragmaExecCharsetHandler : public PragmaHandler {
1530PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1531
1532void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1533Token &Tok) override {
1534// Parse things like:
1535// execution_character_set(push, "UTF-8")
1536// execution_character_set(pop)
1537SourceLocation DiagLoc = Tok.getLocation();
1538PPCallbacks *Callbacks = PP.getPPCallbacks();
1539
1540PP.Lex(Tok);
1541if (Tok.isNot(tok::l_paren)) {
1542PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1543return;
1544}
1545
1546PP.Lex(Tok);
1547IdentifierInfo *II = Tok.getIdentifierInfo();
1548
1549if (II && II->isStr("push")) {
1550// #pragma execution_character_set( push[ , string ] )
1551PP.Lex(Tok);
1552if (Tok.is(tok::comma)) {
1553PP.Lex(Tok);
1554
1555std::string ExecCharset;
1556if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1557"pragma execution_character_set",
1558/*AllowMacroExpansion=*/false))
1559return;
1560
1561// MSVC supports either of these, but nothing else.
1562if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
1563PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1564return;
1565}
1566}
1567if (Callbacks)
1568Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1569} else if (II && II->isStr("pop")) {
1570// #pragma execution_character_set( pop )
1571PP.Lex(Tok);
1572if (Callbacks)
1573Callbacks->PragmaExecCharsetPop(DiagLoc);
1574} else {
1575PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1576return;
1577}
1578
1579if (Tok.isNot(tok::r_paren)) {
1580PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1581return;
1582}
1583
1584PP.Lex(Tok);
1585if (Tok.isNot(tok::eod))
1586PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1587}
1588};
1589
1590/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1591struct PragmaIncludeAliasHandler : public PragmaHandler {
1592PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1593
1594void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1595Token &IncludeAliasTok) override {
1596PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1597}
1598};
1599
1600/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1601/// extension. The syntax is:
1602/// \code
1603/// #pragma message(string)
1604/// \endcode
1605/// OR, in GCC mode:
1606/// \code
1607/// #pragma message string
1608/// \endcode
1609/// string is a string, which is fully macro expanded, and permits string
1610/// concatenation, embedded escape characters, etc... See MSDN for more details.
1611/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1612/// form as \#pragma message.
1613struct PragmaMessageHandler : public PragmaHandler {
1614private:
1615const PPCallbacks::PragmaMessageKind Kind;
1616const StringRef Namespace;
1617
1618static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1619bool PragmaNameOnly = false) {
1620switch (Kind) {
1621case PPCallbacks::PMK_Message:
1622return PragmaNameOnly ? "message" : "pragma message";
1623case PPCallbacks::PMK_Warning:
1624return PragmaNameOnly ? "warning" : "pragma warning";
1625case PPCallbacks::PMK_Error:
1626return PragmaNameOnly ? "error" : "pragma error";
1627}
1628llvm_unreachable("Unknown PragmaMessageKind!");
1629}
1630
1631public:
1632PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1633StringRef Namespace = StringRef())
1634: PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1635Namespace(Namespace) {}
1636
1637void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1638Token &Tok) override {
1639SourceLocation MessageLoc = Tok.getLocation();
1640PP.Lex(Tok);
1641bool ExpectClosingParen = false;
1642switch (Tok.getKind()) {
1643case tok::l_paren:
1644// We have a MSVC style pragma message.
1645ExpectClosingParen = true;
1646// Read the string.
1647PP.Lex(Tok);
1648break;
1649case tok::string_literal:
1650// We have a GCC style pragma message, and we just read the string.
1651break;
1652default:
1653PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1654return;
1655}
1656
1657std::string MessageString;
1658if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1659/*AllowMacroExpansion=*/true))
1660return;
1661
1662if (ExpectClosingParen) {
1663if (Tok.isNot(tok::r_paren)) {
1664PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1665return;
1666}
1667PP.Lex(Tok); // eat the r_paren.
1668}
1669
1670if (Tok.isNot(tok::eod)) {
1671PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1672return;
1673}
1674
1675// Output the message.
1676PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1677? diag::err_pragma_message
1678: diag::warn_pragma_message) << MessageString;
1679
1680// If the pragma is lexically sound, notify any interested PPCallbacks.
1681if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1682Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1683}
1684};
1685
1686/// Handle the clang \#pragma module import extension. The syntax is:
1687/// \code
1688/// #pragma clang module import some.module.name
1689/// \endcode
1690struct PragmaModuleImportHandler : public PragmaHandler {
1691PragmaModuleImportHandler() : PragmaHandler("import") {}
1692
1693void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1694Token &Tok) override {
1695SourceLocation ImportLoc = Tok.getLocation();
1696
1697// Read the module name.
1698llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1699ModuleName;
1700if (LexModuleName(PP, Tok, ModuleName))
1701return;
1702
1703if (Tok.isNot(tok::eod))
1704PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1705
1706// If we have a non-empty module path, load the named module.
1707Module *Imported =
1708PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1709/*IsInclusionDirective=*/false);
1710if (!Imported)
1711return;
1712
1713PP.makeModuleVisible(Imported, ImportLoc);
1714PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1715tok::annot_module_include, Imported);
1716if (auto *CB = PP.getPPCallbacks())
1717CB->moduleImport(ImportLoc, ModuleName, Imported);
1718}
1719};
1720
1721/// Handle the clang \#pragma module begin extension. The syntax is:
1722/// \code
1723/// #pragma clang module begin some.module.name
1724/// ...
1725/// #pragma clang module end
1726/// \endcode
1727struct PragmaModuleBeginHandler : public PragmaHandler {
1728PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1729
1730void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1731Token &Tok) override {
1732SourceLocation BeginLoc = Tok.getLocation();
1733
1734// Read the module name.
1735llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1736ModuleName;
1737if (LexModuleName(PP, Tok, ModuleName))
1738return;
1739
1740if (Tok.isNot(tok::eod))
1741PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1742
1743// We can only enter submodules of the current module.
1744StringRef Current = PP.getLangOpts().CurrentModule;
1745if (ModuleName.front().first->getName() != Current) {
1746PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1747<< ModuleName.front().first << (ModuleName.size() > 1)
1748<< Current.empty() << Current;
1749return;
1750}
1751
1752// Find the module we're entering. We require that a module map for it
1753// be loaded or implicitly loadable.
1754auto &HSI = PP.getHeaderSearchInfo();
1755Module *M = HSI.lookupModule(Current, ModuleName.front().second);
1756if (!M) {
1757PP.Diag(ModuleName.front().second,
1758diag::err_pp_module_begin_no_module_map) << Current;
1759return;
1760}
1761for (unsigned I = 1; I != ModuleName.size(); ++I) {
1762auto *NewM = M->findOrInferSubmodule(ModuleName[I].first->getName());
1763if (!NewM) {
1764PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1765<< M->getFullModuleName() << ModuleName[I].first;
1766return;
1767}
1768M = NewM;
1769}
1770
1771// If the module isn't available, it doesn't make sense to enter it.
1772if (Preprocessor::checkModuleIsAvailable(
1773PP.getLangOpts(), PP.getTargetInfo(), *M, PP.getDiagnostics())) {
1774PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1775<< M->getTopLevelModuleName();
1776return;
1777}
1778
1779// Enter the scope of the submodule.
1780PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1781PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1782tok::annot_module_begin, M);
1783}
1784};
1785
1786/// Handle the clang \#pragma module end extension.
1787struct PragmaModuleEndHandler : public PragmaHandler {
1788PragmaModuleEndHandler() : PragmaHandler("end") {}
1789
1790void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1791Token &Tok) override {
1792SourceLocation Loc = Tok.getLocation();
1793
1794PP.LexUnexpandedToken(Tok);
1795if (Tok.isNot(tok::eod))
1796PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1797
1798Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1799if (M)
1800PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1801else
1802PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
1803}
1804};
1805
1806/// Handle the clang \#pragma module build extension.
1807struct PragmaModuleBuildHandler : public PragmaHandler {
1808PragmaModuleBuildHandler() : PragmaHandler("build") {}
1809
1810void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1811Token &Tok) override {
1812PP.HandlePragmaModuleBuild(Tok);
1813}
1814};
1815
1816/// Handle the clang \#pragma module load extension.
1817struct PragmaModuleLoadHandler : public PragmaHandler {
1818PragmaModuleLoadHandler() : PragmaHandler("load") {}
1819
1820void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1821Token &Tok) override {
1822SourceLocation Loc = Tok.getLocation();
1823
1824// Read the module name.
1825llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1826ModuleName;
1827if (LexModuleName(PP, Tok, ModuleName))
1828return;
1829
1830if (Tok.isNot(tok::eod))
1831PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1832
1833// Load the module, don't make it visible.
1834PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1835/*IsInclusionDirective=*/false);
1836}
1837};
1838
1839/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1840/// macro on the top of the stack.
1841struct PragmaPushMacroHandler : public PragmaHandler {
1842PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1843
1844void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1845Token &PushMacroTok) override {
1846PP.HandlePragmaPushMacro(PushMacroTok);
1847}
1848};
1849
1850/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1851/// macro to the value on the top of the stack.
1852struct PragmaPopMacroHandler : public PragmaHandler {
1853PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1854
1855void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1856Token &PopMacroTok) override {
1857PP.HandlePragmaPopMacro(PopMacroTok);
1858}
1859};
1860
1861/// PragmaARCCFCodeAuditedHandler -
1862/// \#pragma clang arc_cf_code_audited begin/end
1863struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1864PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1865
1866void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1867Token &NameTok) override {
1868SourceLocation Loc = NameTok.getLocation();
1869bool IsBegin;
1870
1871Token Tok;
1872
1873// Lex the 'begin' or 'end'.
1874PP.LexUnexpandedToken(Tok);
1875const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1876if (BeginEnd && BeginEnd->isStr("begin")) {
1877IsBegin = true;
1878} else if (BeginEnd && BeginEnd->isStr("end")) {
1879IsBegin = false;
1880} else {
1881PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1882return;
1883}
1884
1885// Verify that this is followed by EOD.
1886PP.LexUnexpandedToken(Tok);
1887if (Tok.isNot(tok::eod))
1888PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1889
1890// The start location of the active audit.
1891SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedInfo().second;
1892
1893// The start location we want after processing this.
1894SourceLocation NewLoc;
1895
1896if (IsBegin) {
1897// Complain about attempts to re-enter an audit.
1898if (BeginLoc.isValid()) {
1899PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1900PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1901}
1902NewLoc = Loc;
1903} else {
1904// Complain about attempts to leave an audit that doesn't exist.
1905if (!BeginLoc.isValid()) {
1906PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1907return;
1908}
1909NewLoc = SourceLocation();
1910}
1911
1912PP.setPragmaARCCFCodeAuditedInfo(NameTok.getIdentifierInfo(), NewLoc);
1913}
1914};
1915
1916/// PragmaAssumeNonNullHandler -
1917/// \#pragma clang assume_nonnull begin/end
1918struct PragmaAssumeNonNullHandler : public PragmaHandler {
1919PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1920
1921void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1922Token &NameTok) override {
1923SourceLocation Loc = NameTok.getLocation();
1924bool IsBegin;
1925
1926Token Tok;
1927
1928// Lex the 'begin' or 'end'.
1929PP.LexUnexpandedToken(Tok);
1930const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1931if (BeginEnd && BeginEnd->isStr("begin")) {
1932IsBegin = true;
1933} else if (BeginEnd && BeginEnd->isStr("end")) {
1934IsBegin = false;
1935} else {
1936PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1937return;
1938}
1939
1940// Verify that this is followed by EOD.
1941PP.LexUnexpandedToken(Tok);
1942if (Tok.isNot(tok::eod))
1943PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1944
1945// The start location of the active audit.
1946SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1947
1948// The start location we want after processing this.
1949SourceLocation NewLoc;
1950PPCallbacks *Callbacks = PP.getPPCallbacks();
1951
1952if (IsBegin) {
1953// Complain about attempts to re-enter an audit.
1954if (BeginLoc.isValid()) {
1955PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1956PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1957}
1958NewLoc = Loc;
1959if (Callbacks)
1960Callbacks->PragmaAssumeNonNullBegin(NewLoc);
1961} else {
1962// Complain about attempts to leave an audit that doesn't exist.
1963if (!BeginLoc.isValid()) {
1964PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1965return;
1966}
1967NewLoc = SourceLocation();
1968if (Callbacks)
1969Callbacks->PragmaAssumeNonNullEnd(NewLoc);
1970}
1971
1972PP.setPragmaAssumeNonNullLoc(NewLoc);
1973}
1974};
1975
1976/// Handle "\#pragma region [...]"
1977///
1978/// The syntax is
1979/// \code
1980/// #pragma region [optional name]
1981/// #pragma endregion [optional comment]
1982/// \endcode
1983///
1984/// \note This is
1985/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1986/// pragma, just skipped by compiler.
1987struct PragmaRegionHandler : public PragmaHandler {
1988PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
1989
1990void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1991Token &NameTok) override {
1992// #pragma region: endregion matches can be verified
1993// __pragma(region): no sense, but ignored by msvc
1994// _Pragma is not valid for MSVC, but there isn't any point
1995// to handle a _Pragma differently.
1996}
1997};
1998
1999/// "\#pragma managed"
2000/// "\#pragma managed(...)"
2001/// "\#pragma unmanaged"
2002/// MSVC ignores this pragma when not compiling using /clr, which clang doesn't
2003/// support. We parse it and ignore it to avoid -Wunknown-pragma warnings.
2004struct PragmaManagedHandler : public EmptyPragmaHandler {
2005PragmaManagedHandler(const char *pragma) : EmptyPragmaHandler(pragma) {}
2006};
2007
2008/// This handles parsing pragmas that take a macro name and optional message
2009static IdentifierInfo *HandleMacroAnnotationPragma(Preprocessor &PP, Token &Tok,
2010const char *Pragma,
2011std::string &MessageString) {
2012PP.Lex(Tok);
2013if (Tok.isNot(tok::l_paren)) {
2014PP.Diag(Tok, diag::err_expected) << "(";
2015return nullptr;
2016}
2017
2018PP.LexUnexpandedToken(Tok);
2019if (!Tok.is(tok::identifier)) {
2020PP.Diag(Tok, diag::err_expected) << tok::identifier;
2021return nullptr;
2022}
2023IdentifierInfo *II = Tok.getIdentifierInfo();
2024
2025if (!II->hasMacroDefinition()) {
2026PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
2027return nullptr;
2028}
2029
2030PP.Lex(Tok);
2031if (Tok.is(tok::comma)) {
2032PP.Lex(Tok);
2033if (!PP.FinishLexStringLiteral(Tok, MessageString, Pragma,
2034/*AllowMacroExpansion=*/true))
2035return nullptr;
2036}
2037
2038if (Tok.isNot(tok::r_paren)) {
2039PP.Diag(Tok, diag::err_expected) << ")";
2040return nullptr;
2041}
2042return II;
2043}
2044
2045/// "\#pragma clang deprecated(...)"
2046///
2047/// The syntax is
2048/// \code
2049/// #pragma clang deprecate(MACRO_NAME [, Message])
2050/// \endcode
2051struct PragmaDeprecatedHandler : public PragmaHandler {
2052PragmaDeprecatedHandler() : PragmaHandler("deprecated") {}
2053
2054void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2055Token &Tok) override {
2056std::string MessageString;
2057
2058if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2059PP, Tok, "#pragma clang deprecated", MessageString)) {
2060II->setIsDeprecatedMacro(true);
2061PP.addMacroDeprecationMsg(II, std::move(MessageString),
2062Tok.getLocation());
2063}
2064}
2065};
2066
2067/// "\#pragma clang restrict_expansion(...)"
2068///
2069/// The syntax is
2070/// \code
2071/// #pragma clang restrict_expansion(MACRO_NAME [, Message])
2072/// \endcode
2073struct PragmaRestrictExpansionHandler : public PragmaHandler {
2074PragmaRestrictExpansionHandler() : PragmaHandler("restrict_expansion") {}
2075
2076void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2077Token &Tok) override {
2078std::string MessageString;
2079
2080if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2081PP, Tok, "#pragma clang restrict_expansion", MessageString)) {
2082II->setIsRestrictExpansion(true);
2083PP.addRestrictExpansionMsg(II, std::move(MessageString),
2084Tok.getLocation());
2085}
2086}
2087};
2088
2089/// "\#pragma clang final(...)"
2090///
2091/// The syntax is
2092/// \code
2093/// #pragma clang final(MACRO_NAME)
2094/// \endcode
2095struct PragmaFinalHandler : public PragmaHandler {
2096PragmaFinalHandler() : PragmaHandler("final") {}
2097
2098void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2099Token &Tok) override {
2100PP.Lex(Tok);
2101if (Tok.isNot(tok::l_paren)) {
2102PP.Diag(Tok, diag::err_expected) << "(";
2103return;
2104}
2105
2106PP.LexUnexpandedToken(Tok);
2107if (!Tok.is(tok::identifier)) {
2108PP.Diag(Tok, diag::err_expected) << tok::identifier;
2109return;
2110}
2111IdentifierInfo *II = Tok.getIdentifierInfo();
2112
2113if (!II->hasMacroDefinition()) {
2114PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
2115return;
2116}
2117
2118PP.Lex(Tok);
2119if (Tok.isNot(tok::r_paren)) {
2120PP.Diag(Tok, diag::err_expected) << ")";
2121return;
2122}
2123II->setIsFinal(true);
2124PP.addFinalLoc(II, Tok.getLocation());
2125}
2126};
2127
2128} // namespace
2129
2130/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
2131/// \#pragma GCC poison/system_header/dependency and \#pragma once.
2132void Preprocessor::RegisterBuiltinPragmas() {
2133AddPragmaHandler(new PragmaOnceHandler());
2134AddPragmaHandler(new PragmaMarkHandler());
2135AddPragmaHandler(new PragmaPushMacroHandler());
2136AddPragmaHandler(new PragmaPopMacroHandler());
2137AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
2138
2139// #pragma GCC ...
2140AddPragmaHandler("GCC", new PragmaPoisonHandler());
2141AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
2142AddPragmaHandler("GCC", new PragmaDependencyHandler());
2143AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
2144AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
2145"GCC"));
2146AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
2147"GCC"));
2148// #pragma clang ...
2149AddPragmaHandler("clang", new PragmaPoisonHandler());
2150AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
2151AddPragmaHandler("clang", new PragmaDebugHandler());
2152AddPragmaHandler("clang", new PragmaDependencyHandler());
2153AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
2154AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
2155AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
2156AddPragmaHandler("clang", new PragmaDeprecatedHandler());
2157AddPragmaHandler("clang", new PragmaRestrictExpansionHandler());
2158AddPragmaHandler("clang", new PragmaFinalHandler());
2159
2160// #pragma clang module ...
2161auto *ModuleHandler = new PragmaNamespace("module");
2162AddPragmaHandler("clang", ModuleHandler);
2163ModuleHandler->AddPragma(new PragmaModuleImportHandler());
2164ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
2165ModuleHandler->AddPragma(new PragmaModuleEndHandler());
2166ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
2167ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
2168
2169// Safe Buffers pragmas
2170AddPragmaHandler("clang", new PragmaUnsafeBufferUsageHandler);
2171
2172// Add region pragmas.
2173AddPragmaHandler(new PragmaRegionHandler("region"));
2174AddPragmaHandler(new PragmaRegionHandler("endregion"));
2175
2176// MS extensions.
2177if (LangOpts.MicrosoftExt) {
2178AddPragmaHandler(new PragmaWarningHandler());
2179AddPragmaHandler(new PragmaExecCharsetHandler());
2180AddPragmaHandler(new PragmaIncludeAliasHandler());
2181AddPragmaHandler(new PragmaHdrstopHandler());
2182AddPragmaHandler(new PragmaSystemHeaderHandler());
2183AddPragmaHandler(new PragmaManagedHandler("managed"));
2184AddPragmaHandler(new PragmaManagedHandler("unmanaged"));
2185}
2186
2187// Pragmas added by plugins
2188for (const PragmaHandlerRegistry::entry &handler :
2189PragmaHandlerRegistry::entries()) {
2190AddPragmaHandler(handler.instantiate().release());
2191}
2192}
2193
2194/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
2195/// warn about those pragmas being unknown.
2196void Preprocessor::IgnorePragmas() {
2197AddPragmaHandler(new EmptyPragmaHandler());
2198// Also ignore all pragmas in all namespaces created
2199// in Preprocessor::RegisterBuiltinPragmas().
2200AddPragmaHandler("GCC", new EmptyPragmaHandler());
2201AddPragmaHandler("clang", new EmptyPragmaHandler());
2202}
2203