blob: 3134790ccb90c0321317277bb88e4f48f0b794ec [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"
Alexander Musman6b080fc2015-05-25 11:21:20 +000025#include "llvm/ADT/StringExtras.h"
Daniel Dunbar211a7872010-08-18 23:09:23 +000026#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbarf2cf3292010-08-17 22:32:48 +000027#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000028#include <algorithm>
Chris Lattnerb8761832006-06-24 21:31:03 +000029using namespace clang;
30
Reid Kleckner881dff32013-09-13 22:00:30 +000031#include "llvm/Support/raw_ostream.h"
32
Chris Lattnerb8761832006-06-24 21:31:03 +000033// Out-of-line destructor to provide a home for the class.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000034PragmaHandler::~PragmaHandler() {
35}
Chris Lattnerb8761832006-06-24 21:31:03 +000036
Chris Lattner2e155302006-07-03 05:34:41 +000037//===----------------------------------------------------------------------===//
Daniel Dunbard839e772010-06-11 20:10:12 +000038// EmptyPragmaHandler Implementation.
39//===----------------------------------------------------------------------===//
40
Hans Wennborg7357bbc2015-10-12 20:47:58 +000041EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000042
Douglas Gregorc7d65762010-09-09 22:45:38 +000043void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
44 PragmaIntroducerKind Introducer,
45 Token &FirstToken) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000046
47//===----------------------------------------------------------------------===//
Chris Lattner2e155302006-07-03 05:34:41 +000048// PragmaNamespace Implementation.
49//===----------------------------------------------------------------------===//
50
Chris Lattner2e155302006-07-03 05:34:41 +000051PragmaNamespace::~PragmaNamespace() {
Reid Kleckner588c9372014-02-19 23:44:52 +000052 llvm::DeleteContainerSeconds(Handlers);
Chris Lattner2e155302006-07-03 05:34:41 +000053}
54
55/// FindHandler - Check to see if there is already a handler for the
56/// specified name. If not, return the handler for the null identifier if it
57/// exists, otherwise return null. If IgnoreNull is true (the default) then
58/// the null handler isn't returned on failure to match.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000059PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Chris Lattner2e155302006-07-03 05:34:41 +000060 bool IgnoreNull) const {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000061 if (PragmaHandler *Handler = Handlers.lookup(Name))
62 return Handler;
Craig Topperd2d442c2014-05-17 23:10:59 +000063 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000064}
Mike Stump11289f42009-09-09 15:08:12 +000065
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000066void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
67 assert(!Handlers.lookup(Handler->getName()) &&
68 "A handler with this name is already registered in this namespace");
David Blaikie13156b62014-11-19 03:06:06 +000069 Handlers[Handler->getName()] = Handler;
Chris Lattner2e155302006-07-03 05:34:41 +000070}
71
Daniel Dunbar40596532008-10-04 19:17:46 +000072void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000073 assert(Handlers.lookup(Handler->getName()) &&
74 "Handler not registered in this namespace");
75 Handlers.erase(Handler->getName());
Daniel Dunbar40596532008-10-04 19:17:46 +000076}
77
Douglas Gregorc7d65762010-09-09 22:45:38 +000078void PragmaNamespace::HandlePragma(Preprocessor &PP,
79 PragmaIntroducerKind Introducer,
80 Token &Tok) {
Chris Lattnerb8761832006-06-24 21:31:03 +000081 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
82 // expand it, the user can have a STDC #define, that should not affect this.
83 PP.LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +000084
Chris Lattnerb8761832006-06-24 21:31:03 +000085 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000086 PragmaHandler *Handler
87 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner0e62c1c2011-07-23 10:55:15 +000088 : StringRef(),
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000089 /*IgnoreNull=*/false);
Craig Topperd2d442c2014-05-17 23:10:59 +000090 if (!Handler) {
Chris Lattner21656f22009-04-19 21:10:26 +000091 PP.Diag(Tok, diag::warn_pragma_ignored);
92 return;
93 }
Mike Stump11289f42009-09-09 15:08:12 +000094
Chris Lattnerb8761832006-06-24 21:31:03 +000095 // Otherwise, pass it down.
Douglas Gregorc7d65762010-09-09 22:45:38 +000096 Handler->HandlePragma(PP, Introducer, Tok);
Chris Lattnerb8761832006-06-24 21:31:03 +000097}
Chris Lattnerb694ba72006-07-02 22:41:36 +000098
Chris Lattnerb694ba72006-07-02 22:41:36 +000099//===----------------------------------------------------------------------===//
100// Preprocessor Pragma Directive Handling.
101//===----------------------------------------------------------------------===//
102
James Dennett18a6d792012-06-17 03:26:26 +0000103/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Chris Lattnerb694ba72006-07-02 22:41:36 +0000104/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000105void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
106 PragmaIntroducerKind Introducer) {
107 if (Callbacks)
108 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
109
Jordan Rosede1a2922012-06-08 18:06:21 +0000110 if (!PragmasEnabled)
111 return;
112
Chris Lattnerb694ba72006-07-02 22:41:36 +0000113 ++NumPragma;
Mike Stump11289f42009-09-09 15:08:12 +0000114
Chris Lattnerb694ba72006-07-02 22:41:36 +0000115 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattner146762e2007-07-20 16:59:19 +0000116 Token Tok;
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000117 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000118
Chris Lattnerb694ba72006-07-02 22:41:36 +0000119 // If the pragma handler didn't read the rest of the line, consume it now.
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000120 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
121 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000122 DiscardUntilEndOfDirective();
123}
124
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000125namespace {
126/// \brief Helper class for \see Preprocessor::Handle_Pragma.
127class LexingFor_PragmaRAII {
128 Preprocessor &PP;
129 bool InMacroArgPreExpansion;
130 bool Failed;
131 Token &OutTok;
132 Token PragmaTok;
133
134public:
135 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
136 Token &Tok)
137 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
138 Failed(false), OutTok(Tok) {
139 if (InMacroArgPreExpansion) {
140 PragmaTok = OutTok;
141 PP.EnableBacktrackAtThisPos();
142 }
143 }
144
145 ~LexingFor_PragmaRAII() {
146 if (InMacroArgPreExpansion) {
147 if (Failed) {
148 PP.CommitBacktrackedTokens();
149 } else {
150 PP.Backtrack();
151 OutTok = PragmaTok;
152 }
153 }
154 }
155
156 void failed() {
157 Failed = true;
158 }
159};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000160}
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000161
Chris Lattnerb694ba72006-07-02 22:41:36 +0000162/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
163/// return the first token after the directive. The _Pragma token has just
164/// been read into 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000165void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000166
167 // This works differently if we are pre-expanding a macro argument.
168 // In that case we don't actually "activate" the pragma now, we only lex it
169 // until we are sure it is lexically correct and then we backtrack so that
170 // we activate the pragma whenever we encounter the tokens again in the token
171 // stream. This ensures that we will activate it in the correct location
172 // or that we will ignore it if it never enters the token stream, e.g:
173 //
174 // #define EMPTY(x)
175 // #define INACTIVE(x) EMPTY(x)
176 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
177
178 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
179
Chris Lattnerb694ba72006-07-02 22:41:36 +0000180 // Remember the pragma token location.
181 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000182
Chris Lattnerb694ba72006-07-02 22:41:36 +0000183 // Read the '('.
184 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000185 if (Tok.isNot(tok::l_paren)) {
186 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000187 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000188 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000189
190 // Read the '"..."'.
191 Lex(Tok);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000192 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000193 Diag(PragmaLoc, diag::err__Pragma_malformed);
Hubert Tong0deb6942015-07-30 21:30:00 +0000194 // Skip bad tokens, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000195 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000196 Lex(Tok);
Hubert Tong0deb6942015-07-30 21:30:00 +0000197 while (Tok.isNot(tok::r_paren) &&
198 !Tok.isAtStartOfLine() &&
199 Tok.isNot(tok::eof))
200 Lex(Tok);
Richard Smithd67aea22012-03-06 03:21:47 +0000201 if (Tok.is(tok::r_paren))
202 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000203 return _PragmaLexing.failed();
Richard Smithd67aea22012-03-06 03:21:47 +0000204 }
205
206 if (Tok.hasUDSuffix()) {
207 Diag(Tok, diag::err_invalid_string_udl);
208 // Skip this token, and the ')', if present.
209 Lex(Tok);
210 if (Tok.is(tok::r_paren))
211 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000212 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000213 }
Mike Stump11289f42009-09-09 15:08:12 +0000214
Chris Lattnerb694ba72006-07-02 22:41:36 +0000215 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000216 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000217
218 // Read the ')'.
219 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000220 if (Tok.isNot(tok::r_paren)) {
221 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000222 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000223 }
Mike Stump11289f42009-09-09 15:08:12 +0000224
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000225 if (InMacroArgPreExpansion)
226 return;
227
Chris Lattner9dc9c202009-02-15 20:52:18 +0000228 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000229 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000230
Richard Smithc98bb4e2013-03-09 23:30:15 +0000231 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
232 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattner262d4e32009-01-16 18:59:23 +0000233 // deleting the leading and trailing double-quotes, replacing each escape
234 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
235 // single backslash."
Richard Smithc98bb4e2013-03-09 23:30:15 +0000236 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
237 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000238 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-03-09 23:30:15 +0000239 else if (StrVal[0] == 'u')
240 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
241
242 if (StrVal[0] == 'R') {
243 // FIXME: C++11 does not specify how to handle raw-string-literals here.
244 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
245 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
246 "Invalid raw string token!");
247
248 // Measure the length of the d-char-sequence.
249 unsigned NumDChars = 0;
250 while (StrVal[2 + NumDChars] != '(') {
251 assert(NumDChars < (StrVal.size() - 5) / 2 &&
252 "Invalid raw string token!");
253 ++NumDChars;
254 }
255 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
256
257 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
258 // parens below.
259 StrVal.erase(0, 2 + NumDChars);
260 StrVal.erase(StrVal.size() - 1 - NumDChars);
261 } else {
262 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
263 "Invalid string token!");
264
265 // Remove escaped quotes and escapes.
Benjamin Kramerc2f5f292013-05-04 10:37:20 +0000266 unsigned ResultPos = 1;
Reid Kleckner95e036c2013-09-25 16:42:48 +0000267 for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) {
268 // Skip escapes. \\ -> '\' and \" -> '"'.
269 if (StrVal[i] == '\\' && i + 1 < e &&
270 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
271 ++i;
272 StrVal[ResultPos++] = StrVal[i];
Richard Smithc98bb4e2013-03-09 23:30:15 +0000273 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000274 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000275 }
Mike Stump11289f42009-09-09 15:08:12 +0000276
Chris Lattnerb694ba72006-07-02 22:41:36 +0000277 // Remove the front quote, replacing it with a space, so that the pragma
278 // contents appear to have a space before them.
279 StrVal[0] = ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000281 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000282 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000283
Peter Collingbournef29ce972011-02-22 13:49:06 +0000284 // Plop the string (including the newline and trailing null) into a buffer
285 // where we can lex it.
286 Token TmpTok;
287 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000288 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000289 SourceLocation TokLoc = TmpTok.getLocation();
290
291 // Make and enter a lexer object so that we lex and expand the tokens just
292 // like any others.
293 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
294 StrVal.size(), *this);
295
Craig Topperd2d442c2014-05-17 23:10:59 +0000296 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000297
298 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000299 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-08-28 22:34:47 +0000300
301 // Finally, return whatever came after the pragma directive.
302 return Lex(Tok);
303}
304
305/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
306/// is not enclosed within a string literal.
307void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
308 // Remember the pragma token location.
309 SourceLocation PragmaLoc = Tok.getLocation();
310
311 // Read the '('.
312 Lex(Tok);
313 if (Tok.isNot(tok::l_paren)) {
314 Diag(PragmaLoc, diag::err__Pragma_malformed);
315 return;
316 }
317
Peter Collingbournef29ce972011-02-22 13:49:06 +0000318 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000319 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000320 int NumParens = 0;
321 Lex(Tok);
322 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000323 PragmaToks.push_back(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000324 if (Tok.is(tok::l_paren))
325 NumParens++;
326 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
327 break;
John McCall89e925d2010-08-28 22:34:47 +0000328 Lex(Tok);
329 }
330
John McCall49039d42010-08-29 01:09:54 +0000331 if (Tok.is(tok::eof)) {
332 Diag(PragmaLoc, diag::err_unterminated___pragma);
333 return;
334 }
335
Peter Collingbournef29ce972011-02-22 13:49:06 +0000336 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000337
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000338 // Replace the ')' with an EOD to mark the end of the pragma.
339 PragmaToks.back().setKind(tok::eod);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000340
341 Token *TokArray = new Token[PragmaToks.size()];
342 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
343
344 // Push the tokens onto the stack.
345 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
346
347 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000348 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000349
350 // Finally, return whatever came after the pragma directive.
351 return Lex(Tok);
352}
353
James Dennett18a6d792012-06-17 03:26:26 +0000354/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000355///
Chris Lattner146762e2007-07-20 16:59:19 +0000356void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000357 if (isInPrimaryFile()) {
358 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
359 return;
360 }
Mike Stump11289f42009-09-09 15:08:12 +0000361
Chris Lattnerb694ba72006-07-02 22:41:36 +0000362 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000363 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000364 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000365}
366
Chris Lattnerc2383312007-12-19 19:38:36 +0000367void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000368 assert(CurPPLexer && "No current lexer?");
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000369 if (CurLexer)
370 CurLexer->ReadToEndOfLine();
371 else
372 CurPTHLexer->DiscardToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000373}
374
375
James Dennett18a6d792012-06-17 03:26:26 +0000376/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000377///
Chris Lattner146762e2007-07-20 16:59:19 +0000378void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
379 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000380
Chris Lattnerb694ba72006-07-02 22:41:36 +0000381 while (1) {
382 // Read the next token to poison. While doing this, pretend that we are
383 // skipping while reading the identifier to poison.
384 // This avoids errors on code like:
385 // #pragma GCC poison X
386 // #pragma GCC poison X
Ted Kremenek551c82a2008-11-18 01:12:54 +0000387 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000388 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000389 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000390
Chris Lattnerb694ba72006-07-02 22:41:36 +0000391 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000392 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000393
Chris Lattnerb694ba72006-07-02 22:41:36 +0000394 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000395 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000396 Diag(Tok, diag::err_pp_invalid_poison);
397 return;
398 }
Mike Stump11289f42009-09-09 15:08:12 +0000399
Chris Lattnercefc7682006-07-08 08:28:12 +0000400 // Look up the identifier info for the token. We disabled identifier lookup
401 // by saying we're skipping contents, so we need to do this manually.
402 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattnerb694ba72006-07-02 22:41:36 +0000404 // Already poisoned.
405 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000406
Chris Lattnerb694ba72006-07-02 22:41:36 +0000407 // If this is a macro identifier, emit a warning.
Richard Smith20e883e2015-04-29 23:20:19 +0000408 if (isMacroDefined(II))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000409 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattnerb694ba72006-07-02 22:41:36 +0000411 // Finally, poison it!
412 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000413 if (II->isFromAST())
414 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000415 }
416}
417
James Dennett18a6d792012-06-17 03:26:26 +0000418/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000419/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000420void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000421 if (isInPrimaryFile()) {
422 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
423 return;
424 }
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattnerb694ba72006-07-02 22:41:36 +0000426 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000427 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattnerb694ba72006-07-02 22:41:36 +0000429 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000430 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000431
432
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000433 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000434 if (PLoc.isInvalid())
435 return;
436
Jay Foad9a6b0982011-06-21 15:13:30 +0000437 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000438
Chris Lattner3bdc7672011-05-22 22:10:16 +0000439 // Notify the client, if desired, that we are in a new source file.
440 if (Callbacks)
441 Callbacks->FileChanged(SysHeaderTok.getLocation(),
442 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
443
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000444 // Emit a line marker. This will change any source locations from this point
445 // forward to realize they are in a system header.
446 // Create a line note with this information.
Jordan Rose111c4a62013-04-17 19:09:18 +0000447 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
448 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
449 /*IsSystem=*/true, /*IsExternC=*/false);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000450}
451
James Dennett18a6d792012-06-17 03:26:26 +0000452/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000453///
Chris Lattner146762e2007-07-20 16:59:19 +0000454void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
455 Token FilenameTok;
Ted Kremenek551c82a2008-11-18 01:12:54 +0000456 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000457
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000458 // If the token kind is EOD, the error has already been diagnosed.
459 if (FilenameTok.is(tok::eod))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000460 return;
Mike Stump11289f42009-09-09 15:08:12 +0000461
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000462 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000463 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000464 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000465 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000466 if (Invalid)
467 return;
Mike Stump11289f42009-09-09 15:08:12 +0000468
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000469 bool isAngled =
470 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000471 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
472 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000473 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000474 return;
Mike Stump11289f42009-09-09 15:08:12 +0000475
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000476 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000477 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000478 const FileEntry *File =
479 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
480 nullptr, CurDir, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000481 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000482 if (!SuppressIncludeNotFoundError)
483 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000484 return;
485 }
Mike Stump11289f42009-09-09 15:08:12 +0000486
Chris Lattnerd32480d2009-01-17 06:22:33 +0000487 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000488
489 // If this file is older than the file it depends on, emit a diagnostic.
490 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
491 // Lex tokens at the end of the message and include them in the message.
492 std::string Message;
493 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000494 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000495 Message += getSpelling(DependencyTok) + " ";
496 Lex(DependencyTok);
497 }
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattnerf0b04972010-09-05 23:16:09 +0000499 // Remove the trailing ' ' if present.
500 if (!Message.empty())
501 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000502 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000503 }
504}
505
Reid Kleckner002562a2013-05-06 21:02:12 +0000506/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000507/// Return the IdentifierInfo* associated with the macro to push or pop.
508IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
509 // Remember the pragma token location.
510 Token PragmaTok = Tok;
511
512 // Read the '('.
513 Lex(Tok);
514 if (Tok.isNot(tok::l_paren)) {
515 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
516 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000517 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000518 }
519
520 // Read the macro name string.
521 Lex(Tok);
522 if (Tok.isNot(tok::string_literal)) {
523 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
524 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000525 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000526 }
527
Richard Smithd67aea22012-03-06 03:21:47 +0000528 if (Tok.hasUDSuffix()) {
529 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000530 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000531 }
532
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000533 // Remember the macro string.
534 std::string StrVal = getSpelling(Tok);
535
536 // Read the ')'.
537 Lex(Tok);
538 if (Tok.isNot(tok::r_paren)) {
539 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
540 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000541 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000542 }
543
544 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
545 "Invalid string token!");
546
547 // Create a Token from the string.
548 Token MacroTok;
549 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000550 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000551 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000552
553 // Get the IdentifierInfo of MacroToPushTok.
554 return LookUpIdentifierInfo(MacroTok);
555}
556
James Dennett18a6d792012-06-17 03:26:26 +0000557/// \brief Handle \#pragma push_macro.
558///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000559/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000560/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000561/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000562/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000563void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
564 // Parse the pragma directive and get the macro IdentifierInfo*.
565 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
566 if (!IdentInfo) return;
567
568 // Get the MacroInfo associated with IdentInfo.
569 MacroInfo *MI = getMacroInfo(IdentInfo);
570
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000571 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000572 // Allow the original MacroInfo to be redefined later.
573 MI->setIsAllowRedefinitionsWithoutWarning(true);
574 }
575
576 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000577 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000578}
579
James Dennett18a6d792012-06-17 03:26:26 +0000580/// \brief Handle \#pragma pop_macro.
581///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000582/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000583/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000584/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000585/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000586void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
587 SourceLocation MessageLoc = PopMacroTok.getLocation();
588
589 // Parse the pragma directive and get the macro IdentifierInfo*.
590 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
591 if (!IdentInfo) return;
592
593 // Find the vector<MacroInfo*> associated with the macro.
594 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
595 PragmaPushMacroInfo.find(IdentInfo);
596 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000597 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith20e883e2015-04-29 23:20:19 +0000598 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000599 if (MI->isWarnIfUnused())
600 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
601 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000602 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000603
604 // Get the MacroInfo we want to reinstall.
605 MacroInfo *MacroToReInstall = iter->second.back();
606
Richard Smith713369b2015-04-23 20:40:50 +0000607 if (MacroToReInstall)
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000608 // Reinstall the previously pushed macro.
Richard Smith713369b2015-04-23 20:40:50 +0000609 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000610
611 // Pop PragmaPushMacroInfo stack.
612 iter->second.pop_back();
613 if (iter->second.size() == 0)
614 PragmaPushMacroInfo.erase(iter);
615 } else {
616 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
617 << IdentInfo->getName();
618 }
619}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000620
Aaron Ballman611306e2012-03-02 22:51:54 +0000621void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
622 // We will either get a quoted filename or a bracketed filename, and we
623 // have to track which we got. The first filename is the source name,
624 // and the second name is the mapped filename. If the first is quoted,
625 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman611306e2012-03-02 22:51:54 +0000626
627 // Get the open paren
628 Lex(Tok);
629 if (Tok.isNot(tok::l_paren)) {
630 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
631 return;
632 }
633
634 // We expect either a quoted string literal, or a bracketed name
635 Token SourceFilenameTok;
636 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
637 if (SourceFilenameTok.is(tok::eod)) {
638 // The diagnostic has already been handled
639 return;
640 }
641
642 StringRef SourceFileName;
643 SmallString<128> FileNameBuffer;
644 if (SourceFilenameTok.is(tok::string_literal) ||
645 SourceFilenameTok.is(tok::angle_string_literal)) {
646 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
647 } else if (SourceFilenameTok.is(tok::less)) {
648 // This could be a path instead of just a name
649 FileNameBuffer.push_back('<');
650 SourceLocation End;
651 if (ConcatenateIncludeName(FileNameBuffer, End))
652 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000653 SourceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000654 } else {
655 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
656 return;
657 }
658 FileNameBuffer.clear();
659
660 // Now we expect a comma, followed by another include name
661 Lex(Tok);
662 if (Tok.isNot(tok::comma)) {
663 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
664 return;
665 }
666
667 Token ReplaceFilenameTok;
668 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
669 if (ReplaceFilenameTok.is(tok::eod)) {
670 // The diagnostic has already been handled
671 return;
672 }
673
674 StringRef ReplaceFileName;
675 if (ReplaceFilenameTok.is(tok::string_literal) ||
676 ReplaceFilenameTok.is(tok::angle_string_literal)) {
677 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
678 } else if (ReplaceFilenameTok.is(tok::less)) {
679 // This could be a path instead of just a name
680 FileNameBuffer.push_back('<');
681 SourceLocation End;
682 if (ConcatenateIncludeName(FileNameBuffer, End))
683 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000684 ReplaceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000685 } else {
686 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
687 return;
688 }
689
690 // Finally, we expect the closing paren
691 Lex(Tok);
692 if (Tok.isNot(tok::r_paren)) {
693 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
694 return;
695 }
696
697 // Now that we have the source and target filenames, we need to make sure
698 // they're both of the same type (angled vs non-angled)
699 StringRef OriginalSource = SourceFileName;
700
701 bool SourceIsAngled =
702 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
703 SourceFileName);
704 bool ReplaceIsAngled =
705 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
706 ReplaceFileName);
707 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
708 (SourceIsAngled != ReplaceIsAngled)) {
709 unsigned int DiagID;
710 if (SourceIsAngled)
711 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
712 else
713 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
714
715 Diag(SourceFilenameTok.getLocation(), DiagID)
716 << SourceFileName
717 << ReplaceFileName;
718
719 return;
720 }
721
722 // Now we can let the include handler know about this mapping
723 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
724}
725
Chris Lattnerb694ba72006-07-02 22:41:36 +0000726/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
727/// If 'Namespace' is non-null, then it is a token required to exist on the
728/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000729void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000730 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000731 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattnerb694ba72006-07-02 22:41:36 +0000733 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000734 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000735 // If there is already a pragma handler with the name of this namespace,
736 // we either have an error (directive with the same name as a namespace) or
737 // we already have the namespace to insert into.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000738 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000739 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000740 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +0000741 " handler with the same name!");
742 } else {
743 // Otherwise, this namespace doesn't exist yet, create and insert the
744 // handler for it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000745 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000746 PragmaHandlers->AddPragma(InsertNS);
747 }
748 }
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattnerb694ba72006-07-02 22:41:36 +0000750 // Check to make sure we don't already have a pragma for this identifier.
751 assert(!InsertNS->FindHandler(Handler->getName()) &&
752 "Pragma handler already exists for this identifier!");
753 InsertNS->AddPragma(Handler);
754}
755
Daniel Dunbar40596532008-10-04 19:17:46 +0000756/// RemovePragmaHandler - Remove the specific pragma handler from the
757/// preprocessor. If \arg Namespace is non-null, then it should be the
758/// namespace that \arg Handler was added to. It is an error to remove
759/// a handler that has not been registered.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000760void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000761 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000762 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000763
Daniel Dunbar40596532008-10-04 19:17:46 +0000764 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000765 if (!Namespace.empty()) {
766 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-10-04 19:17:46 +0000767 assert(Existing && "Namespace containing handler does not exist!");
768
769 NS = Existing->getIfNamespace();
770 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
771 }
772
773 NS->RemovePragmaHandler(Handler);
Mike Stump11289f42009-09-09 15:08:12 +0000774
Craig Topperbe250302014-09-12 05:19:24 +0000775 // If this is a non-default namespace and it is now empty, remove it.
776 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000777 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000778 delete NS;
779 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000780}
781
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000782bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
783 Token Tok;
784 LexUnexpandedToken(Tok);
785
786 if (Tok.isNot(tok::identifier)) {
787 Diag(Tok, diag::ext_on_off_switch_syntax);
788 return true;
789 }
790 IdentifierInfo *II = Tok.getIdentifierInfo();
791 if (II->isStr("ON"))
792 Result = tok::OOS_ON;
793 else if (II->isStr("OFF"))
794 Result = tok::OOS_OFF;
795 else if (II->isStr("DEFAULT"))
796 Result = tok::OOS_DEFAULT;
797 else {
798 Diag(Tok, diag::ext_on_off_switch_syntax);
799 return true;
800 }
801
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000802 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000803 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000804 if (Tok.isNot(tok::eod))
805 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000806 return false;
807}
808
Chris Lattnerb694ba72006-07-02 22:41:36 +0000809namespace {
James Dennett18a6d792012-06-17 03:26:26 +0000810/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000811struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000812 PragmaOnceHandler() : PragmaHandler("once") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000813 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
814 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000815 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000816 PP.HandlePragmaOnce(OnceTok);
817 }
818};
819
James Dennett18a6d792012-06-17 03:26:26 +0000820/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000821/// rest of the line is not lexed.
822struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000823 PragmaMarkHandler() : PragmaHandler("mark") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000824 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
825 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +0000826 PP.HandlePragmaMark();
827 }
828};
829
James Dennett18a6d792012-06-17 03:26:26 +0000830/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000831struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000832 PragmaPoisonHandler() : PragmaHandler("poison") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000833 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
834 Token &PoisonTok) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000835 PP.HandlePragmaPoison(PoisonTok);
836 }
837};
838
James Dennett18a6d792012-06-17 03:26:26 +0000839/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +0000840/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000841struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000842 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000843 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
844 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000845 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000846 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000847 }
848};
849struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000850 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000851 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
852 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000853 PP.HandlePragmaDependency(DepToken);
854 }
855};
Mike Stump11289f42009-09-09 15:08:12 +0000856
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000857struct PragmaDebugHandler : public PragmaHandler {
858 PragmaDebugHandler() : PragmaHandler("__debug") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000859 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
860 Token &DepToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000861 Token Tok;
862 PP.LexUnexpandedToken(Tok);
863 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +0000864 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000865 return;
866 }
867 IdentifierInfo *II = Tok.getIdentifierInfo();
868
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000869 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +0000870 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000871 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +0000872 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +0000873 } else if (II->isStr("parser_crash")) {
874 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +0000875 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +0000876 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +0000877 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikie5d577a22012-06-29 22:03:56 +0000878 PP.EnterToken(Crasher);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000879 } else if (II->isStr("llvm_fatal_error")) {
880 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
881 } else if (II->isStr("llvm_unreachable")) {
882 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smith3ffa61d2015-04-30 23:10:40 +0000883 } else if (II->isStr("macro")) {
884 Token MacroName;
885 PP.LexUnexpandedToken(MacroName);
886 auto *MacroII = MacroName.getIdentifierInfo();
887 if (MacroII)
888 PP.dumpMacroInfo(MacroII);
889 else
890 PP.Diag(MacroName, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000891 } else if (II->isStr("overflow_stack")) {
892 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +0000893 } else if (II->isStr("handle_crash")) {
894 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
895 if (CRC)
896 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000897 } else if (II->isStr("captured")) {
898 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000899 } else {
900 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
901 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000902 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000903
904 PPCallbacks *Callbacks = PP.getPPCallbacks();
905 if (Callbacks)
906 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
907 }
908
909 void HandleCaptured(Preprocessor &PP) {
910 // Skip if emitting preprocessed output.
911 if (PP.isPreprocessedOutput())
912 return;
913
914 Token Tok;
915 PP.LexUnexpandedToken(Tok);
916
917 if (Tok.isNot(tok::eod)) {
918 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
919 << "pragma clang __debug captured";
920 return;
921 }
922
923 SourceLocation NameLoc = Tok.getLocation();
924 Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1);
925 Toks->startToken();
926 Toks->setKind(tok::annot_pragma_captured);
927 Toks->setLocation(NameLoc);
928
929 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
930 /*OwnsTokens=*/false);
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000931 }
932
Francois Pichet2e11f5d2011-05-25 16:15:03 +0000933// Disable MSVC warning about runtime stack overflow.
934#ifdef _MSC_VER
935 #pragma warning(disable : 4717)
936#endif
Richard Trieu0732beb2013-12-21 01:04:02 +0000937 static void DebugOverflowStack() {
938 void (*volatile Self)() = DebugOverflowStack;
939 Self();
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000940 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +0000941#ifdef _MSC_VER
942 #pragma warning(default : 4717)
943#endif
944
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000945};
946
James Dennett18a6d792012-06-17 03:26:26 +0000947/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +0000948struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000949private:
950 const char *Namespace;
Chris Lattnerfb42a182009-07-12 21:18:45 +0000951public:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000952 explicit PragmaDiagnosticHandler(const char *NS) :
953 PragmaHandler("diagnostic"), Namespace(NS) {}
Craig Topper9140dd22014-03-11 06:50:42 +0000954 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
955 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000956 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +0000957 Token Tok;
958 PP.LexUnexpandedToken(Tok);
959 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +0000960 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +0000961 return;
962 }
963 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000964 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +0000965
Alp Toker46df1c02014-06-12 10:15:20 +0000966 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000967 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +0000968 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000969 else if (Callbacks)
970 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +0000971 return;
972 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000973 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000974 if (Callbacks)
975 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +0000976 return;
Alp Toker46df1c02014-06-12 10:15:20 +0000977 }
978
979 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
980 .Case("ignored", diag::Severity::Ignored)
981 .Case("warning", diag::Severity::Warning)
982 .Case("error", diag::Severity::Error)
983 .Case("fatal", diag::Severity::Fatal)
984 .Default(diag::Severity());
985
986 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +0000987 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +0000988 return;
989 }
Mike Stump11289f42009-09-09 15:08:12 +0000990
Chris Lattner504af112009-04-19 23:16:58 +0000991 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +0000992 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +0000993
Andy Gibbs58905d22012-11-17 19:15:38 +0000994 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000995 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
996 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +0000997 return;
Mike Stump11289f42009-09-09 15:08:12 +0000998
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000999 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +00001000 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1001 return;
1002 }
Mike Stump11289f42009-09-09 15:08:12 +00001003
Chris Lattner504af112009-04-19 23:16:58 +00001004 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +00001005 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001006 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +00001007 return;
1008 }
Mike Stump11289f42009-09-09 15:08:12 +00001009
Richard Smith3be1cb22014-08-07 00:24:21 +00001010 if (PP.getDiagnostics().setSeverityForGroup(
1011 WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1012 : diag::Flavor::Remark,
1013 WarningName.substr(2), SV, DiagLoc))
Andy Gibbs58905d22012-11-17 19:15:38 +00001014 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1015 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001016 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001017 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001018 }
1019};
Mike Stump11289f42009-09-09 15:08:12 +00001020
Reid Kleckner881dff32013-09-13 22:00:30 +00001021/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1022/// diagnostics, so we don't really implement this pragma. We parse it and
1023/// ignore it to avoid -Wunknown-pragma warnings.
1024struct PragmaWarningHandler : public PragmaHandler {
1025 PragmaWarningHandler() : PragmaHandler("warning") {}
1026
Craig Topper9140dd22014-03-11 06:50:42 +00001027 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1028 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001029 // Parse things like:
1030 // warning(push, 1)
1031 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001032 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001033 SourceLocation DiagLoc = Tok.getLocation();
1034 PPCallbacks *Callbacks = PP.getPPCallbacks();
1035
1036 PP.Lex(Tok);
1037 if (Tok.isNot(tok::l_paren)) {
1038 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1039 return;
1040 }
1041
1042 PP.Lex(Tok);
1043 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner881dff32013-09-13 22:00:30 +00001044
Alexander Musman6b080fc2015-05-25 11:21:20 +00001045 if (II && II->isStr("push")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001046 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001047 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001048 PP.Lex(Tok);
1049 if (Tok.is(tok::comma)) {
1050 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001051 uint64_t Value;
1052 if (Tok.is(tok::numeric_constant) &&
1053 PP.parseSimpleIntegerLiteral(Tok, Value))
1054 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001055 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001056 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1057 return;
1058 }
1059 }
1060 if (Callbacks)
1061 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman6b080fc2015-05-25 11:21:20 +00001062 } else if (II && II->isStr("pop")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001063 // #pragma warning( pop )
1064 PP.Lex(Tok);
1065 if (Callbacks)
1066 Callbacks->PragmaWarningPop(DiagLoc);
1067 } else {
1068 // #pragma warning( warning-specifier : warning-number-list
1069 // [; warning-specifier : warning-number-list...] )
1070 while (true) {
1071 II = Tok.getIdentifierInfo();
Alexander Musman6b080fc2015-05-25 11:21:20 +00001072 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001073 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1074 return;
1075 }
1076
1077 // Figure out which warning specifier this is.
Alexander Musman6b080fc2015-05-25 11:21:20 +00001078 bool SpecifierValid;
1079 StringRef Specifier;
1080 llvm::SmallString<1> SpecifierBuf;
1081 if (II) {
1082 Specifier = II->getName();
1083 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1084 .Cases("default", "disable", "error", "once",
1085 "suppress", true)
1086 .Default(false);
1087 // If we read a correct specifier, snatch next token (that should be
1088 // ":", checked later).
1089 if (SpecifierValid)
1090 PP.Lex(Tok);
1091 } else {
1092 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1093 uint64_t Value;
1094 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1095 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1096 SpecifierValid = (Value >= 1) && (Value <= 4);
1097 } else
1098 SpecifierValid = false;
1099 // Next token already snatched by parseSimpleIntegerLiteral.
1100 }
1101
Reid Kleckner881dff32013-09-13 22:00:30 +00001102 if (!SpecifierValid) {
1103 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1104 return;
1105 }
Reid Kleckner881dff32013-09-13 22:00:30 +00001106 if (Tok.isNot(tok::colon)) {
1107 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1108 return;
1109 }
1110
1111 // Collect the warning ids.
1112 SmallVector<int, 4> Ids;
1113 PP.Lex(Tok);
1114 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001115 uint64_t Value;
1116 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1117 Value > INT_MAX) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001118 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1119 return;
1120 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001121 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001122 }
1123 if (Callbacks)
1124 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1125
1126 // Parse the next specifier if there is a semicolon.
1127 if (Tok.isNot(tok::semi))
1128 break;
1129 PP.Lex(Tok);
1130 }
1131 }
1132
1133 if (Tok.isNot(tok::r_paren)) {
1134 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1135 return;
1136 }
1137
1138 PP.Lex(Tok);
1139 if (Tok.isNot(tok::eod))
1140 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1141 }
1142};
1143
James Dennett18a6d792012-06-17 03:26:26 +00001144/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001145struct PragmaIncludeAliasHandler : public PragmaHandler {
1146 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001147 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1148 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001149 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001150 }
1151};
1152
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001153/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1154/// extension. The syntax is:
1155/// \code
1156/// #pragma message(string)
1157/// \endcode
1158/// OR, in GCC mode:
1159/// \code
1160/// #pragma message string
1161/// \endcode
1162/// string is a string, which is fully macro expanded, and permits string
1163/// concatenation, embedded escape characters, etc... See MSDN for more details.
1164/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1165/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001166struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001167private:
1168 const PPCallbacks::PragmaMessageKind Kind;
1169 const StringRef Namespace;
1170
1171 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1172 bool PragmaNameOnly = false) {
1173 switch (Kind) {
1174 case PPCallbacks::PMK_Message:
1175 return PragmaNameOnly ? "message" : "pragma message";
1176 case PPCallbacks::PMK_Warning:
1177 return PragmaNameOnly ? "warning" : "pragma warning";
1178 case PPCallbacks::PMK_Error:
1179 return PragmaNameOnly ? "error" : "pragma error";
1180 }
1181 llvm_unreachable("Unknown PragmaMessageKind!");
1182 }
1183
1184public:
1185 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1186 StringRef Namespace = StringRef())
1187 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1188
Craig Topper9140dd22014-03-11 06:50:42 +00001189 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1190 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001191 SourceLocation MessageLoc = Tok.getLocation();
1192 PP.Lex(Tok);
1193 bool ExpectClosingParen = false;
1194 switch (Tok.getKind()) {
1195 case tok::l_paren:
1196 // We have a MSVC style pragma message.
1197 ExpectClosingParen = true;
1198 // Read the string.
1199 PP.Lex(Tok);
1200 break;
1201 case tok::string_literal:
1202 // We have a GCC style pragma message, and we just read the string.
1203 break;
1204 default:
1205 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1206 return;
1207 }
1208
1209 std::string MessageString;
1210 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1211 /*MacroExpansion=*/true))
1212 return;
1213
1214 if (ExpectClosingParen) {
1215 if (Tok.isNot(tok::r_paren)) {
1216 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1217 return;
1218 }
1219 PP.Lex(Tok); // eat the r_paren.
1220 }
1221
1222 if (Tok.isNot(tok::eod)) {
1223 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1224 return;
1225 }
1226
1227 // Output the message.
1228 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1229 ? diag::err_pragma_message
1230 : diag::warn_pragma_message) << MessageString;
1231
1232 // If the pragma is lexically sound, notify any interested PPCallbacks.
1233 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1234 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001235 }
1236};
1237
James Dennett18a6d792012-06-17 03:26:26 +00001238/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001239/// macro on the top of the stack.
1240struct PragmaPushMacroHandler : public PragmaHandler {
1241 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001242 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1243 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001244 PP.HandlePragmaPushMacro(PushMacroTok);
1245 }
1246};
1247
1248
James Dennett18a6d792012-06-17 03:26:26 +00001249/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001250/// macro to the value on the top of the stack.
1251struct PragmaPopMacroHandler : public PragmaHandler {
1252 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001253 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1254 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001255 PP.HandlePragmaPopMacro(PopMacroTok);
1256 }
1257};
1258
Chris Lattner958ee042009-04-19 21:20:35 +00001259// Pragma STDC implementations.
Chris Lattner02ef4e32009-04-19 21:50:08 +00001260
James Dennett18a6d792012-06-17 03:26:26 +00001261/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001262struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001263 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001264 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1265 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001266 tok::OnOffSwitch OOS;
1267 if (PP.LexOnOffSwitch(OOS))
1268 return;
1269 if (OOS == tok::OOS_ON)
Chris Lattnerdf222682009-04-19 21:55:32 +00001270 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
Chris Lattner958ee042009-04-19 21:20:35 +00001271 }
1272};
Mike Stump11289f42009-09-09 15:08:12 +00001273
James Dennett18a6d792012-06-17 03:26:26 +00001274/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001275struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001276 PragmaSTDC_CX_LIMITED_RANGEHandler()
1277 : PragmaHandler("CX_LIMITED_RANGE") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001278 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1279 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001280 tok::OnOffSwitch OOS;
1281 PP.LexOnOffSwitch(OOS);
Chris Lattner958ee042009-04-19 21:20:35 +00001282 }
1283};
Mike Stump11289f42009-09-09 15:08:12 +00001284
James Dennett18a6d792012-06-17 03:26:26 +00001285/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001286struct PragmaSTDC_UnknownHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001287 PragmaSTDC_UnknownHandler() {}
Craig Topper9140dd22014-03-11 06:50:42 +00001288 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1289 Token &UnknownTok) override {
Chris Lattner02ef4e32009-04-19 21:50:08 +00001290 // C99 6.10.6p2, unknown forms are not allowed.
Chris Lattnera0b1f762009-04-19 21:25:37 +00001291 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
Chris Lattner958ee042009-04-19 21:20:35 +00001292 }
1293};
Mike Stump11289f42009-09-09 15:08:12 +00001294
John McCall32f5fe12011-09-30 05:12:12 +00001295/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001296/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001297struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1298 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001299 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1300 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001301 SourceLocation Loc = NameTok.getLocation();
1302 bool IsBegin;
1303
1304 Token Tok;
1305
1306 // Lex the 'begin' or 'end'.
1307 PP.LexUnexpandedToken(Tok);
1308 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1309 if (BeginEnd && BeginEnd->isStr("begin")) {
1310 IsBegin = true;
1311 } else if (BeginEnd && BeginEnd->isStr("end")) {
1312 IsBegin = false;
1313 } else {
1314 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1315 return;
1316 }
1317
1318 // Verify that this is followed by EOD.
1319 PP.LexUnexpandedToken(Tok);
1320 if (Tok.isNot(tok::eod))
1321 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1322
1323 // The start location of the active audit.
1324 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1325
1326 // The start location we want after processing this.
1327 SourceLocation NewLoc;
1328
1329 if (IsBegin) {
1330 // Complain about attempts to re-enter an audit.
1331 if (BeginLoc.isValid()) {
1332 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1333 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1334 }
1335 NewLoc = Loc;
1336 } else {
1337 // Complain about attempts to leave an audit that doesn't exist.
1338 if (!BeginLoc.isValid()) {
1339 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1340 return;
1341 }
1342 NewLoc = SourceLocation();
1343 }
1344
1345 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1346 }
1347};
1348
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001349/// PragmaAssumeNonNullHandler -
1350/// \#pragma clang assume_nonnull begin/end
1351struct PragmaAssumeNonNullHandler : public PragmaHandler {
1352 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1353 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1354 Token &NameTok) override {
1355 SourceLocation Loc = NameTok.getLocation();
1356 bool IsBegin;
1357
1358 Token Tok;
1359
1360 // Lex the 'begin' or 'end'.
1361 PP.LexUnexpandedToken(Tok);
1362 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1363 if (BeginEnd && BeginEnd->isStr("begin")) {
1364 IsBegin = true;
1365 } else if (BeginEnd && BeginEnd->isStr("end")) {
1366 IsBegin = false;
1367 } else {
1368 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1369 return;
1370 }
1371
1372 // Verify that this is followed by EOD.
1373 PP.LexUnexpandedToken(Tok);
1374 if (Tok.isNot(tok::eod))
1375 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1376
1377 // The start location of the active audit.
1378 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1379
1380 // The start location we want after processing this.
1381 SourceLocation NewLoc;
1382
1383 if (IsBegin) {
1384 // Complain about attempts to re-enter an audit.
1385 if (BeginLoc.isValid()) {
1386 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1387 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1388 }
1389 NewLoc = Loc;
1390 } else {
1391 // Complain about attempts to leave an audit that doesn't exist.
1392 if (!BeginLoc.isValid()) {
1393 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1394 return;
1395 }
1396 NewLoc = SourceLocation();
1397 }
1398
1399 PP.setPragmaAssumeNonNullLoc(NewLoc);
1400 }
1401};
1402
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001403/// \brief Handle "\#pragma region [...]"
1404///
1405/// The syntax is
1406/// \code
1407/// #pragma region [optional name]
1408/// #pragma endregion [optional comment]
1409/// \endcode
1410///
1411/// \note This is
1412/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1413/// pragma, just skipped by compiler.
1414struct PragmaRegionHandler : public PragmaHandler {
1415 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
Aaron Ballman406ea512012-11-30 19:52:30 +00001416
Craig Topper9140dd22014-03-11 06:50:42 +00001417 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1418 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001419 // #pragma region: endregion matches can be verified
1420 // __pragma(region): no sense, but ignored by msvc
1421 // _Pragma is not valid for MSVC, but there isn't any point
1422 // to handle a _Pragma differently.
1423 }
1424};
Aaron Ballman406ea512012-11-30 19:52:30 +00001425
Chris Lattnerb694ba72006-07-02 22:41:36 +00001426} // end anonymous namespace
1427
1428
1429/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001430/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001431void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001432 AddPragmaHandler(new PragmaOnceHandler());
1433 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001434 AddPragmaHandler(new PragmaPushMacroHandler());
1435 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001436 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001437
Chris Lattnerb61448d2009-05-12 18:21:11 +00001438 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001439 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1440 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1441 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001442 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001443 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1444 "GCC"));
1445 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1446 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001447 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001448 AddPragmaHandler("clang", new PragmaPoisonHandler());
1449 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001450 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001451 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001452 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001453 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001454 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001455
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001456 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1457 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
Chris Lattner958ee042009-04-19 21:20:35 +00001458 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattner2ff698d2009-01-16 08:21:25 +00001460 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001461 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001462 AddPragmaHandler(new PragmaWarningHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001463 AddPragmaHandler(new PragmaIncludeAliasHandler());
Aaron Ballman406ea512012-11-30 19:52:30 +00001464 AddPragmaHandler(new PragmaRegionHandler("region"));
1465 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Chris Lattner30c924b2010-06-26 17:11:39 +00001466 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001467}
Lubos Lunak576a0412014-05-01 12:54:03 +00001468
1469/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1470/// warn about those pragmas being unknown.
1471void Preprocessor::IgnorePragmas() {
1472 AddPragmaHandler(new EmptyPragmaHandler());
1473 // Also ignore all pragmas in all namespaces created
1474 // in Preprocessor::RegisterBuiltinPragmas().
1475 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1476 AddPragmaHandler("clang", new EmptyPragmaHandler());
1477 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1478 // Preprocessor::RegisterBuiltinPragmas() already registers
1479 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1480 // otherwise there will be an assert about a duplicate handler.
1481 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1482 assert(STDCNamespace &&
1483 "Invalid namespace, registered as a regular pragma handler!");
1484 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1485 RemovePragmaHandler("STDC", Existing);
Chandler Carruth4d9c3df2014-05-02 21:44:48 +00001486 delete Existing;
Lubos Lunak576a0412014-05-01 12:54:03 +00001487 }
1488 }
1489 AddPragmaHandler("STDC", new EmptyPragmaHandler());
1490}