blob: 9e3d7b0bbed04a03be11910502b417b2e54b7e77 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Pragma.cpp - Pragma registration and handling --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the PragmaHandler/PragmaTable interfaces and implements
11// pragma related methods of the Preprocessor class.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Pragma.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/SourceManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Lex/HeaderSearch.h"
19#include "clang/Lex/LexDiagnostic.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Lex/MacroInfo.h"
22#include "clang/Lex/Preprocessor.h"
Reid Kleckner2ee042d2013-09-13 22:00:30 +000023#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/StringSwitch.h"
Alexander Musman0495e8d2015-05-25 11:21:20 +000025#include "llvm/ADT/StringExtras.h"
Daniel Dunbarff759a62010-08-18 23:09:23 +000026#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar55054132010-08-17 22:32:48 +000027#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2e222532009-07-02 17:08:52 +000028#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Reid Kleckner2ee042d2013-09-13 22:00:30 +000031#include "llvm/Support/raw_ostream.h"
32
Reid Spencer5f016e22007-07-11 17:01:13 +000033// Out-of-line destructor to provide a home for the class.
34PragmaHandler::~PragmaHandler() {
35}
36
37//===----------------------------------------------------------------------===//
Daniel Dunbarc72cc502010-06-11 20:10:12 +000038// EmptyPragmaHandler Implementation.
39//===----------------------------------------------------------------------===//
40
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000041EmptyPragmaHandler::EmptyPragmaHandler() {}
Daniel Dunbarc72cc502010-06-11 20:10:12 +000042
Douglas Gregor80c60f72010-09-09 22:45:38 +000043void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
44 PragmaIntroducerKind Introducer,
45 Token &FirstToken) {}
Daniel Dunbarc72cc502010-06-11 20:10:12 +000046
47//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000048// PragmaNamespace Implementation.
49//===----------------------------------------------------------------------===//
50
Reid Spencer5f016e22007-07-11 17:01:13 +000051PragmaNamespace::~PragmaNamespace() {
Reid Kleckner26b55ea2014-02-19 23:44:52 +000052 llvm::DeleteContainerSeconds(Handlers);
Reid Spencer5f016e22007-07-11 17:01:13 +000053}
54
55/// FindHandler - Check to see if there is already a handler for the
56/// specified name. If not, return the handler for the null identifier if it
57/// exists, otherwise return null. If IgnoreNull is true (the default) then
58/// the null handler isn't returned on failure to match.
Chris Lattner5f9e2722011-07-23 10:55:15 +000059PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Reid Spencer5f016e22007-07-11 17:01:13 +000060 bool IgnoreNull) const {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000061 if (PragmaHandler *Handler = Handlers.lookup(Name))
62 return Handler;
Craig Topperda176c62014-05-17 23:10:59 +000063 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000064}
Mike Stump1eb44332009-09-09 15:08:12 +000065
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000066void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
67 assert(!Handlers.lookup(Handler->getName()) &&
68 "A handler with this name is already registered in this namespace");
David Blaikie8ee697f2014-11-19 03:06:06 +000069 Handlers[Handler->getName()] = Handler;
Reid Spencer5f016e22007-07-11 17:01:13 +000070}
71
Daniel Dunbar40950802008-10-04 19:17:46 +000072void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000073 assert(Handlers.lookup(Handler->getName()) &&
74 "Handler not registered in this namespace");
75 Handlers.erase(Handler->getName());
Daniel Dunbar40950802008-10-04 19:17:46 +000076}
77
Douglas Gregor80c60f72010-09-09 22:45:38 +000078void PragmaNamespace::HandlePragma(Preprocessor &PP,
79 PragmaIntroducerKind Introducer,
80 Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +000081 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
82 // expand it, the user can have a STDC #define, that should not affect this.
83 PP.LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +000084
Reid Spencer5f016e22007-07-11 17:01:13 +000085 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000086 PragmaHandler *Handler
87 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner5f9e2722011-07-23 10:55:15 +000088 : StringRef(),
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000089 /*IgnoreNull=*/false);
Craig Topperda176c62014-05-17 23:10:59 +000090 if (!Handler) {
Chris Lattneraf7cdf42009-04-19 21:10:26 +000091 PP.Diag(Tok, diag::warn_pragma_ignored);
92 return;
93 }
Mike Stump1eb44332009-09-09 15:08:12 +000094
Reid Spencer5f016e22007-07-11 17:01:13 +000095 // Otherwise, pass it down.
Douglas Gregor80c60f72010-09-09 22:45:38 +000096 Handler->HandlePragma(PP, Introducer, Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +000097}
98
99//===----------------------------------------------------------------------===//
100// Preprocessor Pragma Directive Handling.
101//===----------------------------------------------------------------------===//
102
James Dennettb6e95b72012-06-17 03:26:26 +0000103/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Reid Spencer5f016e22007-07-11 17:01:13 +0000104/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella0189fd62013-07-20 20:09:11 +0000105void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
106 PragmaIntroducerKind Introducer) {
107 if (Callbacks)
108 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
109
Jordan Rose6fe6a492012-06-08 18:06:21 +0000110 if (!PragmasEnabled)
111 return;
112
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 ++NumPragma;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattnerd2177732007-07-20 16:59:19 +0000116 Token Tok;
Enea Zaffanella0189fd62013-07-20 20:09:11 +0000117 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 // If the pragma handler didn't read the rest of the line, consume it now.
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000120 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
121 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 DiscardUntilEndOfDirective();
123}
124
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000125namespace {
126/// \brief Helper class for \see Preprocessor::Handle_Pragma.
127class LexingFor_PragmaRAII {
128 Preprocessor &PP;
129 bool InMacroArgPreExpansion;
130 bool Failed;
131 Token &OutTok;
132 Token PragmaTok;
133
134public:
135 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
136 Token &Tok)
137 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
138 Failed(false), OutTok(Tok) {
139 if (InMacroArgPreExpansion) {
140 PragmaTok = OutTok;
141 PP.EnableBacktrackAtThisPos();
142 }
143 }
144
145 ~LexingFor_PragmaRAII() {
146 if (InMacroArgPreExpansion) {
147 if (Failed) {
148 PP.CommitBacktrackedTokens();
149 } else {
150 PP.Backtrack();
151 OutTok = PragmaTok;
152 }
153 }
154 }
155
156 void failed() {
157 Failed = true;
158 }
159};
Alexander Kornienkoac58acc2015-06-22 09:47:44 +0000160} // namespace
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000161
Reid Spencer5f016e22007-07-11 17:01:13 +0000162/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
163/// return the first token after the directive. The _Pragma token has just
164/// been read into 'Tok'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000165void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000166
167 // This works differently if we are pre-expanding a macro argument.
168 // In that case we don't actually "activate" the pragma now, we only lex it
169 // until we are sure it is lexically correct and then we backtrack so that
170 // we activate the pragma whenever we encounter the tokens again in the token
171 // stream. This ensures that we will activate it in the correct location
172 // or that we will ignore it if it never enters the token stream, e.g:
173 //
174 // #define EMPTY(x)
175 // #define INACTIVE(x) EMPTY(x)
176 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
177
178 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 // Remember the pragma token location.
181 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 // Read the '('.
184 Lex(Tok);
Chris Lattner3692b092008-11-18 07:59:24 +0000185 if (Tok.isNot(tok::l_paren)) {
186 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000187 return _PragmaLexing.failed();
Chris Lattner3692b092008-11-18 07:59:24 +0000188 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000189
190 // Read the '"..."'.
191 Lex(Tok);
Richard Smith0b91cc42013-03-09 23:30:15 +0000192 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner3692b092008-11-18 07:59:24 +0000193 Diag(PragmaLoc, diag::err__Pragma_malformed);
Richard Smith99831e42012-03-06 03:21:47 +0000194 // Skip this token, and the ')', if present.
Reid Kleckner8ca59572014-08-14 19:47:06 +0000195 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smith99831e42012-03-06 03:21:47 +0000196 Lex(Tok);
197 if (Tok.is(tok::r_paren))
198 Lex(Tok);
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000199 return _PragmaLexing.failed();
Richard Smith99831e42012-03-06 03:21:47 +0000200 }
201
202 if (Tok.hasUDSuffix()) {
203 Diag(Tok, diag::err_invalid_string_udl);
204 // Skip this token, and the ')', if present.
205 Lex(Tok);
206 if (Tok.is(tok::r_paren))
207 Lex(Tok);
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000208 return _PragmaLexing.failed();
Chris Lattner3692b092008-11-18 07:59:24 +0000209 }
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 // Remember the string.
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000212 Token StrTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000213
214 // Read the ')'.
215 Lex(Tok);
Chris Lattner3692b092008-11-18 07:59:24 +0000216 if (Tok.isNot(tok::r_paren)) {
217 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000218 return _PragmaLexing.failed();
Chris Lattner3692b092008-11-18 07:59:24 +0000219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000221 if (InMacroArgPreExpansion)
222 return;
223
Chris Lattnere7fb4842009-02-15 20:52:18 +0000224 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000225 std::string StrVal = getSpelling(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Richard Smith0b91cc42013-03-09 23:30:15 +0000227 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
228 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattnera9d91452009-01-16 18:59:23 +0000229 // deleting the leading and trailing double-quotes, replacing each escape
230 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
231 // single backslash."
Richard Smith0b91cc42013-03-09 23:30:15 +0000232 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
233 (StrVal[0] == 'u' && StrVal[1] != '8'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 StrVal.erase(StrVal.begin());
Richard Smith0b91cc42013-03-09 23:30:15 +0000235 else if (StrVal[0] == 'u')
236 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
237
238 if (StrVal[0] == 'R') {
239 // FIXME: C++11 does not specify how to handle raw-string-literals here.
240 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
241 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
242 "Invalid raw string token!");
243
244 // Measure the length of the d-char-sequence.
245 unsigned NumDChars = 0;
246 while (StrVal[2 + NumDChars] != '(') {
247 assert(NumDChars < (StrVal.size() - 5) / 2 &&
248 "Invalid raw string token!");
249 ++NumDChars;
250 }
251 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
252
253 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
254 // parens below.
255 StrVal.erase(0, 2 + NumDChars);
256 StrVal.erase(StrVal.size() - 1 - NumDChars);
257 } else {
258 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
259 "Invalid string token!");
260
261 // Remove escaped quotes and escapes.
Benjamin Kramer269cc2d2013-05-04 10:37:20 +0000262 unsigned ResultPos = 1;
Reid Kleckner48b80c72013-09-25 16:42:48 +0000263 for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) {
264 // Skip escapes. \\ -> '\' and \" -> '"'.
265 if (StrVal[i] == '\\' && i + 1 < e &&
266 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
267 ++i;
268 StrVal[ResultPos++] = StrVal[i];
Richard Smith0b91cc42013-03-09 23:30:15 +0000269 }
Reid Kleckner48b80c72013-09-25 16:42:48 +0000270 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smith0b91cc42013-03-09 23:30:15 +0000271 }
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 // Remove the front quote, replacing it with a space, so that the pragma
274 // contents appear to have a space before them.
275 StrVal[0] = ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Chris Lattner1fa49532009-03-08 08:08:45 +0000277 // Replace the terminating quote with a \n.
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 StrVal[StrVal.size()-1] = '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000280 // Plop the string (including the newline and trailing null) into a buffer
281 // where we can lex it.
282 Token TmpTok;
283 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000284 CreateString(StrVal, TmpTok);
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000285 SourceLocation TokLoc = TmpTok.getLocation();
286
287 // Make and enter a lexer object so that we lex and expand the tokens just
288 // like any others.
289 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
290 StrVal.size(), *this);
291
Craig Topperda176c62014-05-17 23:10:59 +0000292 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000293
294 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella0189fd62013-07-20 20:09:11 +0000295 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall1ef8a2e2010-08-28 22:34:47 +0000296
297 // Finally, return whatever came after the pragma directive.
298 return Lex(Tok);
299}
300
301/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
302/// is not enclosed within a string literal.
303void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
304 // Remember the pragma token location.
305 SourceLocation PragmaLoc = Tok.getLocation();
306
307 // Read the '('.
308 Lex(Tok);
309 if (Tok.isNot(tok::l_paren)) {
310 Diag(PragmaLoc, diag::err__Pragma_malformed);
311 return;
312 }
313
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000314 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000315 SmallVector<Token, 32> PragmaToks;
John McCall1ef8a2e2010-08-28 22:34:47 +0000316 int NumParens = 0;
317 Lex(Tok);
318 while (Tok.isNot(tok::eof)) {
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000319 PragmaToks.push_back(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000320 if (Tok.is(tok::l_paren))
321 NumParens++;
322 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
323 break;
John McCall1ef8a2e2010-08-28 22:34:47 +0000324 Lex(Tok);
325 }
326
John McCall3da92a92010-08-29 01:09:54 +0000327 if (Tok.is(tok::eof)) {
328 Diag(PragmaLoc, diag::err_unterminated___pragma);
329 return;
330 }
331
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000332 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall1ef8a2e2010-08-28 22:34:47 +0000333
Peter Collingbourne84021552011-02-28 02:37:51 +0000334 // Replace the ')' with an EOD to mark the end of the pragma.
335 PragmaToks.back().setKind(tok::eod);
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000336
337 Token *TokArray = new Token[PragmaToks.size()];
338 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
339
340 // Push the tokens onto the stack.
341 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
342
343 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella0189fd62013-07-20 20:09:11 +0000344 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall1ef8a2e2010-08-28 22:34:47 +0000345
346 // Finally, return whatever came after the pragma directive.
347 return Lex(Tok);
348}
349
James Dennettb6e95b72012-06-17 03:26:26 +0000350/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000351///
Chris Lattnerd2177732007-07-20 16:59:19 +0000352void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 if (isInPrimaryFile()) {
354 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
355 return;
356 }
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 // Mark the file as a once-only file now.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000360 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Reid Spencer5f016e22007-07-11 17:01:13 +0000361}
362
Chris Lattner22434492007-12-19 19:38:36 +0000363void Preprocessor::HandlePragmaMark() {
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000364 assert(CurPPLexer && "No current lexer?");
Chris Lattner6896a372009-06-15 05:02:34 +0000365 if (CurLexer)
366 CurLexer->ReadToEndOfLine();
367 else
368 CurPTHLexer->DiscardToEndOfLine();
Chris Lattner22434492007-12-19 19:38:36 +0000369}
370
371
James Dennettb6e95b72012-06-17 03:26:26 +0000372/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000373///
Chris Lattnerd2177732007-07-20 16:59:19 +0000374void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
375 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000376
377 while (1) {
378 // Read the next token to poison. While doing this, pretend that we are
379 // skipping while reading the identifier to poison.
380 // This avoids errors on code like:
381 // #pragma GCC poison X
382 // #pragma GCC poison X
Ted Kremenek68a91d52008-11-18 01:12:54 +0000383 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 LexUnexpandedToken(Tok);
Ted Kremenek68a91d52008-11-18 01:12:54 +0000385 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 // If we reached the end of line, we're done.
Peter Collingbourne84021552011-02-28 02:37:51 +0000388 if (Tok.is(tok::eod)) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 // Can only poison identifiers.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000391 if (Tok.isNot(tok::raw_identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 Diag(Tok, diag::err_pp_invalid_poison);
393 return;
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 // Look up the identifier info for the token. We disabled identifier lookup
397 // by saying we're skipping contents, so we need to do this manually.
398 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // Already poisoned.
401 if (II->isPoisoned()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 // If this is a macro identifier, emit a warning.
Richard Smith1f468122015-04-29 23:20:19 +0000404 if (isMacroDefined(II))
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 // Finally, poison it!
408 II->setIsPoisoned();
Douglas Gregoreee242f2011-10-27 09:33:13 +0000409 if (II->isFromAST())
410 II->setChangedSinceDeserialization();
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 }
412}
413
James Dennettb6e95b72012-06-17 03:26:26 +0000414/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Reid Spencer5f016e22007-07-11 17:01:13 +0000415/// that the whole directive has been parsed.
Chris Lattnerd2177732007-07-20 16:59:19 +0000416void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 if (isInPrimaryFile()) {
418 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
419 return;
420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek35c10c22008-11-20 01:45:11 +0000423 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // Mark the file as a system header.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000426 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump1eb44332009-09-09 15:08:12 +0000427
428
Chris Lattner6896a372009-06-15 05:02:34 +0000429 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000430 if (PLoc.isInvalid())
431 return;
432
Jay Foad65aa6882011-06-21 15:13:30 +0000433 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner784c2572011-05-22 22:10:16 +0000435 // Notify the client, if desired, that we are in a new source file.
436 if (Callbacks)
437 Callbacks->FileChanged(SysHeaderTok.getLocation(),
438 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
439
Chris Lattner6896a372009-06-15 05:02:34 +0000440 // Emit a line marker. This will change any source locations from this point
441 // forward to realize they are in a system header.
442 // Create a line note with this information.
Jordan Rose142b35e2013-04-17 19:09:18 +0000443 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
444 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
445 /*IsSystem=*/true, /*IsExternC=*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000446}
447
James Dennettb6e95b72012-06-17 03:26:26 +0000448/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Reid Spencer5f016e22007-07-11 17:01:13 +0000449///
Chris Lattnerd2177732007-07-20 16:59:19 +0000450void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
451 Token FilenameTok;
Ted Kremenek68a91d52008-11-18 01:12:54 +0000452 CurPPLexer->LexIncludeFilename(FilenameTok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000453
Peter Collingbourne84021552011-02-28 02:37:51 +0000454 // If the token kind is EOD, the error has already been diagnosed.
455 if (FilenameTok.is(tok::eod))
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 // Reserve a buffer to get the spelling.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000459 SmallString<128> FilenameBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +0000460 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000461 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +0000462 if (Invalid)
463 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Chris Lattnera1394812010-01-10 01:35:12 +0000465 bool isAngled =
466 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
468 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000469 if (Filename.empty())
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 // Search include directories for this file.
473 const DirectoryLookup *CurDir;
Richard Smithccaf6242014-10-20 00:15:49 +0000474 const FileEntry *File =
475 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
476 nullptr, CurDir, nullptr, nullptr, nullptr);
Craig Topperda176c62014-05-17 23:10:59 +0000477 if (!File) {
Eli Friedmanf84139a2011-08-30 23:07:51 +0000478 if (!SuppressIncludeNotFoundError)
479 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +0000480 return;
481 }
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattner2b2453a2009-01-17 06:22:33 +0000483 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Reid Spencer5f016e22007-07-11 17:01:13 +0000484
485 // If this file is older than the file it depends on, emit a diagnostic.
486 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
487 // Lex tokens at the end of the message and include them in the message.
488 std::string Message;
489 Lex(DependencyTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000490 while (DependencyTok.isNot(tok::eod)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 Message += getSpelling(DependencyTok) + " ";
492 Lex(DependencyTok);
493 }
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Chris Lattner96de2592010-09-05 23:16:09 +0000495 // Remove the trailing ' ' if present.
496 if (!Message.empty())
497 Message.erase(Message.end()-1);
Chris Lattner56b05c82008-11-18 08:02:48 +0000498 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 }
500}
501
Reid Kleckner7adf79a2013-05-06 21:02:12 +0000502/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerf47724b2010-08-17 15:55:45 +0000503/// Return the IdentifierInfo* associated with the macro to push or pop.
504IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
505 // Remember the pragma token location.
506 Token PragmaTok = Tok;
507
508 // Read the '('.
509 Lex(Tok);
510 if (Tok.isNot(tok::l_paren)) {
511 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
512 << getSpelling(PragmaTok);
Craig Topperda176c62014-05-17 23:10:59 +0000513 return nullptr;
Chris Lattnerf47724b2010-08-17 15:55:45 +0000514 }
515
516 // Read the macro name string.
517 Lex(Tok);
518 if (Tok.isNot(tok::string_literal)) {
519 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
520 << getSpelling(PragmaTok);
Craig Topperda176c62014-05-17 23:10:59 +0000521 return nullptr;
Chris Lattnerf47724b2010-08-17 15:55:45 +0000522 }
523
Richard Smith99831e42012-03-06 03:21:47 +0000524 if (Tok.hasUDSuffix()) {
525 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperda176c62014-05-17 23:10:59 +0000526 return nullptr;
Richard Smith99831e42012-03-06 03:21:47 +0000527 }
528
Chris Lattnerf47724b2010-08-17 15:55:45 +0000529 // Remember the macro string.
530 std::string StrVal = getSpelling(Tok);
531
532 // Read the ')'.
533 Lex(Tok);
534 if (Tok.isNot(tok::r_paren)) {
535 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
536 << getSpelling(PragmaTok);
Craig Topperda176c62014-05-17 23:10:59 +0000537 return nullptr;
Chris Lattnerf47724b2010-08-17 15:55:45 +0000538 }
539
540 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
541 "Invalid string token!");
542
543 // Create a Token from the string.
544 Token MacroTok;
545 MacroTok.startToken();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000546 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000547 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerf47724b2010-08-17 15:55:45 +0000548
549 // Get the IdentifierInfo of MacroToPushTok.
550 return LookUpIdentifierInfo(MacroTok);
551}
552
James Dennettb6e95b72012-06-17 03:26:26 +0000553/// \brief Handle \#pragma push_macro.
554///
Chris Lattnerf47724b2010-08-17 15:55:45 +0000555/// The syntax is:
James Dennettb6e95b72012-06-17 03:26:26 +0000556/// \code
Dmitri Gribenkoe74dc192012-11-30 20:04:39 +0000557/// #pragma push_macro("macro")
James Dennettb6e95b72012-06-17 03:26:26 +0000558/// \endcode
Chris Lattnerf47724b2010-08-17 15:55:45 +0000559void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
560 // Parse the pragma directive and get the macro IdentifierInfo*.
561 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
562 if (!IdentInfo) return;
563
564 // Get the MacroInfo associated with IdentInfo.
565 MacroInfo *MI = getMacroInfo(IdentInfo);
566
Chris Lattnerf47724b2010-08-17 15:55:45 +0000567 if (MI) {
Chris Lattnerf47724b2010-08-17 15:55:45 +0000568 // Allow the original MacroInfo to be redefined later.
569 MI->setIsAllowRedefinitionsWithoutWarning(true);
570 }
571
572 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000573 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerf47724b2010-08-17 15:55:45 +0000574}
575
James Dennettb6e95b72012-06-17 03:26:26 +0000576/// \brief Handle \#pragma pop_macro.
577///
Chris Lattnerf47724b2010-08-17 15:55:45 +0000578/// The syntax is:
James Dennettb6e95b72012-06-17 03:26:26 +0000579/// \code
Chris Lattnerf47724b2010-08-17 15:55:45 +0000580/// #pragma pop_macro("macro")
James Dennettb6e95b72012-06-17 03:26:26 +0000581/// \endcode
Chris Lattnerf47724b2010-08-17 15:55:45 +0000582void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
583 SourceLocation MessageLoc = PopMacroTok.getLocation();
584
585 // Parse the pragma directive and get the macro IdentifierInfo*.
586 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
587 if (!IdentInfo) return;
588
589 // Find the vector<MacroInfo*> associated with the macro.
590 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
591 PragmaPushMacroInfo.find(IdentInfo);
592 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8a64bb52012-08-29 00:20:03 +0000593 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith1f468122015-04-29 23:20:19 +0000594 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000595 if (MI->isWarnIfUnused())
596 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
597 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000598 }
Chris Lattnerf47724b2010-08-17 15:55:45 +0000599
600 // Get the MacroInfo we want to reinstall.
601 MacroInfo *MacroToReInstall = iter->second.back();
602
Richard Smitha09eec82015-04-23 20:40:50 +0000603 if (MacroToReInstall)
Alexander Kornienkoe40c4232012-08-29 16:56:24 +0000604 // Reinstall the previously pushed macro.
Richard Smitha09eec82015-04-23 20:40:50 +0000605 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerf47724b2010-08-17 15:55:45 +0000606
607 // Pop PragmaPushMacroInfo stack.
608 iter->second.pop_back();
609 if (iter->second.size() == 0)
610 PragmaPushMacroInfo.erase(iter);
611 } else {
612 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
613 << IdentInfo->getName();
614 }
615}
Reid Spencer5f016e22007-07-11 17:01:13 +0000616
Aaron Ballman4c55c542012-03-02 22:51:54 +0000617void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
618 // We will either get a quoted filename or a bracketed filename, and we
619 // have to track which we got. The first filename is the source name,
620 // and the second name is the mapped filename. If the first is quoted,
621 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman4c55c542012-03-02 22:51:54 +0000622
623 // Get the open paren
624 Lex(Tok);
625 if (Tok.isNot(tok::l_paren)) {
626 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
627 return;
628 }
629
630 // We expect either a quoted string literal, or a bracketed name
631 Token SourceFilenameTok;
632 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
633 if (SourceFilenameTok.is(tok::eod)) {
634 // The diagnostic has already been handled
635 return;
636 }
637
638 StringRef SourceFileName;
639 SmallString<128> FileNameBuffer;
640 if (SourceFilenameTok.is(tok::string_literal) ||
641 SourceFilenameTok.is(tok::angle_string_literal)) {
642 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
643 } else if (SourceFilenameTok.is(tok::less)) {
644 // This could be a path instead of just a name
645 FileNameBuffer.push_back('<');
646 SourceLocation End;
647 if (ConcatenateIncludeName(FileNameBuffer, End))
648 return; // Diagnostic already emitted
Yaron Keren9bd91b62015-03-18 10:17:07 +0000649 SourceFileName = FileNameBuffer;
Aaron Ballman4c55c542012-03-02 22:51:54 +0000650 } else {
651 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
652 return;
653 }
654 FileNameBuffer.clear();
655
656 // Now we expect a comma, followed by another include name
657 Lex(Tok);
658 if (Tok.isNot(tok::comma)) {
659 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
660 return;
661 }
662
663 Token ReplaceFilenameTok;
664 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
665 if (ReplaceFilenameTok.is(tok::eod)) {
666 // The diagnostic has already been handled
667 return;
668 }
669
670 StringRef ReplaceFileName;
671 if (ReplaceFilenameTok.is(tok::string_literal) ||
672 ReplaceFilenameTok.is(tok::angle_string_literal)) {
673 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
674 } else if (ReplaceFilenameTok.is(tok::less)) {
675 // This could be a path instead of just a name
676 FileNameBuffer.push_back('<');
677 SourceLocation End;
678 if (ConcatenateIncludeName(FileNameBuffer, End))
679 return; // Diagnostic already emitted
Yaron Keren9bd91b62015-03-18 10:17:07 +0000680 ReplaceFileName = FileNameBuffer;
Aaron Ballman4c55c542012-03-02 22:51:54 +0000681 } else {
682 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
683 return;
684 }
685
686 // Finally, we expect the closing paren
687 Lex(Tok);
688 if (Tok.isNot(tok::r_paren)) {
689 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
690 return;
691 }
692
693 // Now that we have the source and target filenames, we need to make sure
694 // they're both of the same type (angled vs non-angled)
695 StringRef OriginalSource = SourceFileName;
696
697 bool SourceIsAngled =
698 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
699 SourceFileName);
700 bool ReplaceIsAngled =
701 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
702 ReplaceFileName);
703 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
704 (SourceIsAngled != ReplaceIsAngled)) {
705 unsigned int DiagID;
706 if (SourceIsAngled)
707 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
708 else
709 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
710
711 Diag(SourceFilenameTok.getLocation(), DiagID)
712 << SourceFileName
713 << ReplaceFileName;
714
715 return;
716 }
717
718 // Now we can let the include handler know about this mapping
719 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
720}
721
Reid Spencer5f016e22007-07-11 17:01:13 +0000722/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
723/// If 'Namespace' is non-null, then it is a token required to exist on the
724/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner5f9e2722011-07-23 10:55:15 +0000725void Preprocessor::AddPragmaHandler(StringRef Namespace,
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 PragmaHandler *Handler) {
Craig Topper9f51fe82014-09-12 05:19:24 +0000727 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000730 if (!Namespace.empty()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 // If there is already a pragma handler with the name of this namespace,
732 // we either have an error (directive with the same name as a namespace) or
733 // we already have the namespace to insert into.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000734 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 InsertNS = Existing->getIfNamespace();
Craig Topperda176c62014-05-17 23:10:59 +0000736 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 " handler with the same name!");
738 } else {
739 // Otherwise, this namespace doesn't exist yet, create and insert the
740 // handler for it.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000741 InsertNS = new PragmaNamespace(Namespace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 PragmaHandlers->AddPragma(InsertNS);
743 }
744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 // Check to make sure we don't already have a pragma for this identifier.
747 assert(!InsertNS->FindHandler(Handler->getName()) &&
748 "Pragma handler already exists for this identifier!");
749 InsertNS->AddPragma(Handler);
750}
751
Daniel Dunbar40950802008-10-04 19:17:46 +0000752/// RemovePragmaHandler - Remove the specific pragma handler from the
753/// preprocessor. If \arg Namespace is non-null, then it should be the
754/// namespace that \arg Handler was added to. It is an error to remove
755/// a handler that has not been registered.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000756void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40950802008-10-04 19:17:46 +0000757 PragmaHandler *Handler) {
Craig Topper9f51fe82014-09-12 05:19:24 +0000758 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Daniel Dunbar40950802008-10-04 19:17:46 +0000760 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000761 if (!Namespace.empty()) {
762 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40950802008-10-04 19:17:46 +0000763 assert(Existing && "Namespace containing handler does not exist!");
764
765 NS = Existing->getIfNamespace();
766 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
767 }
768
769 NS->RemovePragmaHandler(Handler);
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Craig Topper9f51fe82014-09-12 05:19:24 +0000771 // If this is a non-default namespace and it is now empty, remove it.
772 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40950802008-10-04 19:17:46 +0000773 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidisce52bb32012-01-06 00:22:09 +0000774 delete NS;
775 }
Daniel Dunbar40950802008-10-04 19:17:46 +0000776}
777
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +0000778bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
779 Token Tok;
780 LexUnexpandedToken(Tok);
781
782 if (Tok.isNot(tok::identifier)) {
783 Diag(Tok, diag::ext_on_off_switch_syntax);
784 return true;
785 }
786 IdentifierInfo *II = Tok.getIdentifierInfo();
787 if (II->isStr("ON"))
788 Result = tok::OOS_ON;
789 else if (II->isStr("OFF"))
790 Result = tok::OOS_OFF;
791 else if (II->isStr("DEFAULT"))
792 Result = tok::OOS_DEFAULT;
793 else {
794 Diag(Tok, diag::ext_on_off_switch_syntax);
795 return true;
796 }
797
Peter Collingbourne84021552011-02-28 02:37:51 +0000798 // Verify that this is followed by EOD.
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +0000799 LexUnexpandedToken(Tok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000800 if (Tok.isNot(tok::eod))
801 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +0000802 return false;
803}
804
Reid Spencer5f016e22007-07-11 17:01:13 +0000805namespace {
James Dennettb6e95b72012-06-17 03:26:26 +0000806/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Reid Spencer5f016e22007-07-11 17:01:13 +0000807struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000808 PragmaOnceHandler() : PragmaHandler("once") {}
Craig Topper260dbc32014-03-11 06:50:42 +0000809 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
810 Token &OnceTok) override {
Chris Lattner35410d52009-04-14 05:07:49 +0000811 PP.CheckEndOfDirective("pragma once");
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 PP.HandlePragmaOnce(OnceTok);
813 }
814};
815
James Dennettb6e95b72012-06-17 03:26:26 +0000816/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattner22434492007-12-19 19:38:36 +0000817/// rest of the line is not lexed.
818struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000819 PragmaMarkHandler() : PragmaHandler("mark") {}
Craig Topper260dbc32014-03-11 06:50:42 +0000820 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
821 Token &MarkTok) override {
Chris Lattner22434492007-12-19 19:38:36 +0000822 PP.HandlePragmaMark();
823 }
824};
825
James Dennettb6e95b72012-06-17 03:26:26 +0000826/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Reid Spencer5f016e22007-07-11 17:01:13 +0000827struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000828 PragmaPoisonHandler() : PragmaHandler("poison") {}
Craig Topper260dbc32014-03-11 06:50:42 +0000829 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
830 Token &PoisonTok) override {
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 PP.HandlePragmaPoison(PoisonTok);
832 }
833};
834
James Dennettb6e95b72012-06-17 03:26:26 +0000835/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattner22434492007-12-19 19:38:36 +0000836/// as a system header, which silences warnings in it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000837struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000838 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Craig Topper260dbc32014-03-11 06:50:42 +0000839 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
840 Token &SHToken) override {
Reid Spencer5f016e22007-07-11 17:01:13 +0000841 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattner35410d52009-04-14 05:07:49 +0000842 PP.CheckEndOfDirective("pragma");
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 }
844};
845struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000846 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Craig Topper260dbc32014-03-11 06:50:42 +0000847 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
848 Token &DepToken) override {
Reid Spencer5f016e22007-07-11 17:01:13 +0000849 PP.HandlePragmaDependency(DepToken);
850 }
851};
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000853struct PragmaDebugHandler : public PragmaHandler {
854 PragmaDebugHandler() : PragmaHandler("__debug") {}
Craig Topper260dbc32014-03-11 06:50:42 +0000855 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
856 Token &DepToken) override {
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000857 Token Tok;
858 PP.LexUnexpandedToken(Tok);
859 if (Tok.isNot(tok::identifier)) {
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000860 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000861 return;
862 }
863 IdentifierInfo *II = Tok.getIdentifierInfo();
864
Daniel Dunbar55054132010-08-17 22:32:48 +0000865 if (II->isStr("assert")) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000866 llvm_unreachable("This is an assertion!");
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000867 } else if (II->isStr("crash")) {
David Blaikie377da4c2012-08-21 18:56:49 +0000868 LLVM_BUILTIN_TRAP;
David Blaikiee75d9cf2012-06-29 22:03:56 +0000869 } else if (II->isStr("parser_crash")) {
870 Token Crasher;
Benjamin Kramerfa202752015-03-08 19:28:24 +0000871 Crasher.startToken();
David Blaikiee75d9cf2012-06-29 22:03:56 +0000872 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramerfa202752015-03-08 19:28:24 +0000873 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikiee75d9cf2012-06-29 22:03:56 +0000874 PP.EnterToken(Crasher);
Daniel Dunbar55054132010-08-17 22:32:48 +0000875 } else if (II->isStr("llvm_fatal_error")) {
876 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
877 } else if (II->isStr("llvm_unreachable")) {
878 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smitha105ad12015-04-30 23:10:40 +0000879 } else if (II->isStr("macro")) {
880 Token MacroName;
881 PP.LexUnexpandedToken(MacroName);
882 auto *MacroII = MacroName.getIdentifierInfo();
883 if (MacroII)
884 PP.dumpMacroInfo(MacroII);
885 else
886 PP.Diag(MacroName, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbar55054132010-08-17 22:32:48 +0000887 } else if (II->isStr("overflow_stack")) {
888 DebugOverflowStack();
Daniel Dunbarff759a62010-08-18 23:09:23 +0000889 } else if (II->isStr("handle_crash")) {
890 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
891 if (CRC)
892 CRC->HandleCrash();
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000893 } else if (II->isStr("captured")) {
894 HandleCaptured(PP);
Daniel Dunbar55054132010-08-17 22:32:48 +0000895 } else {
896 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
897 << II->getName();
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000898 }
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000899
900 PPCallbacks *Callbacks = PP.getPPCallbacks();
901 if (Callbacks)
902 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
903 }
904
905 void HandleCaptured(Preprocessor &PP) {
906 // Skip if emitting preprocessed output.
907 if (PP.isPreprocessedOutput())
908 return;
909
910 Token Tok;
911 PP.LexUnexpandedToken(Tok);
912
913 if (Tok.isNot(tok::eod)) {
914 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
915 << "pragma clang __debug captured";
916 return;
917 }
918
919 SourceLocation NameLoc = Tok.getLocation();
920 Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1);
921 Toks->startToken();
922 Toks->setKind(tok::annot_pragma_captured);
923 Toks->setLocation(NameLoc);
924
925 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
926 /*OwnsTokens=*/false);
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000927 }
928
Francois Pichet1066c6c2011-05-25 16:15:03 +0000929// Disable MSVC warning about runtime stack overflow.
930#ifdef _MSC_VER
931 #pragma warning(disable : 4717)
932#endif
Richard Trieu573f9a12013-12-21 01:04:02 +0000933 static void DebugOverflowStack() {
934 void (*volatile Self)() = DebugOverflowStack;
935 Self();
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000936 }
Francois Pichet1066c6c2011-05-25 16:15:03 +0000937#ifdef _MSC_VER
938 #pragma warning(default : 4717)
939#endif
940
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000941};
942
James Dennettb6e95b72012-06-17 03:26:26 +0000943/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattneredaf8772009-04-19 23:16:58 +0000944struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000945private:
946 const char *Namespace;
Chris Lattner04ae2df2009-07-12 21:18:45 +0000947public:
Douglas Gregorc09ce122011-06-22 19:41:48 +0000948 explicit PragmaDiagnosticHandler(const char *NS) :
949 PragmaHandler("diagnostic"), Namespace(NS) {}
Craig Topper260dbc32014-03-11 06:50:42 +0000950 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
951 Token &DiagToken) override {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000952 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattneredaf8772009-04-19 23:16:58 +0000953 Token Tok;
954 PP.LexUnexpandedToken(Tok);
955 if (Tok.isNot(tok::identifier)) {
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000956 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattneredaf8772009-04-19 23:16:58 +0000957 return;
958 }
959 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000960 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Alp Toker18a9b662014-06-12 10:15:20 +0000962 if (II->isStr("pop")) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000963 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000964 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000965 else if (Callbacks)
966 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000967 return;
968 } else if (II->isStr("push")) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000969 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000970 if (Callbacks)
971 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattner04ae2df2009-07-12 21:18:45 +0000972 return;
Alp Toker18a9b662014-06-12 10:15:20 +0000973 }
974
975 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
976 .Case("ignored", diag::Severity::Ignored)
977 .Case("warning", diag::Severity::Warning)
978 .Case("error", diag::Severity::Error)
979 .Case("fatal", diag::Severity::Fatal)
980 .Default(diag::Severity());
981
982 if (SV == diag::Severity()) {
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000983 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattneredaf8772009-04-19 23:16:58 +0000984 return;
985 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattneredaf8772009-04-19 23:16:58 +0000987 PP.LexUnexpandedToken(Tok);
Andy Gibbs02a17682012-11-17 19:15:38 +0000988 SourceLocation StringLoc = Tok.getLocation();
Chris Lattneredaf8772009-04-19 23:16:58 +0000989
Andy Gibbs02a17682012-11-17 19:15:38 +0000990 std::string WarningName;
Andy Gibbs97f84612012-11-17 19:16:52 +0000991 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
992 /*MacroExpansion=*/false))
Chris Lattneredaf8772009-04-19 23:16:58 +0000993 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Peter Collingbourne84021552011-02-28 02:37:51 +0000995 if (Tok.isNot(tok::eod)) {
Chris Lattneredaf8772009-04-19 23:16:58 +0000996 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
997 return;
998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Chris Lattneredaf8772009-04-19 23:16:58 +00001000 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith1bdad152014-08-07 00:24:21 +00001001 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs02a17682012-11-17 19:15:38 +00001002 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattneredaf8772009-04-19 23:16:58 +00001003 return;
1004 }
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Richard Smith1bdad152014-08-07 00:24:21 +00001006 if (PP.getDiagnostics().setSeverityForGroup(
1007 WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1008 : diag::Flavor::Remark,
1009 WarningName.substr(2), SV, DiagLoc))
Andy Gibbs02a17682012-11-17 19:15:38 +00001010 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1011 << WarningName;
Douglas Gregorc09ce122011-06-22 19:41:48 +00001012 else if (Callbacks)
Alp Toker18a9b662014-06-12 10:15:20 +00001013 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattneredaf8772009-04-19 23:16:58 +00001014 }
1015};
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001017/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1018/// diagnostics, so we don't really implement this pragma. We parse it and
1019/// ignore it to avoid -Wunknown-pragma warnings.
1020struct PragmaWarningHandler : public PragmaHandler {
1021 PragmaWarningHandler() : PragmaHandler("warning") {}
1022
Craig Topper260dbc32014-03-11 06:50:42 +00001023 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1024 Token &Tok) override {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001025 // Parse things like:
1026 // warning(push, 1)
1027 // warning(pop)
John Thompsonfaea5bf2013-11-16 00:16:03 +00001028 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001029 SourceLocation DiagLoc = Tok.getLocation();
1030 PPCallbacks *Callbacks = PP.getPPCallbacks();
1031
1032 PP.Lex(Tok);
1033 if (Tok.isNot(tok::l_paren)) {
1034 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1035 return;
1036 }
1037
1038 PP.Lex(Tok);
1039 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001040
Alexander Musman0495e8d2015-05-25 11:21:20 +00001041 if (II && II->isStr("push")) {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001042 // #pragma warning( push[ ,n ] )
Reid Kleckner72c26c02013-10-02 15:19:23 +00001043 int Level = -1;
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001044 PP.Lex(Tok);
1045 if (Tok.is(tok::comma)) {
1046 PP.Lex(Tok);
Reid Klecknerdd6709e2014-02-12 23:50:26 +00001047 uint64_t Value;
1048 if (Tok.is(tok::numeric_constant) &&
1049 PP.parseSimpleIntegerLiteral(Tok, Value))
1050 Level = int(Value);
Reid Kleckner72c26c02013-10-02 15:19:23 +00001051 if (Level < 0 || Level > 4) {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001052 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1053 return;
1054 }
1055 }
1056 if (Callbacks)
1057 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman0495e8d2015-05-25 11:21:20 +00001058 } else if (II && II->isStr("pop")) {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001059 // #pragma warning( pop )
1060 PP.Lex(Tok);
1061 if (Callbacks)
1062 Callbacks->PragmaWarningPop(DiagLoc);
1063 } else {
1064 // #pragma warning( warning-specifier : warning-number-list
1065 // [; warning-specifier : warning-number-list...] )
1066 while (true) {
1067 II = Tok.getIdentifierInfo();
Alexander Musman0495e8d2015-05-25 11:21:20 +00001068 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001069 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1070 return;
1071 }
1072
1073 // Figure out which warning specifier this is.
Alexander Musman0495e8d2015-05-25 11:21:20 +00001074 bool SpecifierValid;
1075 StringRef Specifier;
1076 llvm::SmallString<1> SpecifierBuf;
1077 if (II) {
1078 Specifier = II->getName();
1079 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1080 .Cases("default", "disable", "error", "once",
1081 "suppress", true)
1082 .Default(false);
1083 // If we read a correct specifier, snatch next token (that should be
1084 // ":", checked later).
1085 if (SpecifierValid)
1086 PP.Lex(Tok);
1087 } else {
1088 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1089 uint64_t Value;
1090 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1091 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1092 SpecifierValid = (Value >= 1) && (Value <= 4);
1093 } else
1094 SpecifierValid = false;
1095 // Next token already snatched by parseSimpleIntegerLiteral.
1096 }
1097
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001098 if (!SpecifierValid) {
1099 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1100 return;
1101 }
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001102 if (Tok.isNot(tok::colon)) {
1103 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1104 return;
1105 }
1106
1107 // Collect the warning ids.
1108 SmallVector<int, 4> Ids;
1109 PP.Lex(Tok);
1110 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerdd6709e2014-02-12 23:50:26 +00001111 uint64_t Value;
1112 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1113 Value > INT_MAX) {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001114 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1115 return;
1116 }
Reid Klecknerdd6709e2014-02-12 23:50:26 +00001117 Ids.push_back(int(Value));
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001118 }
1119 if (Callbacks)
1120 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1121
1122 // Parse the next specifier if there is a semicolon.
1123 if (Tok.isNot(tok::semi))
1124 break;
1125 PP.Lex(Tok);
1126 }
1127 }
1128
1129 if (Tok.isNot(tok::r_paren)) {
1130 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1131 return;
1132 }
1133
1134 PP.Lex(Tok);
1135 if (Tok.isNot(tok::eod))
1136 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1137 }
1138};
1139
James Dennettb6e95b72012-06-17 03:26:26 +00001140/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman4c55c542012-03-02 22:51:54 +00001141struct PragmaIncludeAliasHandler : public PragmaHandler {
1142 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Craig Topper260dbc32014-03-11 06:50:42 +00001143 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1144 Token &IncludeAliasTok) override {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001145 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman4c55c542012-03-02 22:51:54 +00001146 }
1147};
1148
Andy Gibbs076eea22013-04-17 16:16:16 +00001149/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1150/// extension. The syntax is:
1151/// \code
1152/// #pragma message(string)
1153/// \endcode
1154/// OR, in GCC mode:
1155/// \code
1156/// #pragma message string
1157/// \endcode
1158/// string is a string, which is fully macro expanded, and permits string
1159/// concatenation, embedded escape characters, etc... See MSDN for more details.
1160/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1161/// form as \#pragma message.
Chris Lattnerabfe0942010-06-26 17:11:39 +00001162struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs076eea22013-04-17 16:16:16 +00001163private:
1164 const PPCallbacks::PragmaMessageKind Kind;
1165 const StringRef Namespace;
1166
1167 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1168 bool PragmaNameOnly = false) {
1169 switch (Kind) {
1170 case PPCallbacks::PMK_Message:
1171 return PragmaNameOnly ? "message" : "pragma message";
1172 case PPCallbacks::PMK_Warning:
1173 return PragmaNameOnly ? "warning" : "pragma warning";
1174 case PPCallbacks::PMK_Error:
1175 return PragmaNameOnly ? "error" : "pragma error";
1176 }
1177 llvm_unreachable("Unknown PragmaMessageKind!");
1178 }
1179
1180public:
1181 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1182 StringRef Namespace = StringRef())
1183 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1184
Craig Topper260dbc32014-03-11 06:50:42 +00001185 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1186 Token &Tok) override {
Andy Gibbs076eea22013-04-17 16:16:16 +00001187 SourceLocation MessageLoc = Tok.getLocation();
1188 PP.Lex(Tok);
1189 bool ExpectClosingParen = false;
1190 switch (Tok.getKind()) {
1191 case tok::l_paren:
1192 // We have a MSVC style pragma message.
1193 ExpectClosingParen = true;
1194 // Read the string.
1195 PP.Lex(Tok);
1196 break;
1197 case tok::string_literal:
1198 // We have a GCC style pragma message, and we just read the string.
1199 break;
1200 default:
1201 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1202 return;
1203 }
1204
1205 std::string MessageString;
1206 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1207 /*MacroExpansion=*/true))
1208 return;
1209
1210 if (ExpectClosingParen) {
1211 if (Tok.isNot(tok::r_paren)) {
1212 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1213 return;
1214 }
1215 PP.Lex(Tok); // eat the r_paren.
1216 }
1217
1218 if (Tok.isNot(tok::eod)) {
1219 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1220 return;
1221 }
1222
1223 // Output the message.
1224 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1225 ? diag::err_pragma_message
1226 : diag::warn_pragma_message) << MessageString;
1227
1228 // If the pragma is lexically sound, notify any interested PPCallbacks.
1229 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1230 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattnerabfe0942010-06-26 17:11:39 +00001231 }
1232};
1233
James Dennettb6e95b72012-06-17 03:26:26 +00001234/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerf47724b2010-08-17 15:55:45 +00001235/// macro on the top of the stack.
1236struct PragmaPushMacroHandler : public PragmaHandler {
1237 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Craig Topper260dbc32014-03-11 06:50:42 +00001238 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1239 Token &PushMacroTok) override {
Chris Lattnerf47724b2010-08-17 15:55:45 +00001240 PP.HandlePragmaPushMacro(PushMacroTok);
1241 }
1242};
1243
1244
James Dennettb6e95b72012-06-17 03:26:26 +00001245/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerf47724b2010-08-17 15:55:45 +00001246/// macro to the value on the top of the stack.
1247struct PragmaPopMacroHandler : public PragmaHandler {
1248 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Craig Topper260dbc32014-03-11 06:50:42 +00001249 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1250 Token &PopMacroTok) override {
Chris Lattnerf47724b2010-08-17 15:55:45 +00001251 PP.HandlePragmaPopMacro(PopMacroTok);
1252 }
1253};
1254
Chris Lattner062f2322009-04-19 21:20:35 +00001255// Pragma STDC implementations.
Chris Lattner6c5cf4a2009-04-19 21:50:08 +00001256
James Dennettb6e95b72012-06-17 03:26:26 +00001257/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
Chris Lattner062f2322009-04-19 21:20:35 +00001258struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001259 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
Craig Topper260dbc32014-03-11 06:50:42 +00001260 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1261 Token &Tok) override {
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +00001262 tok::OnOffSwitch OOS;
1263 if (PP.LexOnOffSwitch(OOS))
1264 return;
1265 if (OOS == tok::OOS_ON)
Chris Lattner4d8aac32009-04-19 21:55:32 +00001266 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
Chris Lattner062f2322009-04-19 21:20:35 +00001267 }
1268};
Mike Stump1eb44332009-09-09 15:08:12 +00001269
James Dennettb6e95b72012-06-17 03:26:26 +00001270/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
Chris Lattner062f2322009-04-19 21:20:35 +00001271struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001272 PragmaSTDC_CX_LIMITED_RANGEHandler()
1273 : PragmaHandler("CX_LIMITED_RANGE") {}
Craig Topper260dbc32014-03-11 06:50:42 +00001274 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1275 Token &Tok) override {
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +00001276 tok::OnOffSwitch OOS;
1277 PP.LexOnOffSwitch(OOS);
Chris Lattner062f2322009-04-19 21:20:35 +00001278 }
1279};
Mike Stump1eb44332009-09-09 15:08:12 +00001280
James Dennettb6e95b72012-06-17 03:26:26 +00001281/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
Chris Lattner062f2322009-04-19 21:20:35 +00001282struct PragmaSTDC_UnknownHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001283 PragmaSTDC_UnknownHandler() {}
Craig Topper260dbc32014-03-11 06:50:42 +00001284 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1285 Token &UnknownTok) override {
Chris Lattner6c5cf4a2009-04-19 21:50:08 +00001286 // C99 6.10.6p2, unknown forms are not allowed.
Chris Lattnerf545be52009-04-19 21:25:37 +00001287 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
Chris Lattner062f2322009-04-19 21:20:35 +00001288 }
1289};
Mike Stump1eb44332009-09-09 15:08:12 +00001290
John McCall8dfac0b2011-09-30 05:12:12 +00001291/// PragmaARCCFCodeAuditedHandler -
James Dennettb6e95b72012-06-17 03:26:26 +00001292/// \#pragma clang arc_cf_code_audited begin/end
John McCall8dfac0b2011-09-30 05:12:12 +00001293struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1294 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Craig Topper260dbc32014-03-11 06:50:42 +00001295 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1296 Token &NameTok) override {
John McCall8dfac0b2011-09-30 05:12:12 +00001297 SourceLocation Loc = NameTok.getLocation();
1298 bool IsBegin;
1299
1300 Token Tok;
1301
1302 // Lex the 'begin' or 'end'.
1303 PP.LexUnexpandedToken(Tok);
1304 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1305 if (BeginEnd && BeginEnd->isStr("begin")) {
1306 IsBegin = true;
1307 } else if (BeginEnd && BeginEnd->isStr("end")) {
1308 IsBegin = false;
1309 } else {
1310 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1311 return;
1312 }
1313
1314 // Verify that this is followed by EOD.
1315 PP.LexUnexpandedToken(Tok);
1316 if (Tok.isNot(tok::eod))
1317 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1318
1319 // The start location of the active audit.
1320 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1321
1322 // The start location we want after processing this.
1323 SourceLocation NewLoc;
1324
1325 if (IsBegin) {
1326 // Complain about attempts to re-enter an audit.
1327 if (BeginLoc.isValid()) {
1328 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1329 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1330 }
1331 NewLoc = Loc;
1332 } else {
1333 // Complain about attempts to leave an audit that doesn't exist.
1334 if (!BeginLoc.isValid()) {
1335 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1336 return;
1337 }
1338 NewLoc = SourceLocation();
1339 }
1340
1341 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1342 }
1343};
1344
Douglas Gregor109dad22015-06-19 18:25:57 +00001345/// PragmaAssumeNonNullHandler -
1346/// \#pragma clang assume_nonnull begin/end
1347struct PragmaAssumeNonNullHandler : public PragmaHandler {
1348 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1349 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1350 Token &NameTok) override {
1351 SourceLocation Loc = NameTok.getLocation();
1352 bool IsBegin;
1353
1354 Token Tok;
1355
1356 // Lex the 'begin' or 'end'.
1357 PP.LexUnexpandedToken(Tok);
1358 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1359 if (BeginEnd && BeginEnd->isStr("begin")) {
1360 IsBegin = true;
1361 } else if (BeginEnd && BeginEnd->isStr("end")) {
1362 IsBegin = false;
1363 } else {
1364 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1365 return;
1366 }
1367
1368 // Verify that this is followed by EOD.
1369 PP.LexUnexpandedToken(Tok);
1370 if (Tok.isNot(tok::eod))
1371 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1372
1373 // The start location of the active audit.
1374 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1375
1376 // The start location we want after processing this.
1377 SourceLocation NewLoc;
1378
1379 if (IsBegin) {
1380 // Complain about attempts to re-enter an audit.
1381 if (BeginLoc.isValid()) {
1382 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1383 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1384 }
1385 NewLoc = Loc;
1386 } else {
1387 // Complain about attempts to leave an audit that doesn't exist.
1388 if (!BeginLoc.isValid()) {
1389 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1390 return;
1391 }
1392 NewLoc = SourceLocation();
1393 }
1394
1395 PP.setPragmaAssumeNonNullLoc(NewLoc);
1396 }
1397};
1398
David Majnemerad5f8332013-06-30 08:18:16 +00001399/// \brief Handle "\#pragma region [...]"
1400///
1401/// The syntax is
1402/// \code
1403/// #pragma region [optional name]
1404/// #pragma endregion [optional comment]
1405/// \endcode
1406///
1407/// \note This is
1408/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1409/// pragma, just skipped by compiler.
1410struct PragmaRegionHandler : public PragmaHandler {
1411 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
Aaron Ballmanfafd1012012-11-30 19:52:30 +00001412
Craig Topper260dbc32014-03-11 06:50:42 +00001413 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1414 Token &NameTok) override {
David Majnemerad5f8332013-06-30 08:18:16 +00001415 // #pragma region: endregion matches can be verified
1416 // __pragma(region): no sense, but ignored by msvc
1417 // _Pragma is not valid for MSVC, but there isn't any point
1418 // to handle a _Pragma differently.
1419 }
1420};
Aaron Ballmanfafd1012012-11-30 19:52:30 +00001421
Reid Spencer5f016e22007-07-11 17:01:13 +00001422} // end anonymous namespace
1423
1424
1425/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennettb6e95b72012-06-17 03:26:26 +00001426/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001427void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001428 AddPragmaHandler(new PragmaOnceHandler());
1429 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerf47724b2010-08-17 15:55:45 +00001430 AddPragmaHandler(new PragmaPushMacroHandler());
1431 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs076eea22013-04-17 16:16:16 +00001432 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Chris Lattnere8fa06e2009-05-12 18:21:11 +00001434 // #pragma GCC ...
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001435 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1436 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1437 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregorc09ce122011-06-22 19:41:48 +00001438 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs076eea22013-04-17 16:16:16 +00001439 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1440 "GCC"));
1441 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1442 "GCC"));
Chris Lattnere8fa06e2009-05-12 18:21:11 +00001443 // #pragma clang ...
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001444 AddPragmaHandler("clang", new PragmaPoisonHandler());
1445 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarabf7b722010-07-28 15:40:33 +00001446 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001447 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregorc09ce122011-06-22 19:41:48 +00001448 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall8dfac0b2011-09-30 05:12:12 +00001449 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor109dad22015-06-19 18:25:57 +00001450 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnere8fa06e2009-05-12 18:21:11 +00001451
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001452 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1453 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
Chris Lattner062f2322009-04-19 21:20:35 +00001454 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Chris Lattner636c5ef2009-01-16 08:21:25 +00001456 // MS extensions.
David Blaikie4e4d0842012-03-11 07:00:24 +00001457 if (LangOpts.MicrosoftExt) {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001458 AddPragmaHandler(new PragmaWarningHandler());
Aaron Ballman4c55c542012-03-02 22:51:54 +00001459 AddPragmaHandler(new PragmaIncludeAliasHandler());
Aaron Ballmanfafd1012012-11-30 19:52:30 +00001460 AddPragmaHandler(new PragmaRegionHandler("region"));
1461 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Chris Lattnerabfe0942010-06-26 17:11:39 +00001462 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001463}
Lubos Lunakbce3e032014-05-01 12:54:03 +00001464
1465/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1466/// warn about those pragmas being unknown.
1467void Preprocessor::IgnorePragmas() {
1468 AddPragmaHandler(new EmptyPragmaHandler());
1469 // Also ignore all pragmas in all namespaces created
1470 // in Preprocessor::RegisterBuiltinPragmas().
1471 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1472 AddPragmaHandler("clang", new EmptyPragmaHandler());
1473 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1474 // Preprocessor::RegisterBuiltinPragmas() already registers
1475 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1476 // otherwise there will be an assert about a duplicate handler.
1477 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1478 assert(STDCNamespace &&
1479 "Invalid namespace, registered as a regular pragma handler!");
1480 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1481 RemovePragmaHandler("STDC", Existing);
Chandler Carruthf0785ab2014-05-02 21:44:48 +00001482 delete Existing;
Lubos Lunakbce3e032014-05-01 12:54:03 +00001483 }
1484 }
1485 AddPragmaHandler("STDC", new EmptyPragmaHandler());
1486}