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