blob: c16478dd2be48bbfd46f1e87b4f9c5bfecad8dfd [file] [log] [blame]
Chris Lattnerb8761832006-06-24 21:31:03 +00001//===--- Pragma.cpp - Pragma registration and handling --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb8761832006-06-24 21:31:03 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerb694ba72006-07-02 22:41:36 +000010// This file implements the PragmaHandler/PragmaTable interfaces and implements
11// pragma related methods of the Preprocessor class.
Chris Lattnerb8761832006-06-24 21:31:03 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Pragma.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000016#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/SourceLocation.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000019#include "clang/Basic/SourceManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000020#include "clang/Basic/TokenKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/HeaderSearch.h"
22#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000024#include "clang/Lex/PPCallbacks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000026#include "clang/Lex/PreprocessorLexer.h"
27#include "clang/Lex/PTHLexer.h"
28#include "clang/Lex/Token.h"
29#include "clang/Lex/TokenLexer.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/SmallString.h"
33#include "llvm/ADT/SmallVector.h"
Reid Kleckner881dff32013-09-13 22:00:30 +000034#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/StringSwitch.h"
Daniel Dunbar211a7872010-08-18 23:09:23 +000036#include "llvm/Support/CrashRecoveryContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000037#include "llvm/Support/Compiler.h"
Daniel Dunbarf2cf3292010-08-17 22:32:48 +000038#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000039#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include <cassert>
41#include <cstdint>
42#include <limits>
43#include <string>
44#include <vector>
45
Chris Lattnerb8761832006-06-24 21:31:03 +000046using namespace clang;
47
48// Out-of-line destructor to provide a home for the class.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000049PragmaHandler::~PragmaHandler() {
50}
Chris Lattnerb8761832006-06-24 21:31:03 +000051
Chris Lattner2e155302006-07-03 05:34:41 +000052//===----------------------------------------------------------------------===//
Daniel Dunbard839e772010-06-11 20:10:12 +000053// EmptyPragmaHandler Implementation.
54//===----------------------------------------------------------------------===//
55
Hans Wennborg7357bbc2015-10-12 20:47:58 +000056EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000057
Douglas Gregorc7d65762010-09-09 22:45:38 +000058void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
59 PragmaIntroducerKind Introducer,
60 Token &FirstToken) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000061
62//===----------------------------------------------------------------------===//
Chris Lattner2e155302006-07-03 05:34:41 +000063// PragmaNamespace Implementation.
64//===----------------------------------------------------------------------===//
65
Chris Lattner2e155302006-07-03 05:34:41 +000066PragmaNamespace::~PragmaNamespace() {
Reid Kleckner588c9372014-02-19 23:44:52 +000067 llvm::DeleteContainerSeconds(Handlers);
Chris Lattner2e155302006-07-03 05:34:41 +000068}
69
70/// FindHandler - Check to see if there is already a handler for the
71/// specified name. If not, return the handler for the null identifier if it
72/// exists, otherwise return null. If IgnoreNull is true (the default) then
73/// the null handler isn't returned on failure to match.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000074PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Chris Lattner2e155302006-07-03 05:34:41 +000075 bool IgnoreNull) const {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000076 if (PragmaHandler *Handler = Handlers.lookup(Name))
77 return Handler;
Craig Topperd2d442c2014-05-17 23:10:59 +000078 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000079}
Mike Stump11289f42009-09-09 15:08:12 +000080
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000081void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
82 assert(!Handlers.lookup(Handler->getName()) &&
83 "A handler with this name is already registered in this namespace");
David Blaikie13156b62014-11-19 03:06:06 +000084 Handlers[Handler->getName()] = Handler;
Chris Lattner2e155302006-07-03 05:34:41 +000085}
86
Daniel Dunbar40596532008-10-04 19:17:46 +000087void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000088 assert(Handlers.lookup(Handler->getName()) &&
89 "Handler not registered in this namespace");
90 Handlers.erase(Handler->getName());
Daniel Dunbar40596532008-10-04 19:17:46 +000091}
92
Douglas Gregorc7d65762010-09-09 22:45:38 +000093void PragmaNamespace::HandlePragma(Preprocessor &PP,
94 PragmaIntroducerKind Introducer,
95 Token &Tok) {
Chris Lattnerb8761832006-06-24 21:31:03 +000096 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
97 // expand it, the user can have a STDC #define, that should not affect this.
98 PP.LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +000099
Chris Lattnerb8761832006-06-24 21:31:03 +0000100 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000101 PragmaHandler *Handler
102 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000103 : StringRef(),
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000104 /*IgnoreNull=*/false);
Craig Topperd2d442c2014-05-17 23:10:59 +0000105 if (!Handler) {
Chris Lattner21656f22009-04-19 21:10:26 +0000106 PP.Diag(Tok, diag::warn_pragma_ignored);
107 return;
108 }
Mike Stump11289f42009-09-09 15:08:12 +0000109
Chris Lattnerb8761832006-06-24 21:31:03 +0000110 // Otherwise, pass it down.
Douglas Gregorc7d65762010-09-09 22:45:38 +0000111 Handler->HandlePragma(PP, Introducer, Tok);
Chris Lattnerb8761832006-06-24 21:31:03 +0000112}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000113
Chris Lattnerb694ba72006-07-02 22:41:36 +0000114//===----------------------------------------------------------------------===//
115// Preprocessor Pragma Directive Handling.
116//===----------------------------------------------------------------------===//
117
James Dennett18a6d792012-06-17 03:26:26 +0000118/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Chris Lattnerb694ba72006-07-02 22:41:36 +0000119/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000120void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
121 PragmaIntroducerKind Introducer) {
122 if (Callbacks)
123 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
124
Jordan Rosede1a2922012-06-08 18:06:21 +0000125 if (!PragmasEnabled)
126 return;
127
Chris Lattnerb694ba72006-07-02 22:41:36 +0000128 ++NumPragma;
Mike Stump11289f42009-09-09 15:08:12 +0000129
Chris Lattnerb694ba72006-07-02 22:41:36 +0000130 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattner146762e2007-07-20 16:59:19 +0000131 Token Tok;
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000132 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000133
Chris Lattnerb694ba72006-07-02 22:41:36 +0000134 // If the pragma handler didn't read the rest of the line, consume it now.
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000135 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
136 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000137 DiscardUntilEndOfDirective();
138}
139
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000140namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000141
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000142/// \brief Helper class for \see Preprocessor::Handle_Pragma.
143class LexingFor_PragmaRAII {
144 Preprocessor &PP;
145 bool InMacroArgPreExpansion;
146 bool Failed;
147 Token &OutTok;
148 Token PragmaTok;
149
150public:
151 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
152 Token &Tok)
153 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
154 Failed(false), OutTok(Tok) {
155 if (InMacroArgPreExpansion) {
156 PragmaTok = OutTok;
157 PP.EnableBacktrackAtThisPos();
158 }
159 }
160
161 ~LexingFor_PragmaRAII() {
162 if (InMacroArgPreExpansion) {
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000163 // When committing/backtracking the cached pragma tokens in a macro
164 // argument pre-expansion we want to ensure that either the tokens which
165 // have been committed will be removed from the cache or that the tokens
166 // over which we just backtracked won't remain in the cache after they're
167 // consumed and that the caching will stop after consuming them.
168 // Otherwise the caching will interfere with the way macro expansion
169 // works, because we will continue to cache tokens after consuming the
170 // backtracked tokens, which shouldn't happen when we're dealing with
171 // macro argument pre-expansion.
172 auto CachedTokenRange = PP.LastCachedTokenRange();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000173 if (Failed) {
174 PP.CommitBacktrackedTokens();
175 } else {
176 PP.Backtrack();
177 OutTok = PragmaTok;
178 }
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000179 PP.EraseCachedTokens(CachedTokenRange);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000180 }
181 }
182
183 void failed() {
184 Failed = true;
185 }
186};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000187
188} // end anonymous namespace
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000189
Chris Lattnerb694ba72006-07-02 22:41:36 +0000190/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
191/// return the first token after the directive. The _Pragma token has just
192/// been read into 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000193void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000194
195 // This works differently if we are pre-expanding a macro argument.
196 // In that case we don't actually "activate" the pragma now, we only lex it
197 // until we are sure it is lexically correct and then we backtrack so that
198 // we activate the pragma whenever we encounter the tokens again in the token
199 // stream. This ensures that we will activate it in the correct location
200 // or that we will ignore it if it never enters the token stream, e.g:
201 //
202 // #define EMPTY(x)
203 // #define INACTIVE(x) EMPTY(x)
204 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
205
206 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
207
Chris Lattnerb694ba72006-07-02 22:41:36 +0000208 // Remember the pragma token location.
209 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattnerb694ba72006-07-02 22:41:36 +0000211 // Read the '('.
212 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000213 if (Tok.isNot(tok::l_paren)) {
214 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000215 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000216 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000217
218 // Read the '"..."'.
219 Lex(Tok);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000220 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000221 Diag(PragmaLoc, diag::err__Pragma_malformed);
Hubert Tong0deb6942015-07-30 21:30:00 +0000222 // Skip bad tokens, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000223 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000224 Lex(Tok);
Hubert Tong0deb6942015-07-30 21:30:00 +0000225 while (Tok.isNot(tok::r_paren) &&
226 !Tok.isAtStartOfLine() &&
227 Tok.isNot(tok::eof))
228 Lex(Tok);
Richard Smithd67aea22012-03-06 03:21:47 +0000229 if (Tok.is(tok::r_paren))
230 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000231 return _PragmaLexing.failed();
Richard Smithd67aea22012-03-06 03:21:47 +0000232 }
233
234 if (Tok.hasUDSuffix()) {
235 Diag(Tok, diag::err_invalid_string_udl);
236 // Skip this token, and the ')', if present.
237 Lex(Tok);
238 if (Tok.is(tok::r_paren))
239 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000240 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000241 }
Mike Stump11289f42009-09-09 15:08:12 +0000242
Chris Lattnerb694ba72006-07-02 22:41:36 +0000243 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000244 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000245
246 // Read the ')'.
247 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000248 if (Tok.isNot(tok::r_paren)) {
249 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000250 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000251 }
Mike Stump11289f42009-09-09 15:08:12 +0000252
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000253 if (InMacroArgPreExpansion)
254 return;
255
Chris Lattner9dc9c202009-02-15 20:52:18 +0000256 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000257 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000258
Richard Smithc98bb4e2013-03-09 23:30:15 +0000259 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
260 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattner262d4e32009-01-16 18:59:23 +0000261 // deleting the leading and trailing double-quotes, replacing each escape
262 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
263 // single backslash."
Richard Smithc98bb4e2013-03-09 23:30:15 +0000264 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
265 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000266 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-03-09 23:30:15 +0000267 else if (StrVal[0] == 'u')
268 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
269
270 if (StrVal[0] == 'R') {
271 // FIXME: C++11 does not specify how to handle raw-string-literals here.
272 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
273 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
274 "Invalid raw string token!");
275
276 // Measure the length of the d-char-sequence.
277 unsigned NumDChars = 0;
278 while (StrVal[2 + NumDChars] != '(') {
279 assert(NumDChars < (StrVal.size() - 5) / 2 &&
280 "Invalid raw string token!");
281 ++NumDChars;
282 }
283 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
284
285 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
286 // parens below.
287 StrVal.erase(0, 2 + NumDChars);
288 StrVal.erase(StrVal.size() - 1 - NumDChars);
289 } else {
290 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
291 "Invalid string token!");
292
293 // Remove escaped quotes and escapes.
Benjamin Kramerc2f5f292013-05-04 10:37:20 +0000294 unsigned ResultPos = 1;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000295 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
Reid Kleckner95e036c2013-09-25 16:42:48 +0000296 // Skip escapes. \\ -> '\' and \" -> '"'.
297 if (StrVal[i] == '\\' && i + 1 < e &&
298 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
299 ++i;
300 StrVal[ResultPos++] = StrVal[i];
Richard Smithc98bb4e2013-03-09 23:30:15 +0000301 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000302 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000303 }
Mike Stump11289f42009-09-09 15:08:12 +0000304
Chris Lattnerb694ba72006-07-02 22:41:36 +0000305 // Remove the front quote, replacing it with a space, so that the pragma
306 // contents appear to have a space before them.
307 StrVal[0] = ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000308
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000309 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000310 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000311
Peter Collingbournef29ce972011-02-22 13:49:06 +0000312 // Plop the string (including the newline and trailing null) into a buffer
313 // where we can lex it.
314 Token TmpTok;
315 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000316 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000317 SourceLocation TokLoc = TmpTok.getLocation();
318
319 // Make and enter a lexer object so that we lex and expand the tokens just
320 // like any others.
321 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
322 StrVal.size(), *this);
323
Craig Topperd2d442c2014-05-17 23:10:59 +0000324 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000325
326 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000327 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-08-28 22:34:47 +0000328
329 // Finally, return whatever came after the pragma directive.
330 return Lex(Tok);
331}
332
333/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
334/// is not enclosed within a string literal.
335void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
336 // Remember the pragma token location.
337 SourceLocation PragmaLoc = Tok.getLocation();
338
339 // Read the '('.
340 Lex(Tok);
341 if (Tok.isNot(tok::l_paren)) {
342 Diag(PragmaLoc, diag::err__Pragma_malformed);
343 return;
344 }
345
Peter Collingbournef29ce972011-02-22 13:49:06 +0000346 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000347 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000348 int NumParens = 0;
349 Lex(Tok);
350 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000351 PragmaToks.push_back(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000352 if (Tok.is(tok::l_paren))
353 NumParens++;
354 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
355 break;
John McCall89e925d2010-08-28 22:34:47 +0000356 Lex(Tok);
357 }
358
John McCall49039d42010-08-29 01:09:54 +0000359 if (Tok.is(tok::eof)) {
360 Diag(PragmaLoc, diag::err_unterminated___pragma);
361 return;
362 }
363
Peter Collingbournef29ce972011-02-22 13:49:06 +0000364 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000365
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000366 // Replace the ')' with an EOD to mark the end of the pragma.
367 PragmaToks.back().setKind(tok::eod);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000368
369 Token *TokArray = new Token[PragmaToks.size()];
370 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
371
372 // Push the tokens onto the stack.
373 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
374
375 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000376 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000377
378 // Finally, return whatever came after the pragma directive.
379 return Lex(Tok);
380}
381
James Dennett18a6d792012-06-17 03:26:26 +0000382/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000383///
Chris Lattner146762e2007-07-20 16:59:19 +0000384void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Sunil Srivastavafe583272016-07-25 17:17:06 +0000385 // Don't honor the 'once' when handling the primary source file, unless
Erik Verbruggene0bde752016-10-27 14:17:10 +0000386 // this is a prefix to a TU, which indicates we're generating a PCH file, or
387 // when the main file is a header (e.g. when -xc-header is provided on the
388 // commandline).
389 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000390 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
391 return;
392 }
Mike Stump11289f42009-09-09 15:08:12 +0000393
Chris Lattnerb694ba72006-07-02 22:41:36 +0000394 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000395 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000396 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000397}
398
Chris Lattnerc2383312007-12-19 19:38:36 +0000399void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000400 assert(CurPPLexer && "No current lexer?");
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000401 if (CurLexer)
402 CurLexer->ReadToEndOfLine();
403 else
404 CurPTHLexer->DiscardToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000405}
406
James Dennett18a6d792012-06-17 03:26:26 +0000407/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000408///
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000409void Preprocessor::HandlePragmaPoison() {
Chris Lattner146762e2007-07-20 16:59:19 +0000410 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000411
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000412 while (true) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000413 // Read the next token to poison. While doing this, pretend that we are
414 // skipping while reading the identifier to poison.
415 // This avoids errors on code like:
416 // #pragma GCC poison X
417 // #pragma GCC poison X
Ted Kremenek551c82a2008-11-18 01:12:54 +0000418 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000419 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000420 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattnerb694ba72006-07-02 22:41:36 +0000422 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000423 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattnerb694ba72006-07-02 22:41:36 +0000425 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000426 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000427 Diag(Tok, diag::err_pp_invalid_poison);
428 return;
429 }
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattnercefc7682006-07-08 08:28:12 +0000431 // Look up the identifier info for the token. We disabled identifier lookup
432 // by saying we're skipping contents, so we need to do this manually.
433 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattnerb694ba72006-07-02 22:41:36 +0000435 // Already poisoned.
436 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000437
Chris Lattnerb694ba72006-07-02 22:41:36 +0000438 // If this is a macro identifier, emit a warning.
Richard Smith20e883e2015-04-29 23:20:19 +0000439 if (isMacroDefined(II))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000440 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000441
Chris Lattnerb694ba72006-07-02 22:41:36 +0000442 // Finally, poison it!
443 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000444 if (II->isFromAST())
445 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000446 }
447}
448
James Dennett18a6d792012-06-17 03:26:26 +0000449/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000450/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000451void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000452 if (isInPrimaryFile()) {
453 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
454 return;
455 }
Mike Stump11289f42009-09-09 15:08:12 +0000456
Chris Lattnerb694ba72006-07-02 22:41:36 +0000457 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000458 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000459
Chris Lattnerb694ba72006-07-02 22:41:36 +0000460 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000461 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000462
463
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000464 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000465 if (PLoc.isInvalid())
466 return;
467
Jay Foad9a6b0982011-06-21 15:13:30 +0000468 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000469
Chris Lattner3bdc7672011-05-22 22:10:16 +0000470 // Notify the client, if desired, that we are in a new source file.
471 if (Callbacks)
472 Callbacks->FileChanged(SysHeaderTok.getLocation(),
473 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
474
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000475 // Emit a line marker. This will change any source locations from this point
476 // forward to realize they are in a system header.
477 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +0000478 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
Jordan Rose111c4a62013-04-17 19:09:18 +0000479 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000480 SrcMgr::C_System);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000481}
482
James Dennett18a6d792012-06-17 03:26:26 +0000483/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000484///
Chris Lattner146762e2007-07-20 16:59:19 +0000485void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
486 Token FilenameTok;
Ted Kremenek551c82a2008-11-18 01:12:54 +0000487 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000488
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000489 // If the token kind is EOD, the error has already been diagnosed.
490 if (FilenameTok.is(tok::eod))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000491 return;
Mike Stump11289f42009-09-09 15:08:12 +0000492
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000493 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000494 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000495 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000496 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000497 if (Invalid)
498 return;
Mike Stump11289f42009-09-09 15:08:12 +0000499
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000500 bool isAngled =
501 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000502 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
503 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000504 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000505 return;
Mike Stump11289f42009-09-09 15:08:12 +0000506
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000507 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000508 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000509 const FileEntry *File =
510 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000511 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000512 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000513 if (!SuppressIncludeNotFoundError)
514 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000515 return;
516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Chris Lattnerd32480d2009-01-17 06:22:33 +0000518 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000519
520 // If this file is older than the file it depends on, emit a diagnostic.
521 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
522 // Lex tokens at the end of the message and include them in the message.
523 std::string Message;
524 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000525 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000526 Message += getSpelling(DependencyTok) + " ";
527 Lex(DependencyTok);
528 }
Mike Stump11289f42009-09-09 15:08:12 +0000529
Chris Lattnerf0b04972010-09-05 23:16:09 +0000530 // Remove the trailing ' ' if present.
531 if (!Message.empty())
532 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000533 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000534 }
535}
536
Reid Kleckner002562a2013-05-06 21:02:12 +0000537/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000538/// Return the IdentifierInfo* associated with the macro to push or pop.
539IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
540 // Remember the pragma token location.
541 Token PragmaTok = Tok;
542
543 // Read the '('.
544 Lex(Tok);
545 if (Tok.isNot(tok::l_paren)) {
546 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
547 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000548 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000549 }
550
551 // Read the macro name string.
552 Lex(Tok);
553 if (Tok.isNot(tok::string_literal)) {
554 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
555 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000556 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000557 }
558
Richard Smithd67aea22012-03-06 03:21:47 +0000559 if (Tok.hasUDSuffix()) {
560 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000561 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000562 }
563
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000564 // Remember the macro string.
565 std::string StrVal = getSpelling(Tok);
566
567 // Read the ')'.
568 Lex(Tok);
569 if (Tok.isNot(tok::r_paren)) {
570 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
571 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000572 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000573 }
574
575 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
576 "Invalid string token!");
577
578 // Create a Token from the string.
579 Token MacroTok;
580 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000581 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000582 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000583
584 // Get the IdentifierInfo of MacroToPushTok.
585 return LookUpIdentifierInfo(MacroTok);
586}
587
James Dennett18a6d792012-06-17 03:26:26 +0000588/// \brief Handle \#pragma push_macro.
589///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000590/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000591/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000592/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000593/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000594void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
595 // Parse the pragma directive and get the macro IdentifierInfo*.
596 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
597 if (!IdentInfo) return;
598
599 // Get the MacroInfo associated with IdentInfo.
600 MacroInfo *MI = getMacroInfo(IdentInfo);
601
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000602 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000603 // Allow the original MacroInfo to be redefined later.
604 MI->setIsAllowRedefinitionsWithoutWarning(true);
605 }
606
607 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000608 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000609}
610
James Dennett18a6d792012-06-17 03:26:26 +0000611/// \brief Handle \#pragma pop_macro.
612///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000613/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000614/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000615/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000616/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000617void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
618 SourceLocation MessageLoc = PopMacroTok.getLocation();
619
620 // Parse the pragma directive and get the macro IdentifierInfo*.
621 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
622 if (!IdentInfo) return;
623
624 // Find the vector<MacroInfo*> associated with the macro.
625 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
626 PragmaPushMacroInfo.find(IdentInfo);
627 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000628 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith20e883e2015-04-29 23:20:19 +0000629 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000630 if (MI->isWarnIfUnused())
631 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
632 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000633 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000634
635 // Get the MacroInfo we want to reinstall.
636 MacroInfo *MacroToReInstall = iter->second.back();
637
Richard Smith713369b2015-04-23 20:40:50 +0000638 if (MacroToReInstall)
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000639 // Reinstall the previously pushed macro.
Richard Smith713369b2015-04-23 20:40:50 +0000640 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000641
642 // Pop PragmaPushMacroInfo stack.
643 iter->second.pop_back();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000644 if (iter->second.empty())
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000645 PragmaPushMacroInfo.erase(iter);
646 } else {
647 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
648 << IdentInfo->getName();
649 }
650}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000651
Aaron Ballman611306e2012-03-02 22:51:54 +0000652void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
653 // We will either get a quoted filename or a bracketed filename, and we
654 // have to track which we got. The first filename is the source name,
655 // and the second name is the mapped filename. If the first is quoted,
656 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman611306e2012-03-02 22:51:54 +0000657
658 // Get the open paren
659 Lex(Tok);
660 if (Tok.isNot(tok::l_paren)) {
661 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
662 return;
663 }
664
665 // We expect either a quoted string literal, or a bracketed name
666 Token SourceFilenameTok;
667 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
668 if (SourceFilenameTok.is(tok::eod)) {
669 // The diagnostic has already been handled
670 return;
671 }
672
673 StringRef SourceFileName;
674 SmallString<128> FileNameBuffer;
675 if (SourceFilenameTok.is(tok::string_literal) ||
676 SourceFilenameTok.is(tok::angle_string_literal)) {
677 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
678 } else if (SourceFilenameTok.is(tok::less)) {
679 // This could be a path instead of just a name
680 FileNameBuffer.push_back('<');
681 SourceLocation End;
682 if (ConcatenateIncludeName(FileNameBuffer, End))
683 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000684 SourceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000685 } else {
686 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
687 return;
688 }
689 FileNameBuffer.clear();
690
691 // Now we expect a comma, followed by another include name
692 Lex(Tok);
693 if (Tok.isNot(tok::comma)) {
694 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
695 return;
696 }
697
698 Token ReplaceFilenameTok;
699 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
700 if (ReplaceFilenameTok.is(tok::eod)) {
701 // The diagnostic has already been handled
702 return;
703 }
704
705 StringRef ReplaceFileName;
706 if (ReplaceFilenameTok.is(tok::string_literal) ||
707 ReplaceFilenameTok.is(tok::angle_string_literal)) {
708 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
709 } else if (ReplaceFilenameTok.is(tok::less)) {
710 // This could be a path instead of just a name
711 FileNameBuffer.push_back('<');
712 SourceLocation End;
713 if (ConcatenateIncludeName(FileNameBuffer, End))
714 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000715 ReplaceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000716 } else {
717 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
718 return;
719 }
720
721 // Finally, we expect the closing paren
722 Lex(Tok);
723 if (Tok.isNot(tok::r_paren)) {
724 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
725 return;
726 }
727
728 // Now that we have the source and target filenames, we need to make sure
729 // they're both of the same type (angled vs non-angled)
730 StringRef OriginalSource = SourceFileName;
731
732 bool SourceIsAngled =
733 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
734 SourceFileName);
735 bool ReplaceIsAngled =
736 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
737 ReplaceFileName);
738 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
739 (SourceIsAngled != ReplaceIsAngled)) {
740 unsigned int DiagID;
741 if (SourceIsAngled)
742 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
743 else
744 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
745
746 Diag(SourceFilenameTok.getLocation(), DiagID)
747 << SourceFileName
748 << ReplaceFileName;
749
750 return;
751 }
752
753 // Now we can let the include handler know about this mapping
754 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
755}
756
Richard Smith5d2ed482017-06-09 19:22:32 +0000757void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
758 SourceLocation Loc = Tok.getLocation();
759
760 LexUnexpandedToken(Tok);
761 if (Tok.isAnnotation() || !Tok.getIdentifierInfo()) {
762 Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << true;
763 return;
764 }
765 IdentifierInfo *ModuleName = Tok.getIdentifierInfo();
766
767 LexUnexpandedToken(Tok);
768 if (Tok.isNot(tok::eod)) {
769 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
770 DiscardUntilEndOfDirective();
771 }
772
773 if (CurPTHLexer) {
774 // FIXME: Support this somehow?
775 Diag(Loc, diag::err_pp_module_build_pth);
776 return;
777 }
778
779 CurLexer->LexingRawMode = true;
780
781 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
782 if (Tok.getKind() != tok::raw_identifier ||
783 Tok.getRawIdentifier() != Ident)
784 return false;
785 CurLexer->Lex(Tok);
786 return true;
787 };
788
789 // Scan forward looking for the end of the module.
790 const char *Start = CurLexer->getBufferLocation();
791 const char *End = nullptr;
792 unsigned NestingLevel = 1;
793 while (true) {
794 End = CurLexer->getBufferLocation();
795 CurLexer->Lex(Tok);
796
797 if (Tok.is(tok::eof)) {
798 Diag(Loc, diag::err_pp_module_build_missing_end);
799 break;
800 }
801
802 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
803 // Token was part of module; keep going.
804 continue;
805 }
806
807 // We hit something directive-shaped; check to see if this is the end
808 // of the module build.
809 CurLexer->ParsingPreprocessorDirective = true;
810 CurLexer->Lex(Tok);
811 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
812 TryConsumeIdentifier("module")) {
813 if (TryConsumeIdentifier("build"))
814 // #pragma clang module build -> entering a nested module build.
815 ++NestingLevel;
816 else if (TryConsumeIdentifier("endbuild")) {
817 // #pragma clang module endbuild -> leaving a module build.
818 if (--NestingLevel == 0)
819 break;
820 }
821 // We should either be looking at the EOD or more of the current directive
822 // preceding the EOD. Either way we can ignore this token and keep going.
823 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
824 }
825 }
826
827 CurLexer->LexingRawMode = false;
828
829 // Load the extracted text as a preprocessed module.
830 assert(CurLexer->getBuffer().begin() <= Start &&
831 Start <= CurLexer->getBuffer().end() &&
832 CurLexer->getBuffer().begin() <= End &&
833 End <= CurLexer->getBuffer().end() &&
834 "module source range not contained within same file buffer");
835 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
836 StringRef(Start, End - Start));
837}
838
Chris Lattnerb694ba72006-07-02 22:41:36 +0000839/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
840/// If 'Namespace' is non-null, then it is a token required to exist on the
841/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000842void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000843 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000844 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattnerb694ba72006-07-02 22:41:36 +0000846 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000847 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000848 // If there is already a pragma handler with the name of this namespace,
849 // we either have an error (directive with the same name as a namespace) or
850 // we already have the namespace to insert into.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000851 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000852 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000853 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +0000854 " handler with the same name!");
855 } else {
856 // Otherwise, this namespace doesn't exist yet, create and insert the
857 // handler for it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000858 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000859 PragmaHandlers->AddPragma(InsertNS);
860 }
861 }
Mike Stump11289f42009-09-09 15:08:12 +0000862
Chris Lattnerb694ba72006-07-02 22:41:36 +0000863 // Check to make sure we don't already have a pragma for this identifier.
864 assert(!InsertNS->FindHandler(Handler->getName()) &&
865 "Pragma handler already exists for this identifier!");
866 InsertNS->AddPragma(Handler);
867}
868
Daniel Dunbar40596532008-10-04 19:17:46 +0000869/// RemovePragmaHandler - Remove the specific pragma handler from the
870/// preprocessor. If \arg Namespace is non-null, then it should be the
871/// namespace that \arg Handler was added to. It is an error to remove
872/// a handler that has not been registered.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000873void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000874 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000875 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000876
Daniel Dunbar40596532008-10-04 19:17:46 +0000877 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000878 if (!Namespace.empty()) {
879 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-10-04 19:17:46 +0000880 assert(Existing && "Namespace containing handler does not exist!");
881
882 NS = Existing->getIfNamespace();
883 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
884 }
885
886 NS->RemovePragmaHandler(Handler);
Mike Stump11289f42009-09-09 15:08:12 +0000887
Craig Topperbe250302014-09-12 05:19:24 +0000888 // If this is a non-default namespace and it is now empty, remove it.
889 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000890 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000891 delete NS;
892 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000893}
894
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000895bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
896 Token Tok;
897 LexUnexpandedToken(Tok);
898
899 if (Tok.isNot(tok::identifier)) {
900 Diag(Tok, diag::ext_on_off_switch_syntax);
901 return true;
902 }
903 IdentifierInfo *II = Tok.getIdentifierInfo();
904 if (II->isStr("ON"))
905 Result = tok::OOS_ON;
906 else if (II->isStr("OFF"))
907 Result = tok::OOS_OFF;
908 else if (II->isStr("DEFAULT"))
909 Result = tok::OOS_DEFAULT;
910 else {
911 Diag(Tok, diag::ext_on_off_switch_syntax);
912 return true;
913 }
914
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000915 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000916 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000917 if (Tok.isNot(tok::eod))
918 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000919 return false;
920}
921
Chris Lattnerb694ba72006-07-02 22:41:36 +0000922namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000923
James Dennett18a6d792012-06-17 03:26:26 +0000924/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000925struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000926 PragmaOnceHandler() : PragmaHandler("once") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000927 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
928 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000929 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000930 PP.HandlePragmaOnce(OnceTok);
931 }
932};
933
James Dennett18a6d792012-06-17 03:26:26 +0000934/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000935/// rest of the line is not lexed.
936struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000937 PragmaMarkHandler() : PragmaHandler("mark") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000938
Craig Topper9140dd22014-03-11 06:50:42 +0000939 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
940 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +0000941 PP.HandlePragmaMark();
942 }
943};
944
James Dennett18a6d792012-06-17 03:26:26 +0000945/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000946struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000947 PragmaPoisonHandler() : PragmaHandler("poison") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000948
Craig Topper9140dd22014-03-11 06:50:42 +0000949 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
950 Token &PoisonTok) override {
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000951 PP.HandlePragmaPoison();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000952 }
953};
954
James Dennett18a6d792012-06-17 03:26:26 +0000955/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +0000956/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000957struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000958 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000959
Craig Topper9140dd22014-03-11 06:50:42 +0000960 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
961 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000962 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000963 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000964 }
965};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000966
Chris Lattnerb694ba72006-07-02 22:41:36 +0000967struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000968 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000969
Craig Topper9140dd22014-03-11 06:50:42 +0000970 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
971 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000972 PP.HandlePragmaDependency(DepToken);
973 }
974};
Mike Stump11289f42009-09-09 15:08:12 +0000975
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000976struct PragmaDebugHandler : public PragmaHandler {
977 PragmaDebugHandler() : PragmaHandler("__debug") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000978
Craig Topper9140dd22014-03-11 06:50:42 +0000979 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
980 Token &DepToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000981 Token Tok;
982 PP.LexUnexpandedToken(Tok);
983 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +0000984 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000985 return;
986 }
987 IdentifierInfo *II = Tok.getIdentifierInfo();
988
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000989 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +0000990 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000991 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +0000992 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +0000993 } else if (II->isStr("parser_crash")) {
994 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +0000995 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +0000996 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +0000997 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikie5d577a22012-06-29 22:03:56 +0000998 PP.EnterToken(Crasher);
Richard Smithba3a4f92016-01-12 21:59:26 +0000999 } else if (II->isStr("dump")) {
1000 Token Identifier;
1001 PP.LexUnexpandedToken(Identifier);
1002 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1003 Token DumpAnnot;
1004 DumpAnnot.startToken();
1005 DumpAnnot.setKind(tok::annot_pragma_dump);
1006 DumpAnnot.setAnnotationRange(
1007 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1008 DumpAnnot.setAnnotationValue(DumpII);
1009 PP.DiscardUntilEndOfDirective();
1010 PP.EnterToken(DumpAnnot);
1011 } else {
1012 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1013 << II->getName();
1014 }
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001015 } else if (II->isStr("llvm_fatal_error")) {
1016 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1017 } else if (II->isStr("llvm_unreachable")) {
1018 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smith3ffa61d2015-04-30 23:10:40 +00001019 } else if (II->isStr("macro")) {
1020 Token MacroName;
1021 PP.LexUnexpandedToken(MacroName);
1022 auto *MacroII = MacroName.getIdentifierInfo();
1023 if (MacroII)
1024 PP.dumpMacroInfo(MacroII);
1025 else
Richard Smithba3a4f92016-01-12 21:59:26 +00001026 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1027 << II->getName();
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001028 } else if (II->isStr("overflow_stack")) {
1029 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +00001030 } else if (II->isStr("handle_crash")) {
1031 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1032 if (CRC)
1033 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001034 } else if (II->isStr("captured")) {
1035 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001036 } else {
1037 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1038 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001039 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001040
1041 PPCallbacks *Callbacks = PP.getPPCallbacks();
1042 if (Callbacks)
1043 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1044 }
1045
1046 void HandleCaptured(Preprocessor &PP) {
1047 // Skip if emitting preprocessed output.
1048 if (PP.isPreprocessedOutput())
1049 return;
1050
1051 Token Tok;
1052 PP.LexUnexpandedToken(Tok);
1053
1054 if (Tok.isNot(tok::eod)) {
1055 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1056 << "pragma clang __debug captured";
1057 return;
1058 }
1059
1060 SourceLocation NameLoc = Tok.getLocation();
David Blaikie2eabcc92016-02-09 18:52:09 +00001061 MutableArrayRef<Token> Toks(
1062 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1063 Toks[0].startToken();
1064 Toks[0].setKind(tok::annot_pragma_captured);
1065 Toks[0].setLocation(NameLoc);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001066
David Blaikie2eabcc92016-02-09 18:52:09 +00001067 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001068 }
1069
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001070// Disable MSVC warning about runtime stack overflow.
1071#ifdef _MSC_VER
1072 #pragma warning(disable : 4717)
1073#endif
Matthias Braun285f88d2017-04-24 18:41:00 +00001074 static void DebugOverflowStack(void (*P)() = nullptr) {
1075 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1076 Self(reinterpret_cast<void(*)()>(Self));
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001077 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001078#ifdef _MSC_VER
1079 #pragma warning(default : 4717)
1080#endif
1081
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001082};
1083
James Dennett18a6d792012-06-17 03:26:26 +00001084/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +00001085struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001086private:
1087 const char *Namespace;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001088
Chris Lattnerfb42a182009-07-12 21:18:45 +00001089public:
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001090 explicit PragmaDiagnosticHandler(const char *NS) :
1091 PragmaHandler("diagnostic"), Namespace(NS) {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001092
Craig Topper9140dd22014-03-11 06:50:42 +00001093 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1094 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001095 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001096 Token Tok;
1097 PP.LexUnexpandedToken(Tok);
1098 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001099 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001100 return;
1101 }
1102 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001103 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +00001104
Alp Toker46df1c02014-06-12 10:15:20 +00001105 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001106 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +00001107 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001108 else if (Callbacks)
1109 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +00001110 return;
1111 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001112 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001113 if (Callbacks)
1114 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +00001115 return;
Alp Toker46df1c02014-06-12 10:15:20 +00001116 }
1117
1118 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1119 .Case("ignored", diag::Severity::Ignored)
1120 .Case("warning", diag::Severity::Warning)
1121 .Case("error", diag::Severity::Error)
1122 .Case("fatal", diag::Severity::Fatal)
1123 .Default(diag::Severity());
1124
1125 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001126 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001127 return;
1128 }
Mike Stump11289f42009-09-09 15:08:12 +00001129
Chris Lattner504af112009-04-19 23:16:58 +00001130 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +00001131 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001132
Andy Gibbs58905d22012-11-17 19:15:38 +00001133 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001134 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1135 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +00001136 return;
Mike Stump11289f42009-09-09 15:08:12 +00001137
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001138 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +00001139 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1140 return;
1141 }
Mike Stump11289f42009-09-09 15:08:12 +00001142
Chris Lattner504af112009-04-19 23:16:58 +00001143 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +00001144 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001145 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +00001146 return;
1147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
Sunil Srivastava5239de72016-02-13 01:44:05 +00001149 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1150 : diag::Flavor::Remark;
Benjamin Kramer2193e232016-02-13 13:42:41 +00001151 StringRef Group = StringRef(WarningName).substr(2);
Sunil Srivastava5239de72016-02-13 01:44:05 +00001152 bool unknownDiag = false;
1153 if (Group == "everything") {
1154 // Special handling for pragma clang diagnostic ... "-Weverything".
1155 // There is no formal group named "everything", so there has to be a
1156 // special case for it.
1157 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1158 } else
1159 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1160 DiagLoc);
1161 if (unknownDiag)
Andy Gibbs58905d22012-11-17 19:15:38 +00001162 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1163 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001164 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001165 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001166 }
1167};
Mike Stump11289f42009-09-09 15:08:12 +00001168
Reid Kleckner881dff32013-09-13 22:00:30 +00001169/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1170/// diagnostics, so we don't really implement this pragma. We parse it and
1171/// ignore it to avoid -Wunknown-pragma warnings.
1172struct PragmaWarningHandler : public PragmaHandler {
1173 PragmaWarningHandler() : PragmaHandler("warning") {}
1174
Craig Topper9140dd22014-03-11 06:50:42 +00001175 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1176 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001177 // Parse things like:
1178 // warning(push, 1)
1179 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001180 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001181 SourceLocation DiagLoc = Tok.getLocation();
1182 PPCallbacks *Callbacks = PP.getPPCallbacks();
1183
1184 PP.Lex(Tok);
1185 if (Tok.isNot(tok::l_paren)) {
1186 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1187 return;
1188 }
1189
1190 PP.Lex(Tok);
1191 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner881dff32013-09-13 22:00:30 +00001192
Alexander Musman6b080fc2015-05-25 11:21:20 +00001193 if (II && II->isStr("push")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001194 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001195 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001196 PP.Lex(Tok);
1197 if (Tok.is(tok::comma)) {
1198 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001199 uint64_t Value;
1200 if (Tok.is(tok::numeric_constant) &&
1201 PP.parseSimpleIntegerLiteral(Tok, Value))
1202 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001203 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001204 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1205 return;
1206 }
1207 }
1208 if (Callbacks)
1209 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman6b080fc2015-05-25 11:21:20 +00001210 } else if (II && II->isStr("pop")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001211 // #pragma warning( pop )
1212 PP.Lex(Tok);
1213 if (Callbacks)
1214 Callbacks->PragmaWarningPop(DiagLoc);
1215 } else {
1216 // #pragma warning( warning-specifier : warning-number-list
1217 // [; warning-specifier : warning-number-list...] )
1218 while (true) {
1219 II = Tok.getIdentifierInfo();
Alexander Musman6b080fc2015-05-25 11:21:20 +00001220 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001221 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1222 return;
1223 }
1224
1225 // Figure out which warning specifier this is.
Alexander Musman6b080fc2015-05-25 11:21:20 +00001226 bool SpecifierValid;
1227 StringRef Specifier;
1228 llvm::SmallString<1> SpecifierBuf;
1229 if (II) {
1230 Specifier = II->getName();
1231 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1232 .Cases("default", "disable", "error", "once",
1233 "suppress", true)
1234 .Default(false);
1235 // If we read a correct specifier, snatch next token (that should be
1236 // ":", checked later).
1237 if (SpecifierValid)
1238 PP.Lex(Tok);
1239 } else {
1240 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1241 uint64_t Value;
1242 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1243 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1244 SpecifierValid = (Value >= 1) && (Value <= 4);
1245 } else
1246 SpecifierValid = false;
1247 // Next token already snatched by parseSimpleIntegerLiteral.
1248 }
1249
Reid Kleckner881dff32013-09-13 22:00:30 +00001250 if (!SpecifierValid) {
1251 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1252 return;
1253 }
Reid Kleckner881dff32013-09-13 22:00:30 +00001254 if (Tok.isNot(tok::colon)) {
1255 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1256 return;
1257 }
1258
1259 // Collect the warning ids.
1260 SmallVector<int, 4> Ids;
1261 PP.Lex(Tok);
1262 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001263 uint64_t Value;
1264 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001265 Value > std::numeric_limits<int>::max()) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001266 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1267 return;
1268 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001269 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001270 }
1271 if (Callbacks)
1272 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1273
1274 // Parse the next specifier if there is a semicolon.
1275 if (Tok.isNot(tok::semi))
1276 break;
1277 PP.Lex(Tok);
1278 }
1279 }
1280
1281 if (Tok.isNot(tok::r_paren)) {
1282 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1283 return;
1284 }
1285
1286 PP.Lex(Tok);
1287 if (Tok.isNot(tok::eod))
1288 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1289 }
1290};
1291
James Dennett18a6d792012-06-17 03:26:26 +00001292/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001293struct PragmaIncludeAliasHandler : public PragmaHandler {
1294 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001295 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1296 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001297 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001298 }
1299};
1300
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001301/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1302/// extension. The syntax is:
1303/// \code
1304/// #pragma message(string)
1305/// \endcode
1306/// OR, in GCC mode:
1307/// \code
1308/// #pragma message string
1309/// \endcode
1310/// string is a string, which is fully macro expanded, and permits string
1311/// concatenation, embedded escape characters, etc... See MSDN for more details.
1312/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1313/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001314struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001315private:
1316 const PPCallbacks::PragmaMessageKind Kind;
1317 const StringRef Namespace;
1318
1319 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1320 bool PragmaNameOnly = false) {
1321 switch (Kind) {
1322 case PPCallbacks::PMK_Message:
1323 return PragmaNameOnly ? "message" : "pragma message";
1324 case PPCallbacks::PMK_Warning:
1325 return PragmaNameOnly ? "warning" : "pragma warning";
1326 case PPCallbacks::PMK_Error:
1327 return PragmaNameOnly ? "error" : "pragma error";
1328 }
1329 llvm_unreachable("Unknown PragmaMessageKind!");
1330 }
1331
1332public:
1333 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1334 StringRef Namespace = StringRef())
1335 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1336
Craig Topper9140dd22014-03-11 06:50:42 +00001337 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1338 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001339 SourceLocation MessageLoc = Tok.getLocation();
1340 PP.Lex(Tok);
1341 bool ExpectClosingParen = false;
1342 switch (Tok.getKind()) {
1343 case tok::l_paren:
1344 // We have a MSVC style pragma message.
1345 ExpectClosingParen = true;
1346 // Read the string.
1347 PP.Lex(Tok);
1348 break;
1349 case tok::string_literal:
1350 // We have a GCC style pragma message, and we just read the string.
1351 break;
1352 default:
1353 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1354 return;
1355 }
1356
1357 std::string MessageString;
1358 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1359 /*MacroExpansion=*/true))
1360 return;
1361
1362 if (ExpectClosingParen) {
1363 if (Tok.isNot(tok::r_paren)) {
1364 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1365 return;
1366 }
1367 PP.Lex(Tok); // eat the r_paren.
1368 }
1369
1370 if (Tok.isNot(tok::eod)) {
1371 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1372 return;
1373 }
1374
1375 // Output the message.
1376 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1377 ? diag::err_pragma_message
1378 : diag::warn_pragma_message) << MessageString;
1379
1380 // If the pragma is lexically sound, notify any interested PPCallbacks.
1381 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1382 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001383 }
1384};
1385
Richard Smithd1386302017-05-04 00:29:54 +00001386static bool LexModuleName(
1387 Preprocessor &PP, Token &Tok,
1388 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
1389 &ModuleName) {
1390 while (true) {
1391 PP.LexUnexpandedToken(Tok);
Richard Smithce037322017-05-05 22:34:07 +00001392 if (Tok.isAnnotation() || !Tok.getIdentifierInfo()) {
Richard Smithd1386302017-05-04 00:29:54 +00001393 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name)
1394 << ModuleName.empty();
1395 return true;
1396 }
1397
1398 ModuleName.emplace_back(Tok.getIdentifierInfo(), Tok.getLocation());
1399
1400 PP.LexUnexpandedToken(Tok);
1401 if (Tok.isNot(tok::period))
1402 return false;
1403 }
1404}
1405
Richard Smithc51c38b2017-04-29 00:34:47 +00001406/// Handle the clang \#pragma module import extension. The syntax is:
1407/// \code
1408/// #pragma clang module import some.module.name
1409/// \endcode
1410struct PragmaModuleImportHandler : public PragmaHandler {
1411 PragmaModuleImportHandler() : PragmaHandler("import") {}
1412
1413 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smithd1386302017-05-04 00:29:54 +00001414 Token &Tok) override {
1415 SourceLocation ImportLoc = Tok.getLocation();
1416
1417 // Read the module name.
1418 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1419 ModuleName;
1420 if (LexModuleName(PP, Tok, ModuleName))
1421 return;
1422
1423 if (Tok.isNot(tok::eod))
1424 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1425
1426 // If we have a non-empty module path, load the named module.
1427 Module *Imported =
1428 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1429 /*IsIncludeDirective=*/false);
1430 if (!Imported)
1431 return;
1432
1433 PP.makeModuleVisible(Imported, ImportLoc);
1434 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1435 tok::annot_module_include, Imported);
1436 if (auto *CB = PP.getPPCallbacks())
1437 CB->moduleImport(ImportLoc, ModuleName, Imported);
1438 }
1439};
1440
1441/// Handle the clang \#pragma module begin extension. The syntax is:
1442/// \code
1443/// #pragma clang module begin some.module.name
1444/// ...
1445/// #pragma clang module end
1446/// \endcode
1447struct PragmaModuleBeginHandler : public PragmaHandler {
1448 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1449
1450 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1451 Token &Tok) override {
1452 SourceLocation BeginLoc = Tok.getLocation();
1453
1454 // Read the module name.
1455 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1456 ModuleName;
1457 if (LexModuleName(PP, Tok, ModuleName))
1458 return;
1459
1460 if (Tok.isNot(tok::eod))
1461 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1462
1463 // We can only enter submodules of the current module.
1464 StringRef Current = PP.getLangOpts().CurrentModule;
1465 if (ModuleName.front().first->getName() != Current) {
1466 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1467 << ModuleName.front().first << (ModuleName.size() > 1)
1468 << Current.empty() << Current;
1469 return;
1470 }
1471
1472 // Find the module we're entering. We require that a module map for it
1473 // be loaded or implicitly loadable.
1474 // FIXME: We could create the submodule here. We'd need to know whether
1475 // it's supposed to be explicit, but not much else.
1476 Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(Current);
1477 if (!M) {
1478 PP.Diag(ModuleName.front().second,
1479 diag::err_pp_module_begin_no_module_map) << Current;
1480 return;
1481 }
1482 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1483 auto *NewM = M->findSubmodule(ModuleName[I].first->getName());
1484 if (!NewM) {
1485 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1486 << M->getFullModuleName() << ModuleName[I].first;
1487 return;
1488 }
1489 M = NewM;
1490 }
1491
Richard Smith51d09c52017-05-30 05:22:59 +00001492 // If the module isn't available, it doesn't make sense to enter it.
Richard Smith27e5aa02017-06-05 18:57:56 +00001493 if (Preprocessor::checkModuleIsAvailable(
1494 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
Richard Smith51d09c52017-05-30 05:22:59 +00001495 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1496 << M->getTopLevelModuleName();
1497 return;
1498 }
1499
Richard Smithd1386302017-05-04 00:29:54 +00001500 // Enter the scope of the submodule.
1501 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1502 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1503 tok::annot_module_begin, M);
1504 }
1505};
1506
1507/// Handle the clang \#pragma module end extension.
1508struct PragmaModuleEndHandler : public PragmaHandler {
1509 PragmaModuleEndHandler() : PragmaHandler("end") {}
1510
1511 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1512 Token &Tok) override {
1513 SourceLocation Loc = Tok.getLocation();
1514
1515 PP.LexUnexpandedToken(Tok);
1516 if (Tok.isNot(tok::eod))
1517 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1518
1519 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1520 if (M)
1521 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1522 else
1523 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
Richard Smithc51c38b2017-04-29 00:34:47 +00001524 }
1525};
1526
Richard Smith5d2ed482017-06-09 19:22:32 +00001527/// Handle the clang \#pragma module build extension.
1528struct PragmaModuleBuildHandler : public PragmaHandler {
1529 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1530
1531 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1532 Token &Tok) override {
1533 PP.HandlePragmaModuleBuild(Tok);
1534 }
1535};
1536
1537/// Handle the clang \#pragma module load extension.
1538struct PragmaModuleLoadHandler : public PragmaHandler {
1539 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1540
1541 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1542 Token &Tok) override {
1543 SourceLocation Loc = Tok.getLocation();
1544
1545 // Read the module name.
1546 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1547 ModuleName;
1548 if (LexModuleName(PP, Tok, ModuleName))
1549 return;
1550
1551 if (Tok.isNot(tok::eod))
1552 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1553
1554 // Load the module, don't make it visible.
1555 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1556 /*IsIncludeDirective=*/false);
1557 }
1558};
1559
James Dennett18a6d792012-06-17 03:26:26 +00001560/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001561/// macro on the top of the stack.
1562struct PragmaPushMacroHandler : public PragmaHandler {
1563 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001564
Craig Topper9140dd22014-03-11 06:50:42 +00001565 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1566 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001567 PP.HandlePragmaPushMacro(PushMacroTok);
1568 }
1569};
1570
James Dennett18a6d792012-06-17 03:26:26 +00001571/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001572/// macro to the value on the top of the stack.
1573struct PragmaPopMacroHandler : public PragmaHandler {
1574 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001575
Craig Topper9140dd22014-03-11 06:50:42 +00001576 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1577 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001578 PP.HandlePragmaPopMacro(PopMacroTok);
1579 }
1580};
1581
Chris Lattner958ee042009-04-19 21:20:35 +00001582// Pragma STDC implementations.
Chris Lattner02ef4e32009-04-19 21:50:08 +00001583
James Dennett18a6d792012-06-17 03:26:26 +00001584/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001585struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001586 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001587
Craig Topper9140dd22014-03-11 06:50:42 +00001588 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1589 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001590 tok::OnOffSwitch OOS;
1591 if (PP.LexOnOffSwitch(OOS))
1592 return;
1593 if (OOS == tok::OOS_ON)
Chris Lattnerdf222682009-04-19 21:55:32 +00001594 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
Chris Lattner958ee042009-04-19 21:20:35 +00001595 }
1596};
Mike Stump11289f42009-09-09 15:08:12 +00001597
James Dennett18a6d792012-06-17 03:26:26 +00001598/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001599struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001600 PragmaSTDC_CX_LIMITED_RANGEHandler()
1601 : PragmaHandler("CX_LIMITED_RANGE") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001602
Craig Topper9140dd22014-03-11 06:50:42 +00001603 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1604 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001605 tok::OnOffSwitch OOS;
1606 PP.LexOnOffSwitch(OOS);
Chris Lattner958ee042009-04-19 21:20:35 +00001607 }
1608};
Mike Stump11289f42009-09-09 15:08:12 +00001609
James Dennett18a6d792012-06-17 03:26:26 +00001610/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001611struct PragmaSTDC_UnknownHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001612 PragmaSTDC_UnknownHandler() {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001613
Craig Topper9140dd22014-03-11 06:50:42 +00001614 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1615 Token &UnknownTok) override {
Chris Lattner02ef4e32009-04-19 21:50:08 +00001616 // C99 6.10.6p2, unknown forms are not allowed.
Chris Lattnera0b1f762009-04-19 21:25:37 +00001617 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
Chris Lattner958ee042009-04-19 21:20:35 +00001618 }
1619};
Mike Stump11289f42009-09-09 15:08:12 +00001620
John McCall32f5fe12011-09-30 05:12:12 +00001621/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001622/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001623struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1624 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001625
Craig Topper9140dd22014-03-11 06:50:42 +00001626 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1627 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001628 SourceLocation Loc = NameTok.getLocation();
1629 bool IsBegin;
1630
1631 Token Tok;
1632
1633 // Lex the 'begin' or 'end'.
1634 PP.LexUnexpandedToken(Tok);
1635 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1636 if (BeginEnd && BeginEnd->isStr("begin")) {
1637 IsBegin = true;
1638 } else if (BeginEnd && BeginEnd->isStr("end")) {
1639 IsBegin = false;
1640 } else {
1641 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1642 return;
1643 }
1644
1645 // Verify that this is followed by EOD.
1646 PP.LexUnexpandedToken(Tok);
1647 if (Tok.isNot(tok::eod))
1648 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1649
1650 // The start location of the active audit.
1651 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1652
1653 // The start location we want after processing this.
1654 SourceLocation NewLoc;
1655
1656 if (IsBegin) {
1657 // Complain about attempts to re-enter an audit.
1658 if (BeginLoc.isValid()) {
1659 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1660 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1661 }
1662 NewLoc = Loc;
1663 } else {
1664 // Complain about attempts to leave an audit that doesn't exist.
1665 if (!BeginLoc.isValid()) {
1666 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1667 return;
1668 }
1669 NewLoc = SourceLocation();
1670 }
1671
1672 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1673 }
1674};
1675
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001676/// PragmaAssumeNonNullHandler -
1677/// \#pragma clang assume_nonnull begin/end
1678struct PragmaAssumeNonNullHandler : public PragmaHandler {
1679 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001680
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001681 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1682 Token &NameTok) override {
1683 SourceLocation Loc = NameTok.getLocation();
1684 bool IsBegin;
1685
1686 Token Tok;
1687
1688 // Lex the 'begin' or 'end'.
1689 PP.LexUnexpandedToken(Tok);
1690 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1691 if (BeginEnd && BeginEnd->isStr("begin")) {
1692 IsBegin = true;
1693 } else if (BeginEnd && BeginEnd->isStr("end")) {
1694 IsBegin = false;
1695 } else {
1696 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1697 return;
1698 }
1699
1700 // Verify that this is followed by EOD.
1701 PP.LexUnexpandedToken(Tok);
1702 if (Tok.isNot(tok::eod))
1703 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1704
1705 // The start location of the active audit.
1706 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1707
1708 // The start location we want after processing this.
1709 SourceLocation NewLoc;
1710
1711 if (IsBegin) {
1712 // Complain about attempts to re-enter an audit.
1713 if (BeginLoc.isValid()) {
1714 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1715 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1716 }
1717 NewLoc = Loc;
1718 } else {
1719 // Complain about attempts to leave an audit that doesn't exist.
1720 if (!BeginLoc.isValid()) {
1721 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1722 return;
1723 }
1724 NewLoc = SourceLocation();
1725 }
1726
1727 PP.setPragmaAssumeNonNullLoc(NewLoc);
1728 }
1729};
1730
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001731/// \brief Handle "\#pragma region [...]"
1732///
1733/// The syntax is
1734/// \code
1735/// #pragma region [optional name]
1736/// #pragma endregion [optional comment]
1737/// \endcode
1738///
1739/// \note This is
1740/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1741/// pragma, just skipped by compiler.
1742struct PragmaRegionHandler : public PragmaHandler {
1743 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
Aaron Ballman406ea512012-11-30 19:52:30 +00001744
Craig Topper9140dd22014-03-11 06:50:42 +00001745 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1746 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001747 // #pragma region: endregion matches can be verified
1748 // __pragma(region): no sense, but ignored by msvc
1749 // _Pragma is not valid for MSVC, but there isn't any point
1750 // to handle a _Pragma differently.
1751 }
1752};
Aaron Ballman406ea512012-11-30 19:52:30 +00001753
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001754} // end anonymous namespace
Chris Lattnerb694ba72006-07-02 22:41:36 +00001755
1756/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001757/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001758void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001759 AddPragmaHandler(new PragmaOnceHandler());
1760 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001761 AddPragmaHandler(new PragmaPushMacroHandler());
1762 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001763 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001764
Chris Lattnerb61448d2009-05-12 18:21:11 +00001765 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001766 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1767 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1768 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001769 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001770 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1771 "GCC"));
1772 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1773 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001774 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001775 AddPragmaHandler("clang", new PragmaPoisonHandler());
1776 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001777 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001778 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001779 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001780 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001781 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001782
Richard Smithc51c38b2017-04-29 00:34:47 +00001783 // #pragma clang module ...
1784 auto *ModuleHandler = new PragmaNamespace("module");
1785 AddPragmaHandler("clang", ModuleHandler);
1786 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
Richard Smithd1386302017-05-04 00:29:54 +00001787 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1788 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
Richard Smith5d2ed482017-06-09 19:22:32 +00001789 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1790 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
Richard Smithc51c38b2017-04-29 00:34:47 +00001791
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001792 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1793 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
Chris Lattner958ee042009-04-19 21:20:35 +00001794 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
Mike Stump11289f42009-09-09 15:08:12 +00001795
Chris Lattner2ff698d2009-01-16 08:21:25 +00001796 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001797 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001798 AddPragmaHandler(new PragmaWarningHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001799 AddPragmaHandler(new PragmaIncludeAliasHandler());
Aaron Ballman406ea512012-11-30 19:52:30 +00001800 AddPragmaHandler(new PragmaRegionHandler("region"));
1801 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Chris Lattner30c924b2010-06-26 17:11:39 +00001802 }
John Brawn8e62db32016-04-04 14:22:58 +00001803
1804 // Pragmas added by plugins
1805 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1806 ie = PragmaHandlerRegistry::end();
1807 it != ie; ++it) {
1808 AddPragmaHandler(it->instantiate().release());
1809 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001810}
Lubos Lunak576a0412014-05-01 12:54:03 +00001811
1812/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1813/// warn about those pragmas being unknown.
1814void Preprocessor::IgnorePragmas() {
1815 AddPragmaHandler(new EmptyPragmaHandler());
1816 // Also ignore all pragmas in all namespaces created
1817 // in Preprocessor::RegisterBuiltinPragmas().
1818 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1819 AddPragmaHandler("clang", new EmptyPragmaHandler());
1820 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1821 // Preprocessor::RegisterBuiltinPragmas() already registers
1822 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1823 // otherwise there will be an assert about a duplicate handler.
1824 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1825 assert(STDCNamespace &&
1826 "Invalid namespace, registered as a regular pragma handler!");
1827 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1828 RemovePragmaHandler("STDC", Existing);
Chandler Carruth4d9c3df2014-05-02 21:44:48 +00001829 delete Existing;
Lubos Lunak576a0412014-05-01 12:54:03 +00001830 }
1831 }
1832 AddPragmaHandler("STDC", new EmptyPragmaHandler());
1833}