blob: 739ebd41c31e7572d59f5e6f5d3e4788ca5e3965 [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/HeaderSearch.h"
Daniel Jasper07e6c402013-08-05 20:26:17 +000020#include "clang/Lex/HeaderSearchOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/LexDiagnostic.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/ModuleLoader.h"
25#include "clang/Lex/Pragma.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000026#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000027#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000028#include "llvm/Support/Path.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000029#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000030using namespace clang;
31
32//===----------------------------------------------------------------------===//
33// Utility Methods for Preprocessor Directive Handling.
34//===----------------------------------------------------------------------===//
35
Chris Lattnerc0a585d2010-08-17 15:55:45 +000036MacroInfo *Preprocessor::AllocateMacroInfo() {
Richard Smithee0c4c12014-07-24 01:13:23 +000037 MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
Ted Kremenekc8456f82010-10-19 22:15:20 +000038 MIChain->Next = MIChainHead;
Ted Kremenekc8456f82010-10-19 22:15:20 +000039 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000040 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000041}
42
43MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
44 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000045 new (MI) MacroInfo(L);
46 return MI;
47}
48
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000049MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
50 unsigned SubModuleID) {
Chandler Carruth06dde922014-03-02 13:02:01 +000051 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
52 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000053 DeserializedMacroInfoChain *MIChain =
54 BP.Allocate<DeserializedMacroInfoChain>();
55 MIChain->Next = DeserialMIChainHead;
56 DeserialMIChainHead = MIChain;
57
58 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000059 new (MI) MacroInfo(L);
60 MI->FromASTFile = true;
61 MI->setOwningModuleID(SubModuleID);
62 return MI;
63}
64
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000065DefMacroDirective *
66Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
Richard Smithdaa69e02014-07-25 04:40:03 +000067 unsigned ImportedFromModuleID,
68 ArrayRef<unsigned> Overrides) {
69 unsigned NumExtra = (ImportedFromModuleID ? 1 : 0) + Overrides.size();
70 return new (BP.Allocate(sizeof(DefMacroDirective) +
71 sizeof(unsigned) * NumExtra,
72 llvm::alignOf<DefMacroDirective>()))
73 DefMacroDirective(MI, Loc, ImportedFromModuleID, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000074}
75
76UndefMacroDirective *
Richard Smithdaa69e02014-07-25 04:40:03 +000077Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc,
78 unsigned ImportedFromModuleID,
79 ArrayRef<unsigned> Overrides) {
80 unsigned NumExtra = (ImportedFromModuleID ? 1 : 0) + Overrides.size();
81 return new (BP.Allocate(sizeof(UndefMacroDirective) +
82 sizeof(unsigned) * NumExtra,
83 llvm::alignOf<UndefMacroDirective>()))
84 UndefMacroDirective(UndefLoc, ImportedFromModuleID, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000085}
86
87VisibilityMacroDirective *
88Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
89 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000090 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000091}
92
James Dennettf6333ac2012-06-22 05:46:07 +000093/// \brief Read and discard all tokens remaining on the current line until
94/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000095void Preprocessor::DiscardUntilEndOfDirective() {
96 Token Tmp;
97 do {
98 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000099 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000100 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000101}
102
Alp Tokerb05e0b52014-05-21 06:13:51 +0000103bool Preprocessor::CheckMacroName(Token &MacroNameTok, char isDefineUndef) {
104 // Missing macro name?
105 if (MacroNameTok.is(tok::eod))
106 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
107
108 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
109 if (!II) {
110 bool Invalid = false;
111 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
112 if (Invalid)
113 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000114 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000115
Alp Tokerf33619c2014-05-31 03:38:08 +0000116 if (!II->isCPlusPlusOperatorKeyword())
117 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000118
Alp Tokere03e9e12014-05-31 16:32:22 +0000119 // C++ 2.5p2: Alternative tokens behave the same as its primary token
120 // except for their spellings.
121 Diag(MacroNameTok, getLangOpts().MicrosoftExt
122 ? diag::ext_pp_operator_used_as_macro_name
123 : diag::err_pp_operator_used_as_macro_name)
124 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000125
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000126 // Allow #defining |and| and friends for Microsoft compatibility or
127 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000128 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000129 }
130
131 if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
132 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
133 return Diag(MacroNameTok, diag::err_defined_macro_name);
134 }
135
136 if (isDefineUndef == 2 && II->hasMacroDefinition() &&
137 getMacroInfo(II)->isBuiltinMacro()) {
138 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
139 // and C++ [cpp.predefined]p4], but allow it as an extension.
140 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
141 }
142
143 // Okay, we got a good identifier.
144 return false;
145}
146
James Dennettf6333ac2012-06-22 05:46:07 +0000147/// \brief Lex and validate a macro name, which occurs after a
148/// \#define or \#undef.
149///
150/// This sets the token kind to eod and discards the rest
151/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
152/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
153/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000154void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
155 // Read the token, don't allow macro expansion on it.
156 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000157
Douglas Gregor12785102010-08-24 20:21:13 +0000158 if (MacroNameTok.is(tok::code_completion)) {
159 if (CodeComplete)
160 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000161 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000162 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000163 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000164
165 if (!CheckMacroName(MacroNameTok, isDefineUndef))
Chris Lattner907dfe92008-11-18 07:59:24 +0000166 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000167
168 // Invalid macro name, read and discard the rest of the line and set the
169 // token kind to tok::eod if necessary.
170 if (MacroNameTok.isNot(tok::eod)) {
171 MacroNameTok.setKind(tok::eod);
172 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000173 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000174}
175
James Dennettf6333ac2012-06-22 05:46:07 +0000176/// \brief Ensure that the next token is a tok::eod token.
177///
178/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000179/// true, then we consider macros that expand to zero tokens as being ok.
180void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000181 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000182 // Lex unexpanded tokens for most directives: macros might expand to zero
183 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
184 // #line) allow empty macros.
185 if (EnableMacros)
186 Lex(Tmp);
187 else
188 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000189
Chris Lattnerf64b3522008-03-09 01:54:53 +0000190 // There should be no tokens after the directive, but we allow them as an
191 // extension.
192 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
193 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000194
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000195 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000196 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000197 // or if this is a macro-style preprocessing directive, because it is more
198 // trouble than it is worth to insert /**/ and check that there is no /**/
199 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000200 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000201 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000202 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000203 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
204 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000205 DiscardUntilEndOfDirective();
206 }
207}
208
209
210
James Dennettf6333ac2012-06-22 05:46:07 +0000211/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
212/// decided that the subsequent tokens are in the \#if'd out portion of the
213/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000214/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000215/// this \#if directive, so \#else/\#elif blocks should never be entered.
216/// If ElseOk is true, then \#else directives are ok, if not, then we have
217/// already seen one so a \#else directive is a duplicate. When this returns,
218/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000219void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
220 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000221 bool FoundElse,
222 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000223 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000224 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000225
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000226 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000227 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000228
Ted Kremenek56572ab2008-12-12 18:34:08 +0000229 if (CurPTHLexer) {
230 PTHSkipExcludedConditionalBlock();
231 return;
232 }
Mike Stump11289f42009-09-09 15:08:12 +0000233
Chris Lattnerf64b3522008-03-09 01:54:53 +0000234 // Enter raw mode to disable identifier lookup (and thus macro expansion),
235 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000236 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000237 Token Tok;
238 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000239 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000240
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000241 if (Tok.is(tok::code_completion)) {
242 if (CodeComplete)
243 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000244 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000245 continue;
246 }
247
Chris Lattnerf64b3522008-03-09 01:54:53 +0000248 // If this is the end of the buffer, we have an error.
249 if (Tok.is(tok::eof)) {
250 // Emit errors for each unterminated conditional on the stack, including
251 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000252 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000253 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000254 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
255 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000256 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000257 }
258
Chris Lattnerf64b3522008-03-09 01:54:53 +0000259 // Just return and let the caller lex after this #include.
260 break;
261 }
Mike Stump11289f42009-09-09 15:08:12 +0000262
Chris Lattnerf64b3522008-03-09 01:54:53 +0000263 // If this token is not a preprocessor directive, just skip it.
264 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
265 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000266
Chris Lattnerf64b3522008-03-09 01:54:53 +0000267 // We just parsed a # character at the start of a line, so we're in
268 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000269 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000270 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000271 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000272
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattnerf64b3522008-03-09 01:54:53 +0000274 // Read the next token, the directive flavor.
275 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Chris Lattnerf64b3522008-03-09 01:54:53 +0000277 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
278 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000279 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000280 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000281 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000282 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000283 continue;
284 }
285
286 // If the first letter isn't i or e, it isn't intesting to us. We know that
287 // this is safe in the face of spelling differences, because there is no way
288 // to spell an i/e in a strange way that is another letter. Skipping this
289 // allows us to avoid looking up the identifier info for #define/#undef and
290 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000291 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000292
Alp Toker2d57cea2014-05-17 04:53:25 +0000293 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000294 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000296 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000297 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000298 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000299 continue;
300 }
Mike Stump11289f42009-09-09 15:08:12 +0000301
Chris Lattnerf64b3522008-03-09 01:54:53 +0000302 // Get the identifier name without trigraphs or embedded newlines. Note
303 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
304 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000305 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000306 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000307 if (!Tok.needsCleaning() && RI.size() < 20) {
308 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000309 } else {
310 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000311 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000312 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000313 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000315 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000316 continue;
317 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000318 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000319 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000320 }
Mike Stump11289f42009-09-09 15:08:12 +0000321
Benjamin Kramer144884642009-12-31 13:32:38 +0000322 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000323 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000324 if (Sub.empty() || // "if"
325 Sub == "def" || // "ifdef"
326 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000327 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
328 // bother parsing the condition.
329 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000330 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000331 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000332 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000333 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000334 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000335 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000336 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000337 PPConditionalInfo CondInfo;
338 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000339 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000340 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000341 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000342
Chris Lattnerf64b3522008-03-09 01:54:53 +0000343 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000344 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000345 // Restore the value of LexingRawMode so that trailing comments
346 // are handled correctly, if we've reached the outermost block.
347 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000348 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000349 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000350 if (Callbacks)
351 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352 break;
Richard Smithd0124572012-06-21 00:35:03 +0000353 } else {
354 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000355 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000356 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000357 // #else directive in a skipping conditional. If not in some other
358 // skipping conditional, and if #else hasn't already been seen, enter it
359 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000360 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000361
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 // If this is a #else with a #else before it, report the error.
363 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000364
Chris Lattnerf64b3522008-03-09 01:54:53 +0000365 // Note that we've seen a #else in this conditional.
366 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattnerf64b3522008-03-09 01:54:53 +0000368 // If the conditional is at the top level, and the #if block wasn't
369 // entered, enter the #else block now.
370 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
371 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000372 // Restore the value of LexingRawMode so that trailing comments
373 // are handled correctly.
374 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000375 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000376 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000377 if (Callbacks)
378 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000379 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000380 } else {
381 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000382 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000383 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000384 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385
John Thompson17c35732013-12-04 20:19:30 +0000386 // If this is a #elif with a #else before it, report the error.
387 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
388
Chris Lattnerf64b3522008-03-09 01:54:53 +0000389 // If this is in a skipping block or if we're already handled this #if
390 // block, don't bother parsing the condition.
391 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
392 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000393 } else {
John Thompson17c35732013-12-04 20:19:30 +0000394 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000395 // Restore the value of LexingRawMode so that identifiers are
396 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000397 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
398 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000399 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000400 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000401 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000402 if (Callbacks) {
403 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000404 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000405 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000406 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000407 }
408 // If this condition is true, enter it!
409 if (CondValue) {
410 CondInfo.FoundNonSkip = true;
411 break;
412 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000413 }
414 }
415 }
Mike Stump11289f42009-09-09 15:08:12 +0000416
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000417 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000418 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000419 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000420 }
421
422 // Finally, if we are out of the conditional (saw an #endif or ran off the end
423 // of the file, just stop skipping and return to lexing whatever came after
424 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000425 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000426
427 if (Callbacks) {
428 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
429 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
430 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000431}
432
Ted Kremenek56572ab2008-12-12 18:34:08 +0000433void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000434
435 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000436 assert(CurPTHLexer);
437 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000438
Ted Kremenek56572ab2008-12-12 18:34:08 +0000439 // Skip to the next '#else', '#elif', or #endif.
440 if (CurPTHLexer->SkipBlock()) {
441 // We have reached an #endif. Both the '#' and 'endif' tokens
442 // have been consumed by the PTHLexer. Just pop off the condition level.
443 PPConditionalInfo CondInfo;
444 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000445 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000446 assert(!InCond && "Can't be skipping if not in a conditional!");
447 break;
448 }
Mike Stump11289f42009-09-09 15:08:12 +0000449
Ted Kremenek56572ab2008-12-12 18:34:08 +0000450 // We have reached a '#else' or '#elif'. Lex the next token to get
451 // the directive flavor.
452 Token Tok;
453 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000454
Ted Kremenek56572ab2008-12-12 18:34:08 +0000455 // We can actually look up the IdentifierInfo here since we aren't in
456 // raw mode.
457 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
458
459 if (K == tok::pp_else) {
460 // #else: Enter the else condition. We aren't in a nested condition
461 // since we skip those. We're always in the one matching the last
462 // blocked we skipped.
463 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
464 // Note that we've seen a #else in this conditional.
465 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000466
Ted Kremenek56572ab2008-12-12 18:34:08 +0000467 // If the #if block wasn't entered then enter the #else block now.
468 if (!CondInfo.FoundNonSkip) {
469 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000470
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000471 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000472 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000473 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000474 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000475
Ted Kremenek56572ab2008-12-12 18:34:08 +0000476 break;
477 }
Mike Stump11289f42009-09-09 15:08:12 +0000478
Ted Kremenek56572ab2008-12-12 18:34:08 +0000479 // Otherwise skip this block.
480 continue;
481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Ted Kremenek56572ab2008-12-12 18:34:08 +0000483 assert(K == tok::pp_elif);
484 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
485
486 // If this is a #elif with a #else before it, report the error.
487 if (CondInfo.FoundElse)
488 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000489
Ted Kremenek56572ab2008-12-12 18:34:08 +0000490 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000491 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000492 if (CondInfo.FoundNonSkip)
493 continue;
494
495 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000496 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000497 CurPTHLexer->ParsingPreprocessorDirective = true;
498 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
499 CurPTHLexer->ParsingPreprocessorDirective = false;
500
501 // If this condition is true, enter it!
502 if (ShouldEnter) {
503 CondInfo.FoundNonSkip = true;
504 break;
505 }
506
507 // Otherwise, skip this block and go to the next one.
508 continue;
509 }
510}
511
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000512Module *Preprocessor::getModuleForLocation(SourceLocation FilenameLoc) {
513 ModuleMap &ModMap = HeaderInfo.getModuleMap();
514 if (SourceMgr.isInMainFile(FilenameLoc)) {
515 if (Module *CurMod = getCurrentModule())
516 return CurMod; // Compiling a module.
517 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
518 }
519 // Try to determine the module of the include directive.
Daniel Jasper88d86952013-12-03 20:30:36 +0000520 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
Manuel Klimek98a9a6c2014-03-19 10:22:36 +0000521 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(FilenameLoc));
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000522 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
523 // The include comes from a file.
524 return ModMap.findModuleForHeader(EntryOfIncl).getModule();
525 } else {
526 // The include does not come from a file,
527 // so it is probably a module compilation.
528 return getCurrentModule();
529 }
530}
531
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000532const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000533 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000534 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000535 bool isAngled,
536 const DirectoryLookup *FromDir,
Richard Smith25d50752014-10-20 00:15:49 +0000537 const FileEntry *FromFile,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000538 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000539 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000540 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000541 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000542 bool SkipCache) {
Will Wilson0fafd342013-12-27 19:46:16 +0000543 // If the header lookup mechanism may be relative to the current inclusion
544 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000545 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
546 Includers;
Richard Smith25d50752014-10-20 00:15:49 +0000547 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000548 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000549 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000550
Chris Lattner022923a2009-02-04 19:45:07 +0000551 // If there is no file entry associated with this file, it must be the
552 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000553 // it won't be scanned for preprocessor directives. If we have the
554 // predefines buffer, resolve #include references (which come from the
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000555 // -include command line argument) from the current working directory
556 // instead of relative to the main file.
557 if (!FileEnt) {
Will Wilson0fafd342013-12-27 19:46:16 +0000558 FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000559 if (FileEnt)
560 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
561 } else {
562 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
563 }
Will Wilson0fafd342013-12-27 19:46:16 +0000564
565 // MSVC searches the current include stack from top to bottom for
566 // headers included by quoted include directives.
567 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000568 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000569 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
570 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
571 if (IsFileLexer(ISEntry))
572 if ((FileEnt = SourceMgr.getFileEntryForID(
573 ISEntry.ThePPLexer->getFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000574 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000575 }
Chris Lattner022923a2009-02-04 19:45:07 +0000576 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000577 }
Mike Stump11289f42009-09-09 15:08:12 +0000578
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000579 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000580
581 if (FromFile) {
582 // We're supposed to start looking from after a particular file. Search
583 // the include path until we find that file or run out of files.
584 const DirectoryLookup *TmpCurDir = CurDir;
585 const DirectoryLookup *TmpFromDir = nullptr;
586 while (const FileEntry *FE = HeaderInfo.LookupFile(
587 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
588 Includers, SearchPath, RelativePath, SuggestedModule,
589 SkipCache)) {
590 // Keep looking as if this file did a #include_next.
591 TmpFromDir = TmpCurDir;
592 ++TmpFromDir;
593 if (FE == FromFile) {
594 // Found it.
595 FromDir = TmpFromDir;
596 CurDir = TmpCurDir;
597 break;
598 }
599 }
600 }
601
602 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000603 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000604 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
605 RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000606 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000607 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000608 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
609 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000610 return FE;
611 }
Mike Stump11289f42009-09-09 15:08:12 +0000612
Will Wilson0fafd342013-12-27 19:46:16 +0000613 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000614 // Otherwise, see if this is a subframework header. If so, this is relative
615 // to one of the headers on the #include stack. Walk the list of the current
616 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000617 if (IsFileLexer()) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000618 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000619 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000620 SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000621 SuggestedModule))) {
622 if (SuggestedModule && !LangOpts.AsmPreprocessor)
623 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
624 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000625 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000626 }
627 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000628 }
Mike Stump11289f42009-09-09 15:08:12 +0000629
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000630 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
631 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000632 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000633 if ((CurFileEnt =
Ben Langmuir71e1a642014-05-05 21:44:13 +0000634 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000635 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000636 Filename, CurFileEnt, SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000637 SuggestedModule))) {
638 if (SuggestedModule && !LangOpts.AsmPreprocessor)
639 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
640 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000641 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000642 }
643 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000644 }
645 }
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000647 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000648 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000649}
650
Chris Lattnerf64b3522008-03-09 01:54:53 +0000651
652//===----------------------------------------------------------------------===//
653// Preprocessor Directive Handling.
654//===----------------------------------------------------------------------===//
655
David Blaikied5321242012-06-06 18:52:13 +0000656class Preprocessor::ResetMacroExpansionHelper {
657public:
658 ResetMacroExpansionHelper(Preprocessor *pp)
659 : PP(pp), save(pp->DisableMacroExpansion) {
660 if (pp->MacroExpansionInDirectivesOverride)
661 pp->DisableMacroExpansion = false;
662 }
663 ~ResetMacroExpansionHelper() {
664 PP->DisableMacroExpansion = save;
665 }
666private:
667 Preprocessor *PP;
668 bool save;
669};
670
Chris Lattnerf64b3522008-03-09 01:54:53 +0000671/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000672/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000673/// lexer/preprocessor state, and advances the lexer(s) so that the next token
674/// read is the correct one.
675void Preprocessor::HandleDirective(Token &Result) {
676 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000677
Chris Lattnerf64b3522008-03-09 01:54:53 +0000678 // We just parsed a # character at the start of a line, so we're in directive
679 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000680 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000681 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000682 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000683
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000684 bool ImmediatelyAfterTopLevelIfndef =
685 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
686 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
687
Chris Lattnerf64b3522008-03-09 01:54:53 +0000688 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000689
Chris Lattnerf64b3522008-03-09 01:54:53 +0000690 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000691 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000692 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000693 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner2d17ab72009-03-18 21:00:25 +0000695 // Save the '#' token in case we need to return it later.
696 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattnerf64b3522008-03-09 01:54:53 +0000698 // Read the next token, the directive flavor. This isn't expanded due to
699 // C99 6.10.3p8.
700 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000701
Chris Lattnerf64b3522008-03-09 01:54:53 +0000702 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
703 // #define A(x) #x
704 // A(abc
705 // #warning blah
706 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000707 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
708 // not support this for #include-like directives, since that can result in
709 // terrible diagnostics, and does not work in GCC.
710 if (InMacroArgs) {
711 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
712 switch (II->getPPKeywordID()) {
713 case tok::pp_include:
714 case tok::pp_import:
715 case tok::pp_include_next:
716 case tok::pp___include_macros:
717 Diag(Result, diag::err_embedded_include) << II->getName();
718 DiscardUntilEndOfDirective();
719 return;
720 default:
721 break;
722 }
723 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000724 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000725 }
Mike Stump11289f42009-09-09 15:08:12 +0000726
David Blaikied5321242012-06-06 18:52:13 +0000727 // Temporarily enable macro expansion if set so
728 // and reset to previous state when returning from this function.
729 ResetMacroExpansionHelper helper(this);
730
Chris Lattnerf64b3522008-03-09 01:54:53 +0000731 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000732 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000733 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000734 case tok::code_completion:
735 if (CodeComplete)
736 CodeComplete->CodeCompleteDirective(
737 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000738 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000739 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000740 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000741 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000742 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000743 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000744 default:
745 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000746 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000747
Chris Lattnerf64b3522008-03-09 01:54:53 +0000748 // Ask what the preprocessor keyword ID is.
749 switch (II->getPPKeywordID()) {
750 default: break;
751 // C99 6.10.1 - Conditional Inclusion.
752 case tok::pp_if:
753 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
754 case tok::pp_ifdef:
755 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
756 case tok::pp_ifndef:
757 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
758 case tok::pp_elif:
759 return HandleElifDirective(Result);
760 case tok::pp_else:
761 return HandleElseDirective(Result);
762 case tok::pp_endif:
763 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000764
Chris Lattnerf64b3522008-03-09 01:54:53 +0000765 // C99 6.10.2 - Source File Inclusion.
766 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000767 // Handle #include.
768 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000769 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000770 // Handle -imacros.
771 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000772
Chris Lattnerf64b3522008-03-09 01:54:53 +0000773 // C99 6.10.3 - Macro Replacement.
774 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000775 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000776 case tok::pp_undef:
777 return HandleUndefDirective(Result);
778
779 // C99 6.10.4 - Line Control.
780 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000781 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000782
Chris Lattnerf64b3522008-03-09 01:54:53 +0000783 // C99 6.10.5 - Error Directive.
784 case tok::pp_error:
785 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000786
Chris Lattnerf64b3522008-03-09 01:54:53 +0000787 // C99 6.10.6 - Pragma Directive.
788 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000789 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000790
Chris Lattnerf64b3522008-03-09 01:54:53 +0000791 // GNU Extensions.
792 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000793 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000794 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000795 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000796
Chris Lattnerf64b3522008-03-09 01:54:53 +0000797 case tok::pp_warning:
798 Diag(Result, diag::ext_pp_warning_directive);
799 return HandleUserDiagnosticDirective(Result, true);
800 case tok::pp_ident:
801 return HandleIdentSCCSDirective(Result);
802 case tok::pp_sccs:
803 return HandleIdentSCCSDirective(Result);
804 case tok::pp_assert:
805 //isExtension = true; // FIXME: implement #assert
806 break;
807 case tok::pp_unassert:
808 //isExtension = true; // FIXME: implement #unassert
809 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000810
Douglas Gregor663b48f2012-01-03 19:48:16 +0000811 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000812 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000813 return HandleMacroPublicDirective(Result);
814 break;
815
Douglas Gregor663b48f2012-01-03 19:48:16 +0000816 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000817 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000818 return HandleMacroPrivateDirective(Result);
819 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000820 }
821 break;
822 }
Mike Stump11289f42009-09-09 15:08:12 +0000823
Chris Lattner2d17ab72009-03-18 21:00:25 +0000824 // If this is a .S file, treat unknown # directives as non-preprocessor
825 // directives. This is important because # may be a comment or introduce
826 // various pseudo-ops. Just return the # token and push back the following
827 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000828 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000829 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000830 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000831 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000832 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000833
834 // If the second token is a hashhash token, then we need to translate it to
835 // unknown so the token lexer doesn't try to perform token pasting.
836 if (Result.is(tok::hashhash))
837 Toks[1].setKind(tok::unknown);
838
Chris Lattner2d17ab72009-03-18 21:00:25 +0000839 // Enter this token stream so that we re-lex the tokens. Make sure to
840 // enable macro expansion, in case the token after the # is an identifier
841 // that is expanded.
842 EnterTokenStream(Toks, 2, false, true);
843 return;
844 }
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattnerf64b3522008-03-09 01:54:53 +0000846 // If we reached here, the preprocessing token is not valid!
847 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000848
Chris Lattnerf64b3522008-03-09 01:54:53 +0000849 // Read the rest of the PP line.
850 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chris Lattnerf64b3522008-03-09 01:54:53 +0000852 // Okay, we're done parsing the directive.
853}
854
Chris Lattner76e68962009-01-26 06:19:46 +0000855/// GetLineValue - Convert a numeric token into an unsigned value, emitting
856/// Diagnostic DiagID if it is invalid, and returning the value in Val.
857static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000858 unsigned DiagID, Preprocessor &PP,
859 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000860 if (DigitTok.isNot(tok::numeric_constant)) {
861 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000862
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000863 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000864 PP.DiscardUntilEndOfDirective();
865 return true;
866 }
Mike Stump11289f42009-09-09 15:08:12 +0000867
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000868 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000869 IntegerBuffer.resize(DigitTok.getLength());
870 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000871 bool Invalid = false;
872 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
873 if (Invalid)
874 return true;
875
Chris Lattnerd66f1722009-04-18 18:35:15 +0000876 // Verify that we have a simple digit-sequence, and compute the value. This
877 // is always a simple digit string computed in decimal, so we do this manually
878 // here.
879 Val = 0;
880 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +0000881 // C++1y [lex.fcon]p1:
882 // Optional separating single quotes in a digit-sequence are ignored
883 if (DigitTokBegin[i] == '\'')
884 continue;
885
Jordan Rosea7d03842013-02-08 22:30:41 +0000886 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000887 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000888 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000889 PP.DiscardUntilEndOfDirective();
890 return true;
891 }
Mike Stump11289f42009-09-09 15:08:12 +0000892
Chris Lattnerd66f1722009-04-18 18:35:15 +0000893 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
894 if (NextVal < Val) { // overflow.
895 PP.Diag(DigitTok, DiagID);
896 PP.DiscardUntilEndOfDirective();
897 return true;
898 }
899 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000900 }
Mike Stump11289f42009-09-09 15:08:12 +0000901
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000902 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000903 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
904 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Chris Lattner76e68962009-01-26 06:19:46 +0000906 return false;
907}
908
James Dennettf6333ac2012-06-22 05:46:07 +0000909/// \brief Handle a \#line directive: C99 6.10.4.
910///
911/// The two acceptable forms are:
912/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000913/// # line digit-sequence
914/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000915/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000916void Preprocessor::HandleLineDirective(Token &Tok) {
917 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
918 // expanded.
919 Token DigitTok;
920 Lex(DigitTok);
921
Chris Lattner100c65e2009-01-26 05:29:08 +0000922 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000923 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000924 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000925 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000926
927 if (LineNo == 0)
928 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000929
Chris Lattner76e68962009-01-26 06:19:46 +0000930 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
931 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000932 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000933 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000934 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000935 if (LineNo >= LineLimit)
936 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000937 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000938 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000939
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000940 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000941 Token StrTok;
942 Lex(StrTok);
943
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000944 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
945 // string followed by eod.
946 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000947 ; // ok
948 else if (StrTok.isNot(tok::string_literal)) {
949 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000950 return DiscardUntilEndOfDirective();
951 } else if (StrTok.hasUDSuffix()) {
952 Diag(StrTok, diag::err_invalid_string_udl);
953 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000954 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000955 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +0000956 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000957 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000958 if (Literal.hadError)
959 return DiscardUntilEndOfDirective();
960 if (Literal.Pascal) {
961 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
962 return DiscardUntilEndOfDirective();
963 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000964 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000965
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000966 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000967 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
968 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000969 }
Mike Stump11289f42009-09-09 15:08:12 +0000970
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000971 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattner839150e2009-03-27 17:13:49 +0000973 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000974 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
975 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000976 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000977}
978
Chris Lattner76e68962009-01-26 06:19:46 +0000979/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
980/// marker directive.
981static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
982 bool &IsSystemHeader, bool &IsExternCHeader,
983 Preprocessor &PP) {
984 unsigned FlagVal;
985 Token FlagTok;
986 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000987 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000988 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
989 return true;
990
991 if (FlagVal == 1) {
992 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chris Lattner76e68962009-01-26 06:19:46 +0000994 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000995 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000996 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
997 return true;
998 } else if (FlagVal == 2) {
999 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001000
Chris Lattner1c967782009-02-04 06:25:26 +00001001 SourceManager &SM = PP.getSourceManager();
1002 // If we are leaving the current presumed file, check to make sure the
1003 // presumed include stack isn't empty!
1004 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001005 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001006 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001007 if (PLoc.isInvalid())
1008 return true;
1009
Chris Lattner1c967782009-02-04 06:25:26 +00001010 // If there is no include loc (main file) or if the include loc is in a
1011 // different physical file, then we aren't in a "1" line marker flag region.
1012 SourceLocation IncLoc = PLoc.getIncludeLoc();
1013 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001014 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001015 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1016 PP.DiscardUntilEndOfDirective();
1017 return true;
1018 }
Mike Stump11289f42009-09-09 15:08:12 +00001019
Chris Lattner76e68962009-01-26 06:19:46 +00001020 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001021 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001022 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1023 return true;
1024 }
1025
1026 // We must have 3 if there are still flags.
1027 if (FlagVal != 3) {
1028 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001029 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001030 return true;
1031 }
Mike Stump11289f42009-09-09 15:08:12 +00001032
Chris Lattner76e68962009-01-26 06:19:46 +00001033 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001034
Chris Lattner76e68962009-01-26 06:19:46 +00001035 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001036 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001037 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001038 return true;
1039
1040 // We must have 4 if there is yet another flag.
1041 if (FlagVal != 4) {
1042 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001043 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001044 return true;
1045 }
Mike Stump11289f42009-09-09 15:08:12 +00001046
Chris Lattner76e68962009-01-26 06:19:46 +00001047 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001048
Chris Lattner76e68962009-01-26 06:19:46 +00001049 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001050 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001051
1052 // There are no more valid flags here.
1053 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001054 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001055 return true;
1056}
1057
1058/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1059/// one of the following forms:
1060///
1061/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001062/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001063/// # 42 "file" ('1' | '2')? '3' '4'?
1064///
1065void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1066 // Validate the number and convert it to an unsigned. GNU does not have a
1067 // line # limit other than it fit in 32-bits.
1068 unsigned LineNo;
1069 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001070 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001071 return;
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattner76e68962009-01-26 06:19:46 +00001073 Token StrTok;
1074 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001075
Chris Lattner76e68962009-01-26 06:19:46 +00001076 bool IsFileEntry = false, IsFileExit = false;
1077 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001078 int FilenameID = -1;
1079
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001080 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1081 // string followed by eod.
1082 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001083 ; // ok
1084 else if (StrTok.isNot(tok::string_literal)) {
1085 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001086 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001087 } else if (StrTok.hasUDSuffix()) {
1088 Diag(StrTok, diag::err_invalid_string_udl);
1089 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001090 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001091 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001092 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001093 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001094 if (Literal.hadError)
1095 return DiscardUntilEndOfDirective();
1096 if (Literal.Pascal) {
1097 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1098 return DiscardUntilEndOfDirective();
1099 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001100 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001101
Chris Lattner76e68962009-01-26 06:19:46 +00001102 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001103 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001104 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001105 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001106 }
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001108 // Create a line note with this information.
1109 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001110 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001111 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001112
Chris Lattner839150e2009-03-27 17:13:49 +00001113 // If the preprocessor has callbacks installed, notify them of the #line
1114 // change. This is used so that the line marker comes out in -E mode for
1115 // example.
1116 if (Callbacks) {
1117 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1118 if (IsFileEntry)
1119 Reason = PPCallbacks::EnterFile;
1120 else if (IsFileExit)
1121 Reason = PPCallbacks::ExitFile;
1122 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1123 if (IsExternCHeader)
1124 FileKind = SrcMgr::C_ExternCSystem;
1125 else if (IsSystemHeader)
1126 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattnerc745cec2010-04-14 04:28:50 +00001128 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001129 }
Chris Lattner76e68962009-01-26 06:19:46 +00001130}
1131
1132
Chris Lattner38d7fd22009-01-26 05:30:54 +00001133/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1134///
Mike Stump11289f42009-09-09 15:08:12 +00001135void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001136 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001137 // PTH doesn't emit #warning or #error directives.
1138 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001139 return CurPTHLexer->DiscardToEndOfLine();
1140
Chris Lattnerf64b3522008-03-09 01:54:53 +00001141 // Read the rest of the line raw. We do this because we don't want macros
1142 // to be expanded and we don't require that the tokens be valid preprocessing
1143 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1144 // collapse multiple consequtive white space between tokens, but this isn't
1145 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001146 SmallString<128> Message;
1147 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001148
1149 // Find the first non-whitespace character, so that we can make the
1150 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001151 StringRef Msg = Message.str().ltrim(" ");
1152
Chris Lattner100c65e2009-01-26 05:29:08 +00001153 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001154 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001155 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001156 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001157}
1158
1159/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1160///
1161void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1162 // Yes, this directive is an extension.
1163 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001164
Chris Lattnerf64b3522008-03-09 01:54:53 +00001165 // Read the string argument.
1166 Token StrTok;
1167 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Chris Lattnerf64b3522008-03-09 01:54:53 +00001169 // If the token kind isn't a string, it's a malformed directive.
1170 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001171 StrTok.isNot(tok::wide_string_literal)) {
1172 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001173 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001174 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001175 return;
1176 }
Mike Stump11289f42009-09-09 15:08:12 +00001177
Richard Smithd67aea22012-03-06 03:21:47 +00001178 if (StrTok.hasUDSuffix()) {
1179 Diag(StrTok, diag::err_invalid_string_udl);
1180 return DiscardUntilEndOfDirective();
1181 }
1182
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001183 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001184 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001185
Douglas Gregordc970f02010-03-16 22:30:13 +00001186 if (Callbacks) {
1187 bool Invalid = false;
1188 std::string Str = getSpelling(StrTok, &Invalid);
1189 if (!Invalid)
1190 Callbacks->Ident(Tok.getLocation(), Str);
1191 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001192}
1193
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001194/// \brief Handle a #public directive.
1195void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001196 Token MacroNameTok;
1197 ReadMacroName(MacroNameTok, 2);
1198
1199 // Error reading macro name? If so, diagnostic already issued.
1200 if (MacroNameTok.is(tok::eod))
1201 return;
1202
Douglas Gregor663b48f2012-01-03 19:48:16 +00001203 // Check to see if this is the last token on the #__public_macro line.
1204 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001205
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001206 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001207 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001208 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001209
1210 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001211 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001212 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001213 return;
1214 }
1215
1216 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001217 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1218 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001219}
1220
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001221/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001222void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1223 Token MacroNameTok;
1224 ReadMacroName(MacroNameTok, 2);
1225
1226 // Error reading macro name? If so, diagnostic already issued.
1227 if (MacroNameTok.is(tok::eod))
1228 return;
1229
Douglas Gregor663b48f2012-01-03 19:48:16 +00001230 // Check to see if this is the last token on the #__private_macro line.
1231 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001232
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001233 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001234 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001235 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001236
1237 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001238 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001239 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001240 return;
1241 }
1242
1243 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001244 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1245 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001246}
1247
Chris Lattnerf64b3522008-03-09 01:54:53 +00001248//===----------------------------------------------------------------------===//
1249// Preprocessor Include Directive Handling.
1250//===----------------------------------------------------------------------===//
1251
1252/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001253/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001254/// true if the input filename was in <>'s or false if it were in ""'s. The
1255/// caller is expected to provide a buffer that is large enough to hold the
1256/// spelling of the filename, but is also expected to handle the case when
1257/// this method decides to use a different buffer.
1258bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001259 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001260 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001261 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001262
Chris Lattnerf64b3522008-03-09 01:54:53 +00001263 // Make sure the filename is <x> or "x".
1264 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001265 if (Buffer[0] == '<') {
1266 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001267 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001268 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001269 return true;
1270 }
1271 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001272 } else if (Buffer[0] == '"') {
1273 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001274 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001275 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001276 return true;
1277 }
1278 isAngled = false;
1279 } else {
1280 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001281 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001282 return true;
1283 }
Mike Stump11289f42009-09-09 15:08:12 +00001284
Chris Lattnerf64b3522008-03-09 01:54:53 +00001285 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001286 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001287 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001288 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001289 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001290 }
Mike Stump11289f42009-09-09 15:08:12 +00001291
Chris Lattnerf64b3522008-03-09 01:54:53 +00001292 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001293 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001294 return isAngled;
1295}
1296
James Dennett4a4f72d2013-11-27 01:27:40 +00001297// \brief Handle cases where the \#include name is expanded from a macro
1298// as multiple tokens, which need to be glued together.
1299//
1300// This occurs for code like:
1301// \code
1302// \#define FOO <a/b.h>
1303// \#include FOO
1304// \endcode
1305// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1306//
1307// This code concatenates and consumes tokens up to the '>' token. It returns
1308// false if the > was found, otherwise it returns true if it finds and consumes
1309// the EOD marker.
1310bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001311 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001312 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001313
John Thompsonb5353522009-10-30 13:49:06 +00001314 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001315 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001316 End = CurTok.getLocation();
1317
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001318 // FIXME: Provide code completion for #includes.
1319 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001320 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001321 Lex(CurTok);
1322 continue;
1323 }
1324
Chris Lattnerf64b3522008-03-09 01:54:53 +00001325 // Append the spelling of this token to the buffer. If there was a space
1326 // before it, add it now.
1327 if (CurTok.hasLeadingSpace())
1328 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001329
Chris Lattnerf64b3522008-03-09 01:54:53 +00001330 // Get the spelling of the token, directly into FilenameBuffer if possible.
1331 unsigned PreAppendSize = FilenameBuffer.size();
1332 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001333
Chris Lattnerf64b3522008-03-09 01:54:53 +00001334 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001335 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001336
Chris Lattnerf64b3522008-03-09 01:54:53 +00001337 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1338 if (BufPtr != &FilenameBuffer[PreAppendSize])
1339 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattnerf64b3522008-03-09 01:54:53 +00001341 // Resize FilenameBuffer to the correct size.
1342 if (CurTok.getLength() != ActualLen)
1343 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001344
Chris Lattnerf64b3522008-03-09 01:54:53 +00001345 // If we found the '>' marker, return success.
1346 if (CurTok.is(tok::greater))
1347 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001348
John Thompsonb5353522009-10-30 13:49:06 +00001349 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001350 }
1351
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001352 // If we hit the eod marker, emit an error and return true so that the caller
1353 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001354 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001355 return true;
1356}
1357
Richard Smith34f30512013-11-23 04:06:09 +00001358/// \brief Push a token onto the token stream containing an annotation.
1359static void EnterAnnotationToken(Preprocessor &PP,
1360 SourceLocation Begin, SourceLocation End,
1361 tok::TokenKind Kind, void *AnnotationVal) {
1362 Token *Tok = new Token[1];
1363 Tok[0].startToken();
1364 Tok[0].setKind(Kind);
1365 Tok[0].setLocation(Begin);
1366 Tok[0].setAnnotationEndLoc(End);
1367 Tok[0].setAnnotationValue(AnnotationVal);
1368 PP.EnterTokenStream(Tok, 1, true, true);
1369}
1370
James Dennettf6333ac2012-06-22 05:46:07 +00001371/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1372/// the file to be included from the lexer, then include it! This is a common
1373/// routine with functionality shared between \#include, \#include_next and
1374/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001375/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001376void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1377 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001378 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001379 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001380 bool isImport) {
1381
1382 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001383 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001384
Chris Lattnerf64b3522008-03-09 01:54:53 +00001385 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001386 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001387 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001388 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001389 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001390
Chris Lattnerf64b3522008-03-09 01:54:53 +00001391 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001392 case tok::eod:
1393 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001394 return;
Mike Stump11289f42009-09-09 15:08:12 +00001395
Chris Lattnerf64b3522008-03-09 01:54:53 +00001396 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001397 case tok::string_literal:
1398 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001399 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001400 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001401 break;
Mike Stump11289f42009-09-09 15:08:12 +00001402
Chris Lattnerf64b3522008-03-09 01:54:53 +00001403 case tok::less:
1404 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1405 // case, glue the tokens together into FilenameBuffer and interpret those.
1406 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001407 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001408 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001409 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001410 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001411 break;
1412 default:
1413 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1414 DiscardUntilEndOfDirective();
1415 return;
1416 }
Mike Stump11289f42009-09-09 15:08:12 +00001417
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001418 CharSourceRange FilenameRange
1419 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001420 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001421 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001422 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001423 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1424 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001425 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001426 DiscardUntilEndOfDirective();
1427 return;
1428 }
Mike Stump11289f42009-09-09 15:08:12 +00001429
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001430 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001431 // we allow macros that expand to nothing after the filename, because this
1432 // falls into the category of "#include pp-tokens new-line" specified in
1433 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001434 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001435
1436 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001437 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1438 Diag(FilenameTok, diag::err_pp_include_too_deep);
1439 return;
1440 }
Mike Stump11289f42009-09-09 15:08:12 +00001441
John McCall32f5fe12011-09-30 05:12:12 +00001442 // Complain about attempts to #include files in an audit pragma.
1443 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1444 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1445 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1446
1447 // Immediately leave the pragma.
1448 PragmaARCCFCodeAuditedLoc = SourceLocation();
1449 }
1450
Aaron Ballman611306e2012-03-02 22:51:54 +00001451 if (HeaderInfo.HasIncludeAliasMap()) {
1452 // Map the filename with the brackets still attached. If the name doesn't
1453 // map to anything, fall back on the filename we've already gotten the
1454 // spelling for.
1455 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1456 if (!NewName.empty())
1457 Filename = NewName;
1458 }
1459
Chris Lattnerf64b3522008-03-09 01:54:53 +00001460 // Search include directories.
1461 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001462 SmallString<1024> SearchPath;
1463 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001464 // We get the raw path only if we have 'Callbacks' to which we later pass
1465 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001466 ModuleMap::KnownHeader SuggestedModule;
1467 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001468 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001469 if (LangOpts.MSVCCompat) {
1470 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001471#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001472 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001473#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001474 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001475 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001476 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001477 isAngled, LookupFrom, LookupFromFile, CurDir,
1478 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001479 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : nullptr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001480
Douglas Gregor11729f02011-11-30 18:12:06 +00001481 if (Callbacks) {
1482 if (!File) {
1483 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001484 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001485 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1486 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1487 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001488 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001489 HeaderInfo.AddSearchPath(DL, isAngled);
1490
1491 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001492 File = LookupFile(
1493 FilenameLoc,
1494 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1495 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
1496 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1497 : nullptr,
1498 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001499 }
1500 }
1501 }
1502
Daniel Jasper07e6c402013-08-05 20:26:17 +00001503 if (!SuggestedModule || !getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001504 // Notify the callback object that we've seen an inclusion directive.
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001505 Callbacks->InclusionDirective(HashLoc, IncludeTok,
1506 LangOpts.MSVCCompat ? NormalizedPath.c_str()
1507 : Filename,
1508 isAngled, FilenameRange, File, SearchPath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001509 RelativePath, /*ImportedModule=*/nullptr);
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001510 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001511 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001512
1513 if (!File) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001514 if (!SuppressIncludeNotFoundError) {
1515 // If the file could not be located and it was included via angle
1516 // brackets, we can attempt a lookup as though it were a quoted path to
1517 // provide the user with a possible fixit.
1518 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001519 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001520 FilenameLoc,
1521 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1522 LookupFrom, LookupFromFile, CurDir,
1523 Callbacks ? &SearchPath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001524 Callbacks ? &RelativePath : nullptr,
1525 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1526 : nullptr);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001527 if (File) {
1528 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1529 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1530 Filename <<
1531 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1532 }
1533 }
1534 // If the file is still not found, just go with the vanilla diagnostic
1535 if (!File)
1536 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1537 }
1538 if (!File)
1539 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001540 }
1541
Douglas Gregor97eec242011-09-15 22:00:41 +00001542 // If we are supposed to import a module rather than including the header,
1543 // do so now.
Ben Langmuirb537a3a2014-07-23 15:30:23 +00001544 if (SuggestedModule && getLangOpts().Modules &&
1545 SuggestedModule.getModule()->getTopLevelModuleName() !=
1546 getLangOpts().ImplementationOfModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001547 // Compute the module access path corresponding to this module.
1548 // FIXME: Should we have a second loadModule() overload to avoid this
1549 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001550 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001551 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001552 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1553 FilenameTok.getLocation()));
1554 std::reverse(Path.begin(), Path.end());
1555
Douglas Gregor41e115a2011-11-30 18:02:36 +00001556 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001557 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001558 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1559 if (I)
1560 PathString += '.';
1561 PathString += Path[I].first->getName();
1562 }
1563 int IncludeKind = 0;
1564
1565 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1566 case tok::pp_include:
1567 IncludeKind = 0;
1568 break;
1569
1570 case tok::pp_import:
1571 IncludeKind = 1;
1572 break;
1573
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001574 case tok::pp_include_next:
1575 IncludeKind = 2;
1576 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001577
1578 case tok::pp___include_macros:
1579 IncludeKind = 3;
1580 break;
1581
1582 default:
1583 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001584 }
1585
Douglas Gregor2537a362011-12-08 17:01:29 +00001586 // Determine whether we are actually building the module that this
1587 // include directive maps to.
1588 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001589 = Path[0].first->getName() == getLangOpts().CurrentModule;
Richard Smith34f30512013-11-23 04:06:09 +00001590
David Blaikiebbafb8a2012-03-11 07:00:24 +00001591 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001592 // If we're not building the imported module, warn that we're going
1593 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001594 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001595 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1596 /*IsTokenRange=*/false);
1597 Diag(HashLoc, diag::warn_auto_module_import)
1598 << IncludeKind << PathString
1599 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001600 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001601 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001602
Richard Smithce587f52013-11-15 04:24:58 +00001603 // Load the module. Only make macros visible. We'll make the declarations
1604 // visible when the parser gets here.
1605 Module::NameVisibilityKind Visibility = Module::MacrosVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001606 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001607 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1608 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001609 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001610 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001611
1612 if (!Imported && hadModuleLoaderFatalFailure()) {
1613 // With a fatal failure in the module loader, we abort parsing.
1614 Token &Result = IncludeTok;
1615 if (CurLexer) {
1616 Result.startToken();
1617 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1618 CurLexer->cutOffLexing();
1619 } else {
1620 assert(CurPTHLexer && "#include but no current lexer set!");
1621 CurPTHLexer->getEOF(Result);
1622 }
1623 return;
1624 }
Richard Smithce587f52013-11-15 04:24:58 +00001625
Douglas Gregor2537a362011-12-08 17:01:29 +00001626 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001627 if (!BuildingImportedModule && Imported) {
1628 if (Callbacks) {
1629 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1630 FilenameRange, File,
1631 SearchPath, RelativePath, Imported);
1632 }
Richard Smithce587f52013-11-15 04:24:58 +00001633
1634 if (IncludeKind != 3) {
1635 // Let the parser know that we hit a module import, and it should
1636 // make the module visible.
1637 // FIXME: Produce this as the current token directly, rather than
1638 // allocating a new token for it.
Richard Smith34f30512013-11-23 04:06:09 +00001639 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include,
1640 Imported);
Richard Smithce587f52013-11-15 04:24:58 +00001641 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001642 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001643 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001644
1645 // If we failed to find a submodule that we expected to find, we can
1646 // continue. Otherwise, there's an error in the included file, so we
1647 // don't want to include it.
1648 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1649 return;
1650 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001651 }
1652
1653 if (Callbacks && SuggestedModule) {
1654 // We didn't notify the callback object that we've seen an inclusion
1655 // directive before. Now that we are parsing the include normally and not
1656 // turning it to a module import, notify the callback object.
1657 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1658 FilenameRange, File,
1659 SearchPath, RelativePath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001660 /*ImportedModule=*/nullptr);
Douglas Gregor97eec242011-09-15 22:00:41 +00001661 }
1662
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001663 // The #included file will be considered to be a system header if either it is
1664 // in a system include directory, or if the #includer is a system include
1665 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001666 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001667 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001668 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001669
Chris Lattner72286d62010-04-19 20:44:31 +00001670 // Ask HeaderInfo if we should enter this #include file. If not, #including
1671 // this file will have no effect.
1672 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001673 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001674 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001675 return;
1676 }
1677
Chris Lattnerf64b3522008-03-09 01:54:53 +00001678 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001679 SourceLocation IncludePos = End;
1680 // If the filename string was the result of macro expansions, set the include
1681 // position on the file where it will be included and after the expansions.
1682 if (IncludePos.isMacroID())
1683 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1684 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001685 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001686
Richard Smith34f30512013-11-23 04:06:09 +00001687 // Determine if we're switching to building a new submodule, and which one.
1688 ModuleMap::KnownHeader BuildingModule;
1689 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) {
1690 Module *RequestingModule = getModuleForLocation(FilenameLoc);
1691 BuildingModule =
1692 HeaderInfo.getModuleMap().findModuleForHeader(File, RequestingModule);
1693 }
1694
1695 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00001696 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
1697 return;
Richard Smith34f30512013-11-23 04:06:09 +00001698
1699 // If we're walking into another part of the same module, let the parser
1700 // know that any future declarations are within that other submodule.
Richard Smith67294e22014-01-31 20:47:44 +00001701 if (BuildingModule) {
1702 assert(!CurSubmodule && "should not have marked this as a module yet");
1703 CurSubmodule = BuildingModule.getModule();
1704
Richard Smith34f30512013-11-23 04:06:09 +00001705 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin,
Richard Smith67294e22014-01-31 20:47:44 +00001706 CurSubmodule);
1707 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001708}
1709
James Dennettf6333ac2012-06-22 05:46:07 +00001710/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001711///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001712void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1713 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001714 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001715
Chris Lattnerf64b3522008-03-09 01:54:53 +00001716 // #include_next is like #include, except that we start searching after
1717 // the current found directory. If we can't do this, issue a
1718 // diagnostic.
1719 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00001720 const FileEntry *LookupFromFile = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001721 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001722 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001723 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001724 } else if (CurSubmodule) {
1725 // Start looking up in the directory *after* the one in which the current
1726 // file would be found, if any.
1727 assert(CurPPLexer && "#include_next directive in macro?");
1728 LookupFromFile = CurPPLexer->getFileEntry();
1729 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001730 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001731 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1732 } else {
1733 // Start looking up in the next directory.
1734 ++Lookup;
1735 }
Mike Stump11289f42009-09-09 15:08:12 +00001736
Richard Smith25d50752014-10-20 00:15:49 +00001737 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
1738 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001739}
1740
James Dennettf6333ac2012-06-22 05:46:07 +00001741/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001742void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1743 // The Microsoft #import directive takes a type library and generates header
1744 // files from it, and includes those. This is beyond the scope of what clang
1745 // does, so we ignore it and error out. However, #import can optionally have
1746 // trailing attributes that span multiple lines. We're going to eat those
1747 // so we can continue processing from there.
1748 Diag(Tok, diag::err_pp_import_directive_ms );
1749
1750 // Read tokens until we get to the end of the directive. Note that the
1751 // directive can be split over multiple lines using the backslash character.
1752 DiscardUntilEndOfDirective();
1753}
1754
James Dennettf6333ac2012-06-22 05:46:07 +00001755/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001756///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001757void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1758 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001759 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00001760 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00001761 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001762 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001763 }
Richard Smith25d50752014-10-20 00:15:49 +00001764 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001765}
1766
Chris Lattner58a1eb02009-04-08 18:46:40 +00001767/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1768/// pseudo directive in the predefines buffer. This handles it by sucking all
1769/// tokens through the preprocessor and discarding them (only keeping the side
1770/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001771void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1772 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001773 // This directive should only occur in the predefines buffer. If not, emit an
1774 // error and reject it.
1775 SourceLocation Loc = IncludeMacrosTok.getLocation();
1776 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1777 Diag(IncludeMacrosTok.getLocation(),
1778 diag::pp_include_macros_out_of_predefines);
1779 DiscardUntilEndOfDirective();
1780 return;
1781 }
Mike Stump11289f42009-09-09 15:08:12 +00001782
Chris Lattnere01d82b2009-04-08 20:53:24 +00001783 // Treat this as a normal #include for checking purposes. If this is
1784 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00001785 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00001786
Chris Lattnere01d82b2009-04-08 20:53:24 +00001787 Token TmpTok;
1788 do {
1789 Lex(TmpTok);
1790 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1791 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001792}
1793
Chris Lattnerf64b3522008-03-09 01:54:53 +00001794//===----------------------------------------------------------------------===//
1795// Preprocessor Macro Directive Handling.
1796//===----------------------------------------------------------------------===//
1797
1798/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1799/// definition has just been read. Lex the rest of the arguments and the
1800/// closing ), updating MI with what we learn. Return true if an error occurs
1801/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001802bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001803 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001804
Chris Lattnerf64b3522008-03-09 01:54:53 +00001805 while (1) {
1806 LexUnexpandedToken(Tok);
1807 switch (Tok.getKind()) {
1808 case tok::r_paren:
1809 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001810 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001811 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001812 // Otherwise we have #define FOO(A,)
1813 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1814 return true;
1815 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001816 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001817 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001818 diag::warn_cxx98_compat_variadic_macro :
1819 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001820
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001821 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1822 if (LangOpts.OpenCL) {
1823 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1824 return true;
1825 }
1826
Chris Lattnerf64b3522008-03-09 01:54:53 +00001827 // Lex the token after the identifier.
1828 LexUnexpandedToken(Tok);
1829 if (Tok.isNot(tok::r_paren)) {
1830 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1831 return true;
1832 }
1833 // Add the __VA_ARGS__ identifier as an argument.
1834 Arguments.push_back(Ident__VA_ARGS__);
1835 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001836 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001837 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001838 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001839 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1840 return true;
1841 default:
1842 // Handle keywords and identifiers here to accept things like
1843 // #define Foo(for) for.
1844 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00001845 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846 // #define X(1
1847 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1848 return true;
1849 }
1850
1851 // If this is already used as an argument, it is used multiple times (e.g.
1852 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001853 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001854 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001855 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001856 return true;
1857 }
Mike Stump11289f42009-09-09 15:08:12 +00001858
Chris Lattnerf64b3522008-03-09 01:54:53 +00001859 // Add the argument to the macro info.
1860 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Chris Lattnerf64b3522008-03-09 01:54:53 +00001862 // Lex the token after the identifier.
1863 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001864
Chris Lattnerf64b3522008-03-09 01:54:53 +00001865 switch (Tok.getKind()) {
1866 default: // #define X(A B
1867 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1868 return true;
1869 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001870 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001871 return false;
1872 case tok::comma: // #define X(A,
1873 break;
1874 case tok::ellipsis: // #define X(A... -> GCC extension
1875 // Diagnose extension.
1876 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001877
Chris Lattnerf64b3522008-03-09 01:54:53 +00001878 // Lex the token after the identifier.
1879 LexUnexpandedToken(Tok);
1880 if (Tok.isNot(tok::r_paren)) {
1881 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1882 return true;
1883 }
Mike Stump11289f42009-09-09 15:08:12 +00001884
Chris Lattnerf64b3522008-03-09 01:54:53 +00001885 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001886 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001887 return false;
1888 }
1889 }
1890 }
1891}
1892
James Dennettf6333ac2012-06-22 05:46:07 +00001893/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001894/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001895void Preprocessor::HandleDefineDirective(Token &DefineTok,
1896 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001897 ++NumDefined;
1898
1899 Token MacroNameTok;
1900 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001901
Chris Lattnerf64b3522008-03-09 01:54:53 +00001902 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001903 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001904 return;
1905
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001906 Token LastTok = MacroNameTok;
1907
Chris Lattnerf64b3522008-03-09 01:54:53 +00001908 // If we are supposed to keep comments in #defines, reenable comment saving
1909 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001910 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001911
Chris Lattnerf64b3522008-03-09 01:54:53 +00001912 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001913 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001914
Chris Lattnerf64b3522008-03-09 01:54:53 +00001915 Token Tok;
1916 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001917
Chris Lattnerf64b3522008-03-09 01:54:53 +00001918 // If this is a function-like macro definition, parse the argument list,
1919 // marking each of the identifiers as being used as macro arguments. Also,
1920 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001921 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001922 if (ImmediatelyAfterHeaderGuard) {
1923 // Save this macro information since it may part of a header guard.
1924 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
1925 MacroNameTok.getLocation());
1926 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001927 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001928 } else if (Tok.hasLeadingSpace()) {
1929 // This is a normal token with leading space. Clear the leading space
1930 // marker on the first token to get proper expansion.
1931 Tok.clearFlag(Token::LeadingSpace);
1932 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001933 // This is a function-like macro definition. Read the argument list.
1934 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001935 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001936 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001937 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001938 DiscardUntilEndOfDirective();
1939 return;
1940 }
1941
Chris Lattner249c38b2009-04-19 18:26:34 +00001942 // If this is a definition of a variadic C99 function-like macro, not using
1943 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001944
Chris Lattner249c38b2009-04-19 18:26:34 +00001945 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1946 // This gets unpoisoned where it is allowed.
1947 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1948 if (MI->isC99Varargs())
1949 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001950
Chris Lattnerf64b3522008-03-09 01:54:53 +00001951 // Read the first token after the arg list for down below.
1952 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001953 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001954 // C99 requires whitespace between the macro definition and the body. Emit
1955 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001956 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001957 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001958 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1959 // first character of a replacement list is not a character required by
1960 // subclause 5.2.1, then there shall be white-space separation between the
1961 // identifier and the replacement list.". 5.2.1 lists this set:
1962 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1963 // is irrelevant here.
1964 bool isInvalid = false;
1965 if (Tok.is(tok::at)) // @ is not in the list above.
1966 isInvalid = true;
1967 else if (Tok.is(tok::unknown)) {
1968 // If we have an unknown token, it is something strange like "`". Since
1969 // all of valid characters would have lexed into a single character
1970 // token of some sort, we know this is not a valid case.
1971 isInvalid = true;
1972 }
1973 if (isInvalid)
1974 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1975 else
1976 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001977 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001978
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001979 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001980 LastTok = Tok;
1981
Chris Lattnerf64b3522008-03-09 01:54:53 +00001982 // Read the rest of the macro body.
1983 if (MI->isObjectLike()) {
1984 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001985 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001986 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001987 MI->AddTokenToBody(Tok);
1988 // Get the next token of the macro.
1989 LexUnexpandedToken(Tok);
1990 }
Mike Stump11289f42009-09-09 15:08:12 +00001991
Chris Lattnerf64b3522008-03-09 01:54:53 +00001992 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001993 // Otherwise, read the body of a function-like macro. While we are at it,
1994 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1995 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001996 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001997 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001998
Eli Friedman14d3c792012-11-14 02:18:46 +00001999 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002000 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002001
Chris Lattnerf64b3522008-03-09 01:54:53 +00002002 // Get the next token of the macro.
2003 LexUnexpandedToken(Tok);
2004 continue;
2005 }
Mike Stump11289f42009-09-09 15:08:12 +00002006
Richard Smith701a3522013-07-09 01:00:29 +00002007 // If we're in -traditional mode, then we should ignore stringification
2008 // and token pasting. Mark the tokens as unknown so as not to confuse
2009 // things.
2010 if (getLangOpts().TraditionalCPP) {
2011 Tok.setKind(tok::unknown);
2012 MI->AddTokenToBody(Tok);
2013
2014 // Get the next token of the macro.
2015 LexUnexpandedToken(Tok);
2016 continue;
2017 }
2018
Eli Friedman14d3c792012-11-14 02:18:46 +00002019 if (Tok.is(tok::hashhash)) {
2020
2021 // If we see token pasting, check if it looks like the gcc comma
2022 // pasting extension. We'll use this information to suppress
2023 // diagnostics later on.
2024
2025 // Get the next token of the macro.
2026 LexUnexpandedToken(Tok);
2027
2028 if (Tok.is(tok::eod)) {
2029 MI->AddTokenToBody(LastTok);
2030 break;
2031 }
2032
2033 unsigned NumTokens = MI->getNumTokens();
2034 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2035 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2036 MI->setHasCommaPasting();
2037
David Majnemer76faf1f2013-11-05 09:30:17 +00002038 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002039 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002040 continue;
2041 }
2042
Chris Lattnerf64b3522008-03-09 01:54:53 +00002043 // Get the next token of the macro.
2044 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002045
Chris Lattner83bd8282009-05-25 17:16:10 +00002046 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002047 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002048 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2049
2050 // If this is assembler-with-cpp mode, we accept random gibberish after
2051 // the '#' because '#' is often a comment character. However, change
2052 // the kind of the token to tok::unknown so that the preprocessor isn't
2053 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002054 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002055 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002056 MI->AddTokenToBody(LastTok);
2057 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002058 } else {
2059 Diag(Tok, diag::err_pp_stringize_not_parameter);
Mike Stump11289f42009-09-09 15:08:12 +00002060
Chris Lattner83bd8282009-05-25 17:16:10 +00002061 // Disable __VA_ARGS__ again.
2062 Ident__VA_ARGS__->setIsPoisoned(true);
2063 return;
2064 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066
Chris Lattner83bd8282009-05-25 17:16:10 +00002067 // Things look ok, add the '#' and param name tokens to the macro.
2068 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002069 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002070 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002071
Chris Lattnerf64b3522008-03-09 01:54:53 +00002072 // Get the next token of the macro.
2073 LexUnexpandedToken(Tok);
2074 }
2075 }
Mike Stump11289f42009-09-09 15:08:12 +00002076
2077
Chris Lattnerf64b3522008-03-09 01:54:53 +00002078 // Disable __VA_ARGS__ again.
2079 Ident__VA_ARGS__->setIsPoisoned(true);
2080
Chris Lattner57540c52011-04-15 05:22:18 +00002081 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002082 // replacement list.
2083 unsigned NumTokens = MI->getNumTokens();
2084 if (NumTokens != 0) {
2085 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2086 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002087 return;
2088 }
2089 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2090 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002091 return;
2092 }
2093 }
Mike Stump11289f42009-09-09 15:08:12 +00002094
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002095 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002096
Chris Lattnerf64b3522008-03-09 01:54:53 +00002097 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002098 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002099 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002100 // It is very common for system headers to have tons of macro redefinitions
2101 // and for warnings to be disabled in system headers. If this is the case,
2102 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002103 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002104 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002105 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002106 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002107
Richard Smith7b242542013-03-06 00:46:00 +00002108 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2109 // C++ [cpp.predefined]p4, but allow it as an extension.
2110 if (OtherMI->isBuiltinMacro())
2111 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002112 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002113 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002114 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002115 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002116 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2117 << MacroNameTok.getIdentifierInfo();
2118 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2119 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002120 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002121 if (OtherMI->isWarnIfUnused())
2122 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002123 }
Mike Stump11289f42009-09-09 15:08:12 +00002124
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002125 DefMacroDirective *MD =
2126 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002127
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002128 assert(!MI->isUsed());
2129 // If we need warning for not using the macro, add its location in the
2130 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002131 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002132 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002133 MI->setIsWarnIfUnused(true);
2134 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2135 }
2136
Chris Lattner928e9092009-04-12 01:39:54 +00002137 // If the callbacks want to know, tell them about the macro definition.
2138 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002139 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002140}
2141
James Dennettf6333ac2012-06-22 05:46:07 +00002142/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002143///
2144void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2145 ++NumUndefined;
2146
2147 Token MacroNameTok;
2148 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00002149
Chris Lattnerf64b3522008-03-09 01:54:53 +00002150 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002151 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002152 return;
Mike Stump11289f42009-09-09 15:08:12 +00002153
Chris Lattnerf64b3522008-03-09 01:54:53 +00002154 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002155 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002156
Chris Lattnerf64b3522008-03-09 01:54:53 +00002157 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002158 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Craig Topperd2d442c2014-05-17 23:10:59 +00002159 const MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002160
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002161 // If the callbacks want to know, tell them about the macro #undef.
2162 // Note: no matter if the macro was defined or not.
2163 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002164 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002165
Chris Lattnerf64b3522008-03-09 01:54:53 +00002166 // If the macro is not defined, this is a noop undef, just return.
Craig Topperd2d442c2014-05-17 23:10:59 +00002167 if (!MI)
2168 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002169
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002170 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002171 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002172
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002173 if (MI->isWarnIfUnused())
2174 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2175
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002176 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2177 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002178}
2179
2180
2181//===----------------------------------------------------------------------===//
2182// Preprocessor Conditional Directive Handling.
2183//===----------------------------------------------------------------------===//
2184
James Dennettf6333ac2012-06-22 05:46:07 +00002185/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2186/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2187/// true if any tokens have been returned or pp-directives activated before this
2188/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002189///
2190void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2191 bool ReadAnyTokensBeforeDirective) {
2192 ++NumIf;
2193 Token DirectiveTok = Result;
2194
2195 Token MacroNameTok;
2196 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002197
Chris Lattnerf64b3522008-03-09 01:54:53 +00002198 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002199 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002200 // Skip code until we get to #endif. This helps with recovery by not
2201 // emitting an error when the #endif is reached.
2202 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2203 /*Foundnonskip*/false, /*FoundElse*/false);
2204 return;
2205 }
Mike Stump11289f42009-09-09 15:08:12 +00002206
Chris Lattnerf64b3522008-03-09 01:54:53 +00002207 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002208 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002209
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002210 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002211 MacroDirective *MD = getMacroDirective(MII);
Craig Topperd2d442c2014-05-17 23:10:59 +00002212 MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002213
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002214 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002215 // If the start of a top-level #ifdef and if the macro is not defined,
2216 // inform MIOpt that this might be the start of a proper include guard.
2217 // Otherwise it is some other form of unknown conditional which we can't
2218 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002219 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002220 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002221 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002222 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002223 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002224 }
2225
Chris Lattnerf64b3522008-03-09 01:54:53 +00002226 // If there is a macro, process it.
2227 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002228 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002229
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002230 if (Callbacks) {
2231 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002232 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002233 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002234 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002235 }
2236
Chris Lattnerf64b3522008-03-09 01:54:53 +00002237 // Should we include the stuff contained by this directive?
2238 if (!MI == isIfndef) {
2239 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002240 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2241 /*wasskip*/false, /*foundnonskip*/true,
2242 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002243 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002244 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002245 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002246 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002247 /*FoundElse*/false);
2248 }
2249}
2250
James Dennettf6333ac2012-06-22 05:46:07 +00002251/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002252///
2253void Preprocessor::HandleIfDirective(Token &IfToken,
2254 bool ReadAnyTokensBeforeDirective) {
2255 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002256
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002257 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002258 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002259 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2260 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2261 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002262
2263 // If this condition is equivalent to #ifndef X, and if this is the first
2264 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002265 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002266 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002267 // FIXME: Pass in the location of the macro name, not the 'if' token.
2268 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002269 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002270 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002271 }
2272
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002273 if (Callbacks)
2274 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002275 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002276 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002277
Chris Lattnerf64b3522008-03-09 01:54:53 +00002278 // Should we include the stuff contained by this directive?
2279 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002280 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002281 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002282 /*foundnonskip*/true, /*foundelse*/false);
2283 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002284 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002285 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002286 /*FoundElse*/false);
2287 }
2288}
2289
James Dennettf6333ac2012-06-22 05:46:07 +00002290/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002291///
2292void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2293 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002294
Chris Lattnerf64b3522008-03-09 01:54:53 +00002295 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002296 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002297
Chris Lattnerf64b3522008-03-09 01:54:53 +00002298 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002299 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002300 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002301 Diag(EndifToken, diag::err_pp_endif_without_if);
2302 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002303 }
Mike Stump11289f42009-09-09 15:08:12 +00002304
Chris Lattnerf64b3522008-03-09 01:54:53 +00002305 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002306 if (CurPPLexer->getConditionalStackDepth() == 0)
2307 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002308
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002309 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002310 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002311
2312 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002313 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002314}
2315
James Dennettf6333ac2012-06-22 05:46:07 +00002316/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002317///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002318void Preprocessor::HandleElseDirective(Token &Result) {
2319 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002320
Chris Lattnerf64b3522008-03-09 01:54:53 +00002321 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002322 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002323
Chris Lattnerf64b3522008-03-09 01:54:53 +00002324 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002325 if (CurPPLexer->popConditionalLevel(CI)) {
2326 Diag(Result, diag::pp_err_else_without_if);
2327 return;
2328 }
Mike Stump11289f42009-09-09 15:08:12 +00002329
Chris Lattnerf64b3522008-03-09 01:54:53 +00002330 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002331 if (CurPPLexer->getConditionalStackDepth() == 0)
2332 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002333
2334 // If this is a #else with a #else before it, report the error.
2335 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002336
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002337 if (Callbacks)
2338 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2339
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002340 // Finally, skip the rest of the contents of this block.
2341 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002342 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002343}
2344
James Dennettf6333ac2012-06-22 05:46:07 +00002345/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002346///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002347void Preprocessor::HandleElifDirective(Token &ElifToken) {
2348 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002349
Chris Lattnerf64b3522008-03-09 01:54:53 +00002350 // #elif directive in a non-skipping conditional... start skipping.
2351 // We don't care what the condition is, because we will always skip it (since
2352 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002353 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002354 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002355 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002356
2357 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002358 if (CurPPLexer->popConditionalLevel(CI)) {
2359 Diag(ElifToken, diag::pp_err_elif_without_if);
2360 return;
2361 }
Mike Stump11289f42009-09-09 15:08:12 +00002362
Chris Lattnerf64b3522008-03-09 01:54:53 +00002363 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002364 if (CurPPLexer->getConditionalStackDepth() == 0)
2365 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002366
Chris Lattnerf64b3522008-03-09 01:54:53 +00002367 // If this is a #elif with a #else before it, report the error.
2368 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002369
2370 if (Callbacks)
2371 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002372 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002373 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002374
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002375 // Finally, skip the rest of the contents of this block.
2376 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002377 /*FoundElse*/CI.FoundElse,
2378 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002379}