blob: a8e27c71da824f9c6ed7c1e7666189455d6046dd [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) {
Yaron Kerenfdbb4a52014-06-19 19:12:02 +0000104 MacroInfoChain *MIChain = (MacroInfoChain *)MI;
Ted Kremenekc8456f82010-10-19 22:15:20 +0000105 if (MacroInfoChain *Prev = MIChain->Prev) {
106 MacroInfoChain *Next = MIChain->Next;
107 Prev->Next = Next;
108 if (Next)
109 Next->Prev = Prev;
Yaron Kerenfdbb4a52014-06-19 19:12:02 +0000110 } else {
Ted Kremenekc8456f82010-10-19 22:15:20 +0000111 assert(MIChainHead == MIChain);
112 MIChainHead = MIChain->Next;
Craig Topperd2d442c2014-05-17 23:10:59 +0000113 MIChainHead->Prev = nullptr;
Ted Kremenekc8456f82010-10-19 22:15:20 +0000114 }
115 MIChain->Next = MICache;
116 MICache = MIChain;
Chris Lattner666f7a42009-02-20 22:19:20 +0000117
Ted Kremenekc8456f82010-10-19 22:15:20 +0000118 MI->Destroy();
119}
Chris Lattner666f7a42009-02-20 22:19:20 +0000120
James Dennettf6333ac2012-06-22 05:46:07 +0000121/// \brief Read and discard all tokens remaining on the current line until
122/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000123void Preprocessor::DiscardUntilEndOfDirective() {
124 Token Tmp;
125 do {
126 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000127 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000128 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000129}
130
Alp Tokerb05e0b52014-05-21 06:13:51 +0000131bool Preprocessor::CheckMacroName(Token &MacroNameTok, char isDefineUndef) {
132 // Missing macro name?
133 if (MacroNameTok.is(tok::eod))
134 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
135
136 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
137 if (!II) {
138 bool Invalid = false;
139 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
140 if (Invalid)
141 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000142 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000143
Alp Tokerf33619c2014-05-31 03:38:08 +0000144 if (!II->isCPlusPlusOperatorKeyword())
145 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000146
Alp Tokere03e9e12014-05-31 16:32:22 +0000147 // C++ 2.5p2: Alternative tokens behave the same as its primary token
148 // except for their spellings.
149 Diag(MacroNameTok, getLangOpts().MicrosoftExt
150 ? diag::ext_pp_operator_used_as_macro_name
151 : diag::err_pp_operator_used_as_macro_name)
152 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000153
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000154 // Allow #defining |and| and friends for Microsoft compatibility or
155 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000156 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000157 }
158
159 if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
160 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
161 return Diag(MacroNameTok, diag::err_defined_macro_name);
162 }
163
164 if (isDefineUndef == 2 && II->hasMacroDefinition() &&
165 getMacroInfo(II)->isBuiltinMacro()) {
166 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
167 // and C++ [cpp.predefined]p4], but allow it as an extension.
168 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
169 }
170
171 // Okay, we got a good identifier.
172 return false;
173}
174
James Dennettf6333ac2012-06-22 05:46:07 +0000175/// \brief Lex and validate a macro name, which occurs after a
176/// \#define or \#undef.
177///
178/// This sets the token kind to eod and discards the rest
179/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if
180/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something
181/// else (e.g. \#ifdef).
Chris Lattnerf64b3522008-03-09 01:54:53 +0000182void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
183 // Read the token, don't allow macro expansion on it.
184 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000185
Douglas Gregor12785102010-08-24 20:21:13 +0000186 if (MacroNameTok.is(tok::code_completion)) {
187 if (CodeComplete)
188 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000189 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000190 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000191 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000192
193 if (!CheckMacroName(MacroNameTok, isDefineUndef))
Chris Lattner907dfe92008-11-18 07:59:24 +0000194 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000195
196 // Invalid macro name, read and discard the rest of the line and set the
197 // token kind to tok::eod if necessary.
198 if (MacroNameTok.isNot(tok::eod)) {
199 MacroNameTok.setKind(tok::eod);
200 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000201 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000202}
203
James Dennettf6333ac2012-06-22 05:46:07 +0000204/// \brief Ensure that the next token is a tok::eod token.
205///
206/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000207/// true, then we consider macros that expand to zero tokens as being ok.
208void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000209 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000210 // Lex unexpanded tokens for most directives: macros might expand to zero
211 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
212 // #line) allow empty macros.
213 if (EnableMacros)
214 Lex(Tmp);
215 else
216 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000217
Chris Lattnerf64b3522008-03-09 01:54:53 +0000218 // There should be no tokens after the directive, but we allow them as an
219 // extension.
220 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
221 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000222
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000223 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000224 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000225 // or if this is a macro-style preprocessing directive, because it is more
226 // trouble than it is worth to insert /**/ and check that there is no /**/
227 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000228 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000229 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000230 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000231 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
232 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000233 DiscardUntilEndOfDirective();
234 }
235}
236
237
238
James Dennettf6333ac2012-06-22 05:46:07 +0000239/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
240/// decided that the subsequent tokens are in the \#if'd out portion of the
241/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000242/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000243/// this \#if directive, so \#else/\#elif blocks should never be entered.
244/// If ElseOk is true, then \#else directives are ok, if not, then we have
245/// already seen one so a \#else directive is a duplicate. When this returns,
246/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000247void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
248 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000249 bool FoundElse,
250 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000251 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000252 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000253
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000254 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000255 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000256
Ted Kremenek56572ab2008-12-12 18:34:08 +0000257 if (CurPTHLexer) {
258 PTHSkipExcludedConditionalBlock();
259 return;
260 }
Mike Stump11289f42009-09-09 15:08:12 +0000261
Chris Lattnerf64b3522008-03-09 01:54:53 +0000262 // Enter raw mode to disable identifier lookup (and thus macro expansion),
263 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000264 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000265 Token Tok;
266 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000267 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000268
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000269 if (Tok.is(tok::code_completion)) {
270 if (CodeComplete)
271 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000272 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000273 continue;
274 }
275
Chris Lattnerf64b3522008-03-09 01:54:53 +0000276 // If this is the end of the buffer, we have an error.
277 if (Tok.is(tok::eof)) {
278 // Emit errors for each unterminated conditional on the stack, including
279 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000280 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000281 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000282 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
283 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000284 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000285 }
286
Chris Lattnerf64b3522008-03-09 01:54:53 +0000287 // Just return and let the caller lex after this #include.
288 break;
289 }
Mike Stump11289f42009-09-09 15:08:12 +0000290
Chris Lattnerf64b3522008-03-09 01:54:53 +0000291 // If this token is not a preprocessor directive, just skip it.
292 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
293 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000294
Chris Lattnerf64b3522008-03-09 01:54:53 +0000295 // We just parsed a # character at the start of a line, so we're in
296 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000297 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000298 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000299 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000300
Mike Stump11289f42009-09-09 15:08:12 +0000301
Chris Lattnerf64b3522008-03-09 01:54:53 +0000302 // Read the next token, the directive flavor.
303 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000304
Chris Lattnerf64b3522008-03-09 01:54:53 +0000305 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
306 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000307 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000308 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000309 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000310 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000311 continue;
312 }
313
314 // If the first letter isn't i or e, it isn't intesting to us. We know that
315 // this is safe in the face of spelling differences, because there is no way
316 // to spell an i/e in a strange way that is another letter. Skipping this
317 // allows us to avoid looking up the identifier info for #define/#undef and
318 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000319 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000320
Alp Toker2d57cea2014-05-17 04:53:25 +0000321 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000322 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000324 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000325 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000326 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000327 continue;
328 }
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattnerf64b3522008-03-09 01:54:53 +0000330 // Get the identifier name without trigraphs or embedded newlines. Note
331 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
332 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000333 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000334 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000335 if (!Tok.needsCleaning() && RI.size() < 20) {
336 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000337 } else {
338 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000339 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000340 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000341 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000342 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000343 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000344 continue;
345 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000346 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000347 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348 }
Mike Stump11289f42009-09-09 15:08:12 +0000349
Benjamin Kramer144884642009-12-31 13:32:38 +0000350 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000351 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000352 if (Sub.empty() || // "if"
353 Sub == "def" || // "ifdef"
354 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000355 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
356 // bother parsing the condition.
357 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000358 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000359 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000360 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000361 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000362 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000363 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000364 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000365 PPConditionalInfo CondInfo;
366 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000367 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000368 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000369 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000370
Chris Lattnerf64b3522008-03-09 01:54:53 +0000371 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000372 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000373 // Restore the value of LexingRawMode so that trailing comments
374 // are handled correctly, if we've reached the outermost block.
375 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000376 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000377 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000378 if (Callbacks)
379 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000380 break;
Richard Smithd0124572012-06-21 00:35:03 +0000381 } else {
382 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000383 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000384 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385 // #else directive in a skipping conditional. If not in some other
386 // skipping conditional, and if #else hasn't already been seen, enter it
387 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000388 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000389
Chris Lattnerf64b3522008-03-09 01:54:53 +0000390 // If this is a #else with a #else before it, report the error.
391 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000392
Chris Lattnerf64b3522008-03-09 01:54:53 +0000393 // Note that we've seen a #else in this conditional.
394 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Chris Lattnerf64b3522008-03-09 01:54:53 +0000396 // If the conditional is at the top level, and the #if block wasn't
397 // entered, enter the #else block now.
398 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
399 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000400 // Restore the value of LexingRawMode so that trailing comments
401 // are handled correctly.
402 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000403 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000404 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000405 if (Callbacks)
406 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000407 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000408 } else {
409 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000410 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000411 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000412 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000413
John Thompson17c35732013-12-04 20:19:30 +0000414 // If this is a #elif with a #else before it, report the error.
415 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
416
Chris Lattnerf64b3522008-03-09 01:54:53 +0000417 // If this is in a skipping block or if we're already handled this #if
418 // block, don't bother parsing the condition.
419 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
420 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000421 } else {
John Thompson17c35732013-12-04 20:19:30 +0000422 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000423 // Restore the value of LexingRawMode so that identifiers are
424 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000425 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
426 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000427 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000428 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000429 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000430 if (Callbacks) {
431 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000432 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000433 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000434 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000435 }
436 // If this condition is true, enter it!
437 if (CondValue) {
438 CondInfo.FoundNonSkip = true;
439 break;
440 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000441 }
442 }
443 }
Mike Stump11289f42009-09-09 15:08:12 +0000444
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000445 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000446 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000447 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000448 }
449
450 // Finally, if we are out of the conditional (saw an #endif or ran off the end
451 // of the file, just stop skipping and return to lexing whatever came after
452 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000453 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000454
455 if (Callbacks) {
456 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
457 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
458 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000459}
460
Ted Kremenek56572ab2008-12-12 18:34:08 +0000461void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000462
463 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000464 assert(CurPTHLexer);
465 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000466
Ted Kremenek56572ab2008-12-12 18:34:08 +0000467 // Skip to the next '#else', '#elif', or #endif.
468 if (CurPTHLexer->SkipBlock()) {
469 // We have reached an #endif. Both the '#' and 'endif' tokens
470 // have been consumed by the PTHLexer. Just pop off the condition level.
471 PPConditionalInfo CondInfo;
472 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000473 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000474 assert(!InCond && "Can't be skipping if not in a conditional!");
475 break;
476 }
Mike Stump11289f42009-09-09 15:08:12 +0000477
Ted Kremenek56572ab2008-12-12 18:34:08 +0000478 // We have reached a '#else' or '#elif'. Lex the next token to get
479 // the directive flavor.
480 Token Tok;
481 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000482
Ted Kremenek56572ab2008-12-12 18:34:08 +0000483 // We can actually look up the IdentifierInfo here since we aren't in
484 // raw mode.
485 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
486
487 if (K == tok::pp_else) {
488 // #else: Enter the else condition. We aren't in a nested condition
489 // since we skip those. We're always in the one matching the last
490 // blocked we skipped.
491 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
492 // Note that we've seen a #else in this conditional.
493 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000494
Ted Kremenek56572ab2008-12-12 18:34:08 +0000495 // If the #if block wasn't entered then enter the #else block now.
496 if (!CondInfo.FoundNonSkip) {
497 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000498
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000499 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000500 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000501 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000502 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000503
Ted Kremenek56572ab2008-12-12 18:34:08 +0000504 break;
505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
Ted Kremenek56572ab2008-12-12 18:34:08 +0000507 // Otherwise skip this block.
508 continue;
509 }
Mike Stump11289f42009-09-09 15:08:12 +0000510
Ted Kremenek56572ab2008-12-12 18:34:08 +0000511 assert(K == tok::pp_elif);
512 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
513
514 // If this is a #elif with a #else before it, report the error.
515 if (CondInfo.FoundElse)
516 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000517
Ted Kremenek56572ab2008-12-12 18:34:08 +0000518 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000519 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000520 if (CondInfo.FoundNonSkip)
521 continue;
522
523 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000524 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000525 CurPTHLexer->ParsingPreprocessorDirective = true;
526 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
527 CurPTHLexer->ParsingPreprocessorDirective = false;
528
529 // If this condition is true, enter it!
530 if (ShouldEnter) {
531 CondInfo.FoundNonSkip = true;
532 break;
533 }
534
535 // Otherwise, skip this block and go to the next one.
536 continue;
537 }
538}
539
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000540Module *Preprocessor::getModuleForLocation(SourceLocation FilenameLoc) {
541 ModuleMap &ModMap = HeaderInfo.getModuleMap();
542 if (SourceMgr.isInMainFile(FilenameLoc)) {
543 if (Module *CurMod = getCurrentModule())
544 return CurMod; // Compiling a module.
545 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
546 }
547 // Try to determine the module of the include directive.
Daniel Jasper88d86952013-12-03 20:30:36 +0000548 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
Manuel Klimek98a9a6c2014-03-19 10:22:36 +0000549 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(FilenameLoc));
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000550 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
551 // The include comes from a file.
552 return ModMap.findModuleForHeader(EntryOfIncl).getModule();
553 } else {
554 // The include does not come from a file,
555 // so it is probably a module compilation.
556 return getCurrentModule();
557 }
558}
559
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000560const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000561 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000562 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000563 bool isAngled,
564 const DirectoryLookup *FromDir,
565 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000566 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000567 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000568 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000569 bool SkipCache) {
Will Wilson0fafd342013-12-27 19:46:16 +0000570 // If the header lookup mechanism may be relative to the current inclusion
571 // stack, record the parent #includes.
572 SmallVector<const FileEntry *, 16> Includers;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000573 if (!FromDir) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000574 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000575 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000576
Chris Lattner022923a2009-02-04 19:45:07 +0000577 // If there is no file entry associated with this file, it must be the
578 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000579 // it won't be scanned for preprocessor directives. If we have the
580 // predefines buffer, resolve #include references (which come from the
581 // -include command line argument) as if they came from the main file, this
582 // affects file lookup etc.
Will Wilson0fafd342013-12-27 19:46:16 +0000583 if (!FileEnt)
584 FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
585
586 if (FileEnt)
587 Includers.push_back(FileEnt);
588
589 // MSVC searches the current include stack from top to bottom for
590 // headers included by quoted include directives.
591 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000592 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000593 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
594 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
595 if (IsFileLexer(ISEntry))
596 if ((FileEnt = SourceMgr.getFileEntryForID(
597 ISEntry.ThePPLexer->getFileID())))
598 Includers.push_back(FileEnt);
599 }
Chris Lattner022923a2009-02-04 19:45:07 +0000600 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000601 }
Mike Stump11289f42009-09-09 15:08:12 +0000602
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000603 // Do a standard file entry lookup.
604 CurDir = CurDirLookup;
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000605 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000606 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
607 RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000608 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000609 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000610 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
611 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000612 return FE;
613 }
Mike Stump11289f42009-09-09 15:08:12 +0000614
Will Wilson0fafd342013-12-27 19:46:16 +0000615 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000616 // Otherwise, see if this is a subframework header. If so, this is relative
617 // to one of the headers on the #include stack. Walk the list of the current
618 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000619 if (IsFileLexer()) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000620 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000621 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000622 SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000623 SuggestedModule))) {
624 if (SuggestedModule && !LangOpts.AsmPreprocessor)
625 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
626 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000627 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000628 }
629 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000630 }
Mike Stump11289f42009-09-09 15:08:12 +0000631
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000632 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
633 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000634 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000635 if ((CurFileEnt =
Ben Langmuir71e1a642014-05-05 21:44:13 +0000636 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000637 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000638 Filename, CurFileEnt, SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000639 SuggestedModule))) {
640 if (SuggestedModule && !LangOpts.AsmPreprocessor)
641 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
642 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000643 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000644 }
645 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000646 }
647 }
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000649 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000650 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000651}
652
Chris Lattnerf64b3522008-03-09 01:54:53 +0000653
654//===----------------------------------------------------------------------===//
655// Preprocessor Directive Handling.
656//===----------------------------------------------------------------------===//
657
David Blaikied5321242012-06-06 18:52:13 +0000658class Preprocessor::ResetMacroExpansionHelper {
659public:
660 ResetMacroExpansionHelper(Preprocessor *pp)
661 : PP(pp), save(pp->DisableMacroExpansion) {
662 if (pp->MacroExpansionInDirectivesOverride)
663 pp->DisableMacroExpansion = false;
664 }
665 ~ResetMacroExpansionHelper() {
666 PP->DisableMacroExpansion = save;
667 }
668private:
669 Preprocessor *PP;
670 bool save;
671};
672
Chris Lattnerf64b3522008-03-09 01:54:53 +0000673/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000674/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000675/// lexer/preprocessor state, and advances the lexer(s) so that the next token
676/// read is the correct one.
677void Preprocessor::HandleDirective(Token &Result) {
678 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000679
Chris Lattnerf64b3522008-03-09 01:54:53 +0000680 // We just parsed a # character at the start of a line, so we're in directive
681 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000682 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000683 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000684 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000685
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000686 bool ImmediatelyAfterTopLevelIfndef =
687 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
688 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
689
Chris Lattnerf64b3522008-03-09 01:54:53 +0000690 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000691
Chris Lattnerf64b3522008-03-09 01:54:53 +0000692 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000693 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000694 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000695 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000696
Chris Lattner2d17ab72009-03-18 21:00:25 +0000697 // Save the '#' token in case we need to return it later.
698 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattnerf64b3522008-03-09 01:54:53 +0000700 // Read the next token, the directive flavor. This isn't expanded due to
701 // C99 6.10.3p8.
702 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000703
Chris Lattnerf64b3522008-03-09 01:54:53 +0000704 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
705 // #define A(x) #x
706 // A(abc
707 // #warning blah
708 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000709 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
710 // not support this for #include-like directives, since that can result in
711 // terrible diagnostics, and does not work in GCC.
712 if (InMacroArgs) {
713 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
714 switch (II->getPPKeywordID()) {
715 case tok::pp_include:
716 case tok::pp_import:
717 case tok::pp_include_next:
718 case tok::pp___include_macros:
719 Diag(Result, diag::err_embedded_include) << II->getName();
720 DiscardUntilEndOfDirective();
721 return;
722 default:
723 break;
724 }
725 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000726 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000727 }
Mike Stump11289f42009-09-09 15:08:12 +0000728
David Blaikied5321242012-06-06 18:52:13 +0000729 // Temporarily enable macro expansion if set so
730 // and reset to previous state when returning from this function.
731 ResetMacroExpansionHelper helper(this);
732
Chris Lattnerf64b3522008-03-09 01:54:53 +0000733 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000734 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000735 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000736 case tok::code_completion:
737 if (CodeComplete)
738 CodeComplete->CodeCompleteDirective(
739 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000740 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000741 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000742 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000743 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000744 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000745 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000746 default:
747 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000748 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattnerf64b3522008-03-09 01:54:53 +0000750 // Ask what the preprocessor keyword ID is.
751 switch (II->getPPKeywordID()) {
752 default: break;
753 // C99 6.10.1 - Conditional Inclusion.
754 case tok::pp_if:
755 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
756 case tok::pp_ifdef:
757 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
758 case tok::pp_ifndef:
759 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
760 case tok::pp_elif:
761 return HandleElifDirective(Result);
762 case tok::pp_else:
763 return HandleElseDirective(Result);
764 case tok::pp_endif:
765 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000766
Chris Lattnerf64b3522008-03-09 01:54:53 +0000767 // C99 6.10.2 - Source File Inclusion.
768 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000769 // Handle #include.
770 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000771 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000772 // Handle -imacros.
773 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000774
Chris Lattnerf64b3522008-03-09 01:54:53 +0000775 // C99 6.10.3 - Macro Replacement.
776 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000777 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000778 case tok::pp_undef:
779 return HandleUndefDirective(Result);
780
781 // C99 6.10.4 - Line Control.
782 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000783 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000784
Chris Lattnerf64b3522008-03-09 01:54:53 +0000785 // C99 6.10.5 - Error Directive.
786 case tok::pp_error:
787 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattnerf64b3522008-03-09 01:54:53 +0000789 // C99 6.10.6 - Pragma Directive.
790 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000791 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000792
Chris Lattnerf64b3522008-03-09 01:54:53 +0000793 // GNU Extensions.
794 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000795 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000796 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000797 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000798
Chris Lattnerf64b3522008-03-09 01:54:53 +0000799 case tok::pp_warning:
800 Diag(Result, diag::ext_pp_warning_directive);
801 return HandleUserDiagnosticDirective(Result, true);
802 case tok::pp_ident:
803 return HandleIdentSCCSDirective(Result);
804 case tok::pp_sccs:
805 return HandleIdentSCCSDirective(Result);
806 case tok::pp_assert:
807 //isExtension = true; // FIXME: implement #assert
808 break;
809 case tok::pp_unassert:
810 //isExtension = true; // FIXME: implement #unassert
811 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000812
Douglas Gregor663b48f2012-01-03 19:48:16 +0000813 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000814 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000815 return HandleMacroPublicDirective(Result);
816 break;
817
Douglas Gregor663b48f2012-01-03 19:48:16 +0000818 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000819 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000820 return HandleMacroPrivateDirective(Result);
821 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000822 }
823 break;
824 }
Mike Stump11289f42009-09-09 15:08:12 +0000825
Chris Lattner2d17ab72009-03-18 21:00:25 +0000826 // If this is a .S file, treat unknown # directives as non-preprocessor
827 // directives. This is important because # may be a comment or introduce
828 // various pseudo-ops. Just return the # token and push back the following
829 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000830 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000831 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000832 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000833 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000834 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000835
836 // If the second token is a hashhash token, then we need to translate it to
837 // unknown so the token lexer doesn't try to perform token pasting.
838 if (Result.is(tok::hashhash))
839 Toks[1].setKind(tok::unknown);
840
Chris Lattner2d17ab72009-03-18 21:00:25 +0000841 // Enter this token stream so that we re-lex the tokens. Make sure to
842 // enable macro expansion, in case the token after the # is an identifier
843 // that is expanded.
844 EnterTokenStream(Toks, 2, false, true);
845 return;
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chris Lattnerf64b3522008-03-09 01:54:53 +0000848 // If we reached here, the preprocessing token is not valid!
849 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000850
Chris Lattnerf64b3522008-03-09 01:54:53 +0000851 // Read the rest of the PP line.
852 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000853
Chris Lattnerf64b3522008-03-09 01:54:53 +0000854 // Okay, we're done parsing the directive.
855}
856
Chris Lattner76e68962009-01-26 06:19:46 +0000857/// GetLineValue - Convert a numeric token into an unsigned value, emitting
858/// Diagnostic DiagID if it is invalid, and returning the value in Val.
859static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000860 unsigned DiagID, Preprocessor &PP,
861 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000862 if (DigitTok.isNot(tok::numeric_constant)) {
863 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000864
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000865 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000866 PP.DiscardUntilEndOfDirective();
867 return true;
868 }
Mike Stump11289f42009-09-09 15:08:12 +0000869
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000870 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000871 IntegerBuffer.resize(DigitTok.getLength());
872 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000873 bool Invalid = false;
874 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
875 if (Invalid)
876 return true;
877
Chris Lattnerd66f1722009-04-18 18:35:15 +0000878 // Verify that we have a simple digit-sequence, and compute the value. This
879 // is always a simple digit string computed in decimal, so we do this manually
880 // here.
881 Val = 0;
882 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +0000883 // C++1y [lex.fcon]p1:
884 // Optional separating single quotes in a digit-sequence are ignored
885 if (DigitTokBegin[i] == '\'')
886 continue;
887
Jordan Rosea7d03842013-02-08 22:30:41 +0000888 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000889 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000890 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000891 PP.DiscardUntilEndOfDirective();
892 return true;
893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
Chris Lattnerd66f1722009-04-18 18:35:15 +0000895 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
896 if (NextVal < Val) { // overflow.
897 PP.Diag(DigitTok, DiagID);
898 PP.DiscardUntilEndOfDirective();
899 return true;
900 }
901 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000902 }
Mike Stump11289f42009-09-09 15:08:12 +0000903
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000904 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000905 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
906 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Chris Lattner76e68962009-01-26 06:19:46 +0000908 return false;
909}
910
James Dennettf6333ac2012-06-22 05:46:07 +0000911/// \brief Handle a \#line directive: C99 6.10.4.
912///
913/// The two acceptable forms are:
914/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000915/// # line digit-sequence
916/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000917/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000918void Preprocessor::HandleLineDirective(Token &Tok) {
919 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
920 // expanded.
921 Token DigitTok;
922 Lex(DigitTok);
923
Chris Lattner100c65e2009-01-26 05:29:08 +0000924 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000925 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000926 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000927 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000928
929 if (LineNo == 0)
930 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000931
Chris Lattner76e68962009-01-26 06:19:46 +0000932 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
933 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000934 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000935 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000936 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000937 if (LineNo >= LineLimit)
938 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000939 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000940 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000942 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000943 Token StrTok;
944 Lex(StrTok);
945
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000946 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
947 // string followed by eod.
948 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000949 ; // ok
950 else if (StrTok.isNot(tok::string_literal)) {
951 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000952 return DiscardUntilEndOfDirective();
953 } else if (StrTok.hasUDSuffix()) {
954 Diag(StrTok, diag::err_invalid_string_udl);
955 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000956 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000957 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +0000958 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000959 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000960 if (Literal.hadError)
961 return DiscardUntilEndOfDirective();
962 if (Literal.Pascal) {
963 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
964 return DiscardUntilEndOfDirective();
965 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000966 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000967
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000968 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000969 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
970 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000971 }
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000973 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattner839150e2009-03-27 17:13:49 +0000975 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000976 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
977 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000978 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000979}
980
Chris Lattner76e68962009-01-26 06:19:46 +0000981/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
982/// marker directive.
983static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
984 bool &IsSystemHeader, bool &IsExternCHeader,
985 Preprocessor &PP) {
986 unsigned FlagVal;
987 Token FlagTok;
988 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000989 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000990 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
991 return true;
992
993 if (FlagVal == 1) {
994 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000995
Chris Lattner76e68962009-01-26 06:19:46 +0000996 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000997 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000998 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
999 return true;
1000 } else if (FlagVal == 2) {
1001 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001002
Chris Lattner1c967782009-02-04 06:25:26 +00001003 SourceManager &SM = PP.getSourceManager();
1004 // If we are leaving the current presumed file, check to make sure the
1005 // presumed include stack isn't empty!
1006 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001007 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001008 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001009 if (PLoc.isInvalid())
1010 return true;
1011
Chris Lattner1c967782009-02-04 06:25:26 +00001012 // If there is no include loc (main file) or if the include loc is in a
1013 // different physical file, then we aren't in a "1" line marker flag region.
1014 SourceLocation IncLoc = PLoc.getIncludeLoc();
1015 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001016 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001017 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1018 PP.DiscardUntilEndOfDirective();
1019 return true;
1020 }
Mike Stump11289f42009-09-09 15:08:12 +00001021
Chris Lattner76e68962009-01-26 06:19:46 +00001022 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001023 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001024 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1025 return true;
1026 }
1027
1028 // We must have 3 if there are still flags.
1029 if (FlagVal != 3) {
1030 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001031 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001032 return true;
1033 }
Mike Stump11289f42009-09-09 15:08:12 +00001034
Chris Lattner76e68962009-01-26 06:19:46 +00001035 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001036
Chris Lattner76e68962009-01-26 06:19:46 +00001037 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001038 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001039 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001040 return true;
1041
1042 // We must have 4 if there is yet another flag.
1043 if (FlagVal != 4) {
1044 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001045 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001046 return true;
1047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048
Chris Lattner76e68962009-01-26 06:19:46 +00001049 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001050
Chris Lattner76e68962009-01-26 06:19:46 +00001051 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001052 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001053
1054 // There are no more valid flags here.
1055 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001056 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001057 return true;
1058}
1059
1060/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1061/// one of the following forms:
1062///
1063/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001064/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001065/// # 42 "file" ('1' | '2')? '3' '4'?
1066///
1067void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1068 // Validate the number and convert it to an unsigned. GNU does not have a
1069 // line # limit other than it fit in 32-bits.
1070 unsigned LineNo;
1071 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001072 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001073 return;
Mike Stump11289f42009-09-09 15:08:12 +00001074
Chris Lattner76e68962009-01-26 06:19:46 +00001075 Token StrTok;
1076 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001077
Chris Lattner76e68962009-01-26 06:19:46 +00001078 bool IsFileEntry = false, IsFileExit = false;
1079 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001080 int FilenameID = -1;
1081
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001082 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1083 // string followed by eod.
1084 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001085 ; // ok
1086 else if (StrTok.isNot(tok::string_literal)) {
1087 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001088 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001089 } else if (StrTok.hasUDSuffix()) {
1090 Diag(StrTok, diag::err_invalid_string_udl);
1091 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001092 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001093 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001094 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001095 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001096 if (Literal.hadError)
1097 return DiscardUntilEndOfDirective();
1098 if (Literal.Pascal) {
1099 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1100 return DiscardUntilEndOfDirective();
1101 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001102 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001103
Chris Lattner76e68962009-01-26 06:19:46 +00001104 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001105 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001106 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001107 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001108 }
Mike Stump11289f42009-09-09 15:08:12 +00001109
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001110 // Create a line note with this information.
1111 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001112 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001113 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001114
Chris Lattner839150e2009-03-27 17:13:49 +00001115 // If the preprocessor has callbacks installed, notify them of the #line
1116 // change. This is used so that the line marker comes out in -E mode for
1117 // example.
1118 if (Callbacks) {
1119 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1120 if (IsFileEntry)
1121 Reason = PPCallbacks::EnterFile;
1122 else if (IsFileExit)
1123 Reason = PPCallbacks::ExitFile;
1124 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1125 if (IsExternCHeader)
1126 FileKind = SrcMgr::C_ExternCSystem;
1127 else if (IsSystemHeader)
1128 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001129
Chris Lattnerc745cec2010-04-14 04:28:50 +00001130 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001131 }
Chris Lattner76e68962009-01-26 06:19:46 +00001132}
1133
1134
Chris Lattner38d7fd22009-01-26 05:30:54 +00001135/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1136///
Mike Stump11289f42009-09-09 15:08:12 +00001137void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001138 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001139 // PTH doesn't emit #warning or #error directives.
1140 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001141 return CurPTHLexer->DiscardToEndOfLine();
1142
Chris Lattnerf64b3522008-03-09 01:54:53 +00001143 // Read the rest of the line raw. We do this because we don't want macros
1144 // to be expanded and we don't require that the tokens be valid preprocessing
1145 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1146 // collapse multiple consequtive white space between tokens, but this isn't
1147 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001148 SmallString<128> Message;
1149 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001150
1151 // Find the first non-whitespace character, so that we can make the
1152 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001153 StringRef Msg = Message.str().ltrim(" ");
1154
Chris Lattner100c65e2009-01-26 05:29:08 +00001155 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001156 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001157 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001158 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001159}
1160
1161/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1162///
1163void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1164 // Yes, this directive is an extension.
1165 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001166
Chris Lattnerf64b3522008-03-09 01:54:53 +00001167 // Read the string argument.
1168 Token StrTok;
1169 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001170
Chris Lattnerf64b3522008-03-09 01:54:53 +00001171 // If the token kind isn't a string, it's a malformed directive.
1172 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001173 StrTok.isNot(tok::wide_string_literal)) {
1174 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001175 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001176 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001177 return;
1178 }
Mike Stump11289f42009-09-09 15:08:12 +00001179
Richard Smithd67aea22012-03-06 03:21:47 +00001180 if (StrTok.hasUDSuffix()) {
1181 Diag(StrTok, diag::err_invalid_string_udl);
1182 return DiscardUntilEndOfDirective();
1183 }
1184
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001185 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001186 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001187
Douglas Gregordc970f02010-03-16 22:30:13 +00001188 if (Callbacks) {
1189 bool Invalid = false;
1190 std::string Str = getSpelling(StrTok, &Invalid);
1191 if (!Invalid)
1192 Callbacks->Ident(Tok.getLocation(), Str);
1193 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001194}
1195
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001196/// \brief Handle a #public directive.
1197void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001198 Token MacroNameTok;
1199 ReadMacroName(MacroNameTok, 2);
1200
1201 // Error reading macro name? If so, diagnostic already issued.
1202 if (MacroNameTok.is(tok::eod))
1203 return;
1204
Douglas Gregor663b48f2012-01-03 19:48:16 +00001205 // Check to see if this is the last token on the #__public_macro line.
1206 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001207
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001208 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001209 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001210 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001211
1212 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001213 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001214 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001215 return;
1216 }
1217
1218 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001219 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1220 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001221}
1222
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001223/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001224void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1225 Token MacroNameTok;
1226 ReadMacroName(MacroNameTok, 2);
1227
1228 // Error reading macro name? If so, diagnostic already issued.
1229 if (MacroNameTok.is(tok::eod))
1230 return;
1231
Douglas Gregor663b48f2012-01-03 19:48:16 +00001232 // Check to see if this is the last token on the #__private_macro line.
1233 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001234
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001235 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001236 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001237 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001238
1239 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001240 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001241 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001242 return;
1243 }
1244
1245 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001246 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1247 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001248}
1249
Chris Lattnerf64b3522008-03-09 01:54:53 +00001250//===----------------------------------------------------------------------===//
1251// Preprocessor Include Directive Handling.
1252//===----------------------------------------------------------------------===//
1253
1254/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001255/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001256/// true if the input filename was in <>'s or false if it were in ""'s. The
1257/// caller is expected to provide a buffer that is large enough to hold the
1258/// spelling of the filename, but is also expected to handle the case when
1259/// this method decides to use a different buffer.
1260bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001261 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001262 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001263 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001264
Chris Lattnerf64b3522008-03-09 01:54:53 +00001265 // Make sure the filename is <x> or "x".
1266 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001267 if (Buffer[0] == '<') {
1268 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001269 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001270 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001271 return true;
1272 }
1273 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001274 } else if (Buffer[0] == '"') {
1275 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001276 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001277 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001278 return true;
1279 }
1280 isAngled = false;
1281 } else {
1282 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001283 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001284 return true;
1285 }
Mike Stump11289f42009-09-09 15:08:12 +00001286
Chris Lattnerf64b3522008-03-09 01:54:53 +00001287 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001288 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001289 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001290 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001291 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001292 }
Mike Stump11289f42009-09-09 15:08:12 +00001293
Chris Lattnerf64b3522008-03-09 01:54:53 +00001294 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001295 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001296 return isAngled;
1297}
1298
James Dennett4a4f72d2013-11-27 01:27:40 +00001299// \brief Handle cases where the \#include name is expanded from a macro
1300// as multiple tokens, which need to be glued together.
1301//
1302// This occurs for code like:
1303// \code
1304// \#define FOO <a/b.h>
1305// \#include FOO
1306// \endcode
1307// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1308//
1309// This code concatenates and consumes tokens up to the '>' token. It returns
1310// false if the > was found, otherwise it returns true if it finds and consumes
1311// the EOD marker.
1312bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001313 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001314 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001315
John Thompsonb5353522009-10-30 13:49:06 +00001316 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001317 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001318 End = CurTok.getLocation();
1319
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001320 // FIXME: Provide code completion for #includes.
1321 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001322 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001323 Lex(CurTok);
1324 continue;
1325 }
1326
Chris Lattnerf64b3522008-03-09 01:54:53 +00001327 // Append the spelling of this token to the buffer. If there was a space
1328 // before it, add it now.
1329 if (CurTok.hasLeadingSpace())
1330 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattnerf64b3522008-03-09 01:54:53 +00001332 // Get the spelling of the token, directly into FilenameBuffer if possible.
1333 unsigned PreAppendSize = FilenameBuffer.size();
1334 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001335
Chris Lattnerf64b3522008-03-09 01:54:53 +00001336 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001337 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001338
Chris Lattnerf64b3522008-03-09 01:54:53 +00001339 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1340 if (BufPtr != &FilenameBuffer[PreAppendSize])
1341 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001342
Chris Lattnerf64b3522008-03-09 01:54:53 +00001343 // Resize FilenameBuffer to the correct size.
1344 if (CurTok.getLength() != ActualLen)
1345 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001346
Chris Lattnerf64b3522008-03-09 01:54:53 +00001347 // If we found the '>' marker, return success.
1348 if (CurTok.is(tok::greater))
1349 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001350
John Thompsonb5353522009-10-30 13:49:06 +00001351 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001352 }
1353
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001354 // If we hit the eod marker, emit an error and return true so that the caller
1355 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001356 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001357 return true;
1358}
1359
Richard Smith34f30512013-11-23 04:06:09 +00001360/// \brief Push a token onto the token stream containing an annotation.
1361static void EnterAnnotationToken(Preprocessor &PP,
1362 SourceLocation Begin, SourceLocation End,
1363 tok::TokenKind Kind, void *AnnotationVal) {
1364 Token *Tok = new Token[1];
1365 Tok[0].startToken();
1366 Tok[0].setKind(Kind);
1367 Tok[0].setLocation(Begin);
1368 Tok[0].setAnnotationEndLoc(End);
1369 Tok[0].setAnnotationValue(AnnotationVal);
1370 PP.EnterTokenStream(Tok, 1, true, true);
1371}
1372
James Dennettf6333ac2012-06-22 05:46:07 +00001373/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1374/// the file to be included from the lexer, then include it! This is a common
1375/// routine with functionality shared between \#include, \#include_next and
1376/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001377/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001378void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1379 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001380 const DirectoryLookup *LookupFrom,
1381 bool isImport) {
1382
1383 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001384 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001385
Chris Lattnerf64b3522008-03-09 01:54:53 +00001386 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001387 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001388 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001389 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001390 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001391
Chris Lattnerf64b3522008-03-09 01:54:53 +00001392 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001393 case tok::eod:
1394 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001395 return;
Mike Stump11289f42009-09-09 15:08:12 +00001396
Chris Lattnerf64b3522008-03-09 01:54:53 +00001397 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001398 case tok::string_literal:
1399 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001400 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001401 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001402 break;
Mike Stump11289f42009-09-09 15:08:12 +00001403
Chris Lattnerf64b3522008-03-09 01:54:53 +00001404 case tok::less:
1405 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1406 // case, glue the tokens together into FilenameBuffer and interpret those.
1407 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001408 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001409 return; // Found <eod> but no ">"? Diagnostic already emitted.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001410 Filename = FilenameBuffer.str();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001411 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001412 break;
1413 default:
1414 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1415 DiscardUntilEndOfDirective();
1416 return;
1417 }
Mike Stump11289f42009-09-09 15:08:12 +00001418
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001419 CharSourceRange FilenameRange
1420 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001421 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001422 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001423 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001424 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1425 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001426 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001427 DiscardUntilEndOfDirective();
1428 return;
1429 }
Mike Stump11289f42009-09-09 15:08:12 +00001430
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001431 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001432 // we allow macros that expand to nothing after the filename, because this
1433 // falls into the category of "#include pp-tokens new-line" specified in
1434 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001435 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001436
1437 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001438 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1439 Diag(FilenameTok, diag::err_pp_include_too_deep);
1440 return;
1441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
John McCall32f5fe12011-09-30 05:12:12 +00001443 // Complain about attempts to #include files in an audit pragma.
1444 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1445 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1446 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1447
1448 // Immediately leave the pragma.
1449 PragmaARCCFCodeAuditedLoc = SourceLocation();
1450 }
1451
Aaron Ballman611306e2012-03-02 22:51:54 +00001452 if (HeaderInfo.HasIncludeAliasMap()) {
1453 // Map the filename with the brackets still attached. If the name doesn't
1454 // map to anything, fall back on the filename we've already gotten the
1455 // spelling for.
1456 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1457 if (!NewName.empty())
1458 Filename = NewName;
1459 }
1460
Chris Lattnerf64b3522008-03-09 01:54:53 +00001461 // Search include directories.
1462 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001463 SmallString<1024> SearchPath;
1464 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001465 // We get the raw path only if we have 'Callbacks' to which we later pass
1466 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001467 ModuleMap::KnownHeader SuggestedModule;
1468 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001469 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001470 if (LangOpts.MSVCCompat) {
1471 NormalizedPath = Filename.str();
1472 llvm::sys::fs::normalize_separators(NormalizedPath);
1473 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001474 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001475 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Craig Topperd2d442c2014-05-17 23:10:59 +00001476 isAngled, LookupFrom, CurDir, Callbacks ? &SearchPath : nullptr,
1477 Callbacks ? &RelativePath : nullptr,
1478 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : nullptr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001479
Douglas Gregor11729f02011-11-30 18:12:06 +00001480 if (Callbacks) {
1481 if (!File) {
1482 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001483 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001484 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1485 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1486 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001487 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001488 HeaderInfo.AddSearchPath(DL, isAngled);
1489
1490 // Try the lookup again, skipping the cache.
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001491 File = LookupFile(FilenameLoc,
1492 LangOpts.MSVCCompat ? NormalizedPath.c_str()
1493 : Filename,
Craig Topperd2d442c2014-05-17 23:10:59 +00001494 isAngled, LookupFrom, CurDir, nullptr, nullptr,
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001495 HeaderInfo.getHeaderSearchOpts().ModuleMaps
Daniel Jasper07e6c402013-08-05 20:26:17 +00001496 ? &SuggestedModule
Craig Topperd2d442c2014-05-17 23:10:59 +00001497 : nullptr,
Daniel Jasper07e6c402013-08-05 20:26:17 +00001498 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001499 }
1500 }
1501 }
1502
Daniel Jasper07e6c402013-08-05 20:26:17 +00001503 if (!SuggestedModule || !getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001504 // Notify the callback object that we've seen an inclusion directive.
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001505 Callbacks->InclusionDirective(HashLoc, IncludeTok,
1506 LangOpts.MSVCCompat ? NormalizedPath.c_str()
1507 : Filename,
1508 isAngled, FilenameRange, File, SearchPath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001509 RelativePath, /*ImportedModule=*/nullptr);
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001510 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001511 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001512
1513 if (!File) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001514 if (!SuppressIncludeNotFoundError) {
1515 // If the file could not be located and it was included via angle
1516 // brackets, we can attempt a lookup as though it were a quoted path to
1517 // provide the user with a possible fixit.
1518 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001519 File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001520 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Craig Topperd2d442c2014-05-17 23:10:59 +00001521 false, LookupFrom, CurDir, Callbacks ? &SearchPath : nullptr,
1522 Callbacks ? &RelativePath : nullptr,
1523 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1524 : nullptr);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001525 if (File) {
1526 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1527 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1528 Filename <<
1529 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1530 }
1531 }
1532 // If the file is still not found, just go with the vanilla diagnostic
1533 if (!File)
1534 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1535 }
1536 if (!File)
1537 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001538 }
1539
Douglas Gregor97eec242011-09-15 22:00:41 +00001540 // If we are supposed to import a module rather than including the header,
1541 // do so now.
Ben Langmuirb537a3a2014-07-23 15:30:23 +00001542 if (SuggestedModule && getLangOpts().Modules &&
1543 SuggestedModule.getModule()->getTopLevelModuleName() !=
1544 getLangOpts().ImplementationOfModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001545 // Compute the module access path corresponding to this module.
1546 // FIXME: Should we have a second loadModule() overload to avoid this
1547 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001548 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001549 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001550 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1551 FilenameTok.getLocation()));
1552 std::reverse(Path.begin(), Path.end());
1553
Douglas Gregor41e115a2011-11-30 18:02:36 +00001554 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001555 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001556 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1557 if (I)
1558 PathString += '.';
1559 PathString += Path[I].first->getName();
1560 }
1561 int IncludeKind = 0;
1562
1563 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1564 case tok::pp_include:
1565 IncludeKind = 0;
1566 break;
1567
1568 case tok::pp_import:
1569 IncludeKind = 1;
1570 break;
1571
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001572 case tok::pp_include_next:
1573 IncludeKind = 2;
1574 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001575
1576 case tok::pp___include_macros:
1577 IncludeKind = 3;
1578 break;
1579
1580 default:
1581 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001582 }
1583
Douglas Gregor2537a362011-12-08 17:01:29 +00001584 // Determine whether we are actually building the module that this
1585 // include directive maps to.
1586 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001587 = Path[0].first->getName() == getLangOpts().CurrentModule;
Richard Smith34f30512013-11-23 04:06:09 +00001588
David Blaikiebbafb8a2012-03-11 07:00:24 +00001589 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001590 // If we're not building the imported module, warn that we're going
1591 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001592 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001593 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1594 /*IsTokenRange=*/false);
1595 Diag(HashLoc, diag::warn_auto_module_import)
1596 << IncludeKind << PathString
1597 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001598 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001599 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001600
Richard Smithce587f52013-11-15 04:24:58 +00001601 // Load the module. Only make macros visible. We'll make the declarations
1602 // visible when the parser gets here.
1603 Module::NameVisibilityKind Visibility = Module::MacrosVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001604 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001605 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1606 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001607 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001608 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001609
1610 if (!Imported && hadModuleLoaderFatalFailure()) {
1611 // With a fatal failure in the module loader, we abort parsing.
1612 Token &Result = IncludeTok;
1613 if (CurLexer) {
1614 Result.startToken();
1615 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1616 CurLexer->cutOffLexing();
1617 } else {
1618 assert(CurPTHLexer && "#include but no current lexer set!");
1619 CurPTHLexer->getEOF(Result);
1620 }
1621 return;
1622 }
Richard Smithce587f52013-11-15 04:24:58 +00001623
Douglas Gregor2537a362011-12-08 17:01:29 +00001624 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001625 if (!BuildingImportedModule && Imported) {
1626 if (Callbacks) {
1627 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1628 FilenameRange, File,
1629 SearchPath, RelativePath, Imported);
1630 }
Richard Smithce587f52013-11-15 04:24:58 +00001631
1632 if (IncludeKind != 3) {
1633 // Let the parser know that we hit a module import, and it should
1634 // make the module visible.
1635 // FIXME: Produce this as the current token directly, rather than
1636 // allocating a new token for it.
Richard Smith34f30512013-11-23 04:06:09 +00001637 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include,
1638 Imported);
Richard Smithce587f52013-11-15 04:24:58 +00001639 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001640 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001641 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001642
1643 // If we failed to find a submodule that we expected to find, we can
1644 // continue. Otherwise, there's an error in the included file, so we
1645 // don't want to include it.
1646 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1647 return;
1648 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001649 }
1650
1651 if (Callbacks && SuggestedModule) {
1652 // We didn't notify the callback object that we've seen an inclusion
1653 // directive before. Now that we are parsing the include normally and not
1654 // turning it to a module import, notify the callback object.
1655 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1656 FilenameRange, File,
1657 SearchPath, RelativePath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001658 /*ImportedModule=*/nullptr);
Douglas Gregor97eec242011-09-15 22:00:41 +00001659 }
1660
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001661 // The #included file will be considered to be a system header if either it is
1662 // in a system include directory, or if the #includer is a system include
1663 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001664 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001665 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001666 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001667
Chris Lattner72286d62010-04-19 20:44:31 +00001668 // Ask HeaderInfo if we should enter this #include file. If not, #including
1669 // this file will have no effect.
1670 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001671 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001672 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001673 return;
1674 }
1675
Chris Lattnerf64b3522008-03-09 01:54:53 +00001676 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001677 SourceLocation IncludePos = End;
1678 // If the filename string was the result of macro expansions, set the include
1679 // position on the file where it will be included and after the expansions.
1680 if (IncludePos.isMacroID())
1681 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1682 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001683 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001684
Richard Smith34f30512013-11-23 04:06:09 +00001685 // Determine if we're switching to building a new submodule, and which one.
1686 ModuleMap::KnownHeader BuildingModule;
1687 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) {
1688 Module *RequestingModule = getModuleForLocation(FilenameLoc);
1689 BuildingModule =
1690 HeaderInfo.getModuleMap().findModuleForHeader(File, RequestingModule);
1691 }
1692
1693 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00001694 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
1695 return;
Richard Smith34f30512013-11-23 04:06:09 +00001696
1697 // If we're walking into another part of the same module, let the parser
1698 // know that any future declarations are within that other submodule.
Richard Smith67294e22014-01-31 20:47:44 +00001699 if (BuildingModule) {
1700 assert(!CurSubmodule && "should not have marked this as a module yet");
1701 CurSubmodule = BuildingModule.getModule();
1702
Richard Smith34f30512013-11-23 04:06:09 +00001703 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin,
Richard Smith67294e22014-01-31 20:47:44 +00001704 CurSubmodule);
1705 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001706}
1707
James Dennettf6333ac2012-06-22 05:46:07 +00001708/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001709///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001710void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1711 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001712 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattnerf64b3522008-03-09 01:54:53 +00001714 // #include_next is like #include, except that we start searching after
1715 // the current found directory. If we can't do this, issue a
1716 // diagnostic.
1717 const DirectoryLookup *Lookup = CurDirLookup;
1718 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001719 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001720 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Craig Topperd2d442c2014-05-17 23:10:59 +00001721 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001722 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1723 } else {
1724 // Start looking up in the next directory.
1725 ++Lookup;
1726 }
Mike Stump11289f42009-09-09 15:08:12 +00001727
Douglas Gregor796d76a2010-10-20 22:00:55 +00001728 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001729}
1730
James Dennettf6333ac2012-06-22 05:46:07 +00001731/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001732void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1733 // The Microsoft #import directive takes a type library and generates header
1734 // files from it, and includes those. This is beyond the scope of what clang
1735 // does, so we ignore it and error out. However, #import can optionally have
1736 // trailing attributes that span multiple lines. We're going to eat those
1737 // so we can continue processing from there.
1738 Diag(Tok, diag::err_pp_import_directive_ms );
1739
1740 // Read tokens until we get to the end of the directive. Note that the
1741 // directive can be split over multiple lines using the backslash character.
1742 DiscardUntilEndOfDirective();
1743}
1744
James Dennettf6333ac2012-06-22 05:46:07 +00001745/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001746///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001747void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1748 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001749 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00001750 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00001751 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001752 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001753 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001754 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001755}
1756
Chris Lattner58a1eb02009-04-08 18:46:40 +00001757/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1758/// pseudo directive in the predefines buffer. This handles it by sucking all
1759/// tokens through the preprocessor and discarding them (only keeping the side
1760/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001761void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1762 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001763 // This directive should only occur in the predefines buffer. If not, emit an
1764 // error and reject it.
1765 SourceLocation Loc = IncludeMacrosTok.getLocation();
1766 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1767 Diag(IncludeMacrosTok.getLocation(),
1768 diag::pp_include_macros_out_of_predefines);
1769 DiscardUntilEndOfDirective();
1770 return;
1771 }
Mike Stump11289f42009-09-09 15:08:12 +00001772
Chris Lattnere01d82b2009-04-08 20:53:24 +00001773 // Treat this as a normal #include for checking purposes. If this is
1774 // successful, it will push a new lexer onto the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001775 HandleIncludeDirective(HashLoc, IncludeMacrosTok, nullptr, false);
Mike Stump11289f42009-09-09 15:08:12 +00001776
Chris Lattnere01d82b2009-04-08 20:53:24 +00001777 Token TmpTok;
1778 do {
1779 Lex(TmpTok);
1780 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1781 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001782}
1783
Chris Lattnerf64b3522008-03-09 01:54:53 +00001784//===----------------------------------------------------------------------===//
1785// Preprocessor Macro Directive Handling.
1786//===----------------------------------------------------------------------===//
1787
1788/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1789/// definition has just been read. Lex the rest of the arguments and the
1790/// closing ), updating MI with what we learn. Return true if an error occurs
1791/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001792bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001793 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001794
Chris Lattnerf64b3522008-03-09 01:54:53 +00001795 while (1) {
1796 LexUnexpandedToken(Tok);
1797 switch (Tok.getKind()) {
1798 case tok::r_paren:
1799 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001800 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001801 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001802 // Otherwise we have #define FOO(A,)
1803 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1804 return true;
1805 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001806 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001807 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001808 diag::warn_cxx98_compat_variadic_macro :
1809 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001810
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001811 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1812 if (LangOpts.OpenCL) {
1813 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1814 return true;
1815 }
1816
Chris Lattnerf64b3522008-03-09 01:54:53 +00001817 // Lex the token after the identifier.
1818 LexUnexpandedToken(Tok);
1819 if (Tok.isNot(tok::r_paren)) {
1820 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1821 return true;
1822 }
1823 // Add the __VA_ARGS__ identifier as an argument.
1824 Arguments.push_back(Ident__VA_ARGS__);
1825 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001826 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001827 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001828 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001829 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1830 return true;
1831 default:
1832 // Handle keywords and identifiers here to accept things like
1833 // #define Foo(for) for.
1834 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00001835 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001836 // #define X(1
1837 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1838 return true;
1839 }
1840
1841 // If this is already used as an argument, it is used multiple times (e.g.
1842 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001843 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001844 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001845 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846 return true;
1847 }
Mike Stump11289f42009-09-09 15:08:12 +00001848
Chris Lattnerf64b3522008-03-09 01:54:53 +00001849 // Add the argument to the macro info.
1850 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001851
Chris Lattnerf64b3522008-03-09 01:54:53 +00001852 // Lex the token after the identifier.
1853 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001854
Chris Lattnerf64b3522008-03-09 01:54:53 +00001855 switch (Tok.getKind()) {
1856 default: // #define X(A B
1857 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1858 return true;
1859 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001860 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001861 return false;
1862 case tok::comma: // #define X(A,
1863 break;
1864 case tok::ellipsis: // #define X(A... -> GCC extension
1865 // Diagnose extension.
1866 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001867
Chris Lattnerf64b3522008-03-09 01:54:53 +00001868 // Lex the token after the identifier.
1869 LexUnexpandedToken(Tok);
1870 if (Tok.isNot(tok::r_paren)) {
1871 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1872 return true;
1873 }
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattnerf64b3522008-03-09 01:54:53 +00001875 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001876 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001877 return false;
1878 }
1879 }
1880 }
1881}
1882
James Dennettf6333ac2012-06-22 05:46:07 +00001883/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001884/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001885void Preprocessor::HandleDefineDirective(Token &DefineTok,
1886 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001887 ++NumDefined;
1888
1889 Token MacroNameTok;
1890 ReadMacroName(MacroNameTok, 1);
Mike Stump11289f42009-09-09 15:08:12 +00001891
Chris Lattnerf64b3522008-03-09 01:54:53 +00001892 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001893 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001894 return;
1895
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001896 Token LastTok = MacroNameTok;
1897
Chris Lattnerf64b3522008-03-09 01:54:53 +00001898 // If we are supposed to keep comments in #defines, reenable comment saving
1899 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001900 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001901
Chris Lattnerf64b3522008-03-09 01:54:53 +00001902 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001903 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001904
Chris Lattnerf64b3522008-03-09 01:54:53 +00001905 Token Tok;
1906 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001907
Chris Lattnerf64b3522008-03-09 01:54:53 +00001908 // If this is a function-like macro definition, parse the argument list,
1909 // marking each of the identifiers as being used as macro arguments. Also,
1910 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001911 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001912 if (ImmediatelyAfterHeaderGuard) {
1913 // Save this macro information since it may part of a header guard.
1914 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
1915 MacroNameTok.getLocation());
1916 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001917 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001918 } else if (Tok.hasLeadingSpace()) {
1919 // This is a normal token with leading space. Clear the leading space
1920 // marker on the first token to get proper expansion.
1921 Tok.clearFlag(Token::LeadingSpace);
1922 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001923 // This is a function-like macro definition. Read the argument list.
1924 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001925 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001926 // Forget about MI.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001927 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001928 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001929 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001930 DiscardUntilEndOfDirective();
1931 return;
1932 }
1933
Chris Lattner249c38b2009-04-19 18:26:34 +00001934 // If this is a definition of a variadic C99 function-like macro, not using
1935 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001936
Chris Lattner249c38b2009-04-19 18:26:34 +00001937 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1938 // This gets unpoisoned where it is allowed.
1939 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1940 if (MI->isC99Varargs())
1941 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001942
Chris Lattnerf64b3522008-03-09 01:54:53 +00001943 // Read the first token after the arg list for down below.
1944 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001945 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001946 // C99 requires whitespace between the macro definition and the body. Emit
1947 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001948 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001949 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001950 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1951 // first character of a replacement list is not a character required by
1952 // subclause 5.2.1, then there shall be white-space separation between the
1953 // identifier and the replacement list.". 5.2.1 lists this set:
1954 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1955 // is irrelevant here.
1956 bool isInvalid = false;
1957 if (Tok.is(tok::at)) // @ is not in the list above.
1958 isInvalid = true;
1959 else if (Tok.is(tok::unknown)) {
1960 // If we have an unknown token, it is something strange like "`". Since
1961 // all of valid characters would have lexed into a single character
1962 // token of some sort, we know this is not a valid case.
1963 isInvalid = true;
1964 }
1965 if (isInvalid)
1966 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1967 else
1968 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001969 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001970
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001971 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001972 LastTok = Tok;
1973
Chris Lattnerf64b3522008-03-09 01:54:53 +00001974 // Read the rest of the macro body.
1975 if (MI->isObjectLike()) {
1976 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001977 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001978 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001979 MI->AddTokenToBody(Tok);
1980 // Get the next token of the macro.
1981 LexUnexpandedToken(Tok);
1982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
Chris Lattnerf64b3522008-03-09 01:54:53 +00001984 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001985 // Otherwise, read the body of a function-like macro. While we are at it,
1986 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1987 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001988 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001989 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001990
Eli Friedman14d3c792012-11-14 02:18:46 +00001991 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00001992 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001993
Chris Lattnerf64b3522008-03-09 01:54:53 +00001994 // Get the next token of the macro.
1995 LexUnexpandedToken(Tok);
1996 continue;
1997 }
Mike Stump11289f42009-09-09 15:08:12 +00001998
Richard Smith701a3522013-07-09 01:00:29 +00001999 // If we're in -traditional mode, then we should ignore stringification
2000 // and token pasting. Mark the tokens as unknown so as not to confuse
2001 // things.
2002 if (getLangOpts().TraditionalCPP) {
2003 Tok.setKind(tok::unknown);
2004 MI->AddTokenToBody(Tok);
2005
2006 // Get the next token of the macro.
2007 LexUnexpandedToken(Tok);
2008 continue;
2009 }
2010
Eli Friedman14d3c792012-11-14 02:18:46 +00002011 if (Tok.is(tok::hashhash)) {
2012
2013 // If we see token pasting, check if it looks like the gcc comma
2014 // pasting extension. We'll use this information to suppress
2015 // diagnostics later on.
2016
2017 // Get the next token of the macro.
2018 LexUnexpandedToken(Tok);
2019
2020 if (Tok.is(tok::eod)) {
2021 MI->AddTokenToBody(LastTok);
2022 break;
2023 }
2024
2025 unsigned NumTokens = MI->getNumTokens();
2026 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2027 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2028 MI->setHasCommaPasting();
2029
David Majnemer76faf1f2013-11-05 09:30:17 +00002030 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002031 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002032 continue;
2033 }
2034
Chris Lattnerf64b3522008-03-09 01:54:53 +00002035 // Get the next token of the macro.
2036 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002037
Chris Lattner83bd8282009-05-25 17:16:10 +00002038 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002039 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002040 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2041
2042 // If this is assembler-with-cpp mode, we accept random gibberish after
2043 // the '#' because '#' is often a comment character. However, change
2044 // the kind of the token to tok::unknown so that the preprocessor isn't
2045 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002046 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002047 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002048 MI->AddTokenToBody(LastTok);
2049 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002050 } else {
2051 Diag(Tok, diag::err_pp_stringize_not_parameter);
2052 ReleaseMacroInfo(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002053
Chris Lattner83bd8282009-05-25 17:16:10 +00002054 // Disable __VA_ARGS__ again.
2055 Ident__VA_ARGS__->setIsPoisoned(true);
2056 return;
2057 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Chris Lattner83bd8282009-05-25 17:16:10 +00002060 // Things look ok, add the '#' and param name tokens to the macro.
2061 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002062 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002063 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002064
Chris Lattnerf64b3522008-03-09 01:54:53 +00002065 // Get the next token of the macro.
2066 LexUnexpandedToken(Tok);
2067 }
2068 }
Mike Stump11289f42009-09-09 15:08:12 +00002069
2070
Chris Lattnerf64b3522008-03-09 01:54:53 +00002071 // Disable __VA_ARGS__ again.
2072 Ident__VA_ARGS__->setIsPoisoned(true);
2073
Chris Lattner57540c52011-04-15 05:22:18 +00002074 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002075 // replacement list.
2076 unsigned NumTokens = MI->getNumTokens();
2077 if (NumTokens != 0) {
2078 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2079 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002080 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002081 return;
2082 }
2083 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2084 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002085 ReleaseMacroInfo(MI);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002086 return;
2087 }
2088 }
Mike Stump11289f42009-09-09 15:08:12 +00002089
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002090 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002091
Chris Lattnerf64b3522008-03-09 01:54:53 +00002092 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002093 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002094 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002095 // It is very common for system headers to have tons of macro redefinitions
2096 // and for warnings to be disabled in system headers. If this is the case,
2097 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002098 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002099 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002100 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002101 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002102
Richard Smith7b242542013-03-06 00:46:00 +00002103 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2104 // C++ [cpp.predefined]p4, but allow it as an extension.
2105 if (OtherMI->isBuiltinMacro())
2106 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002107 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002108 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002109 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002110 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002111 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2112 << MacroNameTok.getIdentifierInfo();
2113 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2114 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002115 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002116 if (OtherMI->isWarnIfUnused())
2117 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002118 }
Mike Stump11289f42009-09-09 15:08:12 +00002119
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002120 DefMacroDirective *MD =
2121 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002122
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002123 assert(!MI->isUsed());
2124 // If we need warning for not using the macro, add its location in the
2125 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002126 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002127 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002128 MI->setIsWarnIfUnused(true);
2129 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2130 }
2131
Chris Lattner928e9092009-04-12 01:39:54 +00002132 // If the callbacks want to know, tell them about the macro definition.
2133 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002134 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002135}
2136
James Dennettf6333ac2012-06-22 05:46:07 +00002137/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002138///
2139void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2140 ++NumUndefined;
2141
2142 Token MacroNameTok;
2143 ReadMacroName(MacroNameTok, 2);
Mike Stump11289f42009-09-09 15:08:12 +00002144
Chris Lattnerf64b3522008-03-09 01:54:53 +00002145 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002146 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002147 return;
Mike Stump11289f42009-09-09 15:08:12 +00002148
Chris Lattnerf64b3522008-03-09 01:54:53 +00002149 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002150 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002151
Chris Lattnerf64b3522008-03-09 01:54:53 +00002152 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002153 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Craig Topperd2d442c2014-05-17 23:10:59 +00002154 const MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002155
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002156 // If the callbacks want to know, tell them about the macro #undef.
2157 // Note: no matter if the macro was defined or not.
2158 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002159 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002160
Chris Lattnerf64b3522008-03-09 01:54:53 +00002161 // If the macro is not defined, this is a noop undef, just return.
Craig Topperd2d442c2014-05-17 23:10:59 +00002162 if (!MI)
2163 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002164
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002165 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002166 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002167
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002168 if (MI->isWarnIfUnused())
2169 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2170
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002171 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2172 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002173}
2174
2175
2176//===----------------------------------------------------------------------===//
2177// Preprocessor Conditional Directive Handling.
2178//===----------------------------------------------------------------------===//
2179
James Dennettf6333ac2012-06-22 05:46:07 +00002180/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2181/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2182/// true if any tokens have been returned or pp-directives activated before this
2183/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002184///
2185void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2186 bool ReadAnyTokensBeforeDirective) {
2187 ++NumIf;
2188 Token DirectiveTok = Result;
2189
2190 Token MacroNameTok;
2191 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002192
Chris Lattnerf64b3522008-03-09 01:54:53 +00002193 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002194 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002195 // Skip code until we get to #endif. This helps with recovery by not
2196 // emitting an error when the #endif is reached.
2197 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2198 /*Foundnonskip*/false, /*FoundElse*/false);
2199 return;
2200 }
Mike Stump11289f42009-09-09 15:08:12 +00002201
Chris Lattnerf64b3522008-03-09 01:54:53 +00002202 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002203 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002204
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002205 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002206 MacroDirective *MD = getMacroDirective(MII);
Craig Topperd2d442c2014-05-17 23:10:59 +00002207 MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002208
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002209 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002210 // If the start of a top-level #ifdef and if the macro is not defined,
2211 // inform MIOpt that this might be the start of a proper include guard.
2212 // Otherwise it is some other form of unknown conditional which we can't
2213 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002214 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002215 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002216 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002217 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002218 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002219 }
2220
Chris Lattnerf64b3522008-03-09 01:54:53 +00002221 // If there is a macro, process it.
2222 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002223 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002224
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002225 if (Callbacks) {
2226 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002227 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002228 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002229 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002230 }
2231
Chris Lattnerf64b3522008-03-09 01:54:53 +00002232 // Should we include the stuff contained by this directive?
2233 if (!MI == isIfndef) {
2234 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002235 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2236 /*wasskip*/false, /*foundnonskip*/true,
2237 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002238 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002239 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002240 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002241 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002242 /*FoundElse*/false);
2243 }
2244}
2245
James Dennettf6333ac2012-06-22 05:46:07 +00002246/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002247///
2248void Preprocessor::HandleIfDirective(Token &IfToken,
2249 bool ReadAnyTokensBeforeDirective) {
2250 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002251
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002252 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002253 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002254 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2255 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2256 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002257
2258 // If this condition is equivalent to #ifndef X, and if this is the first
2259 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002260 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002261 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002262 // FIXME: Pass in the location of the macro name, not the 'if' token.
2263 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002264 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002265 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002266 }
2267
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002268 if (Callbacks)
2269 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002270 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002271 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002272
Chris Lattnerf64b3522008-03-09 01:54:53 +00002273 // Should we include the stuff contained by this directive?
2274 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002275 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002276 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002277 /*foundnonskip*/true, /*foundelse*/false);
2278 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002279 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002280 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002281 /*FoundElse*/false);
2282 }
2283}
2284
James Dennettf6333ac2012-06-22 05:46:07 +00002285/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002286///
2287void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2288 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002289
Chris Lattnerf64b3522008-03-09 01:54:53 +00002290 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002291 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002292
Chris Lattnerf64b3522008-03-09 01:54:53 +00002293 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002294 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002295 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002296 Diag(EndifToken, diag::err_pp_endif_without_if);
2297 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002298 }
Mike Stump11289f42009-09-09 15:08:12 +00002299
Chris Lattnerf64b3522008-03-09 01:54:53 +00002300 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002301 if (CurPPLexer->getConditionalStackDepth() == 0)
2302 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002303
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002304 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002305 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002306
2307 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002308 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002309}
2310
James Dennettf6333ac2012-06-22 05:46:07 +00002311/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002312///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002313void Preprocessor::HandleElseDirective(Token &Result) {
2314 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002315
Chris Lattnerf64b3522008-03-09 01:54:53 +00002316 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002317 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002318
Chris Lattnerf64b3522008-03-09 01:54:53 +00002319 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002320 if (CurPPLexer->popConditionalLevel(CI)) {
2321 Diag(Result, diag::pp_err_else_without_if);
2322 return;
2323 }
Mike Stump11289f42009-09-09 15:08:12 +00002324
Chris Lattnerf64b3522008-03-09 01:54:53 +00002325 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002326 if (CurPPLexer->getConditionalStackDepth() == 0)
2327 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002328
2329 // If this is a #else with a #else before it, report the error.
2330 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002331
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002332 if (Callbacks)
2333 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2334
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002335 // Finally, skip the rest of the contents of this block.
2336 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002337 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002338}
2339
James Dennettf6333ac2012-06-22 05:46:07 +00002340/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002341///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002342void Preprocessor::HandleElifDirective(Token &ElifToken) {
2343 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002344
Chris Lattnerf64b3522008-03-09 01:54:53 +00002345 // #elif directive in a non-skipping conditional... start skipping.
2346 // We don't care what the condition is, because we will always skip it (since
2347 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002348 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002349 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002350 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002351
2352 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002353 if (CurPPLexer->popConditionalLevel(CI)) {
2354 Diag(ElifToken, diag::pp_err_elif_without_if);
2355 return;
2356 }
Mike Stump11289f42009-09-09 15:08:12 +00002357
Chris Lattnerf64b3522008-03-09 01:54:53 +00002358 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002359 if (CurPPLexer->getConditionalStackDepth() == 0)
2360 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002361
Chris Lattnerf64b3522008-03-09 01:54:53 +00002362 // If this is a #elif with a #else before it, report the error.
2363 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002364
2365 if (Callbacks)
2366 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002367 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002368 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002369
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002370 // Finally, skip the rest of the contents of this block.
2371 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002372 /*FoundElse*/CI.FoundElse,
2373 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002374}