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