blob: bfac3fda297cbd53d169b5e43e9e388e7c7759a4 [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"
Daniel Dunbarff759a62010-08-18 23:09:23 +000025#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar55054132010-08-17 22:32:48 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2e222532009-07-02 17:08:52 +000027#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
Reid Kleckner2ee042d2013-09-13 22:00:30 +000030#include "llvm/Support/raw_ostream.h"
31
Reid Spencer5f016e22007-07-11 17:01:13 +000032// Out-of-line destructor to provide a home for the class.
33PragmaHandler::~PragmaHandler() {
34}
35
36//===----------------------------------------------------------------------===//
Daniel Dunbarc72cc502010-06-11 20:10:12 +000037// EmptyPragmaHandler Implementation.
38//===----------------------------------------------------------------------===//
39
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000040EmptyPragmaHandler::EmptyPragmaHandler() {}
Daniel Dunbarc72cc502010-06-11 20:10:12 +000041
Douglas Gregor80c60f72010-09-09 22:45:38 +000042void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
43 PragmaIntroducerKind Introducer,
44 Token &FirstToken) {}
Daniel Dunbarc72cc502010-06-11 20:10:12 +000045
46//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000047// PragmaNamespace Implementation.
48//===----------------------------------------------------------------------===//
49
Reid Spencer5f016e22007-07-11 17:01:13 +000050PragmaNamespace::~PragmaNamespace() {
Stephen Hines651f13c2014-04-23 16:59:28 -070051 llvm::DeleteContainerSeconds(Handlers);
Reid Spencer5f016e22007-07-11 17:01:13 +000052}
53
54/// FindHandler - Check to see if there is already a handler for the
55/// specified name. If not, return the handler for the null identifier if it
56/// exists, otherwise return null. If IgnoreNull is true (the default) then
57/// the null handler isn't returned on failure to match.
Chris Lattner5f9e2722011-07-23 10:55:15 +000058PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Reid Spencer5f016e22007-07-11 17:01:13 +000059 bool IgnoreNull) const {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000060 if (PragmaHandler *Handler = Handlers.lookup(Name))
61 return Handler;
Stephen Hines6bcf27b2014-05-29 04:14:42 -070062 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000063}
Mike Stump1eb44332009-09-09 15:08:12 +000064
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000065void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
66 assert(!Handlers.lookup(Handler->getName()) &&
67 "A handler with this name is already registered in this namespace");
Stephen Hines176edba2014-12-01 14:53:08 -080068 Handlers[Handler->getName()] = Handler;
Reid Spencer5f016e22007-07-11 17:01:13 +000069}
70
Daniel Dunbar40950802008-10-04 19:17:46 +000071void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000072 assert(Handlers.lookup(Handler->getName()) &&
73 "Handler not registered in this namespace");
74 Handlers.erase(Handler->getName());
Daniel Dunbar40950802008-10-04 19:17:46 +000075}
76
Douglas Gregor80c60f72010-09-09 22:45:38 +000077void PragmaNamespace::HandlePragma(Preprocessor &PP,
78 PragmaIntroducerKind Introducer,
79 Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +000080 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
81 // expand it, the user can have a STDC #define, that should not affect this.
82 PP.LexUnexpandedToken(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +000083
Reid Spencer5f016e22007-07-11 17:01:13 +000084 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000085 PragmaHandler *Handler
86 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner5f9e2722011-07-23 10:55:15 +000087 : StringRef(),
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000088 /*IgnoreNull=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070089 if (!Handler) {
Chris Lattneraf7cdf42009-04-19 21:10:26 +000090 PP.Diag(Tok, diag::warn_pragma_ignored);
91 return;
92 }
Mike Stump1eb44332009-09-09 15:08:12 +000093
Reid Spencer5f016e22007-07-11 17:01:13 +000094 // Otherwise, pass it down.
Douglas Gregor80c60f72010-09-09 22:45:38 +000095 Handler->HandlePragma(PP, Introducer, Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +000096}
97
98//===----------------------------------------------------------------------===//
99// Preprocessor Pragma Directive Handling.
100//===----------------------------------------------------------------------===//
101
James Dennettb6e95b72012-06-17 03:26:26 +0000102/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Reid Spencer5f016e22007-07-11 17:01:13 +0000103/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella0189fd62013-07-20 20:09:11 +0000104void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
105 PragmaIntroducerKind Introducer) {
106 if (Callbacks)
107 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
108
Jordan Rose6fe6a492012-06-08 18:06:21 +0000109 if (!PragmasEnabled)
110 return;
111
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 ++NumPragma;
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattnerd2177732007-07-20 16:59:19 +0000115 Token Tok;
Enea Zaffanella0189fd62013-07-20 20:09:11 +0000116 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 // If the pragma handler didn't read the rest of the line, consume it now.
Peter Collingbourneb2eb53d2011-02-22 13:49:00 +0000119 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
120 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 DiscardUntilEndOfDirective();
122}
123
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000124namespace {
125/// \brief Helper class for \see Preprocessor::Handle_Pragma.
126class LexingFor_PragmaRAII {
127 Preprocessor &PP;
128 bool InMacroArgPreExpansion;
129 bool Failed;
130 Token &OutTok;
131 Token PragmaTok;
132
133public:
134 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
135 Token &Tok)
136 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
137 Failed(false), OutTok(Tok) {
138 if (InMacroArgPreExpansion) {
139 PragmaTok = OutTok;
140 PP.EnableBacktrackAtThisPos();
141 }
142 }
143
144 ~LexingFor_PragmaRAII() {
145 if (InMacroArgPreExpansion) {
146 if (Failed) {
147 PP.CommitBacktrackedTokens();
148 } else {
149 PP.Backtrack();
150 OutTok = PragmaTok;
151 }
152 }
153 }
154
155 void failed() {
156 Failed = true;
157 }
158};
159}
160
Reid Spencer5f016e22007-07-11 17:01:13 +0000161/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
162/// return the first token after the directive. The _Pragma token has just
163/// been read into 'Tok'.
Chris Lattnerd2177732007-07-20 16:59:19 +0000164void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000165
166 // This works differently if we are pre-expanding a macro argument.
167 // In that case we don't actually "activate" the pragma now, we only lex it
168 // until we are sure it is lexically correct and then we backtrack so that
169 // we activate the pragma whenever we encounter the tokens again in the token
170 // stream. This ensures that we will activate it in the correct location
171 // or that we will ignore it if it never enters the token stream, e.g:
172 //
173 // #define EMPTY(x)
174 // #define INACTIVE(x) EMPTY(x)
175 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
176
177 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 // Remember the pragma token location.
180 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Reid Spencer5f016e22007-07-11 17:01:13 +0000182 // Read the '('.
183 Lex(Tok);
Chris Lattner3692b092008-11-18 07:59:24 +0000184 if (Tok.isNot(tok::l_paren)) {
185 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000186 return _PragmaLexing.failed();
Chris Lattner3692b092008-11-18 07:59:24 +0000187 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000188
189 // Read the '"..."'.
190 Lex(Tok);
Richard Smith0b91cc42013-03-09 23:30:15 +0000191 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner3692b092008-11-18 07:59:24 +0000192 Diag(PragmaLoc, diag::err__Pragma_malformed);
Richard Smith99831e42012-03-06 03:21:47 +0000193 // Skip this token, and the ')', if present.
Stephen Hines176edba2014-12-01 14:53:08 -0800194 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smith99831e42012-03-06 03:21:47 +0000195 Lex(Tok);
196 if (Tok.is(tok::r_paren))
197 Lex(Tok);
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000198 return _PragmaLexing.failed();
Richard Smith99831e42012-03-06 03:21:47 +0000199 }
200
201 if (Tok.hasUDSuffix()) {
202 Diag(Tok, diag::err_invalid_string_udl);
203 // Skip this token, and the ')', if present.
204 Lex(Tok);
205 if (Tok.is(tok::r_paren))
206 Lex(Tok);
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000207 return _PragmaLexing.failed();
Chris Lattner3692b092008-11-18 07:59:24 +0000208 }
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Reid Spencer5f016e22007-07-11 17:01:13 +0000210 // Remember the string.
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000211 Token StrTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000212
213 // Read the ')'.
214 Lex(Tok);
Chris Lattner3692b092008-11-18 07:59:24 +0000215 if (Tok.isNot(tok::r_paren)) {
216 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000217 return _PragmaLexing.failed();
Chris Lattner3692b092008-11-18 07:59:24 +0000218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000220 if (InMacroArgPreExpansion)
221 return;
222
Chris Lattnere7fb4842009-02-15 20:52:18 +0000223 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +0000224 std::string StrVal = getSpelling(StrTok);
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Richard Smith0b91cc42013-03-09 23:30:15 +0000226 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
227 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattnera9d91452009-01-16 18:59:23 +0000228 // deleting the leading and trailing double-quotes, replacing each escape
229 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
230 // single backslash."
Richard Smith0b91cc42013-03-09 23:30:15 +0000231 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
232 (StrVal[0] == 'u' && StrVal[1] != '8'))
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 StrVal.erase(StrVal.begin());
Richard Smith0b91cc42013-03-09 23:30:15 +0000234 else if (StrVal[0] == 'u')
235 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
236
237 if (StrVal[0] == 'R') {
238 // FIXME: C++11 does not specify how to handle raw-string-literals here.
239 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
240 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
241 "Invalid raw string token!");
242
243 // Measure the length of the d-char-sequence.
244 unsigned NumDChars = 0;
245 while (StrVal[2 + NumDChars] != '(') {
246 assert(NumDChars < (StrVal.size() - 5) / 2 &&
247 "Invalid raw string token!");
248 ++NumDChars;
249 }
250 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
251
252 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
253 // parens below.
254 StrVal.erase(0, 2 + NumDChars);
255 StrVal.erase(StrVal.size() - 1 - NumDChars);
256 } else {
257 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
258 "Invalid string token!");
259
260 // Remove escaped quotes and escapes.
Benjamin Kramer269cc2d2013-05-04 10:37:20 +0000261 unsigned ResultPos = 1;
Reid Kleckner48b80c72013-09-25 16:42:48 +0000262 for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) {
263 // Skip escapes. \\ -> '\' and \" -> '"'.
264 if (StrVal[i] == '\\' && i + 1 < e &&
265 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
266 ++i;
267 StrVal[ResultPos++] = StrVal[i];
Richard Smith0b91cc42013-03-09 23:30:15 +0000268 }
Reid Kleckner48b80c72013-09-25 16:42:48 +0000269 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smith0b91cc42013-03-09 23:30:15 +0000270 }
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 // Remove the front quote, replacing it with a space, so that the pragma
273 // contents appear to have a space before them.
274 StrVal[0] = ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Chris Lattner1fa49532009-03-08 08:08:45 +0000276 // Replace the terminating quote with a \n.
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 StrVal[StrVal.size()-1] = '\n';
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000279 // Plop the string (including the newline and trailing null) into a buffer
280 // where we can lex it.
281 Token TmpTok;
282 TmpTok.startToken();
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000283 CreateString(StrVal, TmpTok);
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000284 SourceLocation TokLoc = TmpTok.getLocation();
285
286 // Make and enter a lexer object so that we lex and expand the tokens just
287 // like any others.
288 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
289 StrVal.size(), *this);
290
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700291 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000292
293 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella0189fd62013-07-20 20:09:11 +0000294 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall1ef8a2e2010-08-28 22:34:47 +0000295
296 // Finally, return whatever came after the pragma directive.
297 return Lex(Tok);
298}
299
300/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
301/// is not enclosed within a string literal.
302void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
303 // Remember the pragma token location.
304 SourceLocation PragmaLoc = Tok.getLocation();
305
306 // Read the '('.
307 Lex(Tok);
308 if (Tok.isNot(tok::l_paren)) {
309 Diag(PragmaLoc, diag::err__Pragma_malformed);
310 return;
311 }
312
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000313 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000314 SmallVector<Token, 32> PragmaToks;
John McCall1ef8a2e2010-08-28 22:34:47 +0000315 int NumParens = 0;
316 Lex(Tok);
317 while (Tok.isNot(tok::eof)) {
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000318 PragmaToks.push_back(Tok);
John McCall1ef8a2e2010-08-28 22:34:47 +0000319 if (Tok.is(tok::l_paren))
320 NumParens++;
321 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
322 break;
John McCall1ef8a2e2010-08-28 22:34:47 +0000323 Lex(Tok);
324 }
325
John McCall3da92a92010-08-29 01:09:54 +0000326 if (Tok.is(tok::eof)) {
327 Diag(PragmaLoc, diag::err_unterminated___pragma);
328 return;
329 }
330
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000331 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall1ef8a2e2010-08-28 22:34:47 +0000332
Peter Collingbourne84021552011-02-28 02:37:51 +0000333 // Replace the ')' with an EOD to mark the end of the pragma.
334 PragmaToks.back().setKind(tok::eod);
Peter Collingbournea5ef5842011-02-22 13:49:06 +0000335
336 Token *TokArray = new Token[PragmaToks.size()];
337 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
338
339 // Push the tokens onto the stack.
340 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
341
342 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella0189fd62013-07-20 20:09:11 +0000343 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall1ef8a2e2010-08-28 22:34:47 +0000344
345 // Finally, return whatever came after the pragma directive.
346 return Lex(Tok);
347}
348
James Dennettb6e95b72012-06-17 03:26:26 +0000349/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000350///
Chris Lattnerd2177732007-07-20 16:59:19 +0000351void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 if (isInPrimaryFile()) {
353 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
354 return;
355 }
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // Mark the file as a once-only file now.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000359 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Reid Spencer5f016e22007-07-11 17:01:13 +0000360}
361
Chris Lattner22434492007-12-19 19:38:36 +0000362void Preprocessor::HandlePragmaMark() {
Ted Kremenek17ff58a2008-11-19 22:21:33 +0000363 assert(CurPPLexer && "No current lexer?");
Chris Lattner6896a372009-06-15 05:02:34 +0000364 if (CurLexer)
365 CurLexer->ReadToEndOfLine();
366 else
367 CurPTHLexer->DiscardToEndOfLine();
Chris Lattner22434492007-12-19 19:38:36 +0000368}
369
370
James Dennettb6e95b72012-06-17 03:26:26 +0000371/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000372///
Chris Lattnerd2177732007-07-20 16:59:19 +0000373void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
374 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000375
376 while (1) {
377 // Read the next token to poison. While doing this, pretend that we are
378 // skipping while reading the identifier to poison.
379 // This avoids errors on code like:
380 // #pragma GCC poison X
381 // #pragma GCC poison X
Ted Kremenek68a91d52008-11-18 01:12:54 +0000382 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 LexUnexpandedToken(Tok);
Ted Kremenek68a91d52008-11-18 01:12:54 +0000384 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // If we reached the end of line, we're done.
Peter Collingbourne84021552011-02-28 02:37:51 +0000387 if (Tok.is(tok::eod)) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // Can only poison identifiers.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000390 if (Tok.isNot(tok::raw_identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 Diag(Tok, diag::err_pp_invalid_poison);
392 return;
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 // Look up the identifier info for the token. We disabled identifier lookup
396 // by saying we're skipping contents, so we need to do this manually.
397 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 // Already poisoned.
400 if (II->isPoisoned()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 // If this is a macro identifier, emit a warning.
Chris Lattner0edde552007-10-07 08:04:56 +0000403 if (II->hasMacroDefinition())
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 // Finally, poison it!
407 II->setIsPoisoned();
Douglas Gregoreee242f2011-10-27 09:33:13 +0000408 if (II->isFromAST())
409 II->setChangedSinceDeserialization();
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 }
411}
412
James Dennettb6e95b72012-06-17 03:26:26 +0000413/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Reid Spencer5f016e22007-07-11 17:01:13 +0000414/// that the whole directive has been parsed.
Chris Lattnerd2177732007-07-20 16:59:19 +0000415void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 if (isInPrimaryFile()) {
417 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
418 return;
419 }
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek35c10c22008-11-20 01:45:11 +0000422 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // Mark the file as a system header.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000425 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump1eb44332009-09-09 15:08:12 +0000426
427
Chris Lattner6896a372009-06-15 05:02:34 +0000428 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000429 if (PLoc.isInvalid())
430 return;
431
Jay Foad65aa6882011-06-21 15:13:30 +0000432 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattner784c2572011-05-22 22:10:16 +0000434 // Notify the client, if desired, that we are in a new source file.
435 if (Callbacks)
436 Callbacks->FileChanged(SysHeaderTok.getLocation(),
437 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
438
Chris Lattner6896a372009-06-15 05:02:34 +0000439 // Emit a line marker. This will change any source locations from this point
440 // forward to realize they are in a system header.
441 // Create a line note with this information.
Jordan Rose142b35e2013-04-17 19:09:18 +0000442 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
443 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
444 /*IsSystem=*/true, /*IsExternC=*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000445}
446
James Dennettb6e95b72012-06-17 03:26:26 +0000447/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Reid Spencer5f016e22007-07-11 17:01:13 +0000448///
Chris Lattnerd2177732007-07-20 16:59:19 +0000449void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
450 Token FilenameTok;
Ted Kremenek68a91d52008-11-18 01:12:54 +0000451 CurPPLexer->LexIncludeFilename(FilenameTok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000452
Peter Collingbourne84021552011-02-28 02:37:51 +0000453 // If the token kind is EOD, the error has already been diagnosed.
454 if (FilenameTok.is(tok::eod))
Reid Spencer5f016e22007-07-11 17:01:13 +0000455 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 // Reserve a buffer to get the spelling.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000458 SmallString<128> FilenameBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +0000459 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000460 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +0000461 if (Invalid)
462 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattnera1394812010-01-10 01:35:12 +0000464 bool isAngled =
465 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
467 // error.
Chris Lattnera1394812010-01-10 01:35:12 +0000468 if (Filename.empty())
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 // Search include directories for this file.
472 const DirectoryLookup *CurDir;
Stephen Hines176edba2014-12-01 14:53:08 -0800473 const FileEntry *File =
474 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
475 nullptr, CurDir, nullptr, nullptr, nullptr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700476 if (!File) {
Eli Friedmanf84139a2011-08-30 23:07:51 +0000477 if (!SuppressIncludeNotFoundError)
478 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner56b05c82008-11-18 08:02:48 +0000479 return;
480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Chris Lattner2b2453a2009-01-17 06:22:33 +0000482 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Reid Spencer5f016e22007-07-11 17:01:13 +0000483
484 // If this file is older than the file it depends on, emit a diagnostic.
485 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
486 // Lex tokens at the end of the message and include them in the message.
487 std::string Message;
488 Lex(DependencyTok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000489 while (DependencyTok.isNot(tok::eod)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 Message += getSpelling(DependencyTok) + " ";
491 Lex(DependencyTok);
492 }
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Chris Lattner96de2592010-09-05 23:16:09 +0000494 // Remove the trailing ' ' if present.
495 if (!Message.empty())
496 Message.erase(Message.end()-1);
Chris Lattner56b05c82008-11-18 08:02:48 +0000497 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 }
499}
500
Reid Kleckner7adf79a2013-05-06 21:02:12 +0000501/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerf47724b2010-08-17 15:55:45 +0000502/// Return the IdentifierInfo* associated with the macro to push or pop.
503IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
504 // Remember the pragma token location.
505 Token PragmaTok = Tok;
506
507 // Read the '('.
508 Lex(Tok);
509 if (Tok.isNot(tok::l_paren)) {
510 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
511 << getSpelling(PragmaTok);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700512 return nullptr;
Chris Lattnerf47724b2010-08-17 15:55:45 +0000513 }
514
515 // Read the macro name string.
516 Lex(Tok);
517 if (Tok.isNot(tok::string_literal)) {
518 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
519 << getSpelling(PragmaTok);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700520 return nullptr;
Chris Lattnerf47724b2010-08-17 15:55:45 +0000521 }
522
Richard Smith99831e42012-03-06 03:21:47 +0000523 if (Tok.hasUDSuffix()) {
524 Diag(Tok, diag::err_invalid_string_udl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700525 return nullptr;
Richard Smith99831e42012-03-06 03:21:47 +0000526 }
527
Chris Lattnerf47724b2010-08-17 15:55:45 +0000528 // Remember the macro string.
529 std::string StrVal = getSpelling(Tok);
530
531 // Read the ')'.
532 Lex(Tok);
533 if (Tok.isNot(tok::r_paren)) {
534 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
535 << getSpelling(PragmaTok);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700536 return nullptr;
Chris Lattnerf47724b2010-08-17 15:55:45 +0000537 }
538
539 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
540 "Invalid string token!");
541
542 // Create a Token from the string.
543 Token MacroTok;
544 MacroTok.startToken();
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000545 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000546 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerf47724b2010-08-17 15:55:45 +0000547
548 // Get the IdentifierInfo of MacroToPushTok.
549 return LookUpIdentifierInfo(MacroTok);
550}
551
James Dennettb6e95b72012-06-17 03:26:26 +0000552/// \brief Handle \#pragma push_macro.
553///
Chris Lattnerf47724b2010-08-17 15:55:45 +0000554/// The syntax is:
James Dennettb6e95b72012-06-17 03:26:26 +0000555/// \code
Dmitri Gribenkoe74dc192012-11-30 20:04:39 +0000556/// #pragma push_macro("macro")
James Dennettb6e95b72012-06-17 03:26:26 +0000557/// \endcode
Chris Lattnerf47724b2010-08-17 15:55:45 +0000558void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
559 // Parse the pragma directive and get the macro IdentifierInfo*.
560 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
561 if (!IdentInfo) return;
562
563 // Get the MacroInfo associated with IdentInfo.
564 MacroInfo *MI = getMacroInfo(IdentInfo);
565
Chris Lattnerf47724b2010-08-17 15:55:45 +0000566 if (MI) {
Chris Lattnerf47724b2010-08-17 15:55:45 +0000567 // Allow the original MacroInfo to be redefined later.
568 MI->setIsAllowRedefinitionsWithoutWarning(true);
569 }
570
571 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000572 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerf47724b2010-08-17 15:55:45 +0000573}
574
James Dennettb6e95b72012-06-17 03:26:26 +0000575/// \brief Handle \#pragma pop_macro.
576///
Chris Lattnerf47724b2010-08-17 15:55:45 +0000577/// The syntax is:
James Dennettb6e95b72012-06-17 03:26:26 +0000578/// \code
Chris Lattnerf47724b2010-08-17 15:55:45 +0000579/// #pragma pop_macro("macro")
James Dennettb6e95b72012-06-17 03:26:26 +0000580/// \endcode
Chris Lattnerf47724b2010-08-17 15:55:45 +0000581void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
582 SourceLocation MessageLoc = PopMacroTok.getLocation();
583
584 // Parse the pragma directive and get the macro IdentifierInfo*.
585 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
586 if (!IdentInfo) return;
587
588 // Find the vector<MacroInfo*> associated with the macro.
589 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
590 PragmaPushMacroInfo.find(IdentInfo);
591 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8a64bb52012-08-29 00:20:03 +0000592 // Forget the MacroInfo currently associated with IdentInfo.
Argyrios Kyrtzidis9818a1d2013-02-20 00:54:57 +0000593 if (MacroDirective *CurrentMD = getMacroDirective(IdentInfo)) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000594 MacroInfo *MI = CurrentMD->getMacroInfo();
595 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
Alexander Kornienkoe40c4232012-08-29 16:56:24 +0000603 if (MacroToReInstall) {
604 // Reinstall the previously pushed macro.
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000605 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc,
Stephen Hines176edba2014-12-01 14:53:08 -0800606 /*isImported=*/false, /*Overrides*/None);
Alexander Kornienkoe40c4232012-08-29 16:56:24 +0000607 }
Chris Lattnerf47724b2010-08-17 15:55:45 +0000608
609 // Pop PragmaPushMacroInfo stack.
610 iter->second.pop_back();
611 if (iter->second.size() == 0)
612 PragmaPushMacroInfo.erase(iter);
613 } else {
614 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
615 << IdentInfo->getName();
616 }
617}
Reid Spencer5f016e22007-07-11 17:01:13 +0000618
Aaron Ballman4c55c542012-03-02 22:51:54 +0000619void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
620 // We will either get a quoted filename or a bracketed filename, and we
621 // have to track which we got. The first filename is the source name,
622 // and the second name is the mapped filename. If the first is quoted,
623 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman4c55c542012-03-02 22:51:54 +0000624
625 // Get the open paren
626 Lex(Tok);
627 if (Tok.isNot(tok::l_paren)) {
628 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
629 return;
630 }
631
632 // We expect either a quoted string literal, or a bracketed name
633 Token SourceFilenameTok;
634 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
635 if (SourceFilenameTok.is(tok::eod)) {
636 // The diagnostic has already been handled
637 return;
638 }
639
640 StringRef SourceFileName;
641 SmallString<128> FileNameBuffer;
642 if (SourceFilenameTok.is(tok::string_literal) ||
643 SourceFilenameTok.is(tok::angle_string_literal)) {
644 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
645 } else if (SourceFilenameTok.is(tok::less)) {
646 // This could be a path instead of just a name
647 FileNameBuffer.push_back('<');
648 SourceLocation End;
649 if (ConcatenateIncludeName(FileNameBuffer, End))
650 return; // Diagnostic already emitted
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700651 SourceFileName = FileNameBuffer;
Aaron Ballman4c55c542012-03-02 22:51:54 +0000652 } else {
653 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
654 return;
655 }
656 FileNameBuffer.clear();
657
658 // Now we expect a comma, followed by another include name
659 Lex(Tok);
660 if (Tok.isNot(tok::comma)) {
661 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
662 return;
663 }
664
665 Token ReplaceFilenameTok;
666 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
667 if (ReplaceFilenameTok.is(tok::eod)) {
668 // The diagnostic has already been handled
669 return;
670 }
671
672 StringRef ReplaceFileName;
673 if (ReplaceFilenameTok.is(tok::string_literal) ||
674 ReplaceFilenameTok.is(tok::angle_string_literal)) {
675 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
676 } else if (ReplaceFilenameTok.is(tok::less)) {
677 // This could be a path instead of just a name
678 FileNameBuffer.push_back('<');
679 SourceLocation End;
680 if (ConcatenateIncludeName(FileNameBuffer, End))
681 return; // Diagnostic already emitted
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700682 ReplaceFileName = FileNameBuffer;
Aaron Ballman4c55c542012-03-02 22:51:54 +0000683 } else {
684 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
685 return;
686 }
687
688 // Finally, we expect the closing paren
689 Lex(Tok);
690 if (Tok.isNot(tok::r_paren)) {
691 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
692 return;
693 }
694
695 // Now that we have the source and target filenames, we need to make sure
696 // they're both of the same type (angled vs non-angled)
697 StringRef OriginalSource = SourceFileName;
698
699 bool SourceIsAngled =
700 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
701 SourceFileName);
702 bool ReplaceIsAngled =
703 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
704 ReplaceFileName);
705 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
706 (SourceIsAngled != ReplaceIsAngled)) {
707 unsigned int DiagID;
708 if (SourceIsAngled)
709 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
710 else
711 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
712
713 Diag(SourceFilenameTok.getLocation(), DiagID)
714 << SourceFileName
715 << ReplaceFileName;
716
717 return;
718 }
719
720 // Now we can let the include handler know about this mapping
721 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
722}
723
Reid Spencer5f016e22007-07-11 17:01:13 +0000724/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
725/// If 'Namespace' is non-null, then it is a token required to exist on the
726/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner5f9e2722011-07-23 10:55:15 +0000727void Preprocessor::AddPragmaHandler(StringRef Namespace,
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 PragmaHandler *Handler) {
Stephen Hines176edba2014-12-01 14:53:08 -0800729 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000732 if (!Namespace.empty()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 // If there is already a pragma handler with the name of this namespace,
734 // we either have an error (directive with the same name as a namespace) or
735 // we already have the namespace to insert into.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000736 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 InsertNS = Existing->getIfNamespace();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700738 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 " handler with the same name!");
740 } else {
741 // Otherwise, this namespace doesn't exist yet, create and insert the
742 // handler for it.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000743 InsertNS = new PragmaNamespace(Namespace);
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 PragmaHandlers->AddPragma(InsertNS);
745 }
746 }
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 // Check to make sure we don't already have a pragma for this identifier.
749 assert(!InsertNS->FindHandler(Handler->getName()) &&
750 "Pragma handler already exists for this identifier!");
751 InsertNS->AddPragma(Handler);
752}
753
Daniel Dunbar40950802008-10-04 19:17:46 +0000754/// RemovePragmaHandler - Remove the specific pragma handler from the
755/// preprocessor. If \arg Namespace is non-null, then it should be the
756/// namespace that \arg Handler was added to. It is an error to remove
757/// a handler that has not been registered.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000758void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40950802008-10-04 19:17:46 +0000759 PragmaHandler *Handler) {
Stephen Hines176edba2014-12-01 14:53:08 -0800760 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Daniel Dunbar40950802008-10-04 19:17:46 +0000762 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000763 if (!Namespace.empty()) {
764 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40950802008-10-04 19:17:46 +0000765 assert(Existing && "Namespace containing handler does not exist!");
766
767 NS = Existing->getIfNamespace();
768 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
769 }
770
771 NS->RemovePragmaHandler(Handler);
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Stephen Hines176edba2014-12-01 14:53:08 -0800773 // If this is a non-default namespace and it is now empty, remove it.
774 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40950802008-10-04 19:17:46 +0000775 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidisce52bb32012-01-06 00:22:09 +0000776 delete NS;
777 }
Daniel Dunbar40950802008-10-04 19:17:46 +0000778}
779
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +0000780bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
781 Token Tok;
782 LexUnexpandedToken(Tok);
783
784 if (Tok.isNot(tok::identifier)) {
785 Diag(Tok, diag::ext_on_off_switch_syntax);
786 return true;
787 }
788 IdentifierInfo *II = Tok.getIdentifierInfo();
789 if (II->isStr("ON"))
790 Result = tok::OOS_ON;
791 else if (II->isStr("OFF"))
792 Result = tok::OOS_OFF;
793 else if (II->isStr("DEFAULT"))
794 Result = tok::OOS_DEFAULT;
795 else {
796 Diag(Tok, diag::ext_on_off_switch_syntax);
797 return true;
798 }
799
Peter Collingbourne84021552011-02-28 02:37:51 +0000800 // Verify that this is followed by EOD.
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +0000801 LexUnexpandedToken(Tok);
Peter Collingbourne84021552011-02-28 02:37:51 +0000802 if (Tok.isNot(tok::eod))
803 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +0000804 return false;
805}
806
Reid Spencer5f016e22007-07-11 17:01:13 +0000807namespace {
James Dennettb6e95b72012-06-17 03:26:26 +0000808/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Reid Spencer5f016e22007-07-11 17:01:13 +0000809struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000810 PragmaOnceHandler() : PragmaHandler("once") {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700811 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
812 Token &OnceTok) override {
Chris Lattner35410d52009-04-14 05:07:49 +0000813 PP.CheckEndOfDirective("pragma once");
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 PP.HandlePragmaOnce(OnceTok);
815 }
816};
817
James Dennettb6e95b72012-06-17 03:26:26 +0000818/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattner22434492007-12-19 19:38:36 +0000819/// rest of the line is not lexed.
820struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000821 PragmaMarkHandler() : PragmaHandler("mark") {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700822 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
823 Token &MarkTok) override {
Chris Lattner22434492007-12-19 19:38:36 +0000824 PP.HandlePragmaMark();
825 }
826};
827
James Dennettb6e95b72012-06-17 03:26:26 +0000828/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Reid Spencer5f016e22007-07-11 17:01:13 +0000829struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000830 PragmaPoisonHandler() : PragmaHandler("poison") {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700831 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
832 Token &PoisonTok) override {
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 PP.HandlePragmaPoison(PoisonTok);
834 }
835};
836
James Dennettb6e95b72012-06-17 03:26:26 +0000837/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattner22434492007-12-19 19:38:36 +0000838/// as a system header, which silences warnings in it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000839struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000840 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700841 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
842 Token &SHToken) override {
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattner35410d52009-04-14 05:07:49 +0000844 PP.CheckEndOfDirective("pragma");
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 }
846};
847struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000848 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700849 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
850 Token &DepToken) override {
Reid Spencer5f016e22007-07-11 17:01:13 +0000851 PP.HandlePragmaDependency(DepToken);
852 }
853};
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000855struct PragmaDebugHandler : public PragmaHandler {
856 PragmaDebugHandler() : PragmaHandler("__debug") {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700857 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
858 Token &DepToken) override {
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000859 Token Tok;
860 PP.LexUnexpandedToken(Tok);
861 if (Tok.isNot(tok::identifier)) {
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000862 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000863 return;
864 }
865 IdentifierInfo *II = Tok.getIdentifierInfo();
866
Daniel Dunbar55054132010-08-17 22:32:48 +0000867 if (II->isStr("assert")) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000868 llvm_unreachable("This is an assertion!");
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000869 } else if (II->isStr("crash")) {
David Blaikie377da4c2012-08-21 18:56:49 +0000870 LLVM_BUILTIN_TRAP;
David Blaikiee75d9cf2012-06-29 22:03:56 +0000871 } else if (II->isStr("parser_crash")) {
872 Token Crasher;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700873 Crasher.startToken();
David Blaikiee75d9cf2012-06-29 22:03:56 +0000874 Crasher.setKind(tok::annot_pragma_parser_crash);
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700875 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikiee75d9cf2012-06-29 22:03:56 +0000876 PP.EnterToken(Crasher);
Daniel Dunbar55054132010-08-17 22:32:48 +0000877 } else if (II->isStr("llvm_fatal_error")) {
878 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
879 } else if (II->isStr("llvm_unreachable")) {
880 llvm_unreachable("#pragma clang __debug llvm_unreachable");
881 } else if (II->isStr("overflow_stack")) {
882 DebugOverflowStack();
Daniel Dunbarff759a62010-08-18 23:09:23 +0000883 } else if (II->isStr("handle_crash")) {
884 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
885 if (CRC)
886 CRC->HandleCrash();
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000887 } else if (II->isStr("captured")) {
888 HandleCaptured(PP);
Daniel Dunbar55054132010-08-17 22:32:48 +0000889 } else {
890 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
891 << II->getName();
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000892 }
Tareq A. Siraj85192c72013-04-16 18:41:26 +0000893
894 PPCallbacks *Callbacks = PP.getPPCallbacks();
895 if (Callbacks)
896 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
897 }
898
899 void HandleCaptured(Preprocessor &PP) {
900 // Skip if emitting preprocessed output.
901 if (PP.isPreprocessedOutput())
902 return;
903
904 Token Tok;
905 PP.LexUnexpandedToken(Tok);
906
907 if (Tok.isNot(tok::eod)) {
908 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
909 << "pragma clang __debug captured";
910 return;
911 }
912
913 SourceLocation NameLoc = Tok.getLocation();
914 Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1);
915 Toks->startToken();
916 Toks->setKind(tok::annot_pragma_captured);
917 Toks->setLocation(NameLoc);
918
919 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
920 /*OwnsTokens=*/false);
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000921 }
922
Francois Pichet1066c6c2011-05-25 16:15:03 +0000923// Disable MSVC warning about runtime stack overflow.
924#ifdef _MSC_VER
925 #pragma warning(disable : 4717)
926#endif
Stephen Hines651f13c2014-04-23 16:59:28 -0700927 static void DebugOverflowStack() {
928 void (*volatile Self)() = DebugOverflowStack;
929 Self();
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000930 }
Francois Pichet1066c6c2011-05-25 16:15:03 +0000931#ifdef _MSC_VER
932 #pragma warning(default : 4717)
933#endif
934
Daniel Dunbarabf7b722010-07-28 15:40:33 +0000935};
936
James Dennettb6e95b72012-06-17 03:26:26 +0000937/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattneredaf8772009-04-19 23:16:58 +0000938struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregorc09ce122011-06-22 19:41:48 +0000939private:
940 const char *Namespace;
Chris Lattner04ae2df2009-07-12 21:18:45 +0000941public:
Douglas Gregorc09ce122011-06-22 19:41:48 +0000942 explicit PragmaDiagnosticHandler(const char *NS) :
943 PragmaHandler("diagnostic"), Namespace(NS) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700944 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
945 Token &DiagToken) override {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000946 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattneredaf8772009-04-19 23:16:58 +0000947 Token Tok;
948 PP.LexUnexpandedToken(Tok);
949 if (Tok.isNot(tok::identifier)) {
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000950 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattneredaf8772009-04-19 23:16:58 +0000951 return;
952 }
953 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregorc09ce122011-06-22 19:41:48 +0000954 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700956 if (II->isStr("pop")) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000957 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000958 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000959 else if (Callbacks)
960 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000961 return;
962 } else if (II->isStr("push")) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000963 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregorc09ce122011-06-22 19:41:48 +0000964 if (Callbacks)
965 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattner04ae2df2009-07-12 21:18:45 +0000966 return;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700967 }
968
969 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
970 .Case("ignored", diag::Severity::Ignored)
971 .Case("warning", diag::Severity::Warning)
972 .Case("error", diag::Severity::Error)
973 .Case("fatal", diag::Severity::Fatal)
974 .Default(diag::Severity());
975
976 if (SV == diag::Severity()) {
Douglas Gregor6493a4d2010-08-30 15:15:34 +0000977 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattneredaf8772009-04-19 23:16:58 +0000978 return;
979 }
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chris Lattneredaf8772009-04-19 23:16:58 +0000981 PP.LexUnexpandedToken(Tok);
Andy Gibbs02a17682012-11-17 19:15:38 +0000982 SourceLocation StringLoc = Tok.getLocation();
Chris Lattneredaf8772009-04-19 23:16:58 +0000983
Andy Gibbs02a17682012-11-17 19:15:38 +0000984 std::string WarningName;
Andy Gibbs97f84612012-11-17 19:16:52 +0000985 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
986 /*MacroExpansion=*/false))
Chris Lattneredaf8772009-04-19 23:16:58 +0000987 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Peter Collingbourne84021552011-02-28 02:37:51 +0000989 if (Tok.isNot(tok::eod)) {
Chris Lattneredaf8772009-04-19 23:16:58 +0000990 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
991 return;
992 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattneredaf8772009-04-19 23:16:58 +0000994 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Stephen Hines176edba2014-12-01 14:53:08 -0800995 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs02a17682012-11-17 19:15:38 +0000996 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattneredaf8772009-04-19 23:16:58 +0000997 return;
998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Stephen Hines176edba2014-12-01 14:53:08 -08001000 if (PP.getDiagnostics().setSeverityForGroup(
1001 WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1002 : diag::Flavor::Remark,
1003 WarningName.substr(2), SV, DiagLoc))
Andy Gibbs02a17682012-11-17 19:15:38 +00001004 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1005 << WarningName;
Douglas Gregorc09ce122011-06-22 19:41:48 +00001006 else if (Callbacks)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001007 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattneredaf8772009-04-19 23:16:58 +00001008 }
1009};
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001011/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1012/// diagnostics, so we don't really implement this pragma. We parse it and
1013/// ignore it to avoid -Wunknown-pragma warnings.
1014struct PragmaWarningHandler : public PragmaHandler {
1015 PragmaWarningHandler() : PragmaHandler("warning") {}
1016
Stephen Hines651f13c2014-04-23 16:59:28 -07001017 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1018 Token &Tok) override {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001019 // Parse things like:
1020 // warning(push, 1)
1021 // warning(pop)
John Thompsonfaea5bf2013-11-16 00:16:03 +00001022 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001023 SourceLocation DiagLoc = Tok.getLocation();
1024 PPCallbacks *Callbacks = PP.getPPCallbacks();
1025
1026 PP.Lex(Tok);
1027 if (Tok.isNot(tok::l_paren)) {
1028 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1029 return;
1030 }
1031
1032 PP.Lex(Tok);
1033 IdentifierInfo *II = Tok.getIdentifierInfo();
1034 if (!II) {
1035 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1036 return;
1037 }
1038
1039 if (II->isStr("push")) {
1040 // #pragma warning( push[ ,n ] )
Reid Kleckner72c26c02013-10-02 15:19:23 +00001041 int Level = -1;
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001042 PP.Lex(Tok);
1043 if (Tok.is(tok::comma)) {
1044 PP.Lex(Tok);
Stephen Hines651f13c2014-04-23 16:59:28 -07001045 uint64_t Value;
1046 if (Tok.is(tok::numeric_constant) &&
1047 PP.parseSimpleIntegerLiteral(Tok, Value))
1048 Level = int(Value);
Reid Kleckner72c26c02013-10-02 15:19:23 +00001049 if (Level < 0 || Level > 4) {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001050 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1051 return;
1052 }
1053 }
1054 if (Callbacks)
1055 Callbacks->PragmaWarningPush(DiagLoc, Level);
1056 } else if (II->isStr("pop")) {
1057 // #pragma warning( pop )
1058 PP.Lex(Tok);
1059 if (Callbacks)
1060 Callbacks->PragmaWarningPop(DiagLoc);
1061 } else {
1062 // #pragma warning( warning-specifier : warning-number-list
1063 // [; warning-specifier : warning-number-list...] )
1064 while (true) {
1065 II = Tok.getIdentifierInfo();
1066 if (!II) {
1067 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1068 return;
1069 }
1070
1071 // Figure out which warning specifier this is.
1072 StringRef Specifier = II->getName();
1073 bool SpecifierValid =
1074 llvm::StringSwitch<bool>(Specifier)
1075 .Cases("1", "2", "3", "4", true)
1076 .Cases("default", "disable", "error", "once", "suppress", true)
1077 .Default(false);
1078 if (!SpecifierValid) {
1079 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1080 return;
1081 }
1082 PP.Lex(Tok);
1083 if (Tok.isNot(tok::colon)) {
1084 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1085 return;
1086 }
1087
1088 // Collect the warning ids.
1089 SmallVector<int, 4> Ids;
1090 PP.Lex(Tok);
1091 while (Tok.is(tok::numeric_constant)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001092 uint64_t Value;
1093 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1094 Value > INT_MAX) {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001095 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1096 return;
1097 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001098 Ids.push_back(int(Value));
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001099 }
1100 if (Callbacks)
1101 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1102
1103 // Parse the next specifier if there is a semicolon.
1104 if (Tok.isNot(tok::semi))
1105 break;
1106 PP.Lex(Tok);
1107 }
1108 }
1109
1110 if (Tok.isNot(tok::r_paren)) {
1111 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1112 return;
1113 }
1114
1115 PP.Lex(Tok);
1116 if (Tok.isNot(tok::eod))
1117 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1118 }
1119};
1120
James Dennettb6e95b72012-06-17 03:26:26 +00001121/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman4c55c542012-03-02 22:51:54 +00001122struct PragmaIncludeAliasHandler : public PragmaHandler {
1123 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Stephen Hines651f13c2014-04-23 16:59:28 -07001124 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1125 Token &IncludeAliasTok) override {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001126 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman4c55c542012-03-02 22:51:54 +00001127 }
1128};
1129
Andy Gibbs076eea22013-04-17 16:16:16 +00001130/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1131/// extension. The syntax is:
1132/// \code
1133/// #pragma message(string)
1134/// \endcode
1135/// OR, in GCC mode:
1136/// \code
1137/// #pragma message string
1138/// \endcode
1139/// string is a string, which is fully macro expanded, and permits string
1140/// concatenation, embedded escape characters, etc... See MSDN for more details.
1141/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1142/// form as \#pragma message.
Chris Lattnerabfe0942010-06-26 17:11:39 +00001143struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs076eea22013-04-17 16:16:16 +00001144private:
1145 const PPCallbacks::PragmaMessageKind Kind;
1146 const StringRef Namespace;
1147
1148 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1149 bool PragmaNameOnly = false) {
1150 switch (Kind) {
1151 case PPCallbacks::PMK_Message:
1152 return PragmaNameOnly ? "message" : "pragma message";
1153 case PPCallbacks::PMK_Warning:
1154 return PragmaNameOnly ? "warning" : "pragma warning";
1155 case PPCallbacks::PMK_Error:
1156 return PragmaNameOnly ? "error" : "pragma error";
1157 }
1158 llvm_unreachable("Unknown PragmaMessageKind!");
1159 }
1160
1161public:
1162 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1163 StringRef Namespace = StringRef())
1164 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1165
Stephen Hines651f13c2014-04-23 16:59:28 -07001166 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1167 Token &Tok) override {
Andy Gibbs076eea22013-04-17 16:16:16 +00001168 SourceLocation MessageLoc = Tok.getLocation();
1169 PP.Lex(Tok);
1170 bool ExpectClosingParen = false;
1171 switch (Tok.getKind()) {
1172 case tok::l_paren:
1173 // We have a MSVC style pragma message.
1174 ExpectClosingParen = true;
1175 // Read the string.
1176 PP.Lex(Tok);
1177 break;
1178 case tok::string_literal:
1179 // We have a GCC style pragma message, and we just read the string.
1180 break;
1181 default:
1182 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1183 return;
1184 }
1185
1186 std::string MessageString;
1187 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1188 /*MacroExpansion=*/true))
1189 return;
1190
1191 if (ExpectClosingParen) {
1192 if (Tok.isNot(tok::r_paren)) {
1193 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1194 return;
1195 }
1196 PP.Lex(Tok); // eat the r_paren.
1197 }
1198
1199 if (Tok.isNot(tok::eod)) {
1200 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1201 return;
1202 }
1203
1204 // Output the message.
1205 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1206 ? diag::err_pragma_message
1207 : diag::warn_pragma_message) << MessageString;
1208
1209 // If the pragma is lexically sound, notify any interested PPCallbacks.
1210 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1211 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattnerabfe0942010-06-26 17:11:39 +00001212 }
1213};
1214
James Dennettb6e95b72012-06-17 03:26:26 +00001215/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerf47724b2010-08-17 15:55:45 +00001216/// macro on the top of the stack.
1217struct PragmaPushMacroHandler : public PragmaHandler {
1218 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Stephen Hines651f13c2014-04-23 16:59:28 -07001219 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1220 Token &PushMacroTok) override {
Chris Lattnerf47724b2010-08-17 15:55:45 +00001221 PP.HandlePragmaPushMacro(PushMacroTok);
1222 }
1223};
1224
1225
James Dennettb6e95b72012-06-17 03:26:26 +00001226/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerf47724b2010-08-17 15:55:45 +00001227/// macro to the value on the top of the stack.
1228struct PragmaPopMacroHandler : public PragmaHandler {
1229 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Stephen Hines651f13c2014-04-23 16:59:28 -07001230 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1231 Token &PopMacroTok) override {
Chris Lattnerf47724b2010-08-17 15:55:45 +00001232 PP.HandlePragmaPopMacro(PopMacroTok);
1233 }
1234};
1235
Chris Lattner062f2322009-04-19 21:20:35 +00001236// Pragma STDC implementations.
Chris Lattner6c5cf4a2009-04-19 21:50:08 +00001237
James Dennettb6e95b72012-06-17 03:26:26 +00001238/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
Chris Lattner062f2322009-04-19 21:20:35 +00001239struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001240 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
Stephen Hines651f13c2014-04-23 16:59:28 -07001241 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1242 Token &Tok) override {
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +00001243 tok::OnOffSwitch OOS;
1244 if (PP.LexOnOffSwitch(OOS))
1245 return;
1246 if (OOS == tok::OOS_ON)
Chris Lattner4d8aac32009-04-19 21:55:32 +00001247 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
Chris Lattner062f2322009-04-19 21:20:35 +00001248 }
1249};
Mike Stump1eb44332009-09-09 15:08:12 +00001250
James Dennettb6e95b72012-06-17 03:26:26 +00001251/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
Chris Lattner062f2322009-04-19 21:20:35 +00001252struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001253 PragmaSTDC_CX_LIMITED_RANGEHandler()
1254 : PragmaHandler("CX_LIMITED_RANGE") {}
Stephen Hines651f13c2014-04-23 16:59:28 -07001255 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1256 Token &Tok) override {
Peter Collingbourne9d3f5f72011-02-14 01:42:24 +00001257 tok::OnOffSwitch OOS;
1258 PP.LexOnOffSwitch(OOS);
Chris Lattner062f2322009-04-19 21:20:35 +00001259 }
1260};
Mike Stump1eb44332009-09-09 15:08:12 +00001261
James Dennettb6e95b72012-06-17 03:26:26 +00001262/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
Chris Lattner062f2322009-04-19 21:20:35 +00001263struct PragmaSTDC_UnknownHandler : public PragmaHandler {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001264 PragmaSTDC_UnknownHandler() {}
Stephen Hines651f13c2014-04-23 16:59:28 -07001265 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1266 Token &UnknownTok) override {
Chris Lattner6c5cf4a2009-04-19 21:50:08 +00001267 // C99 6.10.6p2, unknown forms are not allowed.
Chris Lattnerf545be52009-04-19 21:25:37 +00001268 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
Chris Lattner062f2322009-04-19 21:20:35 +00001269 }
1270};
Mike Stump1eb44332009-09-09 15:08:12 +00001271
John McCall8dfac0b2011-09-30 05:12:12 +00001272/// PragmaARCCFCodeAuditedHandler -
James Dennettb6e95b72012-06-17 03:26:26 +00001273/// \#pragma clang arc_cf_code_audited begin/end
John McCall8dfac0b2011-09-30 05:12:12 +00001274struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1275 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Stephen Hines651f13c2014-04-23 16:59:28 -07001276 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1277 Token &NameTok) override {
John McCall8dfac0b2011-09-30 05:12:12 +00001278 SourceLocation Loc = NameTok.getLocation();
1279 bool IsBegin;
1280
1281 Token Tok;
1282
1283 // Lex the 'begin' or 'end'.
1284 PP.LexUnexpandedToken(Tok);
1285 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1286 if (BeginEnd && BeginEnd->isStr("begin")) {
1287 IsBegin = true;
1288 } else if (BeginEnd && BeginEnd->isStr("end")) {
1289 IsBegin = false;
1290 } else {
1291 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1292 return;
1293 }
1294
1295 // Verify that this is followed by EOD.
1296 PP.LexUnexpandedToken(Tok);
1297 if (Tok.isNot(tok::eod))
1298 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1299
1300 // The start location of the active audit.
1301 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1302
1303 // The start location we want after processing this.
1304 SourceLocation NewLoc;
1305
1306 if (IsBegin) {
1307 // Complain about attempts to re-enter an audit.
1308 if (BeginLoc.isValid()) {
1309 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1310 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1311 }
1312 NewLoc = Loc;
1313 } else {
1314 // Complain about attempts to leave an audit that doesn't exist.
1315 if (!BeginLoc.isValid()) {
1316 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1317 return;
1318 }
1319 NewLoc = SourceLocation();
1320 }
1321
1322 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1323 }
1324};
1325
David Majnemerad5f8332013-06-30 08:18:16 +00001326/// \brief Handle "\#pragma region [...]"
1327///
1328/// The syntax is
1329/// \code
1330/// #pragma region [optional name]
1331/// #pragma endregion [optional comment]
1332/// \endcode
1333///
1334/// \note This is
1335/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1336/// pragma, just skipped by compiler.
1337struct PragmaRegionHandler : public PragmaHandler {
1338 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
Aaron Ballmanfafd1012012-11-30 19:52:30 +00001339
Stephen Hines651f13c2014-04-23 16:59:28 -07001340 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1341 Token &NameTok) override {
David Majnemerad5f8332013-06-30 08:18:16 +00001342 // #pragma region: endregion matches can be verified
1343 // __pragma(region): no sense, but ignored by msvc
1344 // _Pragma is not valid for MSVC, but there isn't any point
1345 // to handle a _Pragma differently.
1346 }
1347};
Aaron Ballmanfafd1012012-11-30 19:52:30 +00001348
Reid Spencer5f016e22007-07-11 17:01:13 +00001349} // end anonymous namespace
1350
1351
1352/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennettb6e95b72012-06-17 03:26:26 +00001353/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001354void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001355 AddPragmaHandler(new PragmaOnceHandler());
1356 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerf47724b2010-08-17 15:55:45 +00001357 AddPragmaHandler(new PragmaPushMacroHandler());
1358 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs076eea22013-04-17 16:16:16 +00001359 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Chris Lattnere8fa06e2009-05-12 18:21:11 +00001361 // #pragma GCC ...
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001362 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1363 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1364 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregorc09ce122011-06-22 19:41:48 +00001365 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs076eea22013-04-17 16:16:16 +00001366 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1367 "GCC"));
1368 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1369 "GCC"));
Chris Lattnere8fa06e2009-05-12 18:21:11 +00001370 // #pragma clang ...
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001371 AddPragmaHandler("clang", new PragmaPoisonHandler());
1372 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarabf7b722010-07-28 15:40:33 +00001373 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001374 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregorc09ce122011-06-22 19:41:48 +00001375 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall8dfac0b2011-09-30 05:12:12 +00001376 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Chris Lattnere8fa06e2009-05-12 18:21:11 +00001377
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +00001378 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1379 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
Chris Lattner062f2322009-04-19 21:20:35 +00001380 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Chris Lattner636c5ef2009-01-16 08:21:25 +00001382 // MS extensions.
David Blaikie4e4d0842012-03-11 07:00:24 +00001383 if (LangOpts.MicrosoftExt) {
Reid Kleckner2ee042d2013-09-13 22:00:30 +00001384 AddPragmaHandler(new PragmaWarningHandler());
Aaron Ballman4c55c542012-03-02 22:51:54 +00001385 AddPragmaHandler(new PragmaIncludeAliasHandler());
Aaron Ballmanfafd1012012-11-30 19:52:30 +00001386 AddPragmaHandler(new PragmaRegionHandler("region"));
1387 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Chris Lattnerabfe0942010-06-26 17:11:39 +00001388 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001389}
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001390
1391/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1392/// warn about those pragmas being unknown.
1393void Preprocessor::IgnorePragmas() {
1394 AddPragmaHandler(new EmptyPragmaHandler());
1395 // Also ignore all pragmas in all namespaces created
1396 // in Preprocessor::RegisterBuiltinPragmas().
1397 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1398 AddPragmaHandler("clang", new EmptyPragmaHandler());
1399 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1400 // Preprocessor::RegisterBuiltinPragmas() already registers
1401 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1402 // otherwise there will be an assert about a duplicate handler.
1403 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1404 assert(STDCNamespace &&
1405 "Invalid namespace, registered as a regular pragma handler!");
1406 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1407 RemovePragmaHandler("STDC", Existing);
1408 delete Existing;
1409 }
1410 }
1411 AddPragmaHandler("STDC", new EmptyPragmaHandler());
1412}