blob: af65bbfc9b19fa60f22b46a88c4feecfa1d4a4e5 [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");
68 llvm::StringMapEntry<PragmaHandler *> &Entry =
69 Handlers.GetOrCreateValue(Handler->getName());
70 Entry.setValue(Handler);
Chris Lattner2e155302006-07-03 05:34:41 +000071}
72
Daniel Dunbar40596532008-10-04 19:17:46 +000073void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000074 assert(Handlers.lookup(Handler->getName()) &&
75 "Handler not registered in this namespace");
76 Handlers.erase(Handler->getName());
Daniel Dunbar40596532008-10-04 19:17:46 +000077}
78
Douglas Gregorc7d65762010-09-09 22:45:38 +000079void PragmaNamespace::HandlePragma(Preprocessor &PP,
80 PragmaIntroducerKind Introducer,
81 Token &Tok) {
Chris Lattnerb8761832006-06-24 21:31:03 +000082 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
83 // expand it, the user can have a STDC #define, that should not affect this.
84 PP.LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +000085
Chris Lattnerb8761832006-06-24 21:31:03 +000086 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000087 PragmaHandler *Handler
88 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner0e62c1c2011-07-23 10:55:15 +000089 : StringRef(),
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000090 /*IgnoreNull=*/false);
Craig Topperd2d442c2014-05-17 23:10:59 +000091 if (!Handler) {
Chris Lattner21656f22009-04-19 21:10:26 +000092 PP.Diag(Tok, diag::warn_pragma_ignored);
93 return;
94 }
Mike Stump11289f42009-09-09 15:08:12 +000095
Chris Lattnerb8761832006-06-24 21:31:03 +000096 // Otherwise, pass it down.
Douglas Gregorc7d65762010-09-09 22:45:38 +000097 Handler->HandlePragma(PP, Introducer, Tok);
Chris Lattnerb8761832006-06-24 21:31:03 +000098}
Chris Lattnerb694ba72006-07-02 22:41:36 +000099
Chris Lattnerb694ba72006-07-02 22:41:36 +0000100//===----------------------------------------------------------------------===//
101// Preprocessor Pragma Directive Handling.
102//===----------------------------------------------------------------------===//
103
James Dennett18a6d792012-06-17 03:26:26 +0000104/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Chris Lattnerb694ba72006-07-02 22:41:36 +0000105/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000106void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
107 PragmaIntroducerKind Introducer) {
108 if (Callbacks)
109 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
110
Jordan Rosede1a2922012-06-08 18:06:21 +0000111 if (!PragmasEnabled)
112 return;
113
Chris Lattnerb694ba72006-07-02 22:41:36 +0000114 ++NumPragma;
Mike Stump11289f42009-09-09 15:08:12 +0000115
Chris Lattnerb694ba72006-07-02 22:41:36 +0000116 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattner146762e2007-07-20 16:59:19 +0000117 Token Tok;
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000118 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000119
Chris Lattnerb694ba72006-07-02 22:41:36 +0000120 // If the pragma handler didn't read the rest of the line, consume it now.
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000121 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
122 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000123 DiscardUntilEndOfDirective();
124}
125
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000126namespace {
127/// \brief Helper class for \see Preprocessor::Handle_Pragma.
128class LexingFor_PragmaRAII {
129 Preprocessor &PP;
130 bool InMacroArgPreExpansion;
131 bool Failed;
132 Token &OutTok;
133 Token PragmaTok;
134
135public:
136 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
137 Token &Tok)
138 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
139 Failed(false), OutTok(Tok) {
140 if (InMacroArgPreExpansion) {
141 PragmaTok = OutTok;
142 PP.EnableBacktrackAtThisPos();
143 }
144 }
145
146 ~LexingFor_PragmaRAII() {
147 if (InMacroArgPreExpansion) {
148 if (Failed) {
149 PP.CommitBacktrackedTokens();
150 } else {
151 PP.Backtrack();
152 OutTok = PragmaTok;
153 }
154 }
155 }
156
157 void failed() {
158 Failed = true;
159 }
160};
161}
162
Chris Lattnerb694ba72006-07-02 22:41:36 +0000163/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
164/// return the first token after the directive. The _Pragma token has just
165/// been read into 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000166void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000167
168 // This works differently if we are pre-expanding a macro argument.
169 // In that case we don't actually "activate" the pragma now, we only lex it
170 // until we are sure it is lexically correct and then we backtrack so that
171 // we activate the pragma whenever we encounter the tokens again in the token
172 // stream. This ensures that we will activate it in the correct location
173 // or that we will ignore it if it never enters the token stream, e.g:
174 //
175 // #define EMPTY(x)
176 // #define INACTIVE(x) EMPTY(x)
177 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
178
179 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
180
Chris Lattnerb694ba72006-07-02 22:41:36 +0000181 // Remember the pragma token location.
182 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000183
Chris Lattnerb694ba72006-07-02 22:41:36 +0000184 // Read the '('.
185 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000186 if (Tok.isNot(tok::l_paren)) {
187 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000188 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000189 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000190
191 // Read the '"..."'.
192 Lex(Tok);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000193 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000194 Diag(PragmaLoc, diag::err__Pragma_malformed);
Richard Smithd67aea22012-03-06 03:21:47 +0000195 // Skip this token, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000196 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000197 Lex(Tok);
198 if (Tok.is(tok::r_paren))
199 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000200 return _PragmaLexing.failed();
Richard Smithd67aea22012-03-06 03:21:47 +0000201 }
202
203 if (Tok.hasUDSuffix()) {
204 Diag(Tok, diag::err_invalid_string_udl);
205 // Skip this token, and the ')', if present.
206 Lex(Tok);
207 if (Tok.is(tok::r_paren))
208 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000209 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000210 }
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattnerb694ba72006-07-02 22:41:36 +0000212 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000213 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000214
215 // Read the ')'.
216 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000217 if (Tok.isNot(tok::r_paren)) {
218 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000219 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000220 }
Mike Stump11289f42009-09-09 15:08:12 +0000221
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000222 if (InMacroArgPreExpansion)
223 return;
224
Chris Lattner9dc9c202009-02-15 20:52:18 +0000225 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000226 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000227
Richard Smithc98bb4e2013-03-09 23:30:15 +0000228 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
229 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattner262d4e32009-01-16 18:59:23 +0000230 // deleting the leading and trailing double-quotes, replacing each escape
231 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
232 // single backslash."
Richard Smithc98bb4e2013-03-09 23:30:15 +0000233 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
234 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000235 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-03-09 23:30:15 +0000236 else if (StrVal[0] == 'u')
237 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
238
239 if (StrVal[0] == 'R') {
240 // FIXME: C++11 does not specify how to handle raw-string-literals here.
241 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
242 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
243 "Invalid raw string token!");
244
245 // Measure the length of the d-char-sequence.
246 unsigned NumDChars = 0;
247 while (StrVal[2 + NumDChars] != '(') {
248 assert(NumDChars < (StrVal.size() - 5) / 2 &&
249 "Invalid raw string token!");
250 ++NumDChars;
251 }
252 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
253
254 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
255 // parens below.
256 StrVal.erase(0, 2 + NumDChars);
257 StrVal.erase(StrVal.size() - 1 - NumDChars);
258 } else {
259 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
260 "Invalid string token!");
261
262 // Remove escaped quotes and escapes.
Benjamin Kramerc2f5f292013-05-04 10:37:20 +0000263 unsigned ResultPos = 1;
Reid Kleckner95e036c2013-09-25 16:42:48 +0000264 for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) {
265 // Skip escapes. \\ -> '\' and \" -> '"'.
266 if (StrVal[i] == '\\' && i + 1 < e &&
267 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
268 ++i;
269 StrVal[ResultPos++] = StrVal[i];
Richard Smithc98bb4e2013-03-09 23:30:15 +0000270 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000271 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000272 }
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattnerb694ba72006-07-02 22:41:36 +0000274 // Remove the front quote, replacing it with a space, so that the pragma
275 // contents appear to have a space before them.
276 StrVal[0] = ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000277
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000278 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000279 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000280
Peter Collingbournef29ce972011-02-22 13:49:06 +0000281 // Plop the string (including the newline and trailing null) into a buffer
282 // where we can lex it.
283 Token TmpTok;
284 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000285 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000286 SourceLocation TokLoc = TmpTok.getLocation();
287
288 // Make and enter a lexer object so that we lex and expand the tokens just
289 // like any others.
290 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
291 StrVal.size(), *this);
292
Craig Topperd2d442c2014-05-17 23:10:59 +0000293 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000294
295 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000296 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-08-28 22:34:47 +0000297
298 // Finally, return whatever came after the pragma directive.
299 return Lex(Tok);
300}
301
302/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
303/// is not enclosed within a string literal.
304void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
305 // Remember the pragma token location.
306 SourceLocation PragmaLoc = Tok.getLocation();
307
308 // Read the '('.
309 Lex(Tok);
310 if (Tok.isNot(tok::l_paren)) {
311 Diag(PragmaLoc, diag::err__Pragma_malformed);
312 return;
313 }
314
Peter Collingbournef29ce972011-02-22 13:49:06 +0000315 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000316 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000317 int NumParens = 0;
318 Lex(Tok);
319 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000320 PragmaToks.push_back(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000321 if (Tok.is(tok::l_paren))
322 NumParens++;
323 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
324 break;
John McCall89e925d2010-08-28 22:34:47 +0000325 Lex(Tok);
326 }
327
John McCall49039d42010-08-29 01:09:54 +0000328 if (Tok.is(tok::eof)) {
329 Diag(PragmaLoc, diag::err_unterminated___pragma);
330 return;
331 }
332
Peter Collingbournef29ce972011-02-22 13:49:06 +0000333 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000334
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000335 // Replace the ')' with an EOD to mark the end of the pragma.
336 PragmaToks.back().setKind(tok::eod);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000337
338 Token *TokArray = new Token[PragmaToks.size()];
339 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
340
341 // Push the tokens onto the stack.
342 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
343
344 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000345 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000346
347 // Finally, return whatever came after the pragma directive.
348 return Lex(Tok);
349}
350
James Dennett18a6d792012-06-17 03:26:26 +0000351/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000352///
Chris Lattner146762e2007-07-20 16:59:19 +0000353void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000354 if (isInPrimaryFile()) {
355 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
356 return;
357 }
Mike Stump11289f42009-09-09 15:08:12 +0000358
Chris Lattnerb694ba72006-07-02 22:41:36 +0000359 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000360 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000361 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000362}
363
Chris Lattnerc2383312007-12-19 19:38:36 +0000364void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000365 assert(CurPPLexer && "No current lexer?");
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000366 if (CurLexer)
367 CurLexer->ReadToEndOfLine();
368 else
369 CurPTHLexer->DiscardToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000370}
371
372
James Dennett18a6d792012-06-17 03:26:26 +0000373/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000374///
Chris Lattner146762e2007-07-20 16:59:19 +0000375void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
376 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000377
Chris Lattnerb694ba72006-07-02 22:41:36 +0000378 while (1) {
379 // Read the next token to poison. While doing this, pretend that we are
380 // skipping while reading the identifier to poison.
381 // This avoids errors on code like:
382 // #pragma GCC poison X
383 // #pragma GCC poison X
Ted Kremenek551c82a2008-11-18 01:12:54 +0000384 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000385 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000386 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000387
Chris Lattnerb694ba72006-07-02 22:41:36 +0000388 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000389 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000390
Chris Lattnerb694ba72006-07-02 22:41:36 +0000391 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000392 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000393 Diag(Tok, diag::err_pp_invalid_poison);
394 return;
395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattnercefc7682006-07-08 08:28:12 +0000397 // Look up the identifier info for the token. We disabled identifier lookup
398 // by saying we're skipping contents, so we need to do this manually.
399 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattnerb694ba72006-07-02 22:41:36 +0000401 // Already poisoned.
402 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattnerb694ba72006-07-02 22:41:36 +0000404 // If this is a macro identifier, emit a warning.
Chris Lattner259716a2007-10-07 08:04:56 +0000405 if (II->hasMacroDefinition())
Chris Lattnerb694ba72006-07-02 22:41:36 +0000406 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattnerb694ba72006-07-02 22:41:36 +0000408 // Finally, poison it!
409 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000410 if (II->isFromAST())
411 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000412 }
413}
414
James Dennett18a6d792012-06-17 03:26:26 +0000415/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000416/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000417void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000418 if (isInPrimaryFile()) {
419 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
420 return;
421 }
Mike Stump11289f42009-09-09 15:08:12 +0000422
Chris Lattnerb694ba72006-07-02 22:41:36 +0000423 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000424 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000425
Chris Lattnerb694ba72006-07-02 22:41:36 +0000426 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000427 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000428
429
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000430 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000431 if (PLoc.isInvalid())
432 return;
433
Jay Foad9a6b0982011-06-21 15:13:30 +0000434 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattner3bdc7672011-05-22 22:10:16 +0000436 // Notify the client, if desired, that we are in a new source file.
437 if (Callbacks)
438 Callbacks->FileChanged(SysHeaderTok.getLocation(),
439 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
440
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000441 // Emit a line marker. This will change any source locations from this point
442 // forward to realize they are in a system header.
443 // Create a line note with this information.
Jordan Rose111c4a62013-04-17 19:09:18 +0000444 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
445 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
446 /*IsSystem=*/true, /*IsExternC=*/false);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000447}
448
James Dennett18a6d792012-06-17 03:26:26 +0000449/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000450///
Chris Lattner146762e2007-07-20 16:59:19 +0000451void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
452 Token FilenameTok;
Ted Kremenek551c82a2008-11-18 01:12:54 +0000453 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000454
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000455 // If the token kind is EOD, the error has already been diagnosed.
456 if (FilenameTok.is(tok::eod))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000457 return;
Mike Stump11289f42009-09-09 15:08:12 +0000458
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000459 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000460 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000461 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000462 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000463 if (Invalid)
464 return;
Mike Stump11289f42009-09-09 15:08:12 +0000465
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000466 bool isAngled =
467 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000468 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
469 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000470 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000471 return;
Mike Stump11289f42009-09-09 15:08:12 +0000472
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000473 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000474 const DirectoryLookup *CurDir;
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000475 const FileEntry *File = LookupFile(FilenameTok.getLocation(), Filename,
Craig Topperd2d442c2014-05-17 23:10:59 +0000476 isAngled, nullptr, CurDir, nullptr,
477 nullptr, nullptr);
478 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000479 if (!SuppressIncludeNotFoundError)
480 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000481 return;
482 }
Mike Stump11289f42009-09-09 15:08:12 +0000483
Chris Lattnerd32480d2009-01-17 06:22:33 +0000484 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000485
486 // If this file is older than the file it depends on, emit a diagnostic.
487 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
488 // Lex tokens at the end of the message and include them in the message.
489 std::string Message;
490 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000491 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000492 Message += getSpelling(DependencyTok) + " ";
493 Lex(DependencyTok);
494 }
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattnerf0b04972010-09-05 23:16:09 +0000496 // Remove the trailing ' ' if present.
497 if (!Message.empty())
498 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000499 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000500 }
501}
502
Reid Kleckner002562a2013-05-06 21:02:12 +0000503/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000504/// Return the IdentifierInfo* associated with the macro to push or pop.
505IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
506 // Remember the pragma token location.
507 Token PragmaTok = Tok;
508
509 // Read the '('.
510 Lex(Tok);
511 if (Tok.isNot(tok::l_paren)) {
512 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
513 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000514 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000515 }
516
517 // Read the macro name string.
518 Lex(Tok);
519 if (Tok.isNot(tok::string_literal)) {
520 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
521 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000522 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000523 }
524
Richard Smithd67aea22012-03-06 03:21:47 +0000525 if (Tok.hasUDSuffix()) {
526 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000527 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000528 }
529
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000530 // Remember the macro string.
531 std::string StrVal = getSpelling(Tok);
532
533 // Read the ')'.
534 Lex(Tok);
535 if (Tok.isNot(tok::r_paren)) {
536 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
537 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000538 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000539 }
540
541 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
542 "Invalid string token!");
543
544 // Create a Token from the string.
545 Token MacroTok;
546 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000547 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000548 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000549
550 // Get the IdentifierInfo of MacroToPushTok.
551 return LookUpIdentifierInfo(MacroTok);
552}
553
James Dennett18a6d792012-06-17 03:26:26 +0000554/// \brief Handle \#pragma push_macro.
555///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000556/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000557/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000558/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000559/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000560void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
561 // Parse the pragma directive and get the macro IdentifierInfo*.
562 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
563 if (!IdentInfo) return;
564
565 // Get the MacroInfo associated with IdentInfo.
566 MacroInfo *MI = getMacroInfo(IdentInfo);
567
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000568 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000569 // Allow the original MacroInfo to be redefined later.
570 MI->setIsAllowRedefinitionsWithoutWarning(true);
571 }
572
573 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000574 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000575}
576
James Dennett18a6d792012-06-17 03:26:26 +0000577/// \brief Handle \#pragma pop_macro.
578///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000579/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000580/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000581/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000582/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000583void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
584 SourceLocation MessageLoc = PopMacroTok.getLocation();
585
586 // Parse the pragma directive and get the macro IdentifierInfo*.
587 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
588 if (!IdentInfo) return;
589
590 // Find the vector<MacroInfo*> associated with the macro.
591 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
592 PragmaPushMacroInfo.find(IdentInfo);
593 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000594 // Forget the MacroInfo currently associated with IdentInfo.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000595 if (MacroDirective *CurrentMD = getMacroDirective(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000596 MacroInfo *MI = CurrentMD->getMacroInfo();
597 if (MI->isWarnIfUnused())
598 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
599 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000600 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000601
602 // Get the MacroInfo we want to reinstall.
603 MacroInfo *MacroToReInstall = iter->second.back();
604
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000605 if (MacroToReInstall) {
606 // Reinstall the previously pushed macro.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000607 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc,
Richard Smithdaa69e02014-07-25 04:40:03 +0000608 /*isImported=*/false, /*Overrides*/None);
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000609 }
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
653 SourceFileName = FileNameBuffer.str();
654 } 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
684 ReplaceFileName = FileNameBuffer.str();
685 } 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) {
731 PragmaNamespace *InsertNS = PragmaHandlers;
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) {
762 PragmaNamespace *NS = PragmaHandlers;
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
Daniel Dunbar40596532008-10-04 19:17:46 +0000775 // If this is a non-default namespace and it is now empty, remove
776 // it.
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000777 if (NS != PragmaHandlers && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000778 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000779 delete NS;
780 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000781}
782
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000783bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
784 Token Tok;
785 LexUnexpandedToken(Tok);
786
787 if (Tok.isNot(tok::identifier)) {
788 Diag(Tok, diag::ext_on_off_switch_syntax);
789 return true;
790 }
791 IdentifierInfo *II = Tok.getIdentifierInfo();
792 if (II->isStr("ON"))
793 Result = tok::OOS_ON;
794 else if (II->isStr("OFF"))
795 Result = tok::OOS_OFF;
796 else if (II->isStr("DEFAULT"))
797 Result = tok::OOS_DEFAULT;
798 else {
799 Diag(Tok, diag::ext_on_off_switch_syntax);
800 return true;
801 }
802
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000803 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000804 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000805 if (Tok.isNot(tok::eod))
806 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000807 return false;
808}
809
Chris Lattnerb694ba72006-07-02 22:41:36 +0000810namespace {
James Dennett18a6d792012-06-17 03:26:26 +0000811/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000812struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000813 PragmaOnceHandler() : PragmaHandler("once") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000814 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
815 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000816 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000817 PP.HandlePragmaOnce(OnceTok);
818 }
819};
820
James Dennett18a6d792012-06-17 03:26:26 +0000821/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000822/// rest of the line is not lexed.
823struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000824 PragmaMarkHandler() : PragmaHandler("mark") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000825 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
826 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +0000827 PP.HandlePragmaMark();
828 }
829};
830
James Dennett18a6d792012-06-17 03:26:26 +0000831/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000832struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000833 PragmaPoisonHandler() : PragmaHandler("poison") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000834 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
835 Token &PoisonTok) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000836 PP.HandlePragmaPoison(PoisonTok);
837 }
838};
839
James Dennett18a6d792012-06-17 03:26:26 +0000840/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +0000841/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000842struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000843 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000844 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
845 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000846 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000847 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000848 }
849};
850struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000851 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000852 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
853 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000854 PP.HandlePragmaDependency(DepToken);
855 }
856};
Mike Stump11289f42009-09-09 15:08:12 +0000857
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000858struct PragmaDebugHandler : public PragmaHandler {
859 PragmaDebugHandler() : PragmaHandler("__debug") {}
Craig Topper9140dd22014-03-11 06:50:42 +0000860 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
861 Token &DepToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000862 Token Tok;
863 PP.LexUnexpandedToken(Tok);
864 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +0000865 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000866 return;
867 }
868 IdentifierInfo *II = Tok.getIdentifierInfo();
869
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000870 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +0000871 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000872 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +0000873 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +0000874 } else if (II->isStr("parser_crash")) {
875 Token Crasher;
876 Crasher.setKind(tok::annot_pragma_parser_crash);
877 PP.EnterToken(Crasher);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000878 } else if (II->isStr("llvm_fatal_error")) {
879 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
880 } else if (II->isStr("llvm_unreachable")) {
881 llvm_unreachable("#pragma clang __debug llvm_unreachable");
882 } else if (II->isStr("overflow_stack")) {
883 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +0000884 } else if (II->isStr("handle_crash")) {
885 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
886 if (CRC)
887 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000888 } else if (II->isStr("captured")) {
889 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +0000890 } else {
891 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
892 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000893 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +0000894
895 PPCallbacks *Callbacks = PP.getPPCallbacks();
896 if (Callbacks)
897 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
898 }
899
900 void HandleCaptured(Preprocessor &PP) {
901 // Skip if emitting preprocessed output.
902 if (PP.isPreprocessedOutput())
903 return;
904
905 Token Tok;
906 PP.LexUnexpandedToken(Tok);
907
908 if (Tok.isNot(tok::eod)) {
909 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
910 << "pragma clang __debug captured";
911 return;
912 }
913
914 SourceLocation NameLoc = Tok.getLocation();
915 Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1);
916 Toks->startToken();
917 Toks->setKind(tok::annot_pragma_captured);
918 Toks->setLocation(NameLoc);
919
920 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
921 /*OwnsTokens=*/false);
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000922 }
923
Francois Pichet2e11f5d2011-05-25 16:15:03 +0000924// Disable MSVC warning about runtime stack overflow.
925#ifdef _MSC_VER
926 #pragma warning(disable : 4717)
927#endif
Richard Trieu0732beb2013-12-21 01:04:02 +0000928 static void DebugOverflowStack() {
929 void (*volatile Self)() = DebugOverflowStack;
930 Self();
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000931 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +0000932#ifdef _MSC_VER
933 #pragma warning(default : 4717)
934#endif
935
Daniel Dunbarb8068c32010-07-28 15:40:33 +0000936};
937
James Dennett18a6d792012-06-17 03:26:26 +0000938/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +0000939struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000940private:
941 const char *Namespace;
Chris Lattnerfb42a182009-07-12 21:18:45 +0000942public:
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000943 explicit PragmaDiagnosticHandler(const char *NS) :
944 PragmaHandler("diagnostic"), Namespace(NS) {}
Craig Topper9140dd22014-03-11 06:50:42 +0000945 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
946 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000947 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +0000948 Token Tok;
949 PP.LexUnexpandedToken(Tok);
950 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +0000951 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +0000952 return;
953 }
954 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000955 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +0000956
Alp Toker46df1c02014-06-12 10:15:20 +0000957 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000958 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +0000959 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000960 else if (Callbacks)
961 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +0000962 return;
963 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000964 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +0000965 if (Callbacks)
966 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +0000967 return;
Alp Toker46df1c02014-06-12 10:15:20 +0000968 }
969
970 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
971 .Case("ignored", diag::Severity::Ignored)
972 .Case("warning", diag::Severity::Warning)
973 .Case("error", diag::Severity::Error)
974 .Case("fatal", diag::Severity::Fatal)
975 .Default(diag::Severity());
976
977 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +0000978 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +0000979 return;
980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981
Chris Lattner504af112009-04-19 23:16:58 +0000982 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +0000983 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +0000984
Andy Gibbs58905d22012-11-17 19:15:38 +0000985 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000986 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
987 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +0000988 return;
Mike Stump11289f42009-09-09 15:08:12 +0000989
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000990 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +0000991 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
992 return;
993 }
Mike Stump11289f42009-09-09 15:08:12 +0000994
Chris Lattner504af112009-04-19 23:16:58 +0000995 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +0000996 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +0000997 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +0000998 return;
999 }
Mike Stump11289f42009-09-09 15:08:12 +00001000
Richard Smith3be1cb22014-08-07 00:24:21 +00001001 if (PP.getDiagnostics().setSeverityForGroup(
1002 WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1003 : diag::Flavor::Remark,
1004 WarningName.substr(2), SV, DiagLoc))
Andy Gibbs58905d22012-11-17 19:15:38 +00001005 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1006 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001007 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001008 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001009 }
1010};
Mike Stump11289f42009-09-09 15:08:12 +00001011
Reid Kleckner881dff32013-09-13 22:00:30 +00001012/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1013/// diagnostics, so we don't really implement this pragma. We parse it and
1014/// ignore it to avoid -Wunknown-pragma warnings.
1015struct PragmaWarningHandler : public PragmaHandler {
1016 PragmaWarningHandler() : PragmaHandler("warning") {}
1017
Craig Topper9140dd22014-03-11 06:50:42 +00001018 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1019 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001020 // Parse things like:
1021 // warning(push, 1)
1022 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001023 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001024 SourceLocation DiagLoc = Tok.getLocation();
1025 PPCallbacks *Callbacks = PP.getPPCallbacks();
1026
1027 PP.Lex(Tok);
1028 if (Tok.isNot(tok::l_paren)) {
1029 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1030 return;
1031 }
1032
1033 PP.Lex(Tok);
1034 IdentifierInfo *II = Tok.getIdentifierInfo();
1035 if (!II) {
1036 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1037 return;
1038 }
1039
1040 if (II->isStr("push")) {
1041 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001042 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001043 PP.Lex(Tok);
1044 if (Tok.is(tok::comma)) {
1045 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001046 uint64_t Value;
1047 if (Tok.is(tok::numeric_constant) &&
1048 PP.parseSimpleIntegerLiteral(Tok, Value))
1049 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001050 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001051 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1052 return;
1053 }
1054 }
1055 if (Callbacks)
1056 Callbacks->PragmaWarningPush(DiagLoc, Level);
1057 } else if (II->isStr("pop")) {
1058 // #pragma warning( pop )
1059 PP.Lex(Tok);
1060 if (Callbacks)
1061 Callbacks->PragmaWarningPop(DiagLoc);
1062 } else {
1063 // #pragma warning( warning-specifier : warning-number-list
1064 // [; warning-specifier : warning-number-list...] )
1065 while (true) {
1066 II = Tok.getIdentifierInfo();
1067 if (!II) {
1068 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1069 return;
1070 }
1071
1072 // Figure out which warning specifier this is.
1073 StringRef Specifier = II->getName();
1074 bool SpecifierValid =
1075 llvm::StringSwitch<bool>(Specifier)
1076 .Cases("1", "2", "3", "4", true)
1077 .Cases("default", "disable", "error", "once", "suppress", true)
1078 .Default(false);
1079 if (!SpecifierValid) {
1080 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1081 return;
1082 }
1083 PP.Lex(Tok);
1084 if (Tok.isNot(tok::colon)) {
1085 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1086 return;
1087 }
1088
1089 // Collect the warning ids.
1090 SmallVector<int, 4> Ids;
1091 PP.Lex(Tok);
1092 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001093 uint64_t Value;
1094 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1095 Value > INT_MAX) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001096 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1097 return;
1098 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001099 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001100 }
1101 if (Callbacks)
1102 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1103
1104 // Parse the next specifier if there is a semicolon.
1105 if (Tok.isNot(tok::semi))
1106 break;
1107 PP.Lex(Tok);
1108 }
1109 }
1110
1111 if (Tok.isNot(tok::r_paren)) {
1112 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1113 return;
1114 }
1115
1116 PP.Lex(Tok);
1117 if (Tok.isNot(tok::eod))
1118 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1119 }
1120};
1121
James Dennett18a6d792012-06-17 03:26:26 +00001122/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001123struct PragmaIncludeAliasHandler : public PragmaHandler {
1124 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001125 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1126 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001127 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001128 }
1129};
1130
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001131/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1132/// extension. The syntax is:
1133/// \code
1134/// #pragma message(string)
1135/// \endcode
1136/// OR, in GCC mode:
1137/// \code
1138/// #pragma message string
1139/// \endcode
1140/// string is a string, which is fully macro expanded, and permits string
1141/// concatenation, embedded escape characters, etc... See MSDN for more details.
1142/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1143/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001144struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001145private:
1146 const PPCallbacks::PragmaMessageKind Kind;
1147 const StringRef Namespace;
1148
1149 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1150 bool PragmaNameOnly = false) {
1151 switch (Kind) {
1152 case PPCallbacks::PMK_Message:
1153 return PragmaNameOnly ? "message" : "pragma message";
1154 case PPCallbacks::PMK_Warning:
1155 return PragmaNameOnly ? "warning" : "pragma warning";
1156 case PPCallbacks::PMK_Error:
1157 return PragmaNameOnly ? "error" : "pragma error";
1158 }
1159 llvm_unreachable("Unknown PragmaMessageKind!");
1160 }
1161
1162public:
1163 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1164 StringRef Namespace = StringRef())
1165 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1166
Craig Topper9140dd22014-03-11 06:50:42 +00001167 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1168 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001169 SourceLocation MessageLoc = Tok.getLocation();
1170 PP.Lex(Tok);
1171 bool ExpectClosingParen = false;
1172 switch (Tok.getKind()) {
1173 case tok::l_paren:
1174 // We have a MSVC style pragma message.
1175 ExpectClosingParen = true;
1176 // Read the string.
1177 PP.Lex(Tok);
1178 break;
1179 case tok::string_literal:
1180 // We have a GCC style pragma message, and we just read the string.
1181 break;
1182 default:
1183 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1184 return;
1185 }
1186
1187 std::string MessageString;
1188 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1189 /*MacroExpansion=*/true))
1190 return;
1191
1192 if (ExpectClosingParen) {
1193 if (Tok.isNot(tok::r_paren)) {
1194 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1195 return;
1196 }
1197 PP.Lex(Tok); // eat the r_paren.
1198 }
1199
1200 if (Tok.isNot(tok::eod)) {
1201 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1202 return;
1203 }
1204
1205 // Output the message.
1206 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1207 ? diag::err_pragma_message
1208 : diag::warn_pragma_message) << MessageString;
1209
1210 // If the pragma is lexically sound, notify any interested PPCallbacks.
1211 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1212 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001213 }
1214};
1215
James Dennett18a6d792012-06-17 03:26:26 +00001216/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001217/// macro on the top of the stack.
1218struct PragmaPushMacroHandler : public PragmaHandler {
1219 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001220 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1221 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001222 PP.HandlePragmaPushMacro(PushMacroTok);
1223 }
1224};
1225
1226
James Dennett18a6d792012-06-17 03:26:26 +00001227/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001228/// macro to the value on the top of the stack.
1229struct PragmaPopMacroHandler : public PragmaHandler {
1230 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001231 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1232 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001233 PP.HandlePragmaPopMacro(PopMacroTok);
1234 }
1235};
1236
Chris Lattner958ee042009-04-19 21:20:35 +00001237// Pragma STDC implementations.
Chris Lattner02ef4e32009-04-19 21:50:08 +00001238
James Dennett18a6d792012-06-17 03:26:26 +00001239/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001240struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001241 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001242 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1243 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001244 tok::OnOffSwitch OOS;
1245 if (PP.LexOnOffSwitch(OOS))
1246 return;
1247 if (OOS == tok::OOS_ON)
Chris Lattnerdf222682009-04-19 21:55:32 +00001248 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
Chris Lattner958ee042009-04-19 21:20:35 +00001249 }
1250};
Mike Stump11289f42009-09-09 15:08:12 +00001251
James Dennett18a6d792012-06-17 03:26:26 +00001252/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001253struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001254 PragmaSTDC_CX_LIMITED_RANGEHandler()
1255 : PragmaHandler("CX_LIMITED_RANGE") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001256 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1257 Token &Tok) override {
Peter Collingbourne3bffa522011-02-14 01:42:24 +00001258 tok::OnOffSwitch OOS;
1259 PP.LexOnOffSwitch(OOS);
Chris Lattner958ee042009-04-19 21:20:35 +00001260 }
1261};
Mike Stump11289f42009-09-09 15:08:12 +00001262
James Dennett18a6d792012-06-17 03:26:26 +00001263/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
Chris Lattner958ee042009-04-19 21:20:35 +00001264struct PragmaSTDC_UnknownHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001265 PragmaSTDC_UnknownHandler() {}
Craig Topper9140dd22014-03-11 06:50:42 +00001266 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1267 Token &UnknownTok) override {
Chris Lattner02ef4e32009-04-19 21:50:08 +00001268 // C99 6.10.6p2, unknown forms are not allowed.
Chris Lattnera0b1f762009-04-19 21:25:37 +00001269 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
Chris Lattner958ee042009-04-19 21:20:35 +00001270 }
1271};
Mike Stump11289f42009-09-09 15:08:12 +00001272
John McCall32f5fe12011-09-30 05:12:12 +00001273/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001274/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001275struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1276 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Craig Topper9140dd22014-03-11 06:50:42 +00001277 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1278 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001279 SourceLocation Loc = NameTok.getLocation();
1280 bool IsBegin;
1281
1282 Token Tok;
1283
1284 // Lex the 'begin' or 'end'.
1285 PP.LexUnexpandedToken(Tok);
1286 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1287 if (BeginEnd && BeginEnd->isStr("begin")) {
1288 IsBegin = true;
1289 } else if (BeginEnd && BeginEnd->isStr("end")) {
1290 IsBegin = false;
1291 } else {
1292 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1293 return;
1294 }
1295
1296 // Verify that this is followed by EOD.
1297 PP.LexUnexpandedToken(Tok);
1298 if (Tok.isNot(tok::eod))
1299 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1300
1301 // The start location of the active audit.
1302 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1303
1304 // The start location we want after processing this.
1305 SourceLocation NewLoc;
1306
1307 if (IsBegin) {
1308 // Complain about attempts to re-enter an audit.
1309 if (BeginLoc.isValid()) {
1310 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1311 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1312 }
1313 NewLoc = Loc;
1314 } else {
1315 // Complain about attempts to leave an audit that doesn't exist.
1316 if (!BeginLoc.isValid()) {
1317 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1318 return;
1319 }
1320 NewLoc = SourceLocation();
1321 }
1322
1323 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1324 }
1325};
1326
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001327/// \brief Handle "\#pragma region [...]"
1328///
1329/// The syntax is
1330/// \code
1331/// #pragma region [optional name]
1332/// #pragma endregion [optional comment]
1333/// \endcode
1334///
1335/// \note This is
1336/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1337/// pragma, just skipped by compiler.
1338struct PragmaRegionHandler : public PragmaHandler {
1339 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
Aaron Ballman406ea512012-11-30 19:52:30 +00001340
Craig Topper9140dd22014-03-11 06:50:42 +00001341 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1342 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001343 // #pragma region: endregion matches can be verified
1344 // __pragma(region): no sense, but ignored by msvc
1345 // _Pragma is not valid for MSVC, but there isn't any point
1346 // to handle a _Pragma differently.
1347 }
1348};
Aaron Ballman406ea512012-11-30 19:52:30 +00001349
Chris Lattnerb694ba72006-07-02 22:41:36 +00001350} // end anonymous namespace
1351
1352
1353/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001354/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001355void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001356 AddPragmaHandler(new PragmaOnceHandler());
1357 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001358 AddPragmaHandler(new PragmaPushMacroHandler());
1359 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001360 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001361
Chris Lattnerb61448d2009-05-12 18:21:11 +00001362 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001363 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1364 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1365 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001366 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001367 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1368 "GCC"));
1369 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1370 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001371 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001372 AddPragmaHandler("clang", new PragmaPoisonHandler());
1373 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001374 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001375 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001376 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001377 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001378
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001379 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1380 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
Chris Lattner958ee042009-04-19 21:20:35 +00001381 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
Mike Stump11289f42009-09-09 15:08:12 +00001382
Chris Lattner2ff698d2009-01-16 08:21:25 +00001383 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001384 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001385 AddPragmaHandler(new PragmaWarningHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001386 AddPragmaHandler(new PragmaIncludeAliasHandler());
Aaron Ballman406ea512012-11-30 19:52:30 +00001387 AddPragmaHandler(new PragmaRegionHandler("region"));
1388 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Chris Lattner30c924b2010-06-26 17:11:39 +00001389 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001390}
Lubos Lunak576a0412014-05-01 12:54:03 +00001391
1392/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1393/// warn about those pragmas being unknown.
1394void Preprocessor::IgnorePragmas() {
1395 AddPragmaHandler(new EmptyPragmaHandler());
1396 // Also ignore all pragmas in all namespaces created
1397 // in Preprocessor::RegisterBuiltinPragmas().
1398 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1399 AddPragmaHandler("clang", new EmptyPragmaHandler());
1400 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1401 // Preprocessor::RegisterBuiltinPragmas() already registers
1402 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1403 // otherwise there will be an assert about a duplicate handler.
1404 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1405 assert(STDCNamespace &&
1406 "Invalid namespace, registered as a regular pragma handler!");
1407 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1408 RemovePragmaHandler("STDC", Existing);
Chandler Carruth4d9c3df2014-05-02 21:44:48 +00001409 delete Existing;
Lubos Lunak576a0412014-05-01 12:54:03 +00001410 }
1411 }
1412 AddPragmaHandler("STDC", new EmptyPragmaHandler());
1413}