blob: bfac3fda297cbd53d169b5e43e9e388e7c7759a4 [file] [log] [blame]
Chris Lattnerb8761832006-06-24 21:31:03 +00001//===--- Pragma.cpp - Pragma registration and handling --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb8761832006-06-24 21:31:03 +00007//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerb694ba72006-07-02 22:41:36 +000010// This file implements the PragmaHandler/PragmaTable interfaces and implements
11// pragma related methods of the Preprocessor class.
Chris Lattnerb8761832006-06-24 21:31:03 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Pragma.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-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 Kleckner881dff32013-09-13 22:00:30 +000023#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/StringSwitch.h"
Daniel Dunbar211a7872010-08-18 23:09:23 +000025#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbarf2cf3292010-08-17 22:32:48 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000027#include <algorithm>
Chris Lattnerb8761832006-06-24 21:31:03 +000028using namespace clang;
29
Reid Kleckner881dff32013-09-13 22:00:30 +000030#include "llvm/Support/raw_ostream.h"
31
Chris Lattnerb8761832006-06-24 21:31:03 +000032// Out-of-line destructor to provide a home for the class.
33PragmaHandler::~PragmaHandler() {
34}
35
Chris Lattner2e155302006-07-03 05:34:41 +000036//===----------------------------------------------------------------------===//
Daniel Dunbard839e772010-06-11 20:10:12 +000037// EmptyPragmaHandler Implementation.
38//===----------------------------------------------------------------------===//
39
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000040EmptyPragmaHandler::EmptyPragmaHandler() {}
Daniel Dunbard839e772010-06-11 20:10:12 +000041
Douglas Gregorc7d65762010-09-09 22:45:38 +000042void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
43 PragmaIntroducerKind Introducer,
44 Token &FirstToken) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000045
46//===----------------------------------------------------------------------===//
Chris Lattner2e155302006-07-03 05:34:41 +000047// PragmaNamespace Implementation.
48//===----------------------------------------------------------------------===//
49
Chris Lattner2e155302006-07-03 05:34:41 +000050PragmaNamespace::~PragmaNamespace() {
Reid Kleckner588c9372014-02-19 23:44:52 +000051 llvm::DeleteContainerSeconds(Handlers);
Chris Lattner2e155302006-07-03 05:34:41 +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 Lattner0e62c1c2011-07-23 10:55:15 +000058PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Chris Lattner2e155302006-07-03 05:34:41 +000059 bool IgnoreNull) const {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000060 if (PragmaHandler *Handler = Handlers.lookup(Name))
61 return Handler;
Craig Topperd2d442c2014-05-17 23:10:59 +000062 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000063}
Mike Stump11289f42009-09-09 15:08:12 +000064
Argyrios Kyrtzidis36745fd2010-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");
David Blaikie13156b62014-11-19 03:06:06 +000068 Handlers[Handler->getName()] = Handler;
Chris Lattner2e155302006-07-03 05:34:41 +000069}
70
Daniel Dunbar40596532008-10-04 19:17:46 +000071void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000072 assert(Handlers.lookup(Handler->getName()) &&
73 "Handler not registered in this namespace");
74 Handlers.erase(Handler->getName());
Daniel Dunbar40596532008-10-04 19:17:46 +000075}
76
Douglas Gregorc7d65762010-09-09 22:45:38 +000077void PragmaNamespace::HandlePragma(Preprocessor &PP,
78 PragmaIntroducerKind Introducer,
79 Token &Tok) {
Chris Lattnerb8761832006-06-24 21:31:03 +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 Stump11289f42009-09-09 15:08:12 +000083
Chris Lattnerb8761832006-06-24 21:31:03 +000084 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000085 PragmaHandler *Handler
86 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner0e62c1c2011-07-23 10:55:15 +000087 : StringRef(),
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000088 /*IgnoreNull=*/false);
Craig Topperd2d442c2014-05-17 23:10:59 +000089 if (!Handler) {
Chris Lattner21656f22009-04-19 21:10:26 +000090 PP.Diag(Tok, diag::warn_pragma_ignored);
91 return;
92 }
Mike Stump11289f42009-09-09 15:08:12 +000093
Chris Lattnerb8761832006-06-24 21:31:03 +000094 // Otherwise, pass it down.
Douglas Gregorc7d65762010-09-09 22:45:38 +000095 Handler->HandlePragma(PP, Introducer, Tok);
Chris Lattnerb8761832006-06-24 21:31:03 +000096}
Chris Lattnerb694ba72006-07-02 22:41:36 +000097
Chris Lattnerb694ba72006-07-02 22:41:36 +000098//===----------------------------------------------------------------------===//
99// Preprocessor Pragma Directive Handling.
100//===----------------------------------------------------------------------===//
101
James Dennett18a6d792012-06-17 03:26:26 +0000102/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Chris Lattnerb694ba72006-07-02 22:41:36 +0000103/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000104void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
105 PragmaIntroducerKind Introducer) {
106 if (Callbacks)
107 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
108
Jordan Rosede1a2922012-06-08 18:06:21 +0000109 if (!PragmasEnabled)
110 return;
111
Chris Lattnerb694ba72006-07-02 22:41:36 +0000112 ++NumPragma;
Mike Stump11289f42009-09-09 15:08:12 +0000113
Chris Lattnerb694ba72006-07-02 22:41:36 +0000114 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattner146762e2007-07-20 16:59:19 +0000115 Token Tok;
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000116 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000117
Chris Lattnerb694ba72006-07-02 22:41:36 +0000118 // If the pragma handler didn't read the rest of the line, consume it now.
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000119 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
120 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000121 DiscardUntilEndOfDirective();
122}
123
Argyrios Kyrtzidisf1b64c62012-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
Chris Lattnerb694ba72006-07-02 22:41:36 +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 Lattner146762e2007-07-20 16:59:19 +0000164void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidisf1b64c62012-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
Chris Lattnerb694ba72006-07-02 22:41:36 +0000179 // Remember the pragma token location.
180 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000181
Chris Lattnerb694ba72006-07-02 22:41:36 +0000182 // Read the '('.
183 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000184 if (Tok.isNot(tok::l_paren)) {
185 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000186 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000187 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000188
189 // Read the '"..."'.
190 Lex(Tok);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000191 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000192 Diag(PragmaLoc, diag::err__Pragma_malformed);
Richard Smithd67aea22012-03-06 03:21:47 +0000193 // Skip this token, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000194 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000195 Lex(Tok);
196 if (Tok.is(tok::r_paren))
197 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000198 return _PragmaLexing.failed();
Richard Smithd67aea22012-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 Kyrtzidisf1b64c62012-04-03 16:47:40 +0000207 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000208 }
Mike Stump11289f42009-09-09 15:08:12 +0000209
Chris Lattnerb694ba72006-07-02 22:41:36 +0000210 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000211 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000212
213 // Read the ')'.
214 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000215 if (Tok.isNot(tok::r_paren)) {
216 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000217 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000218 }
Mike Stump11289f42009-09-09 15:08:12 +0000219
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000220 if (InMacroArgPreExpansion)
221 return;
222
Chris Lattner9dc9c202009-02-15 20:52:18 +0000223 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000224 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000225
Richard Smithc98bb4e2013-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 Lattner262d4e32009-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 Smithc98bb4e2013-03-09 23:30:15 +0000231 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
232 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000233 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-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 Kramerc2f5f292013-05-04 10:37:20 +0000261 unsigned ResultPos = 1;
Reid Kleckner95e036c2013-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 Smithc98bb4e2013-03-09 23:30:15 +0000268 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000269 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000270 }
Mike Stump11289f42009-09-09 15:08:12 +0000271
Chris Lattnerb694ba72006-07-02 22:41:36 +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 Stump11289f42009-09-09 15:08:12 +0000275
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000276 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000277 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000278
Peter Collingbournef29ce972011-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 Gribenkob8e9e752012-09-24 21:07:17 +0000283 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-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
Craig Topperd2d442c2014-05-17 23:10:59 +0000291 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000292
293 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000294 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-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 Collingbournef29ce972011-02-22 13:49:06 +0000313 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000314 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000315 int NumParens = 0;
316 Lex(Tok);
317 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000318 PragmaToks.push_back(Tok);
John McCall89e925d2010-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 McCall89e925d2010-08-28 22:34:47 +0000323 Lex(Tok);
324 }
325
John McCall49039d42010-08-29 01:09:54 +0000326 if (Tok.is(tok::eof)) {
327 Diag(PragmaLoc, diag::err_unterminated___pragma);
328 return;
329 }
330
Peter Collingbournef29ce972011-02-22 13:49:06 +0000331 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000332
Peter Collingbourne2f1e36b2011-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 Collingbournef29ce972011-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 Zaffanella5afb04a2013-07-20 20:09:11 +0000343 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000344
345 // Finally, return whatever came after the pragma directive.
346 return Lex(Tok);
347}
348
James Dennett18a6d792012-06-17 03:26:26 +0000349/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000350///
Chris Lattner146762e2007-07-20 16:59:19 +0000351void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000352 if (isInPrimaryFile()) {
353 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
354 return;
355 }
Mike Stump11289f42009-09-09 15:08:12 +0000356
Chris Lattnerb694ba72006-07-02 22:41:36 +0000357 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000358 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000359 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000360}
361
Chris Lattnerc2383312007-12-19 19:38:36 +0000362void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000363 assert(CurPPLexer && "No current lexer?");
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000364 if (CurLexer)
365 CurLexer->ReadToEndOfLine();
366 else
367 CurPTHLexer->DiscardToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000368}
369
370
James Dennett18a6d792012-06-17 03:26:26 +0000371/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000372///
Chris Lattner146762e2007-07-20 16:59:19 +0000373void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
374 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000375
Chris Lattnerb694ba72006-07-02 22:41:36 +0000376 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 Kremenek551c82a2008-11-18 01:12:54 +0000382 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000383 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000384 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattnerb694ba72006-07-02 22:41:36 +0000386 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000387 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000388
Chris Lattnerb694ba72006-07-02 22:41:36 +0000389 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000390 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000391 Diag(Tok, diag::err_pp_invalid_poison);
392 return;
393 }
Mike Stump11289f42009-09-09 15:08:12 +0000394
Chris Lattnercefc7682006-07-08 08:28:12 +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 Stump11289f42009-09-09 15:08:12 +0000398
Chris Lattnerb694ba72006-07-02 22:41:36 +0000399 // Already poisoned.
400 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattnerb694ba72006-07-02 22:41:36 +0000402 // If this is a macro identifier, emit a warning.
Chris Lattner259716a2007-10-07 08:04:56 +0000403 if (II->hasMacroDefinition())
Chris Lattnerb694ba72006-07-02 22:41:36 +0000404 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattnerb694ba72006-07-02 22:41:36 +0000406 // Finally, poison it!
407 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000408 if (II->isFromAST())
409 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000410 }
411}
412
James Dennett18a6d792012-06-17 03:26:26 +0000413/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000414/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000415void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000416 if (isInPrimaryFile()) {
417 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
418 return;
419 }
Mike Stump11289f42009-09-09 15:08:12 +0000420
Chris Lattnerb694ba72006-07-02 22:41:36 +0000421 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000422 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnerb694ba72006-07-02 22:41:36 +0000424 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000425 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000426
427
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000428 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000429 if (PLoc.isInvalid())
430 return;
431
Jay Foad9a6b0982011-06-21 15:13:30 +0000432 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000433
Chris Lattner3bdc7672011-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 Lattnerd9efb6e2009-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 Rose111c4a62013-04-17 19:09:18 +0000442 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
443 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
444 /*IsSystem=*/true, /*IsExternC=*/false);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000445}
446
James Dennett18a6d792012-06-17 03:26:26 +0000447/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000448///
Chris Lattner146762e2007-07-20 16:59:19 +0000449void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
450 Token FilenameTok;
Ted Kremenek551c82a2008-11-18 01:12:54 +0000451 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000452
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000453 // If the token kind is EOD, the error has already been diagnosed.
454 if (FilenameTok.is(tok::eod))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000455 return;
Mike Stump11289f42009-09-09 15:08:12 +0000456
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000457 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000458 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000459 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000460 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000461 if (Invalid)
462 return;
Mike Stump11289f42009-09-09 15:08:12 +0000463
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000464 bool isAngled =
465 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000466 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
467 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000468 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000469 return;
Mike Stump11289f42009-09-09 15:08:12 +0000470
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000471 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000472 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000473 const FileEntry *File =
474 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
475 nullptr, CurDir, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000476 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000477 if (!SuppressIncludeNotFoundError)
478 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000479 return;
480 }
Mike Stump11289f42009-09-09 15:08:12 +0000481
Chris Lattnerd32480d2009-01-17 06:22:33 +0000482 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +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 Collingbourne2f1e36b2011-02-28 02:37:51 +0000489 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000490 Message += getSpelling(DependencyTok) + " ";
491 Lex(DependencyTok);
492 }
Mike Stump11289f42009-09-09 15:08:12 +0000493
Chris Lattnerf0b04972010-09-05 23:16:09 +0000494 // Remove the trailing ' ' if present.
495 if (!Message.empty())
496 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000497 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000498 }
499}
500
Reid Kleckner002562a2013-05-06 21:02:12 +0000501/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-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);
Craig Topperd2d442c2014-05-17 23:10:59 +0000512 return nullptr;
Chris Lattnerc0a585d2010-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);
Craig Topperd2d442c2014-05-17 23:10:59 +0000520 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000521 }
522
Richard Smithd67aea22012-03-06 03:21:47 +0000523 if (Tok.hasUDSuffix()) {
524 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000525 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000526 }
527
Chris Lattnerc0a585d2010-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);
Craig Topperd2d442c2014-05-17 23:10:59 +0000536 return nullptr;
Chris Lattnerc0a585d2010-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 Bagnaraea4f7c72010-12-22 08:23:18 +0000545 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000546 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000547
548 // Get the IdentifierInfo of MacroToPushTok.
549 return LookUpIdentifierInfo(MacroTok);
550}
551
James Dennett18a6d792012-06-17 03:26:26 +0000552/// \brief Handle \#pragma push_macro.
553///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000554/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000555/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000556/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000557/// \endcode
Chris Lattnerc0a585d2010-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 Lattnerc0a585d2010-08-17 15:55:45 +0000566 if (MI) {
Chris Lattnerc0a585d2010-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 Kyrtzidis09c9e812013-02-20 00:54:57 +0000572 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000573}
574
James Dennett18a6d792012-06-17 03:26:26 +0000575/// \brief Handle \#pragma pop_macro.
576///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000577/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000578/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000579/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000580/// \endcode
Chris Lattnerc0a585d2010-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 Kornienko8b3f6232012-08-29 00:20:03 +0000592 // Forget the MacroInfo currently associated with IdentInfo.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000593 if (MacroDirective *CurrentMD = getMacroDirective(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-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 Kyrtzidis1cb0de12010-12-15 18:44:22 +0000598 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000599
600 // Get the MacroInfo we want to reinstall.
601 MacroInfo *MacroToReInstall = iter->second.back();
602
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000603 if (MacroToReInstall) {
604 // Reinstall the previously pushed macro.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000605 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc,
Richard Smithdaa69e02014-07-25 04:40:03 +0000606 /*isImported=*/false, /*Overrides*/None);
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000607 }
Chris Lattnerc0a585d2010-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}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000618
Aaron Ballman611306e2012-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 Ballman611306e2012-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
Yaron Keren92e1b622015-03-18 10:17:07 +0000651 SourceFileName = FileNameBuffer;
Aaron Ballman611306e2012-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
Yaron Keren92e1b622015-03-18 10:17:07 +0000682 ReplaceFileName = FileNameBuffer;
Aaron Ballman611306e2012-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
Chris Lattnerb694ba72006-07-02 22:41:36 +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 Lattner0e62c1c2011-07-23 10:55:15 +0000727void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000728 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000729 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattnerb694ba72006-07-02 22:41:36 +0000731 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000732 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +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 Kyrtzidis36745fd2010-07-13 09:07:17 +0000736 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000737 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000738 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +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 Kyrtzidis36745fd2010-07-13 09:07:17 +0000743 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000744 PragmaHandlers->AddPragma(InsertNS);
745 }
746 }
Mike Stump11289f42009-09-09 15:08:12 +0000747
Chris Lattnerb694ba72006-07-02 22:41:36 +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 Dunbar40596532008-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 Lattner0e62c1c2011-07-23 10:55:15 +0000758void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000759 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000760 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000761
Daniel Dunbar40596532008-10-04 19:17:46 +0000762 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000763 if (!Namespace.empty()) {
764 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-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 Stump11289f42009-09-09 15:08:12 +0000772
Craig Topperbe250302014-09-12 05:19:24 +0000773 // If this is a non-default namespace and it is now empty, remove it.
774 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000775 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000776 delete NS;
777 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000778}
779
Peter Collingbourne3bffa522011-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 Collingbourne2f1e36b2011-02-28 02:37:51 +0000800 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000801 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000802 if (Tok.isNot(tok::eod))
803 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000804 return false;
805}
806
Chris Lattnerb694ba72006-07-02 22:41:36 +0000807namespace {
James Dennett18a6d792012-06-17 03:26:26 +0000808/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000809struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000810 PragmaOnceHandler() : PragmaHandler("once") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000811 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
812 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000813 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000814 PP.HandlePragmaOnce(OnceTok);
815 }
816};
817
James Dennett18a6d792012-06-17 03:26:26 +0000818/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000819/// rest of the line is not lexed.
820struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000821 PragmaMarkHandler() : PragmaHandler("mark") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000822 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
823 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +0000824 PP.HandlePragmaMark();
825 }
826};
827
James Dennett18a6d792012-06-17 03:26:26 +0000828/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000829struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000830 PragmaPoisonHandler() : PragmaHandler("poison") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000831 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
832 Token &PoisonTok) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000833 PP.HandlePragmaPoison(PoisonTok);
834 }
835};
836
James Dennett18a6d792012-06-17 03:26:26 +0000837/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +0000838/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000839struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000840 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000841 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
842 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000843 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000844 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000845 }
846};
847struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000848 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000849 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
850 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000851 PP.HandlePragmaDependency(DepToken);
852 }
853};
Mike Stump11289f42009-09-09 15:08:12 +0000854
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000855struct PragmaDebugHandler : public PragmaHandler {
856 PragmaDebugHandler() : PragmaHandler("__debug") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000857 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
858 Token &DepToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000859 Token Tok;
860 PP.LexUnexpandedToken(Tok);
861 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +0000862 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000863 return;
864 }
865 IdentifierInfo *II = Tok.getIdentifierInfo();
866
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000867 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +0000868 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000869 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +0000870 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +0000871 } else if (II->isStr("parser_crash")) {
872 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +0000873 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +0000874 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +0000875 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikie5d577a22012-06-29 22:03:56 +0000876 PP.EnterToken(Crasher);
Daniel Dunbarf2cf3292010-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 Dunbar211a7872010-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. Siraj0de0dd42013-04-16 18:41:26 +0000887 } else if (II->isStr("captured")) {
888 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000889 } else {
890 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
891 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000892 }
Tareq A. Siraj0de0dd42013-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 Dunbarb8068c32010-07-28 15:40:33 +0000921 }
922
Francois Pichet2e11f5d2011-05-25 16:15:03 +0000923// Disable MSVC warning about runtime stack overflow.
924#ifdef _MSC_VER
925 #pragma warning(disable : 4717)
926#endif
Richard Trieu0732beb2013-12-21 01:04:02 +0000927 static void DebugOverflowStack() {
928 void (*volatile Self)() = DebugOverflowStack;
929 Self();
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000930 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +0000931#ifdef _MSC_VER
932 #pragma warning(default : 4717)
933#endif
934
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000935};
936
James Dennett18a6d792012-06-17 03:26:26 +0000937/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +0000938struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000939private:
940 const char *Namespace;
Chris Lattnerfb42a182009-07-12 21:18:45 +0000941public:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000942 explicit PragmaDiagnosticHandler(const char *NS) :
943 PragmaHandler("diagnostic"), Namespace(NS) {}
Craig Topper9140dd22014-03-11 06:50:42 +0000944 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
945 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000946 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +0000947 Token Tok;
948 PP.LexUnexpandedToken(Tok);
949 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +0000950 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +0000951 return;
952 }
953 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000954 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +0000955
Alp Toker46df1c02014-06-12 10:15:20 +0000956 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000957 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +0000958 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000959 else if (Callbacks)
960 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +0000961 return;
962 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000963 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000964 if (Callbacks)
965 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +0000966 return;
Alp Toker46df1c02014-06-12 10:15:20 +0000967 }
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 Gregor3cc26482010-08-30 15:15:34 +0000977 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +0000978 return;
979 }
Mike Stump11289f42009-09-09 15:08:12 +0000980
Chris Lattner504af112009-04-19 23:16:58 +0000981 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +0000982 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +0000983
Andy Gibbs58905d22012-11-17 19:15:38 +0000984 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000985 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
986 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +0000987 return;
Mike Stump11289f42009-09-09 15:08:12 +0000988
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000989 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +0000990 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
991 return;
992 }
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chris Lattner504af112009-04-19 23:16:58 +0000994 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +0000995 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +0000996 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +0000997 return;
998 }
Mike Stump11289f42009-09-09 15:08:12 +0000999
Richard Smith3be1cb22014-08-07 00:24:21 +00001000 if (PP.getDiagnostics().setSeverityForGroup(
1001 WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1002 : diag::Flavor::Remark,
1003 WarningName.substr(2), SV, DiagLoc))
Andy Gibbs58905d22012-11-17 19:15:38 +00001004 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1005 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001006 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001007 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001008 }
1009};
Mike Stump11289f42009-09-09 15:08:12 +00001010
Reid Kleckner881dff32013-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
Craig Topper9140dd22014-03-11 06:50:42 +00001017 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1018 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001019 // Parse things like:
1020 // warning(push, 1)
1021 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001022 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-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 Kleckner4d185102013-10-02 15:19:23 +00001041 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001042 PP.Lex(Tok);
1043 if (Tok.is(tok::comma)) {
1044 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001045 uint64_t Value;
1046 if (Tok.is(tok::numeric_constant) &&
1047 PP.parseSimpleIntegerLiteral(Tok, Value))
1048 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001049 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-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)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001092 uint64_t Value;
1093 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1094 Value > INT_MAX) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001095 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1096 return;
1097 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001098 Ids.push_back(int(Value));
Reid Kleckner881dff32013-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 Dennett18a6d792012-06-17 03:26:26 +00001121/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001122struct PragmaIncludeAliasHandler : public PragmaHandler {
1123 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001124 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1125 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001126 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001127 }
1128};
1129
Andy Gibbs9c2ccd62013-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 Lattner30c924b2010-06-26 17:11:39 +00001143struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-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
Craig Topper9140dd22014-03-11 06:50:42 +00001166 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1167 Token &Tok) override {
Andy Gibbs9c2ccd62013-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 Lattner30c924b2010-06-26 17:11:39 +00001212 }
1213};
1214
James Dennett18a6d792012-06-17 03:26:26 +00001215/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001216/// macro on the top of the stack.
1217struct PragmaPushMacroHandler : public PragmaHandler {
1218 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001219 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1220 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001221 PP.HandlePragmaPushMacro(PushMacroTok);
1222 }
1223};
1224
1225
James Dennett18a6d792012-06-17 03:26:26 +00001226/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-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") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001230 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1231 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001232 PP.HandlePragmaPopMacro(PopMacroTok);
1233 }
1234};
1235
Chris Lattner958ee042009-04-19 21:20:35 +00001236// Pragma STDC implementations.
Chris Lattner02ef4e32009-04-19 21:50:08 +00001237
James Dennett18a6d792012-06-17 03:26:26 +00001238/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001239struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001240 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001241 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1242 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001243 tok::OnOffSwitch OOS;
1244 if (PP.LexOnOffSwitch(OOS))
1245 return;
1246 if (OOS == tok::OOS_ON)
Chris Lattnerdf222682009-04-19 21:55:32 +00001247 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
Chris Lattner958ee042009-04-19 21:20:35 +00001248 }
1249};
Mike Stump11289f42009-09-09 15:08:12 +00001250
James Dennett18a6d792012-06-17 03:26:26 +00001251/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001252struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001253 PragmaSTDC_CX_LIMITED_RANGEHandler()
1254 : PragmaHandler("CX_LIMITED_RANGE") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001255 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1256 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001257 tok::OnOffSwitch OOS;
1258 PP.LexOnOffSwitch(OOS);
Chris Lattner958ee042009-04-19 21:20:35 +00001259 }
1260};
Mike Stump11289f42009-09-09 15:08:12 +00001261
James Dennett18a6d792012-06-17 03:26:26 +00001262/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001263struct PragmaSTDC_UnknownHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001264 PragmaSTDC_UnknownHandler() {}
Craig Topper9140dd22014-03-11 06:50:42 +00001265 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1266 Token &UnknownTok) override {
Chris Lattner02ef4e32009-04-19 21:50:08 +00001267 // C99 6.10.6p2, unknown forms are not allowed.
Chris Lattnera0b1f762009-04-19 21:25:37 +00001268 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
Chris Lattner958ee042009-04-19 21:20:35 +00001269 }
1270};
Mike Stump11289f42009-09-09 15:08:12 +00001271
John McCall32f5fe12011-09-30 05:12:12 +00001272/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001273/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001274struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1275 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001276 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1277 Token &NameTok) override {
John McCall32f5fe12011-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 Majnemer7aa8c2f2013-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 Ballman406ea512012-11-30 19:52:30 +00001339
Craig Topper9140dd22014-03-11 06:50:42 +00001340 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1341 Token &NameTok) override {
David Majnemer7aa8c2f2013-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 Ballman406ea512012-11-30 19:52:30 +00001348
Chris Lattnerb694ba72006-07-02 22:41:36 +00001349} // end anonymous namespace
1350
1351
1352/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001353/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001354void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001355 AddPragmaHandler(new PragmaOnceHandler());
1356 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001357 AddPragmaHandler(new PragmaPushMacroHandler());
1358 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001359 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattnerb61448d2009-05-12 18:21:11 +00001361 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001362 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1363 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1364 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001365 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-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 Lattnerb61448d2009-05-12 18:21:11 +00001370 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001371 AddPragmaHandler("clang", new PragmaPoisonHandler());
1372 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001373 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001374 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001375 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001376 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001377
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001378 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1379 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
Chris Lattner958ee042009-04-19 21:20:35 +00001380 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
Mike Stump11289f42009-09-09 15:08:12 +00001381
Chris Lattner2ff698d2009-01-16 08:21:25 +00001382 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001383 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001384 AddPragmaHandler(new PragmaWarningHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001385 AddPragmaHandler(new PragmaIncludeAliasHandler());
Aaron Ballman406ea512012-11-30 19:52:30 +00001386 AddPragmaHandler(new PragmaRegionHandler("region"));
1387 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Chris Lattner30c924b2010-06-26 17:11:39 +00001388 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001389}
Lubos Lunak576a0412014-05-01 12:54:03 +00001390
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);
Chandler Carruth4d9c3df2014-05-02 21:44:48 +00001408 delete Existing;
Lubos Lunak576a0412014-05-01 12:54:03 +00001409 }
1410 }
1411 AddPragmaHandler("STDC", new EmptyPragmaHandler());
1412}