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 = Token::createAnnotation(tok::annot_pragma_parser_crash,
1119 Tok.getLocation());
1120 PP.EnterToken(Crasher, /*IsReinject*/ false);
1121 }
1122 } else if (II->isStr("sleep")) {
1123 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1124 } else if (II->isStr("dump")) {
1125 Token DumpAnnot =
1126 Token::createAnnotation(tok::annot_pragma_dump, Tok.getLocation());
1127 PP.EnterToken(DumpAnnot, /*IsReinject*/false);
1128 } else if (II->isStr("diag_mapping")) {
1129 Token DiagName;
1130 PP.LexUnexpandedToken(DiagName);
1131 if (DiagName.is(tok::eod))
1132 PP.getDiagnostics().dump();
1133 else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1134 StringLiteralParser Literal(DiagName, PP,
1135 StringLiteralEvalMethod::Unevaluated);
1136 if (Literal.hadError)
1137 return;
1138 PP.getDiagnostics().dump(Literal.GetString());
1139 } else {
1140 PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1141 << II->getName();
1142 }
1143 } else if (II->isStr("llvm_fatal_error")) {
1145 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1146 } else if (II->isStr("llvm_unreachable")) {
1148 llvm_unreachable("#pragma clang __debug llvm_unreachable");
1149 } else if (II->isStr("macro")) {
1150 Token MacroName;
1151 PP.LexUnexpandedToken(MacroName);
1152 auto *MacroII = MacroName.getIdentifierInfo();
1153 if (MacroII)
1154 PP.dumpMacroInfo(MacroII);
1155 else
1156 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1157 << II->getName();
1158 } else if (II->isStr("module_map")) {
1159 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1160 if (LexModuleName(PP, Tok, ModuleName))
1161 return;
1162 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
1163 Module *M = nullptr;
1164 for (auto IIAndLoc : ModuleName) {
1165 M = MM.lookupModuleQualified(IIAndLoc.getIdentifierInfo()->getName(),
1166 M);
1167 if (!M) {
1168 PP.Diag(IIAndLoc.getLoc(), diag::warn_pragma_debug_unknown_module)
1169 << IIAndLoc.getIdentifierInfo()->getName();
1170 return;
1171 }
1172 }
1173 M->dump();
1174 } else if (II->isStr("module_lookup")) {
1175 Token MName;
1176 PP.LexUnexpandedToken(MName);
1177 auto *MNameII = MName.getIdentifierInfo();
1178 if (!MNameII) {
1179 PP.Diag(MName, diag::warn_pragma_debug_missing_argument)
1180 << II->getName();
1181 return;
1182 }
1183 Module *M = PP.getHeaderSearchInfo().lookupModule(MNameII->getName());
1184 if (!M) {
1185 PP.Diag(MName, diag::warn_pragma_debug_unable_to_find_module)
1186 << MNameII->getName();
1187 return;
1188 }
1189 M->dump();
1190 } else if (II->isStr("overflow_stack")) {
1192 DebugOverflowStack();
1193 } else if (II->isStr("captured")) {
1194 HandleCaptured(PP);
1195 } else if (II->isStr("modules")) {
1196 struct ModuleVisitor {
1197 Preprocessor &PP;
1198 void visit(Module *M, bool VisibleOnly) {
1199 SourceLocation ImportLoc = PP.getModuleImportLoc(M);
1200 if (!VisibleOnly || ImportLoc.isValid()) {
1201 llvm::errs() << M->getFullModuleName() << " ";
1202 if (ImportLoc.isValid()) {
1203 llvm::errs() << M << " visible ";
1204 ImportLoc.print(llvm::errs(), PP.getSourceManager());
1205 }
1206 llvm::errs() << "\n";
1207 }
1208 for (Module *Sub : M->submodules()) {
1209 if (!VisibleOnly || ImportLoc.isInvalid() || Sub->IsExplicit)
1210 visit(Sub, VisibleOnly);
1211 }
1212 }
1213 void visitAll(bool VisibleOnly) {
1214 for (auto &NameAndMod :
1216 visit(NameAndMod.second, VisibleOnly);
1217 }
1218 } Visitor{PP};
1219
1220 Token Kind;
1221 PP.LexUnexpandedToken(Kind);
1222 auto *DumpII = Kind.getIdentifierInfo();
1223 if (!DumpII) {
1224 PP.Diag(Kind, diag::warn_pragma_debug_missing_argument)
1225 << II->getName();
1226 } else if (DumpII->isStr("all")) {
1227 Visitor.visitAll(false);
1228 } else if (DumpII->isStr("visible")) {
1229 Visitor.visitAll(true);
1230 } else if (DumpII->isStr("building")) {
1231 for (auto &Building : PP.getBuildingSubmodules()) {
1232 llvm::errs() << "in " << Building.M->getFullModuleName();
1233 if (Building.ImportLoc.isValid()) {
1234 llvm::errs() << " imported ";
1235 if (Building.IsPragma)
1236 llvm::errs() << "via pragma ";
1237 llvm::errs() << "at ";
1238 Building.ImportLoc.print(llvm::errs(), PP.getSourceManager());
1239 llvm::errs() << "\n";
1240 }
1241 }
1242 } else {
1243 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1244 << DumpII->getName();
1245 }
1246 } else if (II->isStr("sloc_usage")) {
1247 // An optional integer literal argument specifies the number of files to
1248 // specifically report information about.
1249 std::optional<unsigned> MaxNotes;
1250 Token ArgToken;
1251 PP.Lex(ArgToken);
1253 if (ArgToken.is(tok::numeric_constant) &&
1254 PP.parseSimpleIntegerLiteral(ArgToken, Value)) {
1255 MaxNotes = Value;
1256 } else if (ArgToken.isNot(tok::eod)) {
1257 PP.Diag(ArgToken, diag::warn_pragma_debug_unexpected_argument);
1258 }
1259
1260 PP.Diag(Tok, diag::remark_sloc_usage);
1262 MaxNotes);
1263 } else {
1264 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1265 << II->getName();
1266 }
1267
1268 PPCallbacks *Callbacks = PP.getPPCallbacks();
1269 if (Callbacks)
1270 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1271 }
1272
1273 void HandleCaptured(Preprocessor &PP) {
1274 Token Tok;
1276
1277 if (Tok.isNot(tok::eod)) {
1278 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1279 << "pragma clang __debug captured";
1280 return;
1281 }
1282
1283 SourceLocation NameLoc = Tok.getLocation();
1284 MutableArrayRef<Token> Toks(
1285 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1286 Toks[0] = Token::createAnnotation(tok::annot_pragma_captured, NameLoc);
1287
1288 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1289 /*IsReinject=*/false);
1290 }
1291
1292// Disable MSVC warning about runtime stack overflow.
1293#ifdef _MSC_VER
1294 #pragma warning(disable : 4717)
1295#endif
1296 static void DebugOverflowStack(void (*P)() = nullptr) {
1297 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1298 Self(reinterpret_cast<void(*)()>(Self));
1299 }
1300#ifdef _MSC_VER
1301 #pragma warning(default : 4717)
1302#endif
1303};
1304
1305struct PragmaUnsafeBufferUsageHandler : public PragmaHandler {
1306 PragmaUnsafeBufferUsageHandler() : PragmaHandler("unsafe_buffer_usage") {}
1307 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1308 Token &FirstToken) override {
1309 Token Tok;
1310
1312 if (Tok.isNot(tok::identifier)) {
1313 PP.Diag(Tok, diag::err_pp_pragma_unsafe_buffer_usage_syntax);
1314 return;
1315 }
1316
1317 IdentifierInfo *II = Tok.getIdentifierInfo();
1318 SourceLocation Loc = Tok.getLocation();
1319
1320 if (II->isStr("begin")) {
1321 if (PP.enterOrExitSafeBufferOptOutRegion(true, Loc))
1322 PP.Diag(Loc, diag::err_pp_double_begin_pragma_unsafe_buffer_usage);
1323 } else if (II->isStr("end")) {
1324 if (PP.enterOrExitSafeBufferOptOutRegion(false, Loc))
1325 PP.Diag(Loc, diag::err_pp_unmatched_end_begin_pragma_unsafe_buffer_usage);
1326 } else
1327 PP.Diag(Tok, diag::err_pp_pragma_unsafe_buffer_usage_syntax);
1328 }
1329};
1330
1331/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
1332struct PragmaDiagnosticHandler : public PragmaHandler {
1333private:
1334 const char *Namespace;
1335
1336public:
1337 explicit PragmaDiagnosticHandler(const char *NS)
1338 : PragmaHandler("diagnostic"), Namespace(NS) {}
1339
1340 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1341 Token &DiagToken) override {
1342 SourceLocation DiagLoc = DiagToken.getLocation();
1343 Token Tok;
1345 if (Tok.isNot(tok::identifier)) {
1346 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1347 return;
1348 }
1349 IdentifierInfo *II = Tok.getIdentifierInfo();
1350 PPCallbacks *Callbacks = PP.getPPCallbacks();
1351
1352 // Get the next token, which is either an EOD or a string literal. We lex
1353 // it now so that we can early return if the previous token was push or pop.
1355
1356 if (II->isStr("pop")) {
1357 if (!PP.getDiagnostics().popMappings(DiagLoc))
1358 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1359 else if (Callbacks)
1360 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1361
1362 if (Tok.isNot(tok::eod))
1363 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1364 return;
1365 } else if (II->isStr("push")) {
1366 PP.getDiagnostics().pushMappings(DiagLoc);
1367 if (Callbacks)
1368 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1369
1370 if (Tok.isNot(tok::eod))
1371 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1372 return;
1373 }
1374
1375 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1376 .Case("ignored", diag::Severity::Ignored)
1377 .Case("warning", diag::Severity::Warning)
1378 .Case("error", diag::Severity::Error)
1379 .Case("fatal", diag::Severity::Fatal)
1380 .Default(diag::Severity());
1381
1382 if (SV == diag::Severity()) {
1383 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1384 return;
1385 }
1386
1387 // At this point, we expect a string literal.
1388 SourceLocation StringLoc = Tok.getLocation();
1389 std::string WarningName;
1390 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1391 /*AllowMacroExpansion=*/false))
1392 return;
1393
1394 if (Tok.isNot(tok::eod)) {
1395 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1396 return;
1397 }
1398
1399 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1400 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1401 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1402 return;
1403 }
1404
1405 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1406 : diag::Flavor::Remark;
1407 StringRef Group = StringRef(WarningName).substr(2);
1408 bool unknownDiag = false;
1409 if (Group == "everything") {
1410 // Special handling for pragma clang diagnostic ... "-Weverything".
1411 // There is no formal group named "everything", so there has to be a
1412 // special case for it.
1413 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1414 } else
1415 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1416 DiagLoc);
1417 if (unknownDiag)
1418 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1419 << WarningName;
1420 else if (Callbacks)
1421 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1422 }
1423};
1424
1425/// "\#pragma hdrstop [<header-name-string>]"
1426struct PragmaHdrstopHandler : public PragmaHandler {
1427 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1428 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1429 Token &DepToken) override {
1430 PP.HandlePragmaHdrstop(DepToken);
1431 }
1432};
1433
1434/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1435/// diagnostics, so we don't really implement this pragma. We parse it and
1436/// ignore it to avoid -Wunknown-pragma warnings.
1437struct PragmaWarningHandler : public PragmaHandler {
1438 PragmaWarningHandler() : PragmaHandler("warning") {}
1439
1440 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1441 Token &Tok) override {
1442 // Parse things like:
1443 // warning(push, 1)
1444 // warning(pop)
1445 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1446 SourceLocation DiagLoc = Tok.getLocation();
1447 PPCallbacks *Callbacks = PP.getPPCallbacks();
1448
1449 PP.Lex(Tok);
1450 if (Tok.isNot(tok::l_paren)) {
1451 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1452 return;
1453 }
1454
1455 PP.Lex(Tok);
1456 IdentifierInfo *II = Tok.getIdentifierInfo();
1457
1458 if (II && II->isStr("push")) {
1459 // #pragma warning( push[ ,n ] )
1460 int Level = -1;
1461 PP.Lex(Tok);
1462 if (Tok.is(tok::comma)) {
1463 PP.Lex(Tok);
1465 if (Tok.is(tok::numeric_constant) &&
1467 Level = int(Value);
1468 if (Level < 0 || Level > 4) {
1469 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1470 return;
1471 }
1472 }
1473 PP.getDiagnostics().pushMappings(DiagLoc);
1474 if (Callbacks)
1475 Callbacks->PragmaWarningPush(DiagLoc, Level);
1476 } else if (II && II->isStr("pop")) {
1477 // #pragma warning( pop )
1478 PP.Lex(Tok);
1479 if (!PP.getDiagnostics().popMappings(DiagLoc))
1480 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1481 else if (Callbacks)
1482 Callbacks->PragmaWarningPop(DiagLoc);
1483 } else {
1484 // #pragma warning( warning-specifier : warning-number-list
1485 // [; warning-specifier : warning-number-list...] )
1486 while (true) {
1487 II = Tok.getIdentifierInfo();
1488 if (!II && !Tok.is(tok::numeric_constant)) {
1489 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1490 return;
1491 }
1492
1493 // Figure out which warning specifier this is.
1494 bool SpecifierValid;
1496 if (II) {
1497 int SpecifierInt = llvm::StringSwitch<int>(II->getName())
1498 .Case("default", PPCallbacks::PWS_Default)
1499 .Case("disable", PPCallbacks::PWS_Disable)
1500 .Case("error", PPCallbacks::PWS_Error)
1501 .Case("once", PPCallbacks::PWS_Once)
1502 .Case("suppress", PPCallbacks::PWS_Suppress)
1503 .Default(-1);
1504 SpecifierValid = SpecifierInt != -1;
1505 if (SpecifierValid)
1506 Specifier =
1507 static_cast<PPCallbacks::PragmaWarningSpecifier>(SpecifierInt);
1508
1509 // If we read a correct specifier, snatch next token (that should be
1510 // ":", checked later).
1511 if (SpecifierValid)
1512 PP.Lex(Tok);
1513 } else {
1514 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1517 if ((SpecifierValid = (Value >= 1) && (Value <= 4)))
1520 } else
1521 SpecifierValid = false;
1522 // Next token already snatched by parseSimpleIntegerLiteral.
1523 }
1524
1525 if (!SpecifierValid) {
1526 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1527 return;
1528 }
1529 if (Tok.isNot(tok::colon)) {
1530 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1531 return;
1532 }
1533
1534 // Collect the warning ids.
1535 SmallVector<int, 4> Ids;
1536 PP.Lex(Tok);
1537 while (Tok.is(tok::numeric_constant)) {
1539 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1540 Value > INT_MAX) {
1541 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1542 return;
1543 }
1544 Ids.push_back(int(Value));
1545 }
1546
1547 // Only act on disable for now.
1549 if (Specifier == PPCallbacks::PWS_Disable)
1550 SV = diag::Severity::Ignored;
1551 if (SV != diag::Severity())
1552 for (int Id : Ids) {
1553 if (auto Group = diagGroupFromCLWarningID(Id)) {
1554 bool unknownDiag = PP.getDiagnostics().setSeverityForGroup(
1555 diag::Flavor::WarningOrError, *Group, SV, DiagLoc);
1556 assert(!unknownDiag &&
1557 "wd table should only contain known diags");
1558 (void)unknownDiag;
1559 }
1560 }
1561
1562 if (Callbacks)
1563 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1564
1565 // Parse the next specifier if there is a semicolon.
1566 if (Tok.isNot(tok::semi))
1567 break;
1568 PP.Lex(Tok);
1569 }
1570 }
1571
1572 if (Tok.isNot(tok::r_paren)) {
1573 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1574 return;
1575 }
1576
1577 PP.Lex(Tok);
1578 if (Tok.isNot(tok::eod))
1579 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1580 }
1581};
1582
1583/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1584/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1585/// otherwise to avoid -Wunknown-pragma warnings.
1586struct PragmaExecCharsetHandler : public PragmaHandler {
1587 PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1588
1589 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1590 Token &Tok) override {
1591 // Parse things like:
1592 // execution_character_set(push, "UTF-8")
1593 // execution_character_set(pop)
1594 SourceLocation DiagLoc = Tok.getLocation();
1595 PPCallbacks *Callbacks = PP.getPPCallbacks();
1596
1597 PP.Lex(Tok);
1598 if (Tok.isNot(tok::l_paren)) {
1599 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1600 return;
1601 }
1602
1603 PP.Lex(Tok);
1604 IdentifierInfo *II = Tok.getIdentifierInfo();
1605
1606 if (II && II->isStr("push")) {
1607 // #pragma execution_character_set( push[ , string ] )
1608 PP.Lex(Tok);
1609 if (Tok.is(tok::comma)) {
1610 PP.Lex(Tok);
1611
1612 std::string ExecCharset;
1613 if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1614 "pragma execution_character_set",
1615 /*AllowMacroExpansion=*/false))
1616 return;
1617
1618 // MSVC supports either of these, but nothing else.
1619 if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
1620 PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1621 return;
1622 }
1623 }
1624 if (Callbacks)
1625 Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1626 } else if (II && II->isStr("pop")) {
1627 // #pragma execution_character_set( pop )
1628 PP.Lex(Tok);
1629 if (Callbacks)
1630 Callbacks->PragmaExecCharsetPop(DiagLoc);
1631 } else {
1632 PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1633 return;
1634 }
1635
1636 if (Tok.isNot(tok::r_paren)) {
1637 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1638 return;
1639 }
1640
1641 PP.Lex(Tok);
1642 if (Tok.isNot(tok::eod))
1643 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1644 }
1645};
1646
1647/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1648struct PragmaIncludeAliasHandler : public PragmaHandler {
1649 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1650
1651 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1652 Token &IncludeAliasTok) override {
1653 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1654 }
1655};
1656
1657/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1658/// extension. The syntax is:
1659/// \code
1660/// #pragma message(string)
1661/// \endcode
1662/// OR, in GCC mode:
1663/// \code
1664/// #pragma message string
1665/// \endcode
1666/// string is a string, which is fully macro expanded, and permits string
1667/// concatenation, embedded escape characters, etc... See MSDN for more details.
1668/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1669/// form as \#pragma message.
1670struct PragmaMessageHandler : public PragmaHandler {
1671private:
1673 const StringRef Namespace;
1674
1675 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1676 bool PragmaNameOnly = false) {
1677 switch (Kind) {
1679 return PragmaNameOnly ? "message" : "pragma message";
1681 return PragmaNameOnly ? "warning" : "pragma warning";
1683 return PragmaNameOnly ? "error" : "pragma error";
1684 }
1685 llvm_unreachable("Unknown PragmaMessageKind!");
1686 }
1687
1688public:
1689 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1690 StringRef Namespace = StringRef())
1691 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1693
1694 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1695 Token &Tok) override {
1696 SourceLocation MessageLoc = Tok.getLocation();
1697 PP.Lex(Tok);
1698 bool ExpectClosingParen = false;
1699 switch (Tok.getKind()) {
1700 case tok::l_paren:
1701 // We have a MSVC style pragma message.
1702 ExpectClosingParen = true;
1703 // Read the string.
1704 PP.Lex(Tok);
1705 break;
1706 case tok::string_literal:
1707 // We have a GCC style pragma message, and we just read the string.
1708 break;
1709 default:
1710 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1711 return;
1712 }
1713
1714 std::string MessageString;
1715 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1716 /*AllowMacroExpansion=*/true))
1717 return;
1718
1719 if (ExpectClosingParen) {
1720 if (Tok.isNot(tok::r_paren)) {
1721 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1722 return;
1723 }
1724 PP.Lex(Tok); // eat the r_paren.
1725 }
1726
1727 if (Tok.isNot(tok::eod)) {
1728 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1729 return;
1730 }
1731
1732 // Output the message.
1733 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1734 ? diag::err_pragma_message
1735 : diag::warn_pragma_message) << MessageString;
1736
1737 // If the pragma is lexically sound, notify any interested PPCallbacks.
1738 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1739 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1740 }
1741};
1742
1743/// Handle the clang \#pragma module import extension. The syntax is:
1744/// \code
1745/// #pragma clang module import some.module.name
1746/// \endcode
1747struct PragmaModuleImportHandler : public PragmaHandler {
1748 PragmaModuleImportHandler() : PragmaHandler("import") {}
1749
1750 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1751 Token &Tok) override {
1752 SourceLocation ImportLoc = Tok.getLocation();
1753
1754 // Read the module name.
1755 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1756 if (LexModuleName(PP, Tok, ModuleName))
1757 return;
1758
1759 if (Tok.isNot(tok::eod))
1760 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1761
1762 // If we have a non-empty module path, load the named module.
1763 Module *Imported =
1764 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1765 /*IsInclusionDirective=*/false);
1766 if (!Imported)
1767 return;
1768
1769 PP.makeModuleVisible(Imported, ImportLoc);
1770 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().getLoc()),
1771 tok::annot_module_include, Imported);
1772 if (auto *CB = PP.getPPCallbacks())
1773 CB->moduleImport(ImportLoc, ModuleName, Imported);
1774 }
1775};
1776
1777/// Handle the clang \#pragma module begin extension. The syntax is:
1778/// \code
1779/// #pragma clang module begin some.module.name
1780/// ...
1781/// #pragma clang module end
1782/// \endcode
1783struct PragmaModuleBeginHandler : public PragmaHandler {
1784 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1785
1786 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1787 Token &Tok) override {
1788 SourceLocation BeginLoc = Tok.getLocation();
1789
1790 // Read the module name.
1791 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1792 if (LexModuleName(PP, Tok, ModuleName))
1793 return;
1794
1795 if (Tok.isNot(tok::eod))
1796 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1797
1798 // We can only enter submodules of the current module.
1799 StringRef Current = PP.getLangOpts().CurrentModule;
1800 if (ModuleName.front().getIdentifierInfo()->getName() != Current) {
1801 PP.Diag(ModuleName.front().getLoc(),
1802 diag::err_pp_module_begin_wrong_module)
1803 << ModuleName.front().getIdentifierInfo() << (ModuleName.size() > 1)
1804 << Current.empty() << Current;
1805 return;
1806 }
1807
1808 // Find the module we're entering. We require that a module map for it
1809 // be loaded or implicitly loadable.
1810 auto &HSI = PP.getHeaderSearchInfo();
1811 auto &MM = HSI.getModuleMap();
1812 Module *M = HSI.lookupModule(Current, ModuleName.front().getLoc());
1813 if (!M) {
1814 PP.Diag(ModuleName.front().getLoc(),
1815 diag::err_pp_module_begin_no_module_map)
1816 << Current;
1817 return;
1818 }
1819 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1820 auto *NewM = MM.findOrInferSubmodule(
1821 M, ModuleName[I].getIdentifierInfo()->getName());
1822 if (!NewM) {
1823 PP.Diag(ModuleName[I].getLoc(), diag::err_pp_module_begin_no_submodule)
1824 << M->getFullModuleName() << ModuleName[I].getIdentifierInfo();
1825 return;
1826 }
1827 M = NewM;
1828 }
1829
1830 // If the module isn't available, it doesn't make sense to enter it.
1832 PP.getLangOpts(), PP.getTargetInfo(), *M, PP.getDiagnostics())) {
1833 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1834 << M->getTopLevelModuleName();
1835 return;
1836 }
1837
1838 // Enter the scope of the submodule.
1839 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1840 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().getLoc()),
1841 tok::annot_module_begin, M);
1842 }
1843};
1844
1845/// Handle the clang \#pragma module end extension.
1846struct PragmaModuleEndHandler : public PragmaHandler {
1847 PragmaModuleEndHandler() : PragmaHandler("end") {}
1848
1849 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1850 Token &Tok) override {
1851 SourceLocation Loc = Tok.getLocation();
1852
1854 if (Tok.isNot(tok::eod))
1855 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1856
1857 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1858 if (M)
1859 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1860 else
1861 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
1862 }
1863};
1864
1865/// Handle the clang \#pragma module build extension.
1866struct PragmaModuleBuildHandler : public PragmaHandler {
1867 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1868
1869 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1870 Token &Tok) override {
1872 }
1873};
1874
1875/// Handle the clang \#pragma module load extension.
1876struct PragmaModuleLoadHandler : public PragmaHandler {
1877 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1878
1879 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1880 Token &Tok) override {
1881 SourceLocation Loc = Tok.getLocation();
1882
1883 // Read the module name.
1884 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1885 if (LexModuleName(PP, Tok, ModuleName))
1886 return;
1887
1888 if (Tok.isNot(tok::eod))
1889 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1890
1891 // Load the module, don't make it visible.
1892 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1893 /*IsInclusionDirective=*/false);
1894 }
1895};
1896
1897/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1898/// macro on the top of the stack.
1899struct PragmaPushMacroHandler : public PragmaHandler {
1900 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1901
1902 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1903 Token &PushMacroTok) override {
1904 PP.HandlePragmaPushMacro(PushMacroTok);
1905 }
1906};
1907
1908/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1909/// macro to the value on the top of the stack.
1910struct PragmaPopMacroHandler : public PragmaHandler {
1911 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1912
1913 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1914 Token &PopMacroTok) override {
1915 PP.HandlePragmaPopMacro(PopMacroTok);
1916 }
1917};
1918
1919/// PragmaARCCFCodeAuditedHandler -
1920/// \#pragma clang arc_cf_code_audited begin/end
1921struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1922 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1923
1924 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1925 Token &NameTok) override {
1926 SourceLocation Loc = NameTok.getLocation();
1927 bool IsBegin;
1928
1929 Token Tok;
1930
1931 // Lex the 'begin' or 'end'.
1933 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1934 if (BeginEnd && BeginEnd->isStr("begin")) {
1935 IsBegin = true;
1936 } else if (BeginEnd && BeginEnd->isStr("end")) {
1937 IsBegin = false;
1938 } else {
1939 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1940 return;
1941 }
1942
1943 // Verify that this is followed by EOD.
1945 if (Tok.isNot(tok::eod))
1946 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1947
1948 // The start location of the active audit.
1949 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedInfo().getLoc();
1950
1951 // The start location we want after processing this.
1952 SourceLocation NewLoc;
1953
1954 if (IsBegin) {
1955 // Complain about attempts to re-enter an audit.
1956 if (BeginLoc.isValid()) {
1957 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1958 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1959 }
1960 NewLoc = Loc;
1961 } else {
1962 // Complain about attempts to leave an audit that doesn't exist.
1963 if (!BeginLoc.isValid()) {
1964 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1965 return;
1966 }
1967 NewLoc = SourceLocation();
1968 }
1969
1971 }
1972};
1973
1974/// PragmaAssumeNonNullHandler -
1975/// \#pragma clang assume_nonnull begin/end
1976struct PragmaAssumeNonNullHandler : public PragmaHandler {
1977 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1978
1979 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1980 Token &NameTok) override {
1981 SourceLocation Loc = NameTok.getLocation();
1982 bool IsBegin;
1983
1984 Token Tok;
1985
1986 // Lex the 'begin' or 'end'.
1988 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1989 if (BeginEnd && BeginEnd->isStr("begin")) {
1990 IsBegin = true;
1991 } else if (BeginEnd && BeginEnd->isStr("end")) {
1992 IsBegin = false;
1993 } else {
1994 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1995 return;
1996 }
1997
1998 // Verify that this is followed by EOD.
2000 if (Tok.isNot(tok::eod))
2001 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
2002
2003 // The start location of the active audit.
2004 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
2005
2006 // The start location we want after processing this.
2007 SourceLocation NewLoc;
2008 PPCallbacks *Callbacks = PP.getPPCallbacks();
2009
2010 if (IsBegin) {
2011 // Complain about attempts to re-enter an audit.
2012 if (BeginLoc.isValid()) {
2013 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
2014 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
2015 }
2016 NewLoc = Loc;
2017 if (Callbacks)
2018 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
2019 } else {
2020 // Complain about attempts to leave an audit that doesn't exist.
2021 if (!BeginLoc.isValid()) {
2022 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
2023 return;
2024 }
2025 NewLoc = SourceLocation();
2026 if (Callbacks)
2027 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
2028 }
2029
2030 PP.setPragmaAssumeNonNullLoc(NewLoc);
2031 }
2032};
2033
2034/// Handle "\#pragma region [...]"
2035///
2036/// The syntax is
2037/// \code
2038/// #pragma region [optional name]
2039/// #pragma endregion [optional comment]
2040/// \endcode
2041///
2042/// \note This is
2043/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
2044/// pragma, just skipped by compiler.
2045struct PragmaRegionHandler : public PragmaHandler {
2046 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
2047
2048 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2049 Token &NameTok) override {
2050 // #pragma region: endregion matches can be verified
2051 // __pragma(region): no sense, but ignored by msvc
2052 // _Pragma is not valid for MSVC, but there isn't any point
2053 // to handle a _Pragma differently.
2054 }
2055};
2056
2057/// "\#pragma managed"
2058/// "\#pragma managed(...)"
2059/// "\#pragma unmanaged"
2060/// MSVC ignores this pragma when not compiling using /clr, which clang doesn't
2061/// support. We parse it and ignore it to avoid -Wunknown-pragma warnings.
2062struct PragmaManagedHandler : public EmptyPragmaHandler {
2063 PragmaManagedHandler(const char *pragma) : EmptyPragmaHandler(pragma) {}
2064};
2065
2066/// This handles parsing pragmas that take a macro name and optional message
2067static IdentifierInfo *HandleMacroAnnotationPragma(Preprocessor &PP, Token &Tok,
2068 const char *Pragma,
2069 std::string &MessageString) {
2070 PP.Lex(Tok);
2071 if (Tok.isNot(tok::l_paren)) {
2072 PP.Diag(Tok, diag::err_expected) << "(";
2073 return nullptr;
2074 }
2075
2077 if (!Tok.is(tok::identifier)) {
2078 PP.Diag(Tok, diag::err_expected) << tok::identifier;
2079 return nullptr;
2080 }
2082
2083 if (!II->hasMacroDefinition()) {
2084 PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
2085 return nullptr;
2086 }
2087
2088 PP.Lex(Tok);
2089 if (Tok.is(tok::comma)) {
2090 PP.Lex(Tok);
2091 if (!PP.FinishLexStringLiteral(Tok, MessageString, Pragma,
2092 /*AllowMacroExpansion=*/true))
2093 return nullptr;
2094 }
2095
2096 if (Tok.isNot(tok::r_paren)) {
2097 PP.Diag(Tok, diag::err_expected) << ")";
2098 return nullptr;
2099 }
2100 return II;
2101}
2102
2103/// "\#pragma clang deprecated(...)"
2104///
2105/// The syntax is
2106/// \code
2107/// #pragma clang deprecate(MACRO_NAME [, Message])
2108/// \endcode
2109struct PragmaDeprecatedHandler : public PragmaHandler {
2110 PragmaDeprecatedHandler() : PragmaHandler("deprecated") {}
2111
2112 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2113 Token &Tok) override {
2114 std::string MessageString;
2115
2116 if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2117 PP, Tok, "#pragma clang deprecated", MessageString)) {
2118 II->setIsDeprecatedMacro(true);
2119 PP.addMacroDeprecationMsg(II, std::move(MessageString),
2120 Tok.getLocation());
2121 }
2122 }
2123};
2124
2125/// "\#pragma clang restrict_expansion(...)"
2126///
2127/// The syntax is
2128/// \code
2129/// #pragma clang restrict_expansion(MACRO_NAME [, Message])
2130/// \endcode
2131struct PragmaRestrictExpansionHandler : public PragmaHandler {
2132 PragmaRestrictExpansionHandler() : PragmaHandler("restrict_expansion") {}
2133
2134 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2135 Token &Tok) override {
2136 std::string MessageString;
2137
2138 if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2139 PP, Tok, "#pragma clang restrict_expansion", MessageString)) {
2140 II->setIsRestrictExpansion(true);
2141 PP.addRestrictExpansionMsg(II, std::move(MessageString),
2142 Tok.getLocation());
2143 }
2144 }
2145};
2146
2147/// "\#pragma clang final(...)"
2148///
2149/// The syntax is
2150/// \code
2151/// #pragma clang final(MACRO_NAME)
2152/// \endcode
2153struct PragmaFinalHandler : public PragmaHandler {
2154 PragmaFinalHandler() : PragmaHandler("final") {}
2155
2156 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2157 Token &Tok) override {
2158 PP.Lex(Tok);
2159 if (Tok.isNot(tok::l_paren)) {
2160 PP.Diag(Tok, diag::err_expected) << "(";
2161 return;
2162 }
2163
2165 if (!Tok.is(tok::identifier)) {
2166 PP.Diag(Tok, diag::err_expected) << tok::identifier;
2167 return;
2168 }
2169 IdentifierInfo *II = Tok.getIdentifierInfo();
2170
2171 if (!II->hasMacroDefinition()) {
2172 PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
2173 return;
2174 }
2175
2176 PP.Lex(Tok);
2177 if (Tok.isNot(tok::r_paren)) {
2178 PP.Diag(Tok, diag::err_expected) << ")";
2179 return;
2180 }
2181 II->setIsFinal(true);
2182 PP.addFinalLoc(II, Tok.getLocation());
2183 }
2184};
2185
2186/// "\#pragma clang __set_pp_state ..."
2187///
2188/// This pragma takes an identifier+value pair and sets some internal state in
2189/// the compiler; it is intended primarily to preserve preprocessor state that
2190/// is required for compilation to function properly across preprocessor runs
2191/// if '-E' is used. This is an internal pragma that should not be used by
2192/// users.
2193///
2194/// The syntax is
2195/// \code
2196/// #pragma clang __set_pp_state glibcxx_version INTEGER
2197/// \endcode
2198struct PragmaSetPPStateHandler : PragmaHandler {
2199 PragmaSetPPStateHandler() : PragmaHandler("__set_pp_state") {}
2200 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2201 Token &Tok) override {
2202 PP.HandlePragmaSetPPState(Introducer, Tok);
2203 }
2204};
2205} // namespace
2206
2207/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
2208/// \#pragma GCC poison/system_header/dependency and \#pragma once.
2209void Preprocessor::RegisterBuiltinPragmas() {
2210 AddPragmaHandler(new PragmaOnceHandler());
2211 AddPragmaHandler(new PragmaMarkHandler());
2212 AddPragmaHandler(new PragmaPushMacroHandler());
2213 AddPragmaHandler(new PragmaPopMacroHandler());
2214 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
2215
2216 // #pragma GCC ...
2217 AddPragmaHandler("GCC", new PragmaPoisonHandler());
2218 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
2219 AddPragmaHandler("GCC", new PragmaDependencyHandler());
2220 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
2221 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
2222 "GCC"));
2223 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
2224 "GCC"));
2225 // #pragma clang ...
2226 AddPragmaHandler("clang", new PragmaPoisonHandler());
2227 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
2228 AddPragmaHandler("clang", new PragmaDebugHandler());
2229 AddPragmaHandler("clang", new PragmaDependencyHandler());
2230 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
2231 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
2232 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
2233 AddPragmaHandler("clang", new PragmaDeprecatedHandler());
2234 AddPragmaHandler("clang", new PragmaRestrictExpansionHandler());
2235 AddPragmaHandler("clang", new PragmaFinalHandler());
2236 AddPragmaHandler("clang", new PragmaSetPPStateHandler());
2237
2238 // #pragma clang module ...
2239 auto *ModuleHandler = new PragmaNamespace("module");
2240 AddPragmaHandler("clang", ModuleHandler);
2241 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
2242 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
2243 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
2244 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
2245 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
2246
2247 // Safe Buffers pragmas
2248 AddPragmaHandler("clang", new PragmaUnsafeBufferUsageHandler);
2249
2250 // Add region pragmas.
2251 AddPragmaHandler(new PragmaRegionHandler("region"));
2252 AddPragmaHandler(new PragmaRegionHandler("endregion"));
2253
2254 // MS extensions.
2255 if (LangOpts.MicrosoftExt) {
2256 AddPragmaHandler(new PragmaWarningHandler());
2257 AddPragmaHandler(new PragmaExecCharsetHandler());
2258 AddPragmaHandler(new PragmaIncludeAliasHandler());
2259 AddPragmaHandler(new PragmaHdrstopHandler());
2260 AddPragmaHandler(new PragmaSystemHeaderHandler());
2261 AddPragmaHandler(new PragmaManagedHandler("managed"));
2262 AddPragmaHandler(new PragmaManagedHandler("unmanaged"));
2263 }
2264
2265 // Pragmas added by plugins
2266 for (const PragmaHandlerRegistry::entry &handler :
2267 PragmaHandlerRegistry::entries()) {
2268 AddPragmaHandler(handler.instantiate().release());
2269 }
2270}
2271
2272/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
2273/// warn about those pragmas being unknown.
2276 // Also ignore all pragmas in all namespaces created
2277 // in Preprocessor::RegisterBuiltinPragmas().
2279 AddPragmaHandler("clang", new EmptyPragmaHandler());
2280}
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:808
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:953
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:1079
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:241
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:2274
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:225
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:314
static Token createAnnotation(tok::TokenKind Kind, SourceRange Range, void *Value=nullptr)
Definition Token.h:205
@ 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:349
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:428
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
Top level wrappers for InstallAPI frontend operations.
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