blob: bf2363a0a6f459a032e67897ca68aa2be76841b0 [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"
Richard Smith9565c75b2017-06-19 23:09:36 +000023#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000025#include "clang/Lex/PPCallbacks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Lex/Preprocessor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000027#include "clang/Lex/PreprocessorLexer.h"
28#include "clang/Lex/PTHLexer.h"
29#include "clang/Lex/Token.h"
30#include "clang/Lex/TokenLexer.h"
31#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/ADT/SmallVector.h"
Reid Kleckner881dff32013-09-13 22:00:30 +000035#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/StringSwitch.h"
Daniel Dunbar211a7872010-08-18 23:09:23 +000037#include "llvm/Support/CrashRecoveryContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000038#include "llvm/Support/Compiler.h"
Daniel Dunbarf2cf3292010-08-17 22:32:48 +000039#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000040#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000041#include <cassert>
42#include <cstdint>
43#include <limits>
44#include <string>
45#include <vector>
46
Chris Lattnerb8761832006-06-24 21:31:03 +000047using namespace clang;
48
49// Out-of-line destructor to provide a home for the class.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000050PragmaHandler::~PragmaHandler() {
51}
Chris Lattnerb8761832006-06-24 21:31:03 +000052
Chris Lattner2e155302006-07-03 05:34:41 +000053//===----------------------------------------------------------------------===//
Daniel Dunbard839e772010-06-11 20:10:12 +000054// EmptyPragmaHandler Implementation.
55//===----------------------------------------------------------------------===//
56
Hans Wennborg7357bbc2015-10-12 20:47:58 +000057EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000058
Douglas Gregorc7d65762010-09-09 22:45:38 +000059void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
60 PragmaIntroducerKind Introducer,
61 Token &FirstToken) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000062
63//===----------------------------------------------------------------------===//
Chris Lattner2e155302006-07-03 05:34:41 +000064// PragmaNamespace Implementation.
65//===----------------------------------------------------------------------===//
66
Chris Lattner2e155302006-07-03 05:34:41 +000067PragmaNamespace::~PragmaNamespace() {
Reid Kleckner588c9372014-02-19 23:44:52 +000068 llvm::DeleteContainerSeconds(Handlers);
Chris Lattner2e155302006-07-03 05:34:41 +000069}
70
71/// FindHandler - Check to see if there is already a handler for the
72/// specified name. If not, return the handler for the null identifier if it
73/// exists, otherwise return null. If IgnoreNull is true (the default) then
74/// the null handler isn't returned on failure to match.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000075PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Chris Lattner2e155302006-07-03 05:34:41 +000076 bool IgnoreNull) const {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000077 if (PragmaHandler *Handler = Handlers.lookup(Name))
78 return Handler;
Craig Topperd2d442c2014-05-17 23:10:59 +000079 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000080}
Mike Stump11289f42009-09-09 15:08:12 +000081
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000082void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
83 assert(!Handlers.lookup(Handler->getName()) &&
84 "A handler with this name is already registered in this namespace");
David Blaikie13156b62014-11-19 03:06:06 +000085 Handlers[Handler->getName()] = Handler;
Chris Lattner2e155302006-07-03 05:34:41 +000086}
87
Daniel Dunbar40596532008-10-04 19:17:46 +000088void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000089 assert(Handlers.lookup(Handler->getName()) &&
90 "Handler not registered in this namespace");
91 Handlers.erase(Handler->getName());
Daniel Dunbar40596532008-10-04 19:17:46 +000092}
93
Douglas Gregorc7d65762010-09-09 22:45:38 +000094void PragmaNamespace::HandlePragma(Preprocessor &PP,
95 PragmaIntroducerKind Introducer,
96 Token &Tok) {
Chris Lattnerb8761832006-06-24 21:31:03 +000097 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
98 // expand it, the user can have a STDC #define, that should not affect this.
99 PP.LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000100
Chris Lattnerb8761832006-06-24 21:31:03 +0000101 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000102 PragmaHandler *Handler
103 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000104 : StringRef(),
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000105 /*IgnoreNull=*/false);
Craig Topperd2d442c2014-05-17 23:10:59 +0000106 if (!Handler) {
Chris Lattner21656f22009-04-19 21:10:26 +0000107 PP.Diag(Tok, diag::warn_pragma_ignored);
108 return;
109 }
Mike Stump11289f42009-09-09 15:08:12 +0000110
Chris Lattnerb8761832006-06-24 21:31:03 +0000111 // Otherwise, pass it down.
Douglas Gregorc7d65762010-09-09 22:45:38 +0000112 Handler->HandlePragma(PP, Introducer, Tok);
Chris Lattnerb8761832006-06-24 21:31:03 +0000113}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000114
Chris Lattnerb694ba72006-07-02 22:41:36 +0000115//===----------------------------------------------------------------------===//
116// Preprocessor Pragma Directive Handling.
117//===----------------------------------------------------------------------===//
118
James Dennett18a6d792012-06-17 03:26:26 +0000119/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Chris Lattnerb694ba72006-07-02 22:41:36 +0000120/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000121void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
122 PragmaIntroducerKind Introducer) {
123 if (Callbacks)
124 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
125
Jordan Rosede1a2922012-06-08 18:06:21 +0000126 if (!PragmasEnabled)
127 return;
128
Chris Lattnerb694ba72006-07-02 22:41:36 +0000129 ++NumPragma;
Mike Stump11289f42009-09-09 15:08:12 +0000130
Chris Lattnerb694ba72006-07-02 22:41:36 +0000131 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattner146762e2007-07-20 16:59:19 +0000132 Token Tok;
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000133 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000134
Chris Lattnerb694ba72006-07-02 22:41:36 +0000135 // If the pragma handler didn't read the rest of the line, consume it now.
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000136 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
137 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000138 DiscardUntilEndOfDirective();
139}
140
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000141namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000142
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000143/// \brief Helper class for \see Preprocessor::Handle_Pragma.
144class LexingFor_PragmaRAII {
145 Preprocessor &PP;
146 bool InMacroArgPreExpansion;
147 bool Failed;
148 Token &OutTok;
149 Token PragmaTok;
150
151public:
152 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
153 Token &Tok)
154 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
155 Failed(false), OutTok(Tok) {
156 if (InMacroArgPreExpansion) {
157 PragmaTok = OutTok;
158 PP.EnableBacktrackAtThisPos();
159 }
160 }
161
162 ~LexingFor_PragmaRAII() {
163 if (InMacroArgPreExpansion) {
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000164 // When committing/backtracking the cached pragma tokens in a macro
165 // argument pre-expansion we want to ensure that either the tokens which
166 // have been committed will be removed from the cache or that the tokens
167 // over which we just backtracked won't remain in the cache after they're
168 // consumed and that the caching will stop after consuming them.
169 // Otherwise the caching will interfere with the way macro expansion
170 // works, because we will continue to cache tokens after consuming the
171 // backtracked tokens, which shouldn't happen when we're dealing with
172 // macro argument pre-expansion.
173 auto CachedTokenRange = PP.LastCachedTokenRange();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000174 if (Failed) {
175 PP.CommitBacktrackedTokens();
176 } else {
177 PP.Backtrack();
178 OutTok = PragmaTok;
179 }
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000180 PP.EraseCachedTokens(CachedTokenRange);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000181 }
182 }
183
184 void failed() {
185 Failed = true;
186 }
187};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000188
189} // end anonymous namespace
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000190
Chris Lattnerb694ba72006-07-02 22:41:36 +0000191/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
192/// return the first token after the directive. The _Pragma token has just
193/// been read into 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000194void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000195
196 // This works differently if we are pre-expanding a macro argument.
197 // In that case we don't actually "activate" the pragma now, we only lex it
198 // until we are sure it is lexically correct and then we backtrack so that
199 // we activate the pragma whenever we encounter the tokens again in the token
200 // stream. This ensures that we will activate it in the correct location
201 // or that we will ignore it if it never enters the token stream, e.g:
202 //
203 // #define EMPTY(x)
204 // #define INACTIVE(x) EMPTY(x)
205 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
206
207 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
208
Chris Lattnerb694ba72006-07-02 22:41:36 +0000209 // Remember the pragma token location.
210 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattnerb694ba72006-07-02 22:41:36 +0000212 // Read the '('.
213 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000214 if (Tok.isNot(tok::l_paren)) {
215 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000216 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000217 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000218
219 // Read the '"..."'.
220 Lex(Tok);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000221 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000222 Diag(PragmaLoc, diag::err__Pragma_malformed);
Hubert Tong0deb6942015-07-30 21:30:00 +0000223 // Skip bad tokens, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000224 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000225 Lex(Tok);
Hubert Tong0deb6942015-07-30 21:30:00 +0000226 while (Tok.isNot(tok::r_paren) &&
227 !Tok.isAtStartOfLine() &&
228 Tok.isNot(tok::eof))
229 Lex(Tok);
Richard Smithd67aea22012-03-06 03:21:47 +0000230 if (Tok.is(tok::r_paren))
231 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000232 return _PragmaLexing.failed();
Richard Smithd67aea22012-03-06 03:21:47 +0000233 }
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);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000241 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000242 }
Mike Stump11289f42009-09-09 15:08:12 +0000243
Chris Lattnerb694ba72006-07-02 22:41:36 +0000244 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000245 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000246
247 // Read the ')'.
248 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000249 if (Tok.isNot(tok::r_paren)) {
250 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000251 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000252 }
Mike Stump11289f42009-09-09 15:08:12 +0000253
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000254 if (InMacroArgPreExpansion)
255 return;
256
Chris Lattner9dc9c202009-02-15 20:52:18 +0000257 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000258 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000259
Richard Smithc98bb4e2013-03-09 23:30:15 +0000260 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
261 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattner262d4e32009-01-16 18:59:23 +0000262 // deleting the leading and trailing double-quotes, replacing each escape
263 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
264 // single backslash."
Richard Smithc98bb4e2013-03-09 23:30:15 +0000265 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
266 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000267 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-03-09 23:30:15 +0000268 else if (StrVal[0] == 'u')
269 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
270
271 if (StrVal[0] == 'R') {
272 // FIXME: C++11 does not specify how to handle raw-string-literals here.
273 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
274 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
275 "Invalid raw string token!");
276
277 // Measure the length of the d-char-sequence.
278 unsigned NumDChars = 0;
279 while (StrVal[2 + NumDChars] != '(') {
280 assert(NumDChars < (StrVal.size() - 5) / 2 &&
281 "Invalid raw string token!");
282 ++NumDChars;
283 }
284 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
285
286 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
287 // parens below.
288 StrVal.erase(0, 2 + NumDChars);
289 StrVal.erase(StrVal.size() - 1 - NumDChars);
290 } else {
291 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
292 "Invalid string token!");
293
294 // Remove escaped quotes and escapes.
Benjamin Kramerc2f5f292013-05-04 10:37:20 +0000295 unsigned ResultPos = 1;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000296 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
Reid Kleckner95e036c2013-09-25 16:42:48 +0000297 // Skip escapes. \\ -> '\' and \" -> '"'.
298 if (StrVal[i] == '\\' && i + 1 < e &&
299 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
300 ++i;
301 StrVal[ResultPos++] = StrVal[i];
Richard Smithc98bb4e2013-03-09 23:30:15 +0000302 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000303 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000304 }
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattnerb694ba72006-07-02 22:41:36 +0000306 // Remove the front quote, replacing it with a space, so that the pragma
307 // contents appear to have a space before them.
308 StrVal[0] = ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000309
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000310 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000311 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000312
Peter Collingbournef29ce972011-02-22 13:49:06 +0000313 // Plop the string (including the newline and trailing null) into a buffer
314 // where we can lex it.
315 Token TmpTok;
316 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000317 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000318 SourceLocation TokLoc = TmpTok.getLocation();
319
320 // Make and enter a lexer object so that we lex and expand the tokens just
321 // like any others.
322 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
323 StrVal.size(), *this);
324
Craig Topperd2d442c2014-05-17 23:10:59 +0000325 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000326
327 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000328 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-08-28 22:34:47 +0000329
330 // Finally, return whatever came after the pragma directive.
331 return Lex(Tok);
332}
333
334/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
335/// is not enclosed within a string literal.
336void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
337 // Remember the pragma token location.
338 SourceLocation PragmaLoc = Tok.getLocation();
339
340 // Read the '('.
341 Lex(Tok);
342 if (Tok.isNot(tok::l_paren)) {
343 Diag(PragmaLoc, diag::err__Pragma_malformed);
344 return;
345 }
346
Peter Collingbournef29ce972011-02-22 13:49:06 +0000347 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000348 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000349 int NumParens = 0;
350 Lex(Tok);
351 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000352 PragmaToks.push_back(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000353 if (Tok.is(tok::l_paren))
354 NumParens++;
355 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
356 break;
John McCall89e925d2010-08-28 22:34:47 +0000357 Lex(Tok);
358 }
359
John McCall49039d42010-08-29 01:09:54 +0000360 if (Tok.is(tok::eof)) {
361 Diag(PragmaLoc, diag::err_unterminated___pragma);
362 return;
363 }
364
Peter Collingbournef29ce972011-02-22 13:49:06 +0000365 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000366
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000367 // Replace the ')' with an EOD to mark the end of the pragma.
368 PragmaToks.back().setKind(tok::eod);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000369
370 Token *TokArray = new Token[PragmaToks.size()];
371 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
372
373 // Push the tokens onto the stack.
374 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
375
376 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000377 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000378
379 // Finally, return whatever came after the pragma directive.
380 return Lex(Tok);
381}
382
James Dennett18a6d792012-06-17 03:26:26 +0000383/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000384///
Chris Lattner146762e2007-07-20 16:59:19 +0000385void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Sunil Srivastavafe583272016-07-25 17:17:06 +0000386 // Don't honor the 'once' when handling the primary source file, unless
Erik Verbruggene0bde752016-10-27 14:17:10 +0000387 // this is a prefix to a TU, which indicates we're generating a PCH file, or
388 // when the main file is a header (e.g. when -xc-header is provided on the
389 // commandline).
390 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000391 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
392 return;
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattnerb694ba72006-07-02 22:41:36 +0000395 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000396 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000397 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000398}
399
Chris Lattnerc2383312007-12-19 19:38:36 +0000400void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000401 assert(CurPPLexer && "No current lexer?");
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000402 if (CurLexer)
403 CurLexer->ReadToEndOfLine();
404 else
405 CurPTHLexer->DiscardToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000406}
407
James Dennett18a6d792012-06-17 03:26:26 +0000408/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000409///
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000410void Preprocessor::HandlePragmaPoison() {
Chris Lattner146762e2007-07-20 16:59:19 +0000411 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000412
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000413 while (true) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000414 // Read the next token to poison. While doing this, pretend that we are
415 // skipping while reading the identifier to poison.
416 // This avoids errors on code like:
417 // #pragma GCC poison X
418 // #pragma GCC poison X
Ted Kremenek551c82a2008-11-18 01:12:54 +0000419 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000420 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000421 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chris Lattnerb694ba72006-07-02 22:41:36 +0000423 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000424 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattnerb694ba72006-07-02 22:41:36 +0000426 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000427 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000428 Diag(Tok, diag::err_pp_invalid_poison);
429 return;
430 }
Mike Stump11289f42009-09-09 15:08:12 +0000431
Chris Lattnercefc7682006-07-08 08:28:12 +0000432 // Look up the identifier info for the token. We disabled identifier lookup
433 // by saying we're skipping contents, so we need to do this manually.
434 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattnerb694ba72006-07-02 22:41:36 +0000436 // Already poisoned.
437 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000438
Chris Lattnerb694ba72006-07-02 22:41:36 +0000439 // If this is a macro identifier, emit a warning.
Richard Smith20e883e2015-04-29 23:20:19 +0000440 if (isMacroDefined(II))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000441 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000442
Chris Lattnerb694ba72006-07-02 22:41:36 +0000443 // Finally, poison it!
444 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000445 if (II->isFromAST())
446 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000447 }
448}
449
James Dennett18a6d792012-06-17 03:26:26 +0000450/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000451/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000452void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000453 if (isInPrimaryFile()) {
454 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
455 return;
456 }
Mike Stump11289f42009-09-09 15:08:12 +0000457
Chris Lattnerb694ba72006-07-02 22:41:36 +0000458 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000459 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000460
Chris Lattnerb694ba72006-07-02 22:41:36 +0000461 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000462 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000463
464
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000465 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000466 if (PLoc.isInvalid())
467 return;
468
Jay Foad9a6b0982011-06-21 15:13:30 +0000469 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000470
Chris Lattner3bdc7672011-05-22 22:10:16 +0000471 // Notify the client, if desired, that we are in a new source file.
472 if (Callbacks)
473 Callbacks->FileChanged(SysHeaderTok.getLocation(),
474 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
475
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000476 // Emit a line marker. This will change any source locations from this point
477 // forward to realize they are in a system header.
478 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +0000479 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
Jordan Rose111c4a62013-04-17 19:09:18 +0000480 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000481 SrcMgr::C_System);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000482}
483
James Dennett18a6d792012-06-17 03:26:26 +0000484/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000485///
Chris Lattner146762e2007-07-20 16:59:19 +0000486void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
487 Token FilenameTok;
Ted Kremenek551c82a2008-11-18 01:12:54 +0000488 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000489
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000490 // If the token kind is EOD, the error has already been diagnosed.
491 if (FilenameTok.is(tok::eod))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000492 return;
Mike Stump11289f42009-09-09 15:08:12 +0000493
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000494 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000495 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000496 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000498 if (Invalid)
499 return;
Mike Stump11289f42009-09-09 15:08:12 +0000500
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000501 bool isAngled =
502 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000503 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
504 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000505 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000506 return;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000508 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000509 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000510 const FileEntry *File =
511 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +0000512 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000513 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000514 if (!SuppressIncludeNotFoundError)
515 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000516 return;
517 }
Mike Stump11289f42009-09-09 15:08:12 +0000518
Chris Lattnerd32480d2009-01-17 06:22:33 +0000519 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000520
521 // If this file is older than the file it depends on, emit a diagnostic.
522 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
523 // Lex tokens at the end of the message and include them in the message.
524 std::string Message;
525 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000526 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000527 Message += getSpelling(DependencyTok) + " ";
528 Lex(DependencyTok);
529 }
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattnerf0b04972010-09-05 23:16:09 +0000531 // Remove the trailing ' ' if present.
532 if (!Message.empty())
533 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000534 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000535 }
536}
537
Reid Kleckner002562a2013-05-06 21:02:12 +0000538/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000539/// Return the IdentifierInfo* associated with the macro to push or pop.
540IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
541 // Remember the pragma token location.
542 Token PragmaTok = Tok;
543
544 // Read the '('.
545 Lex(Tok);
546 if (Tok.isNot(tok::l_paren)) {
547 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
548 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000549 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000550 }
551
552 // Read the macro name string.
553 Lex(Tok);
554 if (Tok.isNot(tok::string_literal)) {
555 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
556 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000557 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000558 }
559
Richard Smithd67aea22012-03-06 03:21:47 +0000560 if (Tok.hasUDSuffix()) {
561 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000562 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000563 }
564
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000565 // Remember the macro string.
566 std::string StrVal = getSpelling(Tok);
567
568 // Read the ')'.
569 Lex(Tok);
570 if (Tok.isNot(tok::r_paren)) {
571 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
572 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000573 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000574 }
575
576 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
577 "Invalid string token!");
578
579 // Create a Token from the string.
580 Token MacroTok;
581 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000582 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000583 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000584
585 // Get the IdentifierInfo of MacroToPushTok.
586 return LookUpIdentifierInfo(MacroTok);
587}
588
James Dennett18a6d792012-06-17 03:26:26 +0000589/// \brief Handle \#pragma push_macro.
590///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000591/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000592/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000593/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000594/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000595void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
596 // Parse the pragma directive and get the macro IdentifierInfo*.
597 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
598 if (!IdentInfo) return;
599
600 // Get the MacroInfo associated with IdentInfo.
601 MacroInfo *MI = getMacroInfo(IdentInfo);
602
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000603 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000604 // Allow the original MacroInfo to be redefined later.
605 MI->setIsAllowRedefinitionsWithoutWarning(true);
606 }
607
608 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000609 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000610}
611
James Dennett18a6d792012-06-17 03:26:26 +0000612/// \brief Handle \#pragma pop_macro.
613///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000614/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000615/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000616/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000617/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000618void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
619 SourceLocation MessageLoc = PopMacroTok.getLocation();
620
621 // Parse the pragma directive and get the macro IdentifierInfo*.
622 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
623 if (!IdentInfo) return;
624
625 // Find the vector<MacroInfo*> associated with the macro.
626 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
627 PragmaPushMacroInfo.find(IdentInfo);
628 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000629 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith20e883e2015-04-29 23:20:19 +0000630 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000631 if (MI->isWarnIfUnused())
632 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
633 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000634 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000635
636 // Get the MacroInfo we want to reinstall.
637 MacroInfo *MacroToReInstall = iter->second.back();
638
Richard Smith713369b2015-04-23 20:40:50 +0000639 if (MacroToReInstall)
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000640 // Reinstall the previously pushed macro.
Richard Smith713369b2015-04-23 20:40:50 +0000641 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000642
643 // Pop PragmaPushMacroInfo stack.
644 iter->second.pop_back();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000645 if (iter->second.empty())
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000646 PragmaPushMacroInfo.erase(iter);
647 } else {
648 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
649 << IdentInfo->getName();
650 }
651}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000652
Aaron Ballman611306e2012-03-02 22:51:54 +0000653void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
654 // We will either get a quoted filename or a bracketed filename, and we
655 // have to track which we got. The first filename is the source name,
656 // and the second name is the mapped filename. If the first is quoted,
657 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman611306e2012-03-02 22:51:54 +0000658
659 // Get the open paren
660 Lex(Tok);
661 if (Tok.isNot(tok::l_paren)) {
662 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
663 return;
664 }
665
666 // We expect either a quoted string literal, or a bracketed name
667 Token SourceFilenameTok;
668 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
669 if (SourceFilenameTok.is(tok::eod)) {
670 // The diagnostic has already been handled
671 return;
672 }
673
674 StringRef SourceFileName;
675 SmallString<128> FileNameBuffer;
676 if (SourceFilenameTok.is(tok::string_literal) ||
677 SourceFilenameTok.is(tok::angle_string_literal)) {
678 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
679 } else if (SourceFilenameTok.is(tok::less)) {
680 // This could be a path instead of just a name
681 FileNameBuffer.push_back('<');
682 SourceLocation End;
683 if (ConcatenateIncludeName(FileNameBuffer, End))
684 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000685 SourceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000686 } else {
687 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
688 return;
689 }
690 FileNameBuffer.clear();
691
692 // Now we expect a comma, followed by another include name
693 Lex(Tok);
694 if (Tok.isNot(tok::comma)) {
695 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
696 return;
697 }
698
699 Token ReplaceFilenameTok;
700 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
701 if (ReplaceFilenameTok.is(tok::eod)) {
702 // The diagnostic has already been handled
703 return;
704 }
705
706 StringRef ReplaceFileName;
707 if (ReplaceFilenameTok.is(tok::string_literal) ||
708 ReplaceFilenameTok.is(tok::angle_string_literal)) {
709 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
710 } else if (ReplaceFilenameTok.is(tok::less)) {
711 // This could be a path instead of just a name
712 FileNameBuffer.push_back('<');
713 SourceLocation End;
714 if (ConcatenateIncludeName(FileNameBuffer, End))
715 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000716 ReplaceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000717 } else {
718 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
719 return;
720 }
721
722 // Finally, we expect the closing paren
723 Lex(Tok);
724 if (Tok.isNot(tok::r_paren)) {
725 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
726 return;
727 }
728
729 // Now that we have the source and target filenames, we need to make sure
730 // they're both of the same type (angled vs non-angled)
731 StringRef OriginalSource = SourceFileName;
732
733 bool SourceIsAngled =
734 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
735 SourceFileName);
736 bool ReplaceIsAngled =
737 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
738 ReplaceFileName);
739 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
740 (SourceIsAngled != ReplaceIsAngled)) {
741 unsigned int DiagID;
742 if (SourceIsAngled)
743 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
744 else
745 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
746
747 Diag(SourceFilenameTok.getLocation(), DiagID)
748 << SourceFileName
749 << ReplaceFileName;
750
751 return;
752 }
753
754 // Now we can let the include handler know about this mapping
755 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
756}
757
Richard Smith9565c75b2017-06-19 23:09:36 +0000758// Lex a component of a module name: either an identifier or a string literal;
759// for components that can be expressed both ways, the two forms are equivalent.
760static bool LexModuleNameComponent(
761 Preprocessor &PP, Token &Tok,
762 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
763 bool First) {
764 PP.LexUnexpandedToken(Tok);
765 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
766 StringLiteralParser Literal(Tok, PP);
767 if (Literal.hadError)
768 return true;
769 ModuleNameComponent = std::make_pair(
770 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
771 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
772 ModuleNameComponent =
773 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
774 } else {
775 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
776 return true;
777 }
778 return false;
779}
780
781static bool LexModuleName(
782 Preprocessor &PP, Token &Tok,
783 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
784 &ModuleName) {
785 while (true) {
786 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
787 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
788 return true;
789 ModuleName.push_back(NameComponent);
790
791 PP.LexUnexpandedToken(Tok);
792 if (Tok.isNot(tok::period))
793 return false;
794 }
795}
796
Richard Smith5d2ed482017-06-09 19:22:32 +0000797void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
798 SourceLocation Loc = Tok.getLocation();
799
Richard Smith9565c75b2017-06-19 23:09:36 +0000800 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
801 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
Richard Smith5d2ed482017-06-09 19:22:32 +0000802 return;
Richard Smith9565c75b2017-06-19 23:09:36 +0000803 IdentifierInfo *ModuleName = ModuleNameLoc.first;
Richard Smith5d2ed482017-06-09 19:22:32 +0000804
805 LexUnexpandedToken(Tok);
806 if (Tok.isNot(tok::eod)) {
807 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
808 DiscardUntilEndOfDirective();
809 }
810
811 if (CurPTHLexer) {
812 // FIXME: Support this somehow?
813 Diag(Loc, diag::err_pp_module_build_pth);
814 return;
815 }
816
817 CurLexer->LexingRawMode = true;
818
819 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
820 if (Tok.getKind() != tok::raw_identifier ||
821 Tok.getRawIdentifier() != Ident)
822 return false;
823 CurLexer->Lex(Tok);
824 return true;
825 };
826
827 // Scan forward looking for the end of the module.
828 const char *Start = CurLexer->getBufferLocation();
829 const char *End = nullptr;
830 unsigned NestingLevel = 1;
831 while (true) {
832 End = CurLexer->getBufferLocation();
833 CurLexer->Lex(Tok);
834
835 if (Tok.is(tok::eof)) {
836 Diag(Loc, diag::err_pp_module_build_missing_end);
837 break;
838 }
839
840 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
841 // Token was part of module; keep going.
842 continue;
843 }
844
845 // We hit something directive-shaped; check to see if this is the end
846 // of the module build.
847 CurLexer->ParsingPreprocessorDirective = true;
848 CurLexer->Lex(Tok);
849 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
850 TryConsumeIdentifier("module")) {
851 if (TryConsumeIdentifier("build"))
852 // #pragma clang module build -> entering a nested module build.
853 ++NestingLevel;
854 else if (TryConsumeIdentifier("endbuild")) {
855 // #pragma clang module endbuild -> leaving a module build.
856 if (--NestingLevel == 0)
857 break;
858 }
859 // We should either be looking at the EOD or more of the current directive
860 // preceding the EOD. Either way we can ignore this token and keep going.
861 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
862 }
863 }
864
865 CurLexer->LexingRawMode = false;
866
867 // Load the extracted text as a preprocessed module.
868 assert(CurLexer->getBuffer().begin() <= Start &&
869 Start <= CurLexer->getBuffer().end() &&
870 CurLexer->getBuffer().begin() <= End &&
871 End <= CurLexer->getBuffer().end() &&
872 "module source range not contained within same file buffer");
873 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
874 StringRef(Start, End - Start));
875}
876
Chris Lattnerb694ba72006-07-02 22:41:36 +0000877/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
878/// If 'Namespace' is non-null, then it is a token required to exist on the
879/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000880void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000881 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000882 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000883
Chris Lattnerb694ba72006-07-02 22:41:36 +0000884 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000885 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000886 // If there is already a pragma handler with the name of this namespace,
887 // we either have an error (directive with the same name as a namespace) or
888 // we already have the namespace to insert into.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000889 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000890 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000891 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +0000892 " handler with the same name!");
893 } else {
894 // Otherwise, this namespace doesn't exist yet, create and insert the
895 // handler for it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000896 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000897 PragmaHandlers->AddPragma(InsertNS);
898 }
899 }
Mike Stump11289f42009-09-09 15:08:12 +0000900
Chris Lattnerb694ba72006-07-02 22:41:36 +0000901 // Check to make sure we don't already have a pragma for this identifier.
902 assert(!InsertNS->FindHandler(Handler->getName()) &&
903 "Pragma handler already exists for this identifier!");
904 InsertNS->AddPragma(Handler);
905}
906
Daniel Dunbar40596532008-10-04 19:17:46 +0000907/// RemovePragmaHandler - Remove the specific pragma handler from the
908/// preprocessor. If \arg Namespace is non-null, then it should be the
909/// namespace that \arg Handler was added to. It is an error to remove
910/// a handler that has not been registered.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000911void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000912 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000913 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000914
Daniel Dunbar40596532008-10-04 19:17:46 +0000915 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000916 if (!Namespace.empty()) {
917 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-10-04 19:17:46 +0000918 assert(Existing && "Namespace containing handler does not exist!");
919
920 NS = Existing->getIfNamespace();
921 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
922 }
923
924 NS->RemovePragmaHandler(Handler);
Mike Stump11289f42009-09-09 15:08:12 +0000925
Craig Topperbe250302014-09-12 05:19:24 +0000926 // If this is a non-default namespace and it is now empty, remove it.
927 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000928 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000929 delete NS;
930 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000931}
932
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000933bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
934 Token Tok;
935 LexUnexpandedToken(Tok);
936
937 if (Tok.isNot(tok::identifier)) {
938 Diag(Tok, diag::ext_on_off_switch_syntax);
939 return true;
940 }
941 IdentifierInfo *II = Tok.getIdentifierInfo();
942 if (II->isStr("ON"))
943 Result = tok::OOS_ON;
944 else if (II->isStr("OFF"))
945 Result = tok::OOS_OFF;
946 else if (II->isStr("DEFAULT"))
947 Result = tok::OOS_DEFAULT;
948 else {
949 Diag(Tok, diag::ext_on_off_switch_syntax);
950 return true;
951 }
952
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000953 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000954 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000955 if (Tok.isNot(tok::eod))
956 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000957 return false;
958}
959
Chris Lattnerb694ba72006-07-02 22:41:36 +0000960namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000961
James Dennett18a6d792012-06-17 03:26:26 +0000962/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000963struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000964 PragmaOnceHandler() : PragmaHandler("once") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000965 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
966 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000967 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000968 PP.HandlePragmaOnce(OnceTok);
969 }
970};
971
James Dennett18a6d792012-06-17 03:26:26 +0000972/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000973/// rest of the line is not lexed.
974struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000975 PragmaMarkHandler() : PragmaHandler("mark") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000976
Craig Topper9140dd22014-03-11 06:50:42 +0000977 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
978 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +0000979 PP.HandlePragmaMark();
980 }
981};
982
James Dennett18a6d792012-06-17 03:26:26 +0000983/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000984struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000985 PragmaPoisonHandler() : PragmaHandler("poison") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000986
Craig Topper9140dd22014-03-11 06:50:42 +0000987 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
988 Token &PoisonTok) override {
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000989 PP.HandlePragmaPoison();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000990 }
991};
992
James Dennett18a6d792012-06-17 03:26:26 +0000993/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +0000994/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000995struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000996 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000997
Craig Topper9140dd22014-03-11 06:50:42 +0000998 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
999 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001000 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001001 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +00001002 }
1003};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001004
Chris Lattnerb694ba72006-07-02 22:41:36 +00001005struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001006 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001007
Craig Topper9140dd22014-03-11 06:50:42 +00001008 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1009 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001010 PP.HandlePragmaDependency(DepToken);
1011 }
1012};
Mike Stump11289f42009-09-09 15:08:12 +00001013
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001014struct PragmaDebugHandler : public PragmaHandler {
1015 PragmaDebugHandler() : PragmaHandler("__debug") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001016
Craig Topper9140dd22014-03-11 06:50:42 +00001017 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1018 Token &DepToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001019 Token Tok;
1020 PP.LexUnexpandedToken(Tok);
1021 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001022 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001023 return;
1024 }
1025 IdentifierInfo *II = Tok.getIdentifierInfo();
1026
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001027 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +00001028 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001029 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +00001030 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +00001031 } else if (II->isStr("parser_crash")) {
1032 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +00001033 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +00001034 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +00001035 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikie5d577a22012-06-29 22:03:56 +00001036 PP.EnterToken(Crasher);
Richard Smithba3a4f92016-01-12 21:59:26 +00001037 } else if (II->isStr("dump")) {
1038 Token Identifier;
1039 PP.LexUnexpandedToken(Identifier);
1040 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1041 Token DumpAnnot;
1042 DumpAnnot.startToken();
1043 DumpAnnot.setKind(tok::annot_pragma_dump);
1044 DumpAnnot.setAnnotationRange(
1045 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1046 DumpAnnot.setAnnotationValue(DumpII);
1047 PP.DiscardUntilEndOfDirective();
1048 PP.EnterToken(DumpAnnot);
1049 } else {
1050 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1051 << II->getName();
1052 }
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001053 } else if (II->isStr("llvm_fatal_error")) {
1054 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1055 } else if (II->isStr("llvm_unreachable")) {
1056 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smith3ffa61d2015-04-30 23:10:40 +00001057 } else if (II->isStr("macro")) {
1058 Token MacroName;
1059 PP.LexUnexpandedToken(MacroName);
1060 auto *MacroII = MacroName.getIdentifierInfo();
1061 if (MacroII)
1062 PP.dumpMacroInfo(MacroII);
1063 else
Richard Smithba3a4f92016-01-12 21:59:26 +00001064 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1065 << II->getName();
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001066 } else if (II->isStr("overflow_stack")) {
1067 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +00001068 } else if (II->isStr("handle_crash")) {
1069 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1070 if (CRC)
1071 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001072 } else if (II->isStr("captured")) {
1073 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001074 } else {
1075 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1076 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001077 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001078
1079 PPCallbacks *Callbacks = PP.getPPCallbacks();
1080 if (Callbacks)
1081 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1082 }
1083
1084 void HandleCaptured(Preprocessor &PP) {
1085 // Skip if emitting preprocessed output.
1086 if (PP.isPreprocessedOutput())
1087 return;
1088
1089 Token Tok;
1090 PP.LexUnexpandedToken(Tok);
1091
1092 if (Tok.isNot(tok::eod)) {
1093 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1094 << "pragma clang __debug captured";
1095 return;
1096 }
1097
1098 SourceLocation NameLoc = Tok.getLocation();
David Blaikie2eabcc92016-02-09 18:52:09 +00001099 MutableArrayRef<Token> Toks(
1100 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1101 Toks[0].startToken();
1102 Toks[0].setKind(tok::annot_pragma_captured);
1103 Toks[0].setLocation(NameLoc);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001104
David Blaikie2eabcc92016-02-09 18:52:09 +00001105 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001106 }
1107
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001108// Disable MSVC warning about runtime stack overflow.
1109#ifdef _MSC_VER
1110 #pragma warning(disable : 4717)
1111#endif
Matthias Braun285f88d2017-04-24 18:41:00 +00001112 static void DebugOverflowStack(void (*P)() = nullptr) {
1113 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1114 Self(reinterpret_cast<void(*)()>(Self));
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001115 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001116#ifdef _MSC_VER
1117 #pragma warning(default : 4717)
1118#endif
1119
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001120};
1121
James Dennett18a6d792012-06-17 03:26:26 +00001122/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +00001123struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001124private:
1125 const char *Namespace;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001126
Chris Lattnerfb42a182009-07-12 21:18:45 +00001127public:
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001128 explicit PragmaDiagnosticHandler(const char *NS) :
1129 PragmaHandler("diagnostic"), Namespace(NS) {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001130
Craig Topper9140dd22014-03-11 06:50:42 +00001131 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1132 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001133 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001134 Token Tok;
1135 PP.LexUnexpandedToken(Tok);
1136 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001137 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001138 return;
1139 }
1140 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001141 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +00001142
Alp Toker46df1c02014-06-12 10:15:20 +00001143 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001144 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +00001145 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001146 else if (Callbacks)
1147 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +00001148 return;
1149 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001150 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001151 if (Callbacks)
1152 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +00001153 return;
Alp Toker46df1c02014-06-12 10:15:20 +00001154 }
1155
1156 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1157 .Case("ignored", diag::Severity::Ignored)
1158 .Case("warning", diag::Severity::Warning)
1159 .Case("error", diag::Severity::Error)
1160 .Case("fatal", diag::Severity::Fatal)
1161 .Default(diag::Severity());
1162
1163 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001164 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001165 return;
1166 }
Mike Stump11289f42009-09-09 15:08:12 +00001167
Chris Lattner504af112009-04-19 23:16:58 +00001168 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +00001169 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001170
Andy Gibbs58905d22012-11-17 19:15:38 +00001171 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001172 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1173 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +00001174 return;
Mike Stump11289f42009-09-09 15:08:12 +00001175
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001176 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +00001177 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1178 return;
1179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
Chris Lattner504af112009-04-19 23:16:58 +00001181 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +00001182 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001183 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +00001184 return;
1185 }
Mike Stump11289f42009-09-09 15:08:12 +00001186
Sunil Srivastava5239de72016-02-13 01:44:05 +00001187 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1188 : diag::Flavor::Remark;
Benjamin Kramer2193e232016-02-13 13:42:41 +00001189 StringRef Group = StringRef(WarningName).substr(2);
Sunil Srivastava5239de72016-02-13 01:44:05 +00001190 bool unknownDiag = false;
1191 if (Group == "everything") {
1192 // Special handling for pragma clang diagnostic ... "-Weverything".
1193 // There is no formal group named "everything", so there has to be a
1194 // special case for it.
1195 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1196 } else
1197 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1198 DiagLoc);
1199 if (unknownDiag)
Andy Gibbs58905d22012-11-17 19:15:38 +00001200 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1201 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001202 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001203 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001204 }
1205};
Mike Stump11289f42009-09-09 15:08:12 +00001206
Reid Kleckner881dff32013-09-13 22:00:30 +00001207/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1208/// diagnostics, so we don't really implement this pragma. We parse it and
1209/// ignore it to avoid -Wunknown-pragma warnings.
1210struct PragmaWarningHandler : public PragmaHandler {
1211 PragmaWarningHandler() : PragmaHandler("warning") {}
1212
Craig Topper9140dd22014-03-11 06:50:42 +00001213 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1214 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001215 // Parse things like:
1216 // warning(push, 1)
1217 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001218 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001219 SourceLocation DiagLoc = Tok.getLocation();
1220 PPCallbacks *Callbacks = PP.getPPCallbacks();
1221
1222 PP.Lex(Tok);
1223 if (Tok.isNot(tok::l_paren)) {
1224 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1225 return;
1226 }
1227
1228 PP.Lex(Tok);
1229 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner881dff32013-09-13 22:00:30 +00001230
Alexander Musman6b080fc2015-05-25 11:21:20 +00001231 if (II && II->isStr("push")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001232 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001233 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001234 PP.Lex(Tok);
1235 if (Tok.is(tok::comma)) {
1236 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001237 uint64_t Value;
1238 if (Tok.is(tok::numeric_constant) &&
1239 PP.parseSimpleIntegerLiteral(Tok, Value))
1240 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001241 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001242 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1243 return;
1244 }
1245 }
1246 if (Callbacks)
1247 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman6b080fc2015-05-25 11:21:20 +00001248 } else if (II && II->isStr("pop")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001249 // #pragma warning( pop )
1250 PP.Lex(Tok);
1251 if (Callbacks)
1252 Callbacks->PragmaWarningPop(DiagLoc);
1253 } else {
1254 // #pragma warning( warning-specifier : warning-number-list
1255 // [; warning-specifier : warning-number-list...] )
1256 while (true) {
1257 II = Tok.getIdentifierInfo();
Alexander Musman6b080fc2015-05-25 11:21:20 +00001258 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001259 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1260 return;
1261 }
1262
1263 // Figure out which warning specifier this is.
Alexander Musman6b080fc2015-05-25 11:21:20 +00001264 bool SpecifierValid;
1265 StringRef Specifier;
1266 llvm::SmallString<1> SpecifierBuf;
1267 if (II) {
1268 Specifier = II->getName();
1269 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1270 .Cases("default", "disable", "error", "once",
1271 "suppress", true)
1272 .Default(false);
1273 // If we read a correct specifier, snatch next token (that should be
1274 // ":", checked later).
1275 if (SpecifierValid)
1276 PP.Lex(Tok);
1277 } else {
1278 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1279 uint64_t Value;
1280 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1281 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1282 SpecifierValid = (Value >= 1) && (Value <= 4);
1283 } else
1284 SpecifierValid = false;
1285 // Next token already snatched by parseSimpleIntegerLiteral.
1286 }
1287
Reid Kleckner881dff32013-09-13 22:00:30 +00001288 if (!SpecifierValid) {
1289 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1290 return;
1291 }
Reid Kleckner881dff32013-09-13 22:00:30 +00001292 if (Tok.isNot(tok::colon)) {
1293 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1294 return;
1295 }
1296
1297 // Collect the warning ids.
1298 SmallVector<int, 4> Ids;
1299 PP.Lex(Tok);
1300 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001301 uint64_t Value;
1302 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001303 Value > std::numeric_limits<int>::max()) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001304 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1305 return;
1306 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001307 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001308 }
1309 if (Callbacks)
1310 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1311
1312 // Parse the next specifier if there is a semicolon.
1313 if (Tok.isNot(tok::semi))
1314 break;
1315 PP.Lex(Tok);
1316 }
1317 }
1318
1319 if (Tok.isNot(tok::r_paren)) {
1320 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1321 return;
1322 }
1323
1324 PP.Lex(Tok);
1325 if (Tok.isNot(tok::eod))
1326 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1327 }
1328};
1329
James Dennett18a6d792012-06-17 03:26:26 +00001330/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001331struct PragmaIncludeAliasHandler : public PragmaHandler {
1332 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001333 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1334 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001335 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001336 }
1337};
1338
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001339/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1340/// extension. The syntax is:
1341/// \code
1342/// #pragma message(string)
1343/// \endcode
1344/// OR, in GCC mode:
1345/// \code
1346/// #pragma message string
1347/// \endcode
1348/// string is a string, which is fully macro expanded, and permits string
1349/// concatenation, embedded escape characters, etc... See MSDN for more details.
1350/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1351/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001352struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001353private:
1354 const PPCallbacks::PragmaMessageKind Kind;
1355 const StringRef Namespace;
1356
1357 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1358 bool PragmaNameOnly = false) {
1359 switch (Kind) {
1360 case PPCallbacks::PMK_Message:
1361 return PragmaNameOnly ? "message" : "pragma message";
1362 case PPCallbacks::PMK_Warning:
1363 return PragmaNameOnly ? "warning" : "pragma warning";
1364 case PPCallbacks::PMK_Error:
1365 return PragmaNameOnly ? "error" : "pragma error";
1366 }
1367 llvm_unreachable("Unknown PragmaMessageKind!");
1368 }
1369
1370public:
1371 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1372 StringRef Namespace = StringRef())
1373 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1374
Craig Topper9140dd22014-03-11 06:50:42 +00001375 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1376 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001377 SourceLocation MessageLoc = Tok.getLocation();
1378 PP.Lex(Tok);
1379 bool ExpectClosingParen = false;
1380 switch (Tok.getKind()) {
1381 case tok::l_paren:
1382 // We have a MSVC style pragma message.
1383 ExpectClosingParen = true;
1384 // Read the string.
1385 PP.Lex(Tok);
1386 break;
1387 case tok::string_literal:
1388 // We have a GCC style pragma message, and we just read the string.
1389 break;
1390 default:
1391 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1392 return;
1393 }
1394
1395 std::string MessageString;
1396 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1397 /*MacroExpansion=*/true))
1398 return;
1399
1400 if (ExpectClosingParen) {
1401 if (Tok.isNot(tok::r_paren)) {
1402 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1403 return;
1404 }
1405 PP.Lex(Tok); // eat the r_paren.
1406 }
1407
1408 if (Tok.isNot(tok::eod)) {
1409 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1410 return;
1411 }
1412
1413 // Output the message.
1414 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1415 ? diag::err_pragma_message
1416 : diag::warn_pragma_message) << MessageString;
1417
1418 // If the pragma is lexically sound, notify any interested PPCallbacks.
1419 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1420 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001421 }
1422};
1423
Richard Smithc51c38b2017-04-29 00:34:47 +00001424/// Handle the clang \#pragma module import extension. The syntax is:
1425/// \code
1426/// #pragma clang module import some.module.name
1427/// \endcode
1428struct PragmaModuleImportHandler : public PragmaHandler {
1429 PragmaModuleImportHandler() : PragmaHandler("import") {}
1430
1431 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smithd1386302017-05-04 00:29:54 +00001432 Token &Tok) override {
1433 SourceLocation ImportLoc = Tok.getLocation();
1434
1435 // Read the module name.
1436 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1437 ModuleName;
1438 if (LexModuleName(PP, Tok, ModuleName))
1439 return;
1440
1441 if (Tok.isNot(tok::eod))
1442 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1443
1444 // If we have a non-empty module path, load the named module.
1445 Module *Imported =
1446 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1447 /*IsIncludeDirective=*/false);
1448 if (!Imported)
1449 return;
1450
1451 PP.makeModuleVisible(Imported, ImportLoc);
1452 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1453 tok::annot_module_include, Imported);
1454 if (auto *CB = PP.getPPCallbacks())
1455 CB->moduleImport(ImportLoc, ModuleName, Imported);
1456 }
1457};
1458
1459/// Handle the clang \#pragma module begin extension. The syntax is:
1460/// \code
1461/// #pragma clang module begin some.module.name
1462/// ...
1463/// #pragma clang module end
1464/// \endcode
1465struct PragmaModuleBeginHandler : public PragmaHandler {
1466 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1467
1468 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1469 Token &Tok) override {
1470 SourceLocation BeginLoc = Tok.getLocation();
1471
1472 // Read the module name.
1473 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1474 ModuleName;
1475 if (LexModuleName(PP, Tok, ModuleName))
1476 return;
1477
1478 if (Tok.isNot(tok::eod))
1479 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1480
1481 // We can only enter submodules of the current module.
1482 StringRef Current = PP.getLangOpts().CurrentModule;
1483 if (ModuleName.front().first->getName() != Current) {
1484 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1485 << ModuleName.front().first << (ModuleName.size() > 1)
1486 << Current.empty() << Current;
1487 return;
1488 }
1489
1490 // Find the module we're entering. We require that a module map for it
1491 // be loaded or implicitly loadable.
1492 // FIXME: We could create the submodule here. We'd need to know whether
1493 // it's supposed to be explicit, but not much else.
Richard Smith9565c75b2017-06-19 23:09:36 +00001494 Module *M = PP.getHeaderSearchInfo().lookupModule(Current);
Richard Smithd1386302017-05-04 00:29:54 +00001495 if (!M) {
1496 PP.Diag(ModuleName.front().second,
1497 diag::err_pp_module_begin_no_module_map) << Current;
1498 return;
1499 }
1500 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1501 auto *NewM = M->findSubmodule(ModuleName[I].first->getName());
1502 if (!NewM) {
1503 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1504 << M->getFullModuleName() << ModuleName[I].first;
1505 return;
1506 }
1507 M = NewM;
1508 }
1509
Richard Smith51d09c52017-05-30 05:22:59 +00001510 // If the module isn't available, it doesn't make sense to enter it.
Richard Smith27e5aa02017-06-05 18:57:56 +00001511 if (Preprocessor::checkModuleIsAvailable(
1512 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
Richard Smith51d09c52017-05-30 05:22:59 +00001513 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1514 << M->getTopLevelModuleName();
1515 return;
1516 }
1517
Richard Smithd1386302017-05-04 00:29:54 +00001518 // Enter the scope of the submodule.
1519 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1520 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1521 tok::annot_module_begin, M);
1522 }
1523};
1524
1525/// Handle the clang \#pragma module end extension.
1526struct PragmaModuleEndHandler : public PragmaHandler {
1527 PragmaModuleEndHandler() : PragmaHandler("end") {}
1528
1529 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1530 Token &Tok) override {
1531 SourceLocation Loc = Tok.getLocation();
1532
1533 PP.LexUnexpandedToken(Tok);
1534 if (Tok.isNot(tok::eod))
1535 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1536
1537 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1538 if (M)
1539 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1540 else
1541 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
Richard Smithc51c38b2017-04-29 00:34:47 +00001542 }
1543};
1544
Richard Smith5d2ed482017-06-09 19:22:32 +00001545/// Handle the clang \#pragma module build extension.
1546struct PragmaModuleBuildHandler : public PragmaHandler {
1547 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1548
1549 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1550 Token &Tok) override {
1551 PP.HandlePragmaModuleBuild(Tok);
1552 }
1553};
1554
1555/// Handle the clang \#pragma module load extension.
1556struct PragmaModuleLoadHandler : public PragmaHandler {
1557 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1558
1559 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1560 Token &Tok) override {
1561 SourceLocation Loc = Tok.getLocation();
1562
1563 // Read the module name.
1564 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1565 ModuleName;
1566 if (LexModuleName(PP, Tok, ModuleName))
1567 return;
1568
1569 if (Tok.isNot(tok::eod))
1570 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1571
1572 // Load the module, don't make it visible.
1573 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1574 /*IsIncludeDirective=*/false);
1575 }
1576};
1577
James Dennett18a6d792012-06-17 03:26:26 +00001578/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001579/// macro on the top of the stack.
1580struct PragmaPushMacroHandler : public PragmaHandler {
1581 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001582
Craig Topper9140dd22014-03-11 06:50:42 +00001583 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1584 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001585 PP.HandlePragmaPushMacro(PushMacroTok);
1586 }
1587};
1588
James Dennett18a6d792012-06-17 03:26:26 +00001589/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001590/// macro to the value on the top of the stack.
1591struct PragmaPopMacroHandler : public PragmaHandler {
1592 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001593
Craig Topper9140dd22014-03-11 06:50:42 +00001594 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1595 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001596 PP.HandlePragmaPopMacro(PopMacroTok);
1597 }
1598};
1599
Chris Lattner958ee042009-04-19 21:20:35 +00001600// Pragma STDC implementations.
Chris Lattner02ef4e32009-04-19 21:50:08 +00001601
James Dennett18a6d792012-06-17 03:26:26 +00001602/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001603struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001604 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001605
Craig Topper9140dd22014-03-11 06:50:42 +00001606 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1607 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001608 tok::OnOffSwitch OOS;
1609 if (PP.LexOnOffSwitch(OOS))
1610 return;
1611 if (OOS == tok::OOS_ON)
Chris Lattnerdf222682009-04-19 21:55:32 +00001612 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
Chris Lattner958ee042009-04-19 21:20:35 +00001613 }
1614};
Mike Stump11289f42009-09-09 15:08:12 +00001615
James Dennett18a6d792012-06-17 03:26:26 +00001616/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001617struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001618 PragmaSTDC_CX_LIMITED_RANGEHandler()
1619 : PragmaHandler("CX_LIMITED_RANGE") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001620
Craig Topper9140dd22014-03-11 06:50:42 +00001621 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1622 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001623 tok::OnOffSwitch OOS;
1624 PP.LexOnOffSwitch(OOS);
Chris Lattner958ee042009-04-19 21:20:35 +00001625 }
1626};
Mike Stump11289f42009-09-09 15:08:12 +00001627
James Dennett18a6d792012-06-17 03:26:26 +00001628/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001629struct PragmaSTDC_UnknownHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001630 PragmaSTDC_UnknownHandler() {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001631
Craig Topper9140dd22014-03-11 06:50:42 +00001632 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1633 Token &UnknownTok) override {
Chris Lattner02ef4e32009-04-19 21:50:08 +00001634 // C99 6.10.6p2, unknown forms are not allowed.
Chris Lattnera0b1f762009-04-19 21:25:37 +00001635 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
Chris Lattner958ee042009-04-19 21:20:35 +00001636 }
1637};
Mike Stump11289f42009-09-09 15:08:12 +00001638
John McCall32f5fe12011-09-30 05:12:12 +00001639/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001640/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001641struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1642 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001643
Craig Topper9140dd22014-03-11 06:50:42 +00001644 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1645 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001646 SourceLocation Loc = NameTok.getLocation();
1647 bool IsBegin;
1648
1649 Token Tok;
1650
1651 // Lex the 'begin' or 'end'.
1652 PP.LexUnexpandedToken(Tok);
1653 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1654 if (BeginEnd && BeginEnd->isStr("begin")) {
1655 IsBegin = true;
1656 } else if (BeginEnd && BeginEnd->isStr("end")) {
1657 IsBegin = false;
1658 } else {
1659 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1660 return;
1661 }
1662
1663 // Verify that this is followed by EOD.
1664 PP.LexUnexpandedToken(Tok);
1665 if (Tok.isNot(tok::eod))
1666 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1667
1668 // The start location of the active audit.
1669 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1670
1671 // The start location we want after processing this.
1672 SourceLocation NewLoc;
1673
1674 if (IsBegin) {
1675 // Complain about attempts to re-enter an audit.
1676 if (BeginLoc.isValid()) {
1677 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1678 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1679 }
1680 NewLoc = Loc;
1681 } else {
1682 // Complain about attempts to leave an audit that doesn't exist.
1683 if (!BeginLoc.isValid()) {
1684 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1685 return;
1686 }
1687 NewLoc = SourceLocation();
1688 }
1689
1690 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1691 }
1692};
1693
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001694/// PragmaAssumeNonNullHandler -
1695/// \#pragma clang assume_nonnull begin/end
1696struct PragmaAssumeNonNullHandler : public PragmaHandler {
1697 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001698
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001699 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1700 Token &NameTok) override {
1701 SourceLocation Loc = NameTok.getLocation();
1702 bool IsBegin;
1703
1704 Token Tok;
1705
1706 // Lex the 'begin' or 'end'.
1707 PP.LexUnexpandedToken(Tok);
1708 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1709 if (BeginEnd && BeginEnd->isStr("begin")) {
1710 IsBegin = true;
1711 } else if (BeginEnd && BeginEnd->isStr("end")) {
1712 IsBegin = false;
1713 } else {
1714 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1715 return;
1716 }
1717
1718 // Verify that this is followed by EOD.
1719 PP.LexUnexpandedToken(Tok);
1720 if (Tok.isNot(tok::eod))
1721 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1722
1723 // The start location of the active audit.
1724 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1725
1726 // The start location we want after processing this.
1727 SourceLocation NewLoc;
1728
1729 if (IsBegin) {
1730 // Complain about attempts to re-enter an audit.
1731 if (BeginLoc.isValid()) {
1732 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1733 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1734 }
1735 NewLoc = Loc;
1736 } else {
1737 // Complain about attempts to leave an audit that doesn't exist.
1738 if (!BeginLoc.isValid()) {
1739 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1740 return;
1741 }
1742 NewLoc = SourceLocation();
1743 }
1744
1745 PP.setPragmaAssumeNonNullLoc(NewLoc);
1746 }
1747};
1748
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001749/// \brief Handle "\#pragma region [...]"
1750///
1751/// The syntax is
1752/// \code
1753/// #pragma region [optional name]
1754/// #pragma endregion [optional comment]
1755/// \endcode
1756///
1757/// \note This is
1758/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1759/// pragma, just skipped by compiler.
1760struct PragmaRegionHandler : public PragmaHandler {
1761 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
Aaron Ballman406ea512012-11-30 19:52:30 +00001762
Craig Topper9140dd22014-03-11 06:50:42 +00001763 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1764 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001765 // #pragma region: endregion matches can be verified
1766 // __pragma(region): no sense, but ignored by msvc
1767 // _Pragma is not valid for MSVC, but there isn't any point
1768 // to handle a _Pragma differently.
1769 }
1770};
Aaron Ballman406ea512012-11-30 19:52:30 +00001771
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001772} // end anonymous namespace
Chris Lattnerb694ba72006-07-02 22:41:36 +00001773
1774/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001775/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001776void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001777 AddPragmaHandler(new PragmaOnceHandler());
1778 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001779 AddPragmaHandler(new PragmaPushMacroHandler());
1780 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001781 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001782
Chris Lattnerb61448d2009-05-12 18:21:11 +00001783 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001784 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1785 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1786 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001787 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001788 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1789 "GCC"));
1790 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1791 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001792 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001793 AddPragmaHandler("clang", new PragmaPoisonHandler());
1794 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001795 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001796 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001797 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001798 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001799 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001800
Richard Smithc51c38b2017-04-29 00:34:47 +00001801 // #pragma clang module ...
1802 auto *ModuleHandler = new PragmaNamespace("module");
1803 AddPragmaHandler("clang", ModuleHandler);
1804 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
Richard Smithd1386302017-05-04 00:29:54 +00001805 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1806 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
Richard Smith5d2ed482017-06-09 19:22:32 +00001807 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1808 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
Richard Smithc51c38b2017-04-29 00:34:47 +00001809
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001810 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1811 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
Chris Lattner958ee042009-04-19 21:20:35 +00001812 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
Mike Stump11289f42009-09-09 15:08:12 +00001813
Chris Lattner2ff698d2009-01-16 08:21:25 +00001814 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001815 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001816 AddPragmaHandler(new PragmaWarningHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001817 AddPragmaHandler(new PragmaIncludeAliasHandler());
Aaron Ballman406ea512012-11-30 19:52:30 +00001818 AddPragmaHandler(new PragmaRegionHandler("region"));
1819 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Chris Lattner30c924b2010-06-26 17:11:39 +00001820 }
John Brawn8e62db32016-04-04 14:22:58 +00001821
1822 // Pragmas added by plugins
1823 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1824 ie = PragmaHandlerRegistry::end();
1825 it != ie; ++it) {
1826 AddPragmaHandler(it->instantiate().release());
1827 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001828}
Lubos Lunak576a0412014-05-01 12:54:03 +00001829
1830/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1831/// warn about those pragmas being unknown.
1832void Preprocessor::IgnorePragmas() {
1833 AddPragmaHandler(new EmptyPragmaHandler());
1834 // Also ignore all pragmas in all namespaces created
1835 // in Preprocessor::RegisterBuiltinPragmas().
1836 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1837 AddPragmaHandler("clang", new EmptyPragmaHandler());
1838 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1839 // Preprocessor::RegisterBuiltinPragmas() already registers
1840 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1841 // otherwise there will be an assert about a duplicate handler.
1842 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1843 assert(STDCNamespace &&
1844 "Invalid namespace, registered as a regular pragma handler!");
1845 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1846 RemovePragmaHandler("STDC", Existing);
Chandler Carruth4d9c3df2014-05-02 21:44:48 +00001847 delete Existing;
Lubos Lunak576a0412014-05-01 12:54:03 +00001848 }
1849 }
1850 AddPragmaHandler("STDC", new EmptyPragmaHandler());
1851}