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