blob: a0ec2bf78c5f3b37c3a8cdd48c76faf59b9d07ef [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"
Saleem Abdulrasool19803412014-03-11 22:41:45 +000028#include "llvm/Support/FileSystem.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() {
Ted Kremenekc8456f82010-10-19 22:15:20 +000037 MacroInfoChain *MIChain;
Mike Stump11289f42009-09-09 15:08:12 +000038
Ted Kremenekc8456f82010-10-19 22:15:20 +000039 if (MICache) {
40 MIChain = MICache;
41 MICache = MICache->Next;
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000042 }
Ted Kremenekc8456f82010-10-19 22:15:20 +000043 else {
44 MIChain = BP.Allocate<MacroInfoChain>();
45 }
46
47 MIChain->Next = MIChainHead;
Craig Topperd2d442c2014-05-17 23:10:59 +000048 MIChain->Prev = nullptr;
Ted Kremenekc8456f82010-10-19 22:15:20 +000049 if (MIChainHead)
50 MIChainHead->Prev = MIChain;
51 MIChainHead = MIChain;
52
53 return &(MIChain->MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000054}
55
56MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
57 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000058 new (MI) MacroInfo(L);
59 return MI;
60}
61
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000062MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
63 unsigned SubModuleID) {
Chandler Carruth06dde922014-03-02 13:02:01 +000064 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
65 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000066 DeserializedMacroInfoChain *MIChain =
67 BP.Allocate<DeserializedMacroInfoChain>();
68 MIChain->Next = DeserialMIChainHead;
69 DeserialMIChainHead = MIChain;
70
71 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000072 new (MI) MacroInfo(L);
73 MI->FromASTFile = true;
74 MI->setOwningModuleID(SubModuleID);
75 return MI;
76}
77
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000078DefMacroDirective *
79Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
80 bool isImported) {
81 DefMacroDirective *MD = BP.Allocate<DefMacroDirective>();
82 new (MD) DefMacroDirective(MI, Loc, isImported);
83 return MD;
84}
85
86UndefMacroDirective *
87Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
88 UndefMacroDirective *MD = BP.Allocate<UndefMacroDirective>();
89 new (MD) UndefMacroDirective(UndefLoc);
90 return MD;
91}
92
93VisibilityMacroDirective *
94Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
95 bool isPublic) {
96 VisibilityMacroDirective *MD = BP.Allocate<VisibilityMacroDirective>();
97 new (MD) VisibilityMacroDirective(Loc, isPublic);
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000098 return MD;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000099}
100
James Dennettf6333ac2012-06-22 05:46:07 +0000101/// \brief Release the specified MacroInfo to be reused for allocating
102/// new MacroInfo objects.
Chris Lattner66b67d22010-08-18 16:08:51 +0000103void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
Ted Kremenekc8456f82010-10-19 22:15:20 +0000104 MacroInfoChain *MIChain = (MacroInfoChain*) MI;
105 if (MacroInfoChain *Prev = MIChain->Prev) {
106 MacroInfoChain *Next = MIChain->Next;
107 Prev->Next = Next;
108 if (Next)
109 Next->Prev = Prev;
110 }
111 else {
112 assert(MIChainHead == MIChain);
113 MIChainHead = MIChain->Next;
Craig Topperd2d442c2014-05-17 23:10:59 +0000114 MIChainHead->Prev = nullptr;
Ted Kremenekc8456f82010-10-19 22:15:20 +0000115 }
116 MIChain->Next = MICache;
117 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +0000118
Ted Kremenekc8456f82010-10-19 22:15:20 +0000119 MI->Destroy();
120}
Chris Lattner666f7a42009-02-20 22:19:20 +0000121
James Dennettf6333ac2012-06-22 05:46:07 +0000122/// \brief Read and discard all tokens remaining on the current line until
123/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000124void Preprocessor::DiscardUntilEndOfDirective() {
125 Token Tmp;
126 do {
127 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000128 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000129 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000130}
131
Alp Tokerb05e0b52014-05-21 06:13:51 +0000132bool Preprocessor::CheckMacroName(Token &MacroNameTok, char isDefineUndef) {
133 // Missing macro name?
134 if (MacroNameTok.is(tok::eod))
135 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
136
137 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
138 if (!II) {
139 bool Invalid = false;
140 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
141 if (Invalid)
142 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000143 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000144
Alp Tokerf33619c2014-05-31 03:38:08 +0000145 if (!II->isCPlusPlusOperatorKeyword())
146 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000147
Alp Tokere03e9e12014-05-31 16:32:22 +0000148 // C++ 2.5p2: Alternative tokens behave the same as its primary token
149 // except for their spellings.
150 Diag(MacroNameTok, getLangOpts().MicrosoftExt
151 ? diag::ext_pp_operator_used_as_macro_name
152 : diag::err_pp_operator_used_as_macro_name)
153 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000154
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000155 // Allow #defining |and| and friends for Microsoft compatibility or
156 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000157 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000158 }
159
160 if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
161 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
162 return Diag(MacroNameTok, diag::err_defined_macro_name);
163 }
164
165 if (isDefineUndef == 2 && II->hasMacroDefinition() &&
166 getMacroInfo(II)->isBuiltinMacro()) {
167 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
168 // and C++ [cpp.predefined]p4], but allow it as an extension.
169 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
170 }
171
172 // Okay, we got a good identifier.
173 return false;
174}
175
James Dennettf6333ac2012-06-22 05:46:07 +0000176/// \brief Lex and validate a macro name, which occurs after a
177/// \#define or \#undef.
178///
179/// This sets the token kind to eod and discards the rest
180/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
181/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
182/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000183void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
184 // Read the token, don't allow macro expansion on it.
185 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000186
Douglas Gregor12785102010-08-24 20:21:13 +0000187 if (MacroNameTok.is(tok::code_completion)) {
188 if (CodeComplete)
189 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000190 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000191 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000192 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000193
194 if (!CheckMacroName(MacroNameTok, isDefineUndef))
Chris Lattner907dfe92008-11-18 07:59:24 +0000195 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000196
197 // Invalid macro name, read and discard the rest of the line and set the
198 // token kind to tok::eod if necessary.
199 if (MacroNameTok.isNot(tok::eod)) {
200 MacroNameTok.setKind(tok::eod);
201 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000202 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000203}
204
James Dennettf6333ac2012-06-22 05:46:07 +0000205/// \brief Ensure that the next token is a tok::eod token.
206///
207/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000208/// true, then we consider macros that expand to zero tokens as being ok.
209void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000210 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000211 // Lex unexpanded tokens for most directives: macros might expand to zero
212 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
213 // #line) allow empty macros.
214 if (EnableMacros)
215 Lex(Tmp);
216 else
217 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000218
Chris Lattnerf64b3522008-03-09 01:54:53 +0000219 // There should be no tokens after the directive, but we allow them as an
220 // extension.
221 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
222 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000223
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000224 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000225 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000226 // or if this is a macro-style preprocessing directive, because it is more
227 // trouble than it is worth to insert /**/ and check that there is no /**/
228 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000229 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000230 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000231 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000232 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
233 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000234 DiscardUntilEndOfDirective();
235 }
236}
237
238
239
James Dennettf6333ac2012-06-22 05:46:07 +0000240/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
241/// decided that the subsequent tokens are in the \#if'd out portion of the
242/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000243/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000244/// this \#if directive, so \#else/\#elif blocks should never be entered.
245/// If ElseOk is true, then \#else directives are ok, if not, then we have
246/// already seen one so a \#else directive is a duplicate. When this returns,
247/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000248void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
249 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000250 bool FoundElse,
251 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000252 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000253 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000254
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000255 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000256 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000257
Ted Kremenek56572ab2008-12-12 18:34:08 +0000258 if (CurPTHLexer) {
259 PTHSkipExcludedConditionalBlock();
260 return;
261 }
Mike Stump11289f42009-09-09 15:08:12 +0000262
Chris Lattnerf64b3522008-03-09 01:54:53 +0000263 // Enter raw mode to disable identifier lookup (and thus macro expansion),
264 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000265 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000266 Token Tok;
267 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000268 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000269
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000270 if (Tok.is(tok::code_completion)) {
271 if (CodeComplete)
272 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000273 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000274 continue;
275 }
276
Chris Lattnerf64b3522008-03-09 01:54:53 +0000277 // If this is the end of the buffer, we have an error.
278 if (Tok.is(tok::eof)) {
279 // Emit errors for each unterminated conditional on the stack, including
280 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000281 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000282 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000283 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
284 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000285 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000286 }
287
Chris Lattnerf64b3522008-03-09 01:54:53 +0000288 // Just return and let the caller lex after this #include.
289 break;
290 }
Mike Stump11289f42009-09-09 15:08:12 +0000291
Chris Lattnerf64b3522008-03-09 01:54:53 +0000292 // If this token is not a preprocessor directive, just skip it.
293 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
294 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000295
Chris Lattnerf64b3522008-03-09 01:54:53 +0000296 // We just parsed a # character at the start of a line, so we're in
297 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000298 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000299 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000300 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000301
Mike Stump11289f42009-09-09 15:08:12 +0000302
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 // Read the next token, the directive flavor.
304 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattnerf64b3522008-03-09 01:54:53 +0000306 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
307 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000308 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000309 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000311 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000312 continue;
313 }
314
315 // If the first letter isn't i or e, it isn't intesting to us. We know that
316 // this is safe in the face of spelling differences, because there is no way
317 // to spell an i/e in a strange way that is another letter. Skipping this
318 // allows us to avoid looking up the identifier info for #define/#undef and
319 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000320 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000321
Alp Toker2d57cea2014-05-17 04:53:25 +0000322 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000323 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000324 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000325 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000326 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000327 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000328 continue;
329 }
Mike Stump11289f42009-09-09 15:08:12 +0000330
Chris Lattnerf64b3522008-03-09 01:54:53 +0000331 // Get the identifier name without trigraphs or embedded newlines. Note
332 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
333 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000334 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000335 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000336 if (!Tok.needsCleaning() && RI.size() < 20) {
337 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000338 } else {
339 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000340 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000341 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000342 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000343 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000344 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000345 continue;
346 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000347 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000348 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349 }
Mike Stump11289f42009-09-09 15:08:12 +0000350
Benjamin Kramer144884642009-12-31 13:32:38 +0000351 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000353 if (Sub.empty() || // "if"
354 Sub == "def" || // "ifdef"
355 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000356 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
357 // bother parsing the condition.
358 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000359 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000360 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000361 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000363 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000364 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000365 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000366 PPConditionalInfo CondInfo;
367 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000368 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000369 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000370 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000371
Chris Lattnerf64b3522008-03-09 01:54:53 +0000372 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000373 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000374 // Restore the value of LexingRawMode so that trailing comments
375 // are handled correctly, if we've reached the outermost block.
376 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000377 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000378 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000379 if (Callbacks)
380 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000381 break;
Richard Smithd0124572012-06-21 00:35:03 +0000382 } else {
383 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000384 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000385 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 // #else directive in a skipping conditional. If not in some other
387 // skipping conditional, and if #else hasn't already been seen, enter it
388 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000389 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000390
Chris Lattnerf64b3522008-03-09 01:54:53 +0000391 // If this is a #else with a #else before it, report the error.
392 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000393
Chris Lattnerf64b3522008-03-09 01:54:53 +0000394 // Note that we've seen a #else in this conditional.
395 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattnerf64b3522008-03-09 01:54:53 +0000397 // If the conditional is at the top level, and the #if block wasn't
398 // entered, enter the #else block now.
399 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
400 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000401 // Restore the value of LexingRawMode so that trailing comments
402 // are handled correctly.
403 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000404 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000405 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000406 if (Callbacks)
407 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000408 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000409 } else {
410 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000411 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000412 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000413 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000414
John Thompson17c35732013-12-04 20:19:30 +0000415 // If this is a #elif with a #else before it, report the error.
416 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
417
Chris Lattnerf64b3522008-03-09 01:54:53 +0000418 // If this is in a skipping block or if we're already handled this #if
419 // block, don't bother parsing the condition.
420 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
421 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000422 } else {
John Thompson17c35732013-12-04 20:19:30 +0000423 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000424 // Restore the value of LexingRawMode so that identifiers are
425 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000426 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
427 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000428 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000429 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000430 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000431 if (Callbacks) {
432 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000433 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000434 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000435 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000436 }
437 // If this condition is true, enter it!
438 if (CondValue) {
439 CondInfo.FoundNonSkip = true;
440 break;
441 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000442 }
443 }
444 }
Mike Stump11289f42009-09-09 15:08:12 +0000445
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000446 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000447 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000448 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000449 }
450
451 // Finally, if we are out of the conditional (saw an #endif or ran off the end
452 // of the file, just stop skipping and return to lexing whatever came after
453 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000454 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000455
456 if (Callbacks) {
457 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
458 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
459 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000460}
461
Ted Kremenek56572ab2008-12-12 18:34:08 +0000462void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000463
464 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000465 assert(CurPTHLexer);
466 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000467
Ted Kremenek56572ab2008-12-12 18:34:08 +0000468 // Skip to the next '#else', '#elif', or #endif.
469 if (CurPTHLexer->SkipBlock()) {
470 // We have reached an #endif. Both the '#' and 'endif' tokens
471 // have been consumed by the PTHLexer. Just pop off the condition level.
472 PPConditionalInfo CondInfo;
473 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000474 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000475 assert(!InCond && "Can't be skipping if not in a conditional!");
476 break;
477 }
Mike Stump11289f42009-09-09 15:08:12 +0000478
Ted Kremenek56572ab2008-12-12 18:34:08 +0000479 // We have reached a '#else' or '#elif'. Lex the next token to get
480 // the directive flavor.
481 Token Tok;
482 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000483
Ted Kremenek56572ab2008-12-12 18:34:08 +0000484 // We can actually look up the IdentifierInfo here since we aren't in
485 // raw mode.
486 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
487
488 if (K == tok::pp_else) {
489 // #else: Enter the else condition. We aren't in a nested condition
490 // since we skip those. We're always in the one matching the last
491 // blocked we skipped.
492 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
493 // Note that we've seen a #else in this conditional.
494 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000495
Ted Kremenek56572ab2008-12-12 18:34:08 +0000496 // If the #if block wasn't entered then enter the #else block now.
497 if (!CondInfo.FoundNonSkip) {
498 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000499
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000500 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000501 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000502 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000503 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000504
Ted Kremenek56572ab2008-12-12 18:34:08 +0000505 break;
506 }
Mike Stump11289f42009-09-09 15:08:12 +0000507
Ted Kremenek56572ab2008-12-12 18:34:08 +0000508 // Otherwise skip this block.
509 continue;
510 }
Mike Stump11289f42009-09-09 15:08:12 +0000511
Ted Kremenek56572ab2008-12-12 18:34:08 +0000512 assert(K == tok::pp_elif);
513 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
514
515 // If this is a #elif with a #else before it, report the error.
516 if (CondInfo.FoundElse)
517 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000518
Ted Kremenek56572ab2008-12-12 18:34:08 +0000519 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000520 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000521 if (CondInfo.FoundNonSkip)
522 continue;
523
524 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000525 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000526 CurPTHLexer->ParsingPreprocessorDirective = true;
527 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
528 CurPTHLexer->ParsingPreprocessorDirective = false;
529
530 // If this condition is true, enter it!
531 if (ShouldEnter) {
532 CondInfo.FoundNonSkip = true;
533 break;
534 }
535
536 // Otherwise, skip this block and go to the next one.
537 continue;
538 }
539}
540
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000541Module *Preprocessor::getModuleForLocation(SourceLocation FilenameLoc) {
542 ModuleMap &ModMap = HeaderInfo.getModuleMap();
543 if (SourceMgr.isInMainFile(FilenameLoc)) {
544 if (Module *CurMod = getCurrentModule())
545 return CurMod; // Compiling a module.
546 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
547 }
548 // Try to determine the module of the include directive.
Daniel Jasper88d86952013-12-03 20:30:36 +0000549 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
Manuel Klimek98a9a6c2014-03-19 10:22:36 +0000550 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(FilenameLoc));
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000551 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
552 // The include comes from a file.
553 return ModMap.findModuleForHeader(EntryOfIncl).getModule();
554 } else {
555 // The include does not come from a file,
556 // so it is probably a module compilation.
557 return getCurrentModule();
558 }
559}
560
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000561const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000562 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000563 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000564 bool isAngled,
565 const DirectoryLookup *FromDir,
566 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000567 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000568 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000569 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000570 bool SkipCache) {
Will Wilson0fafd342013-12-27 19:46:16 +0000571 // If the header lookup mechanism may be relative to the current inclusion
572 // stack, record the parent #includes.
573 SmallVector<const FileEntry *, 16> Includers;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000574 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000575 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000576 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000577
Chris Lattner022923a2009-02-04 19:45:07 +0000578 // If there is no file entry associated with this file, it must be the
579 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000580 // it won't be scanned for preprocessor directives. If we have the
581 // predefines buffer, resolve #include references (which come from the
582 // -include command line argument) as if they came from the main file, this
583 // affects file lookup etc.
Will Wilson0fafd342013-12-27 19:46:16 +0000584 if (!FileEnt)
585 FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
586
587 if (FileEnt)
588 Includers.push_back(FileEnt);
589
590 // MSVC searches the current include stack from top to bottom for
591 // headers included by quoted include directives.
592 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000593 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000594 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
595 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
596 if (IsFileLexer(ISEntry))
597 if ((FileEnt = SourceMgr.getFileEntryForID(
598 ISEntry.ThePPLexer->getFileID())))
599 Includers.push_back(FileEnt);
600 }
Chris Lattner022923a2009-02-04 19:45:07 +0000601 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000602 }
Mike Stump11289f42009-09-09 15:08:12 +0000603
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000604 // Do a standard file entry lookup.
605 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000606 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000607 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
608 RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000609 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000610 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000611 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
612 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000613 return FE;
614 }
Mike Stump11289f42009-09-09 15:08:12 +0000615
Will Wilson0fafd342013-12-27 19:46:16 +0000616 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000617 // Otherwise, see if this is a subframework header. If so, this is relative
618 // to one of the headers on the #include stack. Walk the list of the current
619 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000620 if (IsFileLexer()) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000621 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000622 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000623 SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000624 SuggestedModule))) {
625 if (SuggestedModule && !LangOpts.AsmPreprocessor)
626 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
627 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000628 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000629 }
630 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000631 }
Mike Stump11289f42009-09-09 15:08:12 +0000632
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000633 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
634 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000635 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000636 if ((CurFileEnt =
Ben Langmuir71e1a642014-05-05 21:44:13 +0000637 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000638 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000639 Filename, CurFileEnt, SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000640 SuggestedModule))) {
641 if (SuggestedModule && !LangOpts.AsmPreprocessor)
642 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
643 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000644 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000645 }
646 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000647 }
648 }
Mike Stump11289f42009-09-09 15:08:12 +0000649
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000650 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000651 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000652}
653
Chris Lattnerf64b3522008-03-09 01:54:53 +0000654
655//===----------------------------------------------------------------------===//
656// Preprocessor Directive Handling.
657//===----------------------------------------------------------------------===//
658
David Blaikied5321242012-06-06 18:52:13 +0000659class Preprocessor::ResetMacroExpansionHelper {
660public:
661 ResetMacroExpansionHelper(Preprocessor *pp)
662 : PP(pp), save(pp->DisableMacroExpansion) {
663 if (pp->MacroExpansionInDirectivesOverride)
664 pp->DisableMacroExpansion = false;
665 }
666 ~ResetMacroExpansionHelper() {
667 PP->DisableMacroExpansion = save;
668 }
669private:
670 Preprocessor *PP;
671 bool save;
672};
673
Chris Lattnerf64b3522008-03-09 01:54:53 +0000674/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000675/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000676/// lexer/preprocessor state, and advances the lexer(s) so that the next token
677/// read is the correct one.
678void Preprocessor::HandleDirective(Token &Result) {
679 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000680
Chris Lattnerf64b3522008-03-09 01:54:53 +0000681 // We just parsed a # character at the start of a line, so we're in directive
682 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000683 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000684 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000685 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000686
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000687 bool ImmediatelyAfterTopLevelIfndef =
688 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
689 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
690
Chris Lattnerf64b3522008-03-09 01:54:53 +0000691 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000692
Chris Lattnerf64b3522008-03-09 01:54:53 +0000693 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000694 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000695 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000696 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner2d17ab72009-03-18 21:00:25 +0000698 // Save the '#' token in case we need to return it later.
699 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000700
Chris Lattnerf64b3522008-03-09 01:54:53 +0000701 // Read the next token, the directive flavor. This isn't expanded due to
702 // C99 6.10.3p8.
703 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000704
Chris Lattnerf64b3522008-03-09 01:54:53 +0000705 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
706 // #define A(x) #x
707 // A(abc
708 // #warning blah
709 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000710 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
711 // not support this for #include-like directives, since that can result in
712 // terrible diagnostics, and does not work in GCC.
713 if (InMacroArgs) {
714 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
715 switch (II->getPPKeywordID()) {
716 case tok::pp_include:
717 case tok::pp_import:
718 case tok::pp_include_next:
719 case tok::pp___include_macros:
720 Diag(Result, diag::err_embedded_include) << II->getName();
721 DiscardUntilEndOfDirective();
722 return;
723 default:
724 break;
725 }
726 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000727 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000728 }
Mike Stump11289f42009-09-09 15:08:12 +0000729
David Blaikied5321242012-06-06 18:52:13 +0000730 // Temporarily enable macro expansion if set so
731 // and reset to previous state when returning from this function.
732 ResetMacroExpansionHelper helper(this);
733
Chris Lattnerf64b3522008-03-09 01:54:53 +0000734 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000735 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000736 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000737 case tok::code_completion:
738 if (CodeComplete)
739 CodeComplete->CodeCompleteDirective(
740 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000741 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000742 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000743 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000744 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000745 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000746 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000747 default:
748 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000749 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000750
Chris Lattnerf64b3522008-03-09 01:54:53 +0000751 // Ask what the preprocessor keyword ID is.
752 switch (II->getPPKeywordID()) {
753 default: break;
754 // C99 6.10.1 - Conditional Inclusion.
755 case tok::pp_if:
756 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
757 case tok::pp_ifdef:
758 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
759 case tok::pp_ifndef:
760 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
761 case tok::pp_elif:
762 return HandleElifDirective(Result);
763 case tok::pp_else:
764 return HandleElseDirective(Result);
765 case tok::pp_endif:
766 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000767
Chris Lattnerf64b3522008-03-09 01:54:53 +0000768 // C99 6.10.2 - Source File Inclusion.
769 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000770 // Handle #include.
771 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000772 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000773 // Handle -imacros.
774 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000775
Chris Lattnerf64b3522008-03-09 01:54:53 +0000776 // C99 6.10.3 - Macro Replacement.
777 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000778 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000779 case tok::pp_undef:
780 return HandleUndefDirective(Result);
781
782 // C99 6.10.4 - Line Control.
783 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000784 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattnerf64b3522008-03-09 01:54:53 +0000786 // C99 6.10.5 - Error Directive.
787 case tok::pp_error:
788 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000789
Chris Lattnerf64b3522008-03-09 01:54:53 +0000790 // C99 6.10.6 - Pragma Directive.
791 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000792 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattnerf64b3522008-03-09 01:54:53 +0000794 // GNU Extensions.
795 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000796 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000797 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000798 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000799
Chris Lattnerf64b3522008-03-09 01:54:53 +0000800 case tok::pp_warning:
801 Diag(Result, diag::ext_pp_warning_directive);
802 return HandleUserDiagnosticDirective(Result, true);
803 case tok::pp_ident:
804 return HandleIdentSCCSDirective(Result);
805 case tok::pp_sccs:
806 return HandleIdentSCCSDirective(Result);
807 case tok::pp_assert:
808 //isExtension = true; // FIXME: implement #assert
809 break;
810 case tok::pp_unassert:
811 //isExtension = true; // FIXME: implement #unassert
812 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000813
Douglas Gregor663b48f2012-01-03 19:48:16 +0000814 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000815 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000816 return HandleMacroPublicDirective(Result);
817 break;
818
Douglas Gregor663b48f2012-01-03 19:48:16 +0000819 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000820 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000821 return HandleMacroPrivateDirective(Result);
822 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000823 }
824 break;
825 }
Mike Stump11289f42009-09-09 15:08:12 +0000826
Chris Lattner2d17ab72009-03-18 21:00:25 +0000827 // If this is a .S file, treat unknown # directives as non-preprocessor
828 // directives. This is important because # may be a comment or introduce
829 // various pseudo-ops. Just return the # token and push back the following
830 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000831 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000832 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000833 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000834 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000835 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000836
837 // If the second token is a hashhash token, then we need to translate it to
838 // unknown so the token lexer doesn't try to perform token pasting.
839 if (Result.is(tok::hashhash))
840 Toks[1].setKind(tok::unknown);
841
Chris Lattner2d17ab72009-03-18 21:00:25 +0000842 // Enter this token stream so that we re-lex the tokens. Make sure to
843 // enable macro expansion, in case the token after the # is an identifier
844 // that is expanded.
845 EnterTokenStream(Toks, 2, false, true);
846 return;
847 }
Mike Stump11289f42009-09-09 15:08:12 +0000848
Chris Lattnerf64b3522008-03-09 01:54:53 +0000849 // If we reached here, the preprocessing token is not valid!
850 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chris Lattnerf64b3522008-03-09 01:54:53 +0000852 // Read the rest of the PP line.
853 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000854
Chris Lattnerf64b3522008-03-09 01:54:53 +0000855 // Okay, we're done parsing the directive.
856}
857
Chris Lattner76e68962009-01-26 06:19:46 +0000858/// GetLineValue - Convert a numeric token into an unsigned value, emitting
859/// Diagnostic DiagID if it is invalid, and returning the value in Val.
860static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000861 unsigned DiagID, Preprocessor &PP,
862 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000863 if (DigitTok.isNot(tok::numeric_constant)) {
864 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000865
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000866 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000867 PP.DiscardUntilEndOfDirective();
868 return true;
869 }
Mike Stump11289f42009-09-09 15:08:12 +0000870
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000871 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000872 IntegerBuffer.resize(DigitTok.getLength());
873 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000874 bool Invalid = false;
875 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
876 if (Invalid)
877 return true;
878
Chris Lattnerd66f1722009-04-18 18:35:15 +0000879 // Verify that we have a simple digit-sequence, and compute the value. This
880 // is always a simple digit string computed in decimal, so we do this manually
881 // here.
882 Val = 0;
883 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +0000884 // C++1y [lex.fcon]p1:
885 // Optional separating single quotes in a digit-sequence are ignored
886 if (DigitTokBegin[i] == '\'')
887 continue;
888
Jordan Rosea7d03842013-02-08 22:30:41 +0000889 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000890 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000891 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000892 PP.DiscardUntilEndOfDirective();
893 return true;
894 }
Mike Stump11289f42009-09-09 15:08:12 +0000895
Chris Lattnerd66f1722009-04-18 18:35:15 +0000896 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
897 if (NextVal < Val) { // overflow.
898 PP.Diag(DigitTok, DiagID);
899 PP.DiscardUntilEndOfDirective();
900 return true;
901 }
902 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000903 }
Mike Stump11289f42009-09-09 15:08:12 +0000904
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000905 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000906 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
907 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000908
Chris Lattner76e68962009-01-26 06:19:46 +0000909 return false;
910}
911
James Dennettf6333ac2012-06-22 05:46:07 +0000912/// \brief Handle a \#line directive: C99 6.10.4.
913///
914/// The two acceptable forms are:
915/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000916/// # line digit-sequence
917/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000918/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000919void Preprocessor::HandleLineDirective(Token &Tok) {
920 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
921 // expanded.
922 Token DigitTok;
923 Lex(DigitTok);
924
Chris Lattner100c65e2009-01-26 05:29:08 +0000925 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000926 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000927 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000928 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000929
930 if (LineNo == 0)
931 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000932
Chris Lattner76e68962009-01-26 06:19:46 +0000933 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
934 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000935 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000936 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000937 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000938 if (LineNo >= LineLimit)
939 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000940 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000941 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000943 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000944 Token StrTok;
945 Lex(StrTok);
946
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000947 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
948 // string followed by eod.
949 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000950 ; // ok
951 else if (StrTok.isNot(tok::string_literal)) {
952 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000953 return DiscardUntilEndOfDirective();
954 } else if (StrTok.hasUDSuffix()) {
955 Diag(StrTok, diag::err_invalid_string_udl);
956 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000957 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000958 // Parse and validate the string, converting it into a unique ID.
959 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000960 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000961 if (Literal.hadError)
962 return DiscardUntilEndOfDirective();
963 if (Literal.Pascal) {
964 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
965 return DiscardUntilEndOfDirective();
966 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000967 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000968
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000969 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000970 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
971 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000972 }
Mike Stump11289f42009-09-09 15:08:12 +0000973
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000974 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Chris Lattner839150e2009-03-27 17:13:49 +0000976 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000977 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
978 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000979 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000980}
981
Chris Lattner76e68962009-01-26 06:19:46 +0000982/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
983/// marker directive.
984static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
985 bool &IsSystemHeader, bool &IsExternCHeader,
986 Preprocessor &PP) {
987 unsigned FlagVal;
988 Token FlagTok;
989 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000990 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000991 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
992 return true;
993
994 if (FlagVal == 1) {
995 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000996
Chris Lattner76e68962009-01-26 06:19:46 +0000997 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000998 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000999 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1000 return true;
1001 } else if (FlagVal == 2) {
1002 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001003
Chris Lattner1c967782009-02-04 06:25:26 +00001004 SourceManager &SM = PP.getSourceManager();
1005 // If we are leaving the current presumed file, check to make sure the
1006 // presumed include stack isn't empty!
1007 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001008 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001009 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001010 if (PLoc.isInvalid())
1011 return true;
1012
Chris Lattner1c967782009-02-04 06:25:26 +00001013 // If there is no include loc (main file) or if the include loc is in a
1014 // different physical file, then we aren't in a "1" line marker flag region.
1015 SourceLocation IncLoc = PLoc.getIncludeLoc();
1016 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001017 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001018 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1019 PP.DiscardUntilEndOfDirective();
1020 return true;
1021 }
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattner76e68962009-01-26 06:19:46 +00001023 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001024 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001025 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1026 return true;
1027 }
1028
1029 // We must have 3 if there are still flags.
1030 if (FlagVal != 3) {
1031 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001032 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001033 return true;
1034 }
Mike Stump11289f42009-09-09 15:08:12 +00001035
Chris Lattner76e68962009-01-26 06:19:46 +00001036 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001037
Chris Lattner76e68962009-01-26 06:19:46 +00001038 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001039 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001040 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001041 return true;
1042
1043 // We must have 4 if there is yet another flag.
1044 if (FlagVal != 4) {
1045 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001046 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001047 return true;
1048 }
Mike Stump11289f42009-09-09 15:08:12 +00001049
Chris Lattner76e68962009-01-26 06:19:46 +00001050 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chris Lattner76e68962009-01-26 06:19:46 +00001052 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001053 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001054
1055 // There are no more valid flags here.
1056 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001057 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001058 return true;
1059}
1060
1061/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1062/// one of the following forms:
1063///
1064/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001065/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001066/// # 42 "file" ('1' | '2')? '3' '4'?
1067///
1068void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1069 // Validate the number and convert it to an unsigned. GNU does not have a
1070 // line # limit other than it fit in 32-bits.
1071 unsigned LineNo;
1072 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001073 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001074 return;
Mike Stump11289f42009-09-09 15:08:12 +00001075
Chris Lattner76e68962009-01-26 06:19:46 +00001076 Token StrTok;
1077 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001078
Chris Lattner76e68962009-01-26 06:19:46 +00001079 bool IsFileEntry = false, IsFileExit = false;
1080 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001081 int FilenameID = -1;
1082
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001083 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1084 // string followed by eod.
1085 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001086 ; // ok
1087 else if (StrTok.isNot(tok::string_literal)) {
1088 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001089 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001090 } else if (StrTok.hasUDSuffix()) {
1091 Diag(StrTok, diag::err_invalid_string_udl);
1092 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001093 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001094 // Parse and validate the string, converting it into a unique ID.
1095 StringLiteralParser Literal(&StrTok, 1, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001096 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001097 if (Literal.hadError)
1098 return DiscardUntilEndOfDirective();
1099 if (Literal.Pascal) {
1100 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1101 return DiscardUntilEndOfDirective();
1102 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001103 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001104
Chris Lattner76e68962009-01-26 06:19:46 +00001105 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001106 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001107 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001108 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001109 }
Mike Stump11289f42009-09-09 15:08:12 +00001110
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001111 // Create a line note with this information.
1112 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001113 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001114 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001115
Chris Lattner839150e2009-03-27 17:13:49 +00001116 // If the preprocessor has callbacks installed, notify them of the #line
1117 // change. This is used so that the line marker comes out in -E mode for
1118 // example.
1119 if (Callbacks) {
1120 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1121 if (IsFileEntry)
1122 Reason = PPCallbacks::EnterFile;
1123 else if (IsFileExit)
1124 Reason = PPCallbacks::ExitFile;
1125 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1126 if (IsExternCHeader)
1127 FileKind = SrcMgr::C_ExternCSystem;
1128 else if (IsSystemHeader)
1129 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001130
Chris Lattnerc745cec2010-04-14 04:28:50 +00001131 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001132 }
Chris Lattner76e68962009-01-26 06:19:46 +00001133}
1134
1135
Chris Lattner38d7fd22009-01-26 05:30:54 +00001136/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1137///
Mike Stump11289f42009-09-09 15:08:12 +00001138void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001139 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001140 // PTH doesn't emit #warning or #error directives.
1141 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001142 return CurPTHLexer->DiscardToEndOfLine();
1143
Chris Lattnerf64b3522008-03-09 01:54:53 +00001144 // Read the rest of the line raw. We do this because we don't want macros
1145 // to be expanded and we don't require that the tokens be valid preprocessing
1146 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1147 // collapse multiple consequtive white space between tokens, but this isn't
1148 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001149 SmallString<128> Message;
1150 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001151
1152 // Find the first non-whitespace character, so that we can make the
1153 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001154 StringRef Msg = Message.str().ltrim(" ");
1155
Chris Lattner100c65e2009-01-26 05:29:08 +00001156 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001157 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001158 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001159 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001160}
1161
1162/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1163///
1164void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1165 // Yes, this directive is an extension.
1166 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001167
Chris Lattnerf64b3522008-03-09 01:54:53 +00001168 // Read the string argument.
1169 Token StrTok;
1170 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001171
Chris Lattnerf64b3522008-03-09 01:54:53 +00001172 // If the token kind isn't a string, it's a malformed directive.
1173 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001174 StrTok.isNot(tok::wide_string_literal)) {
1175 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001176 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001177 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001178 return;
1179 }
Mike Stump11289f42009-09-09 15:08:12 +00001180
Richard Smithd67aea22012-03-06 03:21:47 +00001181 if (StrTok.hasUDSuffix()) {
1182 Diag(StrTok, diag::err_invalid_string_udl);
1183 return DiscardUntilEndOfDirective();
1184 }
1185
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001186 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001187 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001188
Douglas Gregordc970f02010-03-16 22:30:13 +00001189 if (Callbacks) {
1190 bool Invalid = false;
1191 std::string Str = getSpelling(StrTok, &Invalid);
1192 if (!Invalid)
1193 Callbacks->Ident(Tok.getLocation(), Str);
1194 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001195}
1196
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001197/// \brief Handle a #public directive.
1198void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001199 Token MacroNameTok;
1200 ReadMacroName(MacroNameTok, 2);
1201
1202 // Error reading macro name? If so, diagnostic already issued.
1203 if (MacroNameTok.is(tok::eod))
1204 return;
1205
Douglas Gregor663b48f2012-01-03 19:48:16 +00001206 // Check to see if this is the last token on the #__public_macro line.
1207 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001208
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001209 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001210 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001211 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001212
1213 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001214 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001215 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001216 return;
1217 }
1218
1219 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001220 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1221 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001222}
1223
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001224/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001225void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1226 Token MacroNameTok;
1227 ReadMacroName(MacroNameTok, 2);
1228
1229 // Error reading macro name? If so, diagnostic already issued.
1230 if (MacroNameTok.is(tok::eod))
1231 return;
1232
Douglas Gregor663b48f2012-01-03 19:48:16 +00001233 // Check to see if this is the last token on the #__private_macro line.
1234 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001235
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001236 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001237 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001238 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001239
1240 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001241 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001242 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001243 return;
1244 }
1245
1246 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001247 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1248 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001249}
1250
Chris Lattnerf64b3522008-03-09 01:54:53 +00001251//===----------------------------------------------------------------------===//
1252// Preprocessor Include Directive Handling.
1253//===----------------------------------------------------------------------===//
1254
1255/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001256/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001257/// true if the input filename was in <>'s or false if it were in ""'s. The
1258/// caller is expected to provide a buffer that is large enough to hold the
1259/// spelling of the filename, but is also expected to handle the case when
1260/// this method decides to use a different buffer.
1261bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001262 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001263 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001264 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001265
Chris Lattnerf64b3522008-03-09 01:54:53 +00001266 // Make sure the filename is <x> or "x".
1267 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001268 if (Buffer[0] == '<') {
1269 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001270 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001271 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001272 return true;
1273 }
1274 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001275 } else if (Buffer[0] == '"') {
1276 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001277 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001278 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001279 return true;
1280 }
1281 isAngled = false;
1282 } else {
1283 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001284 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001285 return true;
1286 }
Mike Stump11289f42009-09-09 15:08:12 +00001287
Chris Lattnerf64b3522008-03-09 01:54:53 +00001288 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001289 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001290 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001291 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001292 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
Chris Lattnerf64b3522008-03-09 01:54:53 +00001295 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001296 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001297 return isAngled;
1298}
1299
James Dennett4a4f72d2013-11-27 01:27:40 +00001300// \brief Handle cases where the \#include name is expanded from a macro
1301// as multiple tokens, which need to be glued together.
1302//
1303// This occurs for code like:
1304// \code
1305// \#define FOO <a/b.h>
1306// \#include FOO
1307// \endcode
1308// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1309//
1310// This code concatenates and consumes tokens up to the '>' token. It returns
1311// false if the > was found, otherwise it returns true if it finds and consumes
1312// the EOD marker.
1313bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001314 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001315 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001316
John Thompsonb5353522009-10-30 13:49:06 +00001317 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001318 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001319 End = CurTok.getLocation();
1320
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001321 // FIXME: Provide code completion for #includes.
1322 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001323 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001324 Lex(CurTok);
1325 continue;
1326 }
1327
Chris Lattnerf64b3522008-03-09 01:54:53 +00001328 // Append the spelling of this token to the buffer. If there was a space
1329 // before it, add it now.
1330 if (CurTok.hasLeadingSpace())
1331 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001332
Chris Lattnerf64b3522008-03-09 01:54:53 +00001333 // Get the spelling of the token, directly into FilenameBuffer if possible.
1334 unsigned PreAppendSize = FilenameBuffer.size();
1335 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001336
Chris Lattnerf64b3522008-03-09 01:54:53 +00001337 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001338 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001339
Chris Lattnerf64b3522008-03-09 01:54:53 +00001340 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1341 if (BufPtr != &FilenameBuffer[PreAppendSize])
1342 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001343
Chris Lattnerf64b3522008-03-09 01:54:53 +00001344 // Resize FilenameBuffer to the correct size.
1345 if (CurTok.getLength() != ActualLen)
1346 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001347
Chris Lattnerf64b3522008-03-09 01:54:53 +00001348 // If we found the '>' marker, return success.
1349 if (CurTok.is(tok::greater))
1350 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001351
John Thompsonb5353522009-10-30 13:49:06 +00001352 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001353 }
1354
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001355 // If we hit the eod marker, emit an error and return true so that the caller
1356 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001357 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001358 return true;
1359}
1360
Richard Smith34f30512013-11-23 04:06:09 +00001361/// \brief Push a token onto the token stream containing an annotation.
1362static void EnterAnnotationToken(Preprocessor &PP,
1363 SourceLocation Begin, SourceLocation End,
1364 tok::TokenKind Kind, void *AnnotationVal) {
1365 Token *Tok = new Token[1];
1366 Tok[0].startToken();
1367 Tok[0].setKind(Kind);
1368 Tok[0].setLocation(Begin);
1369 Tok[0].setAnnotationEndLoc(End);
1370 Tok[0].setAnnotationValue(AnnotationVal);
1371 PP.EnterTokenStream(Tok, 1, true, true);
1372}
1373
James Dennettf6333ac2012-06-22 05:46:07 +00001374/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1375/// the file to be included from the lexer, then include it! This is a common
1376/// routine with functionality shared between \#include, \#include_next and
1377/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001378/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001379void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1380 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001381 const DirectoryLookup *LookupFrom,
1382 bool isImport) {
1383
1384 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001385 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001386
Chris Lattnerf64b3522008-03-09 01:54:53 +00001387 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001388 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001389 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001390 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001391 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001392
Chris Lattnerf64b3522008-03-09 01:54:53 +00001393 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001394 case tok::eod:
1395 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001396 return;
Mike Stump11289f42009-09-09 15:08:12 +00001397
Chris Lattnerf64b3522008-03-09 01:54:53 +00001398 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001399 case tok::string_literal:
1400 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001401 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001402 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001403 break;
Mike Stump11289f42009-09-09 15:08:12 +00001404
Chris Lattnerf64b3522008-03-09 01:54:53 +00001405 case tok::less:
1406 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1407 // case, glue the tokens together into FilenameBuffer and interpret those.
1408 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001409 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001410 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001411 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001412 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001413 break;
1414 default:
1415 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1416 DiscardUntilEndOfDirective();
1417 return;
1418 }
Mike Stump11289f42009-09-09 15:08:12 +00001419
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001420 CharSourceRange FilenameRange
1421 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001422 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001423 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001424 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001425 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1426 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001427 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001428 DiscardUntilEndOfDirective();
1429 return;
1430 }
Mike Stump11289f42009-09-09 15:08:12 +00001431
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001432 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001433 // we allow macros that expand to nothing after the filename, because this
1434 // falls into the category of "#include pp-tokens new-line" specified in
1435 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001436 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001437
1438 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001439 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1440 Diag(FilenameTok, diag::err_pp_include_too_deep);
1441 return;
1442 }
Mike Stump11289f42009-09-09 15:08:12 +00001443
John McCall32f5fe12011-09-30 05:12:12 +00001444 // Complain about attempts to #include files in an audit pragma.
1445 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1446 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1447 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1448
1449 // Immediately leave the pragma.
1450 PragmaARCCFCodeAuditedLoc = SourceLocation();
1451 }
1452
Aaron Ballman611306e2012-03-02 22:51:54 +00001453 if (HeaderInfo.HasIncludeAliasMap()) {
1454 // Map the filename with the brackets still attached. If the name doesn't
1455 // map to anything, fall back on the filename we've already gotten the
1456 // spelling for.
1457 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1458 if (!NewName.empty())
1459 Filename = NewName;
1460 }
1461
Chris Lattnerf64b3522008-03-09 01:54:53 +00001462 // Search include directories.
1463 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001464 SmallString<1024> SearchPath;
1465 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001466 // We get the raw path only if we have 'Callbacks' to which we later pass
1467 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001468 ModuleMap::KnownHeader SuggestedModule;
1469 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001470 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001471 if (LangOpts.MSVCCompat) {
1472 NormalizedPath = Filename.str();
1473 llvm::sys::fs::normalize_separators(NormalizedPath);
1474 }
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,
Craig Topperd2d442c2014-05-17 23:10:59 +00001477 isAngled, LookupFrom, CurDir, Callbacks ? &SearchPath : nullptr,
1478 Callbacks ? &RelativePath : nullptr,
1479 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.
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001492 File = LookupFile(FilenameLoc,
1493 LangOpts.MSVCCompat ? NormalizedPath.c_str()
1494 : Filename,
Craig Topperd2d442c2014-05-17 23:10:59 +00001495 isAngled, LookupFrom, CurDir, nullptr, nullptr,
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001496 HeaderInfo.getHeaderSearchOpts().ModuleMaps
Daniel Jasper07e6c402013-08-05 20:26:17 +00001497 ? &SuggestedModule
Craig Topperd2d442c2014-05-17 23:10:59 +00001498 : nullptr,
Daniel Jasper07e6c402013-08-05 20:26:17 +00001499 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001500 }
1501 }
1502 }
1503
Daniel Jasper07e6c402013-08-05 20:26:17 +00001504 if (!SuggestedModule || !getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001505 // Notify the callback object that we've seen an inclusion directive.
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001506 Callbacks->InclusionDirective(HashLoc, IncludeTok,
1507 LangOpts.MSVCCompat ? NormalizedPath.c_str()
1508 : Filename,
1509 isAngled, FilenameRange, File, SearchPath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001510 RelativePath, /*ImportedModule=*/nullptr);
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001511 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001512 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001513
1514 if (!File) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001515 if (!SuppressIncludeNotFoundError) {
1516 // If the file could not be located and it was included via angle
1517 // brackets, we can attempt a lookup as though it were a quoted path to
1518 // provide the user with a possible fixit.
1519 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001520 File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001521 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Craig Topperd2d442c2014-05-17 23:10:59 +00001522 false, LookupFrom, CurDir, Callbacks ? &SearchPath : nullptr,
1523 Callbacks ? &RelativePath : nullptr,
1524 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1525 : nullptr);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001526 if (File) {
1527 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1528 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1529 Filename <<
1530 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1531 }
1532 }
1533 // If the file is still not found, just go with the vanilla diagnostic
1534 if (!File)
1535 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1536 }
1537 if (!File)
1538 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001539 }
1540
Douglas Gregor97eec242011-09-15 22:00:41 +00001541 // If we are supposed to import a module rather than including the header,
1542 // do so now.
Daniel Jasper07e6c402013-08-05 20:26:17 +00001543 if (SuggestedModule && getLangOpts().Modules) {
Douglas Gregor71944202011-11-30 00:36:36 +00001544 // Compute the module access path corresponding to this module.
1545 // FIXME: Should we have a second loadModule() overload to avoid this
1546 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001547 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001548 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001549 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1550 FilenameTok.getLocation()));
1551 std::reverse(Path.begin(), Path.end());
1552
Douglas Gregor41e115a2011-11-30 18:02:36 +00001553 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001554 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001555 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1556 if (I)
1557 PathString += '.';
1558 PathString += Path[I].first->getName();
1559 }
1560 int IncludeKind = 0;
1561
1562 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1563 case tok::pp_include:
1564 IncludeKind = 0;
1565 break;
1566
1567 case tok::pp_import:
1568 IncludeKind = 1;
1569 break;
1570
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001571 case tok::pp_include_next:
1572 IncludeKind = 2;
1573 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001574
1575 case tok::pp___include_macros:
1576 IncludeKind = 3;
1577 break;
1578
1579 default:
1580 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001581 }
1582
Douglas Gregor2537a362011-12-08 17:01:29 +00001583 // Determine whether we are actually building the module that this
1584 // include directive maps to.
1585 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001586 = Path[0].first->getName() == getLangOpts().CurrentModule;
Richard Smith34f30512013-11-23 04:06:09 +00001587
David Blaikiebbafb8a2012-03-11 07:00:24 +00001588 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001589 // If we're not building the imported module, warn that we're going
1590 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001591 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001592 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1593 /*IsTokenRange=*/false);
1594 Diag(HashLoc, diag::warn_auto_module_import)
1595 << IncludeKind << PathString
1596 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001597 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001598 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001599
Richard Smithce587f52013-11-15 04:24:58 +00001600 // Load the module. Only make macros visible. We'll make the declarations
1601 // visible when the parser gets here.
1602 Module::NameVisibilityKind Visibility = Module::MacrosVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001603 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001604 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1605 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001606 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001607 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001608
1609 if (!Imported && hadModuleLoaderFatalFailure()) {
1610 // With a fatal failure in the module loader, we abort parsing.
1611 Token &Result = IncludeTok;
1612 if (CurLexer) {
1613 Result.startToken();
1614 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1615 CurLexer->cutOffLexing();
1616 } else {
1617 assert(CurPTHLexer && "#include but no current lexer set!");
1618 CurPTHLexer->getEOF(Result);
1619 }
1620 return;
1621 }
Richard Smithce587f52013-11-15 04:24:58 +00001622
Douglas Gregor2537a362011-12-08 17:01:29 +00001623 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001624 if (!BuildingImportedModule && Imported) {
1625 if (Callbacks) {
1626 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1627 FilenameRange, File,
1628 SearchPath, RelativePath, Imported);
1629 }
Richard Smithce587f52013-11-15 04:24:58 +00001630
1631 if (IncludeKind != 3) {
1632 // Let the parser know that we hit a module import, and it should
1633 // make the module visible.
1634 // FIXME: Produce this as the current token directly, rather than
1635 // allocating a new token for it.
Richard Smith34f30512013-11-23 04:06:09 +00001636 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include,
1637 Imported);
Richard Smithce587f52013-11-15 04:24:58 +00001638 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001639 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001640 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001641
1642 // If we failed to find a submodule that we expected to find, we can
1643 // continue. Otherwise, there's an error in the included file, so we
1644 // don't want to include it.
1645 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1646 return;
1647 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001648 }
1649
1650 if (Callbacks && SuggestedModule) {
1651 // We didn't notify the callback object that we've seen an inclusion
1652 // directive before. Now that we are parsing the include normally and not
1653 // turning it to a module import, notify the callback object.
1654 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1655 FilenameRange, File,
1656 SearchPath, RelativePath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001657 /*ImportedModule=*/nullptr);
Douglas Gregor97eec242011-09-15 22:00:41 +00001658 }
1659
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001660 // The #included file will be considered to be a system header if either it is
1661 // in a system include directory, or if the #includer is a system include
1662 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001663 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001664 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001665 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001666
Chris Lattner72286d62010-04-19 20:44:31 +00001667 // Ask HeaderInfo if we should enter this #include file. If not, #including
1668 // this file will have no effect.
1669 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001670 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001671 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001672 return;
1673 }
1674
Chris Lattnerf64b3522008-03-09 01:54:53 +00001675 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001676 SourceLocation IncludePos = End;
1677 // If the filename string was the result of macro expansions, set the include
1678 // position on the file where it will be included and after the expansions.
1679 if (IncludePos.isMacroID())
1680 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1681 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001682 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001683
Richard Smith34f30512013-11-23 04:06:09 +00001684 // Determine if we're switching to building a new submodule, and which one.
1685 ModuleMap::KnownHeader BuildingModule;
1686 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) {
1687 Module *RequestingModule = getModuleForLocation(FilenameLoc);
1688 BuildingModule =
1689 HeaderInfo.getModuleMap().findModuleForHeader(File, RequestingModule);
1690 }
1691
1692 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00001693 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
1694 return;
Richard Smith34f30512013-11-23 04:06:09 +00001695
1696 // If we're walking into another part of the same module, let the parser
1697 // know that any future declarations are within that other submodule.
Richard Smith67294e22014-01-31 20:47:44 +00001698 if (BuildingModule) {
1699 assert(!CurSubmodule && "should not have marked this as a module yet");
1700 CurSubmodule = BuildingModule.getModule();
1701
Richard Smith34f30512013-11-23 04:06:09 +00001702 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin,
Richard Smith67294e22014-01-31 20:47:44 +00001703 CurSubmodule);
1704 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001705}
1706
James Dennettf6333ac2012-06-22 05:46:07 +00001707/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001708///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001709void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1710 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001711 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001712
Chris Lattnerf64b3522008-03-09 01:54:53 +00001713 // #include_next is like #include, except that we start searching after
1714 // the current found directory. If we can't do this, issue a
1715 // diagnostic.
1716 const DirectoryLookup *Lookup = CurDirLookup;
1717 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001718 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001719 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Craig Topperd2d442c2014-05-17 23:10:59 +00001720 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001721 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1722 } else {
1723 // Start looking up in the next directory.
1724 ++Lookup;
1725 }
Mike Stump11289f42009-09-09 15:08:12 +00001726
Douglas Gregor796d76a2010-10-20 22:00:55 +00001727 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001728}
1729
James Dennettf6333ac2012-06-22 05:46:07 +00001730/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001731void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1732 // The Microsoft #import directive takes a type library and generates header
1733 // files from it, and includes those. This is beyond the scope of what clang
1734 // does, so we ignore it and error out. However, #import can optionally have
1735 // trailing attributes that span multiple lines. We're going to eat those
1736 // so we can continue processing from there.
1737 Diag(Tok, diag::err_pp_import_directive_ms );
1738
1739 // Read tokens until we get to the end of the directive. Note that the
1740 // directive can be split over multiple lines using the backslash character.
1741 DiscardUntilEndOfDirective();
1742}
1743
James Dennettf6333ac2012-06-22 05:46:07 +00001744/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001745///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001746void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1747 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001748 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00001749 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00001750 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001751 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001752 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001753 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001754}
1755
Chris Lattner58a1eb02009-04-08 18:46:40 +00001756/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1757/// pseudo directive in the predefines buffer. This handles it by sucking all
1758/// tokens through the preprocessor and discarding them (only keeping the side
1759/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001760void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1761 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001762 // This directive should only occur in the predefines buffer. If not, emit an
1763 // error and reject it.
1764 SourceLocation Loc = IncludeMacrosTok.getLocation();
1765 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1766 Diag(IncludeMacrosTok.getLocation(),
1767 diag::pp_include_macros_out_of_predefines);
1768 DiscardUntilEndOfDirective();
1769 return;
1770 }
Mike Stump11289f42009-09-09 15:08:12 +00001771
Chris Lattnere01d82b2009-04-08 20:53:24 +00001772 // Treat this as a normal #include for checking purposes. If this is
1773 // successful, it will push a new lexer onto the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001774 HandleIncludeDirective(HashLoc, IncludeMacrosTok, nullptr, false);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Chris Lattnere01d82b2009-04-08 20:53:24 +00001776 Token TmpTok;
1777 do {
1778 Lex(TmpTok);
1779 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1780 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001781}
1782
Chris Lattnerf64b3522008-03-09 01:54:53 +00001783//===----------------------------------------------------------------------===//
1784// Preprocessor Macro Directive Handling.
1785//===----------------------------------------------------------------------===//
1786
1787/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1788/// definition has just been read. Lex the rest of the arguments and the
1789/// closing ), updating MI with what we learn. Return true if an error occurs
1790/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001791bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001792 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001793
Chris Lattnerf64b3522008-03-09 01:54:53 +00001794 while (1) {
1795 LexUnexpandedToken(Tok);
1796 switch (Tok.getKind()) {
1797 case tok::r_paren:
1798 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001799 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001800 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001801 // Otherwise we have #define FOO(A,)
1802 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1803 return true;
1804 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001805 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001806 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001807 diag::warn_cxx98_compat_variadic_macro :
1808 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001809
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001810 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1811 if (LangOpts.OpenCL) {
1812 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1813 return true;
1814 }
1815
Chris Lattnerf64b3522008-03-09 01:54:53 +00001816 // Lex the token after the identifier.
1817 LexUnexpandedToken(Tok);
1818 if (Tok.isNot(tok::r_paren)) {
1819 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1820 return true;
1821 }
1822 // Add the __VA_ARGS__ identifier as an argument.
1823 Arguments.push_back(Ident__VA_ARGS__);
1824 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001825 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001826 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001827 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001828 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1829 return true;
1830 default:
1831 // Handle keywords and identifiers here to accept things like
1832 // #define Foo(for) for.
1833 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00001834 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001835 // #define X(1
1836 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1837 return true;
1838 }
1839
1840 // If this is already used as an argument, it is used multiple times (e.g.
1841 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001842 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001843 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001844 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001845 return true;
1846 }
Mike Stump11289f42009-09-09 15:08:12 +00001847
Chris Lattnerf64b3522008-03-09 01:54:53 +00001848 // Add the argument to the macro info.
1849 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001850
Chris Lattnerf64b3522008-03-09 01:54:53 +00001851 // Lex the token after the identifier.
1852 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001853
Chris Lattnerf64b3522008-03-09 01:54:53 +00001854 switch (Tok.getKind()) {
1855 default: // #define X(A B
1856 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1857 return true;
1858 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001859 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001860 return false;
1861 case tok::comma: // #define X(A,
1862 break;
1863 case tok::ellipsis: // #define X(A... -> GCC extension
1864 // Diagnose extension.
1865 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001866
Chris Lattnerf64b3522008-03-09 01:54:53 +00001867 // Lex the token after the identifier.
1868 LexUnexpandedToken(Tok);
1869 if (Tok.isNot(tok::r_paren)) {
1870 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1871 return true;
1872 }
Mike Stump11289f42009-09-09 15:08:12 +00001873
Chris Lattnerf64b3522008-03-09 01:54:53 +00001874 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001875 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001876 return false;
1877 }
1878 }
1879 }
1880}
1881
James Dennettf6333ac2012-06-22 05:46:07 +00001882/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001883/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001884void Preprocessor::HandleDefineDirective(Token &DefineTok,
1885 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001886 ++NumDefined;
1887
1888 Token MacroNameTok;
1889 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001890
Chris Lattnerf64b3522008-03-09 01:54:53 +00001891 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001892 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001893 return;
1894
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001895 Token LastTok = MacroNameTok;
1896
Chris Lattnerf64b3522008-03-09 01:54:53 +00001897 // If we are supposed to keep comments in #defines, reenable comment saving
1898 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001899 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001900
Chris Lattnerf64b3522008-03-09 01:54:53 +00001901 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001902 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001903
Chris Lattnerf64b3522008-03-09 01:54:53 +00001904 Token Tok;
1905 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001906
Chris Lattnerf64b3522008-03-09 01:54:53 +00001907 // If this is a function-like macro definition, parse the argument list,
1908 // marking each of the identifiers as being used as macro arguments. Also,
1909 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001910 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001911 if (ImmediatelyAfterHeaderGuard) {
1912 // Save this macro information since it may part of a header guard.
1913 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
1914 MacroNameTok.getLocation());
1915 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001916 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001917 } else if (Tok.hasLeadingSpace()) {
1918 // This is a normal token with leading space. Clear the leading space
1919 // marker on the first token to get proper expansion.
1920 Tok.clearFlag(Token::LeadingSpace);
1921 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001922 // This is a function-like macro definition. Read the argument list.
1923 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001924 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001925 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001926 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001927 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001928 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001929 DiscardUntilEndOfDirective();
1930 return;
1931 }
1932
Chris Lattner249c38b2009-04-19 18:26:34 +00001933 // If this is a definition of a variadic C99 function-like macro, not using
1934 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001935
Chris Lattner249c38b2009-04-19 18:26:34 +00001936 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1937 // This gets unpoisoned where it is allowed.
1938 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1939 if (MI->isC99Varargs())
1940 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001941
Chris Lattnerf64b3522008-03-09 01:54:53 +00001942 // Read the first token after the arg list for down below.
1943 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001944 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001945 // C99 requires whitespace between the macro definition and the body. Emit
1946 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001947 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001948 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001949 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1950 // first character of a replacement list is not a character required by
1951 // subclause 5.2.1, then there shall be white-space separation between the
1952 // identifier and the replacement list.". 5.2.1 lists this set:
1953 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1954 // is irrelevant here.
1955 bool isInvalid = false;
1956 if (Tok.is(tok::at)) // @ is not in the list above.
1957 isInvalid = true;
1958 else if (Tok.is(tok::unknown)) {
1959 // If we have an unknown token, it is something strange like "`". Since
1960 // all of valid characters would have lexed into a single character
1961 // token of some sort, we know this is not a valid case.
1962 isInvalid = true;
1963 }
1964 if (isInvalid)
1965 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1966 else
1967 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001968 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001969
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001970 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001971 LastTok = Tok;
1972
Chris Lattnerf64b3522008-03-09 01:54:53 +00001973 // Read the rest of the macro body.
1974 if (MI->isObjectLike()) {
1975 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001976 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001977 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001978 MI->AddTokenToBody(Tok);
1979 // Get the next token of the macro.
1980 LexUnexpandedToken(Tok);
1981 }
Mike Stump11289f42009-09-09 15:08:12 +00001982
Chris Lattnerf64b3522008-03-09 01:54:53 +00001983 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001984 // Otherwise, read the body of a function-like macro. While we are at it,
1985 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1986 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001987 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001988 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001989
Eli Friedman14d3c792012-11-14 02:18:46 +00001990 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001991 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001992
Chris Lattnerf64b3522008-03-09 01:54:53 +00001993 // Get the next token of the macro.
1994 LexUnexpandedToken(Tok);
1995 continue;
1996 }
Mike Stump11289f42009-09-09 15:08:12 +00001997
Richard Smith701a3522013-07-09 01:00:29 +00001998 // If we're in -traditional mode, then we should ignore stringification
1999 // and token pasting. Mark the tokens as unknown so as not to confuse
2000 // things.
2001 if (getLangOpts().TraditionalCPP) {
2002 Tok.setKind(tok::unknown);
2003 MI->AddTokenToBody(Tok);
2004
2005 // Get the next token of the macro.
2006 LexUnexpandedToken(Tok);
2007 continue;
2008 }
2009
Eli Friedman14d3c792012-11-14 02:18:46 +00002010 if (Tok.is(tok::hashhash)) {
2011
2012 // If we see token pasting, check if it looks like the gcc comma
2013 // pasting extension. We'll use this information to suppress
2014 // diagnostics later on.
2015
2016 // Get the next token of the macro.
2017 LexUnexpandedToken(Tok);
2018
2019 if (Tok.is(tok::eod)) {
2020 MI->AddTokenToBody(LastTok);
2021 break;
2022 }
2023
2024 unsigned NumTokens = MI->getNumTokens();
2025 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2026 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2027 MI->setHasCommaPasting();
2028
David Majnemer76faf1f2013-11-05 09:30:17 +00002029 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002030 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002031 continue;
2032 }
2033
Chris Lattnerf64b3522008-03-09 01:54:53 +00002034 // Get the next token of the macro.
2035 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002036
Chris Lattner83bd8282009-05-25 17:16:10 +00002037 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002038 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002039 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2040
2041 // If this is assembler-with-cpp mode, we accept random gibberish after
2042 // the '#' because '#' is often a comment character. However, change
2043 // the kind of the token to tok::unknown so that the preprocessor isn't
2044 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002045 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002046 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002047 MI->AddTokenToBody(LastTok);
2048 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002049 } else {
2050 Diag(Tok, diag::err_pp_stringize_not_parameter);
2051 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002052
Chris Lattner83bd8282009-05-25 17:16:10 +00002053 // Disable __VA_ARGS__ again.
2054 Ident__VA_ARGS__->setIsPoisoned(true);
2055 return;
2056 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Chris Lattner83bd8282009-05-25 17:16:10 +00002059 // Things look ok, add the '#' and param name tokens to the macro.
2060 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002061 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002062 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002063
Chris Lattnerf64b3522008-03-09 01:54:53 +00002064 // Get the next token of the macro.
2065 LexUnexpandedToken(Tok);
2066 }
2067 }
Mike Stump11289f42009-09-09 15:08:12 +00002068
2069
Chris Lattnerf64b3522008-03-09 01:54:53 +00002070 // Disable __VA_ARGS__ again.
2071 Ident__VA_ARGS__->setIsPoisoned(true);
2072
Chris Lattner57540c52011-04-15 05:22:18 +00002073 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002074 // replacement list.
2075 unsigned NumTokens = MI->getNumTokens();
2076 if (NumTokens != 0) {
2077 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2078 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002079 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002080 return;
2081 }
2082 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2083 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002084 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002085 return;
2086 }
2087 }
Mike Stump11289f42009-09-09 15:08:12 +00002088
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002089 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002090
Chris Lattnerf64b3522008-03-09 01:54:53 +00002091 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002092 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002093 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002094 // It is very common for system headers to have tons of macro redefinitions
2095 // and for warnings to be disabled in system headers. If this is the case,
2096 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002097 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002098 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002099 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002100 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002101
Richard Smith7b242542013-03-06 00:46:00 +00002102 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2103 // C++ [cpp.predefined]p4, but allow it as an extension.
2104 if (OtherMI->isBuiltinMacro())
2105 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002106 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002107 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002108 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002109 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002110 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2111 << MacroNameTok.getIdentifierInfo();
2112 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2113 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002114 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002115 if (OtherMI->isWarnIfUnused())
2116 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002117 }
Mike Stump11289f42009-09-09 15:08:12 +00002118
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002119 DefMacroDirective *MD =
2120 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002121
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002122 assert(!MI->isUsed());
2123 // If we need warning for not using the macro, add its location in the
2124 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002125 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002126 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002127 MI->setIsWarnIfUnused(true);
2128 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2129 }
2130
Chris Lattner928e9092009-04-12 01:39:54 +00002131 // If the callbacks want to know, tell them about the macro definition.
2132 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002133 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002134}
2135
James Dennettf6333ac2012-06-22 05:46:07 +00002136/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002137///
2138void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2139 ++NumUndefined;
2140
2141 Token MacroNameTok;
2142 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00002143
Chris Lattnerf64b3522008-03-09 01:54:53 +00002144 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002145 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002146 return;
Mike Stump11289f42009-09-09 15:08:12 +00002147
Chris Lattnerf64b3522008-03-09 01:54:53 +00002148 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002149 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002150
Chris Lattnerf64b3522008-03-09 01:54:53 +00002151 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002152 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Craig Topperd2d442c2014-05-17 23:10:59 +00002153 const MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002154
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002155 // If the callbacks want to know, tell them about the macro #undef.
2156 // Note: no matter if the macro was defined or not.
2157 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002158 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002159
Chris Lattnerf64b3522008-03-09 01:54:53 +00002160 // If the macro is not defined, this is a noop undef, just return.
Craig Topperd2d442c2014-05-17 23:10:59 +00002161 if (!MI)
2162 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002163
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002164 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002165 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002166
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002167 if (MI->isWarnIfUnused())
2168 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2169
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002170 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2171 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002172}
2173
2174
2175//===----------------------------------------------------------------------===//
2176// Preprocessor Conditional Directive Handling.
2177//===----------------------------------------------------------------------===//
2178
James Dennettf6333ac2012-06-22 05:46:07 +00002179/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2180/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2181/// true if any tokens have been returned or pp-directives activated before this
2182/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002183///
2184void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2185 bool ReadAnyTokensBeforeDirective) {
2186 ++NumIf;
2187 Token DirectiveTok = Result;
2188
2189 Token MacroNameTok;
2190 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002191
Chris Lattnerf64b3522008-03-09 01:54:53 +00002192 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002193 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002194 // Skip code until we get to #endif. This helps with recovery by not
2195 // emitting an error when the #endif is reached.
2196 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2197 /*Foundnonskip*/false, /*FoundElse*/false);
2198 return;
2199 }
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattnerf64b3522008-03-09 01:54:53 +00002201 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002202 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002203
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002204 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002205 MacroDirective *MD = getMacroDirective(MII);
Craig Topperd2d442c2014-05-17 23:10:59 +00002206 MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002207
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002208 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002209 // If the start of a top-level #ifdef and if the macro is not defined,
2210 // inform MIOpt that this might be the start of a proper include guard.
2211 // Otherwise it is some other form of unknown conditional which we can't
2212 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002213 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002214 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002215 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002216 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002217 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002218 }
2219
Chris Lattnerf64b3522008-03-09 01:54:53 +00002220 // If there is a macro, process it.
2221 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002222 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002223
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002224 if (Callbacks) {
2225 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002226 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002227 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002228 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002229 }
2230
Chris Lattnerf64b3522008-03-09 01:54:53 +00002231 // Should we include the stuff contained by this directive?
2232 if (!MI == isIfndef) {
2233 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002234 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2235 /*wasskip*/false, /*foundnonskip*/true,
2236 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002237 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002238 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002239 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002240 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002241 /*FoundElse*/false);
2242 }
2243}
2244
James Dennettf6333ac2012-06-22 05:46:07 +00002245/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002246///
2247void Preprocessor::HandleIfDirective(Token &IfToken,
2248 bool ReadAnyTokensBeforeDirective) {
2249 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002250
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002251 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002252 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002253 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2254 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2255 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002256
2257 // If this condition is equivalent to #ifndef X, and if this is the first
2258 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002259 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002260 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002261 // FIXME: Pass in the location of the macro name, not the 'if' token.
2262 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002263 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002264 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002265 }
2266
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002267 if (Callbacks)
2268 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002269 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002270 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002271
Chris Lattnerf64b3522008-03-09 01:54:53 +00002272 // Should we include the stuff contained by this directive?
2273 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002274 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002275 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002276 /*foundnonskip*/true, /*foundelse*/false);
2277 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002278 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002279 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002280 /*FoundElse*/false);
2281 }
2282}
2283
James Dennettf6333ac2012-06-22 05:46:07 +00002284/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002285///
2286void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2287 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002288
Chris Lattnerf64b3522008-03-09 01:54:53 +00002289 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002290 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002291
Chris Lattnerf64b3522008-03-09 01:54:53 +00002292 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002293 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002294 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002295 Diag(EndifToken, diag::err_pp_endif_without_if);
2296 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002297 }
Mike Stump11289f42009-09-09 15:08:12 +00002298
Chris Lattnerf64b3522008-03-09 01:54:53 +00002299 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002300 if (CurPPLexer->getConditionalStackDepth() == 0)
2301 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002302
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002303 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002304 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002305
2306 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002307 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002308}
2309
James Dennettf6333ac2012-06-22 05:46:07 +00002310/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002311///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002312void Preprocessor::HandleElseDirective(Token &Result) {
2313 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002314
Chris Lattnerf64b3522008-03-09 01:54:53 +00002315 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002316 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002317
Chris Lattnerf64b3522008-03-09 01:54:53 +00002318 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002319 if (CurPPLexer->popConditionalLevel(CI)) {
2320 Diag(Result, diag::pp_err_else_without_if);
2321 return;
2322 }
Mike Stump11289f42009-09-09 15:08:12 +00002323
Chris Lattnerf64b3522008-03-09 01:54:53 +00002324 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002325 if (CurPPLexer->getConditionalStackDepth() == 0)
2326 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002327
2328 // If this is a #else with a #else before it, report the error.
2329 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002330
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002331 if (Callbacks)
2332 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2333
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002334 // Finally, skip the rest of the contents of this block.
2335 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002336 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002337}
2338
James Dennettf6333ac2012-06-22 05:46:07 +00002339/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002340///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002341void Preprocessor::HandleElifDirective(Token &ElifToken) {
2342 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002343
Chris Lattnerf64b3522008-03-09 01:54:53 +00002344 // #elif directive in a non-skipping conditional... start skipping.
2345 // We don't care what the condition is, because we will always skip it (since
2346 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002347 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002348 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002349 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002350
2351 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002352 if (CurPPLexer->popConditionalLevel(CI)) {
2353 Diag(ElifToken, diag::pp_err_elif_without_if);
2354 return;
2355 }
Mike Stump11289f42009-09-09 15:08:12 +00002356
Chris Lattnerf64b3522008-03-09 01:54:53 +00002357 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002358 if (CurPPLexer->getConditionalStackDepth() == 0)
2359 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002360
Chris Lattnerf64b3522008-03-09 01:54:53 +00002361 // If this is a #elif with a #else before it, report the error.
2362 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002363
2364 if (Callbacks)
2365 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002366 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002367 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002368
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002369 // Finally, skip the rest of the contents of this block.
2370 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002371 /*FoundElse*/CI.FoundElse,
2372 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002373}