blob: 04f3b29bd5b7c1db7c987ecad0135fe907ede5c4 [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/HeaderSearch.h"
Daniel Jasper07e6c402013-08-05 20:26:17 +000020#include "clang/Lex/HeaderSearchOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/LexDiagnostic.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/ModuleLoader.h"
25#include "clang/Lex/Pragma.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000026#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000027#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000028#include "llvm/Support/Path.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000029#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000030using namespace clang;
31
32//===----------------------------------------------------------------------===//
33// Utility Methods for Preprocessor Directive Handling.
34//===----------------------------------------------------------------------===//
35
Chris Lattnerc0a585d2010-08-17 15:55:45 +000036MacroInfo *Preprocessor::AllocateMacroInfo() {
Richard Smithee0c4c12014-07-24 01:13:23 +000037 MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
Ted Kremenekc8456f82010-10-19 22:15:20 +000038 MIChain->Next = MIChainHead;
Ted Kremenekc8456f82010-10-19 22:15:20 +000039 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000040 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000041}
42
43MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
44 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000045 new (MI) MacroInfo(L);
46 return MI;
47}
48
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000049MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
50 unsigned SubModuleID) {
Chandler Carruth06dde922014-03-02 13:02:01 +000051 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
52 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000053 DeserializedMacroInfoChain *MIChain =
54 BP.Allocate<DeserializedMacroInfoChain>();
55 MIChain->Next = DeserialMIChainHead;
56 DeserialMIChainHead = MIChain;
57
58 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000059 new (MI) MacroInfo(L);
60 MI->FromASTFile = true;
61 MI->setOwningModuleID(SubModuleID);
62 return MI;
63}
64
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000065DefMacroDirective *
66Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc,
Richard Smithdaa69e02014-07-25 04:40:03 +000067 unsigned ImportedFromModuleID,
68 ArrayRef<unsigned> Overrides) {
69 unsigned NumExtra = (ImportedFromModuleID ? 1 : 0) + Overrides.size();
70 return new (BP.Allocate(sizeof(DefMacroDirective) +
71 sizeof(unsigned) * NumExtra,
72 llvm::alignOf<DefMacroDirective>()))
73 DefMacroDirective(MI, Loc, ImportedFromModuleID, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000074}
75
76UndefMacroDirective *
Richard Smithdaa69e02014-07-25 04:40:03 +000077Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc,
78 unsigned ImportedFromModuleID,
79 ArrayRef<unsigned> Overrides) {
80 unsigned NumExtra = (ImportedFromModuleID ? 1 : 0) + Overrides.size();
81 return new (BP.Allocate(sizeof(UndefMacroDirective) +
82 sizeof(unsigned) * NumExtra,
83 llvm::alignOf<UndefMacroDirective>()))
84 UndefMacroDirective(UndefLoc, ImportedFromModuleID, Overrides);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000085}
86
87VisibilityMacroDirective *
88Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
89 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000090 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000091}
92
James Dennettf6333ac2012-06-22 05:46:07 +000093/// \brief Read and discard all tokens remaining on the current line until
94/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000095void Preprocessor::DiscardUntilEndOfDirective() {
96 Token Tmp;
97 do {
98 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000099 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000100 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +0000101}
102
Serge Pavlovd024f522014-10-24 17:31:32 +0000103bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000104 // Missing macro name?
105 if (MacroNameTok.is(tok::eod))
106 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
107
108 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
109 if (!II) {
110 bool Invalid = false;
111 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
112 if (Invalid)
113 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000114 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000115
Alp Tokerf33619c2014-05-31 03:38:08 +0000116 if (!II->isCPlusPlusOperatorKeyword())
117 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000118
Alp Tokere03e9e12014-05-31 16:32:22 +0000119 // C++ 2.5p2: Alternative tokens behave the same as its primary token
120 // except for their spellings.
121 Diag(MacroNameTok, getLangOpts().MicrosoftExt
122 ? diag::ext_pp_operator_used_as_macro_name
123 : diag::err_pp_operator_used_as_macro_name)
124 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000125
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000126 // Allow #defining |and| and friends for Microsoft compatibility or
127 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000128 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000129 }
130
Serge Pavlovd024f522014-10-24 17:31:32 +0000131 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000132 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
133 return Diag(MacroNameTok, diag::err_defined_macro_name);
134 }
135
Serge Pavlovd024f522014-10-24 17:31:32 +0000136 if (isDefineUndef == MU_Undef && II->hasMacroDefinition() &&
Alp Tokerb05e0b52014-05-21 06:13:51 +0000137 getMacroInfo(II)->isBuiltinMacro()) {
138 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
139 // and C++ [cpp.predefined]p4], but allow it as an extension.
140 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
141 }
142
143 // Okay, we got a good identifier.
144 return false;
145}
146
James Dennettf6333ac2012-06-22 05:46:07 +0000147/// \brief Lex and validate a macro name, which occurs after a
148/// \#define or \#undef.
149///
Serge Pavlovd024f522014-10-24 17:31:32 +0000150/// This sets the token kind to eod and discards the rest of the macro line if
151/// the macro name is invalid.
152///
153/// \param MacroNameTok Token that is expected to be a macro name.
154/// \papam isDefineUndef Context in which macro is used.
155void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000156 // Read the token, don't allow macro expansion on it.
157 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000158
Douglas Gregor12785102010-08-24 20:21:13 +0000159 if (MacroNameTok.is(tok::code_completion)) {
160 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000161 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000162 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000163 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000164 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000165
166 if (!CheckMacroName(MacroNameTok, isDefineUndef))
Chris Lattner907dfe92008-11-18 07:59:24 +0000167 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000168
169 // Invalid macro name, read and discard the rest of the line and set the
170 // token kind to tok::eod if necessary.
171 if (MacroNameTok.isNot(tok::eod)) {
172 MacroNameTok.setKind(tok::eod);
173 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000174 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000175}
176
James Dennettf6333ac2012-06-22 05:46:07 +0000177/// \brief Ensure that the next token is a tok::eod token.
178///
179/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000180/// true, then we consider macros that expand to zero tokens as being ok.
181void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000182 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000183 // Lex unexpanded tokens for most directives: macros might expand to zero
184 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
185 // #line) allow empty macros.
186 if (EnableMacros)
187 Lex(Tmp);
188 else
189 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000190
Chris Lattnerf64b3522008-03-09 01:54:53 +0000191 // There should be no tokens after the directive, but we allow them as an
192 // extension.
193 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
194 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000195
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000196 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000197 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000198 // or if this is a macro-style preprocessing directive, because it is more
199 // trouble than it is worth to insert /**/ and check that there is no /**/
200 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000201 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000202 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000203 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000204 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
205 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000206 DiscardUntilEndOfDirective();
207 }
208}
209
210
211
James Dennettf6333ac2012-06-22 05:46:07 +0000212/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
213/// decided that the subsequent tokens are in the \#if'd out portion of the
214/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000215/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000216/// this \#if directive, so \#else/\#elif blocks should never be entered.
217/// If ElseOk is true, then \#else directives are ok, if not, then we have
218/// already seen one so a \#else directive is a duplicate. When this returns,
219/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000220void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
221 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000222 bool FoundElse,
223 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000224 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000225 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000226
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000227 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000228 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000229
Ted Kremenek56572ab2008-12-12 18:34:08 +0000230 if (CurPTHLexer) {
231 PTHSkipExcludedConditionalBlock();
232 return;
233 }
Mike Stump11289f42009-09-09 15:08:12 +0000234
Chris Lattnerf64b3522008-03-09 01:54:53 +0000235 // Enter raw mode to disable identifier lookup (and thus macro expansion),
236 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000237 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000238 Token Tok;
239 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000240 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000242 if (Tok.is(tok::code_completion)) {
243 if (CodeComplete)
244 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000245 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000246 continue;
247 }
248
Chris Lattnerf64b3522008-03-09 01:54:53 +0000249 // If this is the end of the buffer, we have an error.
250 if (Tok.is(tok::eof)) {
251 // Emit errors for each unterminated conditional on the stack, including
252 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000253 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000254 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000255 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
256 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000257 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000258 }
259
Chris Lattnerf64b3522008-03-09 01:54:53 +0000260 // Just return and let the caller lex after this #include.
261 break;
262 }
Mike Stump11289f42009-09-09 15:08:12 +0000263
Chris Lattnerf64b3522008-03-09 01:54:53 +0000264 // If this token is not a preprocessor directive, just skip it.
265 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
266 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000267
Chris Lattnerf64b3522008-03-09 01:54:53 +0000268 // We just parsed a # character at the start of a line, so we're in
269 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000270 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000271 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000272 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000273
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattnerf64b3522008-03-09 01:54:53 +0000275 // Read the next token, the directive flavor.
276 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Chris Lattnerf64b3522008-03-09 01:54:53 +0000278 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
279 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000280 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000281 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000282 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000283 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000284 continue;
285 }
286
287 // If the first letter isn't i or e, it isn't intesting to us. We know that
288 // this is safe in the face of spelling differences, because there is no way
289 // to spell an i/e in a strange way that is another letter. Skipping this
290 // allows us to avoid looking up the identifier info for #define/#undef and
291 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000292 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000293
Alp Toker2d57cea2014-05-17 04:53:25 +0000294 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000295 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000296 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000297 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000298 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000299 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000300 continue;
301 }
Mike Stump11289f42009-09-09 15:08:12 +0000302
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 // Get the identifier name without trigraphs or embedded newlines. Note
304 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
305 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000306 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000307 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000308 if (!Tok.needsCleaning() && RI.size() < 20) {
309 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000310 } else {
311 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000312 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000313 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000314 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000315 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000316 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000317 continue;
318 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000319 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000320 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000321 }
Mike Stump11289f42009-09-09 15:08:12 +0000322
Benjamin Kramer144884642009-12-31 13:32:38 +0000323 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000325 if (Sub.empty() || // "if"
326 Sub == "def" || // "ifdef"
327 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000328 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
329 // bother parsing the condition.
330 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000331 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000332 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000333 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000334 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000335 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000336 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000337 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000338 PPConditionalInfo CondInfo;
339 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000340 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000341 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000342 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattnerf64b3522008-03-09 01:54:53 +0000344 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000345 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000346 // Restore the value of LexingRawMode so that trailing comments
347 // are handled correctly, if we've reached the outermost block.
348 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000349 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000350 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000351 if (Callbacks)
352 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000353 break;
Richard Smithd0124572012-06-21 00:35:03 +0000354 } else {
355 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000356 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000357 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000358 // #else directive in a skipping conditional. If not in some other
359 // skipping conditional, and if #else hasn't already been seen, enter it
360 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000361 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000362
Chris Lattnerf64b3522008-03-09 01:54:53 +0000363 // If this is a #else with a #else before it, report the error.
364 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000365
Chris Lattnerf64b3522008-03-09 01:54:53 +0000366 // Note that we've seen a #else in this conditional.
367 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000368
Chris Lattnerf64b3522008-03-09 01:54:53 +0000369 // If the conditional is at the top level, and the #if block wasn't
370 // entered, enter the #else block now.
371 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
372 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000373 // Restore the value of LexingRawMode so that trailing comments
374 // are handled correctly.
375 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000376 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000377 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000378 if (Callbacks)
379 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000380 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000381 } else {
382 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000383 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000384 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000385 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386
John Thompson17c35732013-12-04 20:19:30 +0000387 // If this is a #elif with a #else before it, report the error.
388 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
389
Chris Lattnerf64b3522008-03-09 01:54:53 +0000390 // If this is in a skipping block or if we're already handled this #if
391 // block, don't bother parsing the condition.
392 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
393 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000394 } else {
John Thompson17c35732013-12-04 20:19:30 +0000395 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000396 // Restore the value of LexingRawMode so that identifiers are
397 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000398 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
399 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000400 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000401 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000402 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000403 if (Callbacks) {
404 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000405 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000406 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000407 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000408 }
409 // If this condition is true, enter it!
410 if (CondValue) {
411 CondInfo.FoundNonSkip = true;
412 break;
413 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000414 }
415 }
416 }
Mike Stump11289f42009-09-09 15:08:12 +0000417
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000418 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000419 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000420 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000421 }
422
423 // Finally, if we are out of the conditional (saw an #endif or ran off the end
424 // of the file, just stop skipping and return to lexing whatever came after
425 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000426 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000427
428 if (Callbacks) {
429 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
430 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
431 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000432}
433
Ted Kremenek56572ab2008-12-12 18:34:08 +0000434void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000435
436 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000437 assert(CurPTHLexer);
438 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000439
Ted Kremenek56572ab2008-12-12 18:34:08 +0000440 // Skip to the next '#else', '#elif', or #endif.
441 if (CurPTHLexer->SkipBlock()) {
442 // We have reached an #endif. Both the '#' and 'endif' tokens
443 // have been consumed by the PTHLexer. Just pop off the condition level.
444 PPConditionalInfo CondInfo;
445 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000446 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000447 assert(!InCond && "Can't be skipping if not in a conditional!");
448 break;
449 }
Mike Stump11289f42009-09-09 15:08:12 +0000450
Ted Kremenek56572ab2008-12-12 18:34:08 +0000451 // We have reached a '#else' or '#elif'. Lex the next token to get
452 // the directive flavor.
453 Token Tok;
454 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000455
Ted Kremenek56572ab2008-12-12 18:34:08 +0000456 // We can actually look up the IdentifierInfo here since we aren't in
457 // raw mode.
458 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
459
460 if (K == tok::pp_else) {
461 // #else: Enter the else condition. We aren't in a nested condition
462 // since we skip those. We're always in the one matching the last
463 // blocked we skipped.
464 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
465 // Note that we've seen a #else in this conditional.
466 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000467
Ted Kremenek56572ab2008-12-12 18:34:08 +0000468 // If the #if block wasn't entered then enter the #else block now.
469 if (!CondInfo.FoundNonSkip) {
470 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000471
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000472 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000473 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000474 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000475 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000476
Ted Kremenek56572ab2008-12-12 18:34:08 +0000477 break;
478 }
Mike Stump11289f42009-09-09 15:08:12 +0000479
Ted Kremenek56572ab2008-12-12 18:34:08 +0000480 // Otherwise skip this block.
481 continue;
482 }
Mike Stump11289f42009-09-09 15:08:12 +0000483
Ted Kremenek56572ab2008-12-12 18:34:08 +0000484 assert(K == tok::pp_elif);
485 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
486
487 // If this is a #elif with a #else before it, report the error.
488 if (CondInfo.FoundElse)
489 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000490
Ted Kremenek56572ab2008-12-12 18:34:08 +0000491 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000492 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000493 if (CondInfo.FoundNonSkip)
494 continue;
495
496 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000497 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000498 CurPTHLexer->ParsingPreprocessorDirective = true;
499 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
500 CurPTHLexer->ParsingPreprocessorDirective = false;
501
502 // If this condition is true, enter it!
503 if (ShouldEnter) {
504 CondInfo.FoundNonSkip = true;
505 break;
506 }
507
508 // Otherwise, skip this block and go to the next one.
509 continue;
510 }
511}
512
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000513Module *Preprocessor::getModuleForLocation(SourceLocation FilenameLoc) {
514 ModuleMap &ModMap = HeaderInfo.getModuleMap();
515 if (SourceMgr.isInMainFile(FilenameLoc)) {
516 if (Module *CurMod = getCurrentModule())
517 return CurMod; // Compiling a module.
518 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
519 }
520 // Try to determine the module of the include directive.
Daniel Jasper88d86952013-12-03 20:30:36 +0000521 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
Manuel Klimek98a9a6c2014-03-19 10:22:36 +0000522 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(FilenameLoc));
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000523 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
524 // The include comes from a file.
525 return ModMap.findModuleForHeader(EntryOfIncl).getModule();
526 } else {
527 // The include does not come from a file,
528 // so it is probably a module compilation.
529 return getCurrentModule();
530 }
531}
532
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000533const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000534 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000535 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000536 bool isAngled,
537 const DirectoryLookup *FromDir,
Richard Smith25d50752014-10-20 00:15:49 +0000538 const FileEntry *FromFile,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000539 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000540 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000541 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000542 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000543 bool SkipCache) {
Will Wilson0fafd342013-12-27 19:46:16 +0000544 // If the header lookup mechanism may be relative to the current inclusion
545 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000546 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
547 Includers;
Richard Smith25d50752014-10-20 00:15:49 +0000548 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000549 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000550 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000551
Chris Lattner022923a2009-02-04 19:45:07 +0000552 // If there is no file entry associated with this file, it must be the
553 // predefines buffer. Any other file is not lexed with a normal lexer, so
Douglas Gregor618e64a2010-08-08 07:49:23 +0000554 // it won't be scanned for preprocessor directives. If we have the
555 // predefines buffer, resolve #include references (which come from the
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000556 // -include command line argument) from the current working directory
557 // instead of relative to the main file.
558 if (!FileEnt) {
Will Wilson0fafd342013-12-27 19:46:16 +0000559 FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000560 if (FileEnt)
561 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
562 } else {
563 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
564 }
Will Wilson0fafd342013-12-27 19:46:16 +0000565
566 // MSVC searches the current include stack from top to bottom for
567 // headers included by quoted include directives.
568 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000569 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000570 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
571 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
572 if (IsFileLexer(ISEntry))
573 if ((FileEnt = SourceMgr.getFileEntryForID(
574 ISEntry.ThePPLexer->getFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000575 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000576 }
Chris Lattner022923a2009-02-04 19:45:07 +0000577 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000580 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000581
582 if (FromFile) {
583 // We're supposed to start looking from after a particular file. Search
584 // the include path until we find that file or run out of files.
585 const DirectoryLookup *TmpCurDir = CurDir;
586 const DirectoryLookup *TmpFromDir = nullptr;
587 while (const FileEntry *FE = HeaderInfo.LookupFile(
588 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
589 Includers, SearchPath, RelativePath, SuggestedModule,
590 SkipCache)) {
591 // Keep looking as if this file did a #include_next.
592 TmpFromDir = TmpCurDir;
593 ++TmpFromDir;
594 if (FE == FromFile) {
595 // Found it.
596 FromDir = TmpFromDir;
597 CurDir = TmpCurDir;
598 break;
599 }
600 }
601 }
602
603 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000604 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000605 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
606 RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000607 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000608 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000609 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
610 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000611 return FE;
612 }
Mike Stump11289f42009-09-09 15:08:12 +0000613
Will Wilson0fafd342013-12-27 19:46:16 +0000614 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000615 // Otherwise, see if this is a subframework header. If so, this is relative
616 // to one of the headers on the #include stack. Walk the list of the current
617 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000618 if (IsFileLexer()) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000619 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000620 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000621 SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000622 SuggestedModule))) {
623 if (SuggestedModule && !LangOpts.AsmPreprocessor)
624 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
625 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000626 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000627 }
628 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000629 }
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000631 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
632 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000633 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000634 if ((CurFileEnt =
Ben Langmuir71e1a642014-05-05 21:44:13 +0000635 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000636 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000637 Filename, CurFileEnt, SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000638 SuggestedModule))) {
639 if (SuggestedModule && !LangOpts.AsmPreprocessor)
640 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
641 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000642 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000643 }
644 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000645 }
646 }
Mike Stump11289f42009-09-09 15:08:12 +0000647
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000648 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000649 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000650}
651
Chris Lattnerf64b3522008-03-09 01:54:53 +0000652
653//===----------------------------------------------------------------------===//
654// Preprocessor Directive Handling.
655//===----------------------------------------------------------------------===//
656
David Blaikied5321242012-06-06 18:52:13 +0000657class Preprocessor::ResetMacroExpansionHelper {
658public:
659 ResetMacroExpansionHelper(Preprocessor *pp)
660 : PP(pp), save(pp->DisableMacroExpansion) {
661 if (pp->MacroExpansionInDirectivesOverride)
662 pp->DisableMacroExpansion = false;
663 }
664 ~ResetMacroExpansionHelper() {
665 PP->DisableMacroExpansion = save;
666 }
667private:
668 Preprocessor *PP;
669 bool save;
670};
671
Chris Lattnerf64b3522008-03-09 01:54:53 +0000672/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000673/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000674/// lexer/preprocessor state, and advances the lexer(s) so that the next token
675/// read is the correct one.
676void Preprocessor::HandleDirective(Token &Result) {
677 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000678
Chris Lattnerf64b3522008-03-09 01:54:53 +0000679 // We just parsed a # character at the start of a line, so we're in directive
680 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000681 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000682 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000683 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000684
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000685 bool ImmediatelyAfterTopLevelIfndef =
686 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
687 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
688
Chris Lattnerf64b3522008-03-09 01:54:53 +0000689 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000690
Chris Lattnerf64b3522008-03-09 01:54:53 +0000691 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000692 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000693 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000694 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000695
Chris Lattner2d17ab72009-03-18 21:00:25 +0000696 // Save the '#' token in case we need to return it later.
697 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000698
Chris Lattnerf64b3522008-03-09 01:54:53 +0000699 // Read the next token, the directive flavor. This isn't expanded due to
700 // C99 6.10.3p8.
701 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000702
Chris Lattnerf64b3522008-03-09 01:54:53 +0000703 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
704 // #define A(x) #x
705 // A(abc
706 // #warning blah
707 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000708 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
709 // not support this for #include-like directives, since that can result in
710 // terrible diagnostics, and does not work in GCC.
711 if (InMacroArgs) {
712 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
713 switch (II->getPPKeywordID()) {
714 case tok::pp_include:
715 case tok::pp_import:
716 case tok::pp_include_next:
717 case tok::pp___include_macros:
718 Diag(Result, diag::err_embedded_include) << II->getName();
719 DiscardUntilEndOfDirective();
720 return;
721 default:
722 break;
723 }
724 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000725 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000726 }
Mike Stump11289f42009-09-09 15:08:12 +0000727
David Blaikied5321242012-06-06 18:52:13 +0000728 // Temporarily enable macro expansion if set so
729 // and reset to previous state when returning from this function.
730 ResetMacroExpansionHelper helper(this);
731
Chris Lattnerf64b3522008-03-09 01:54:53 +0000732 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000733 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000734 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000735 case tok::code_completion:
736 if (CodeComplete)
737 CodeComplete->CodeCompleteDirective(
738 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000739 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000740 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000741 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000742 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000743 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000744 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000745 default:
746 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000747 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000748
Chris Lattnerf64b3522008-03-09 01:54:53 +0000749 // Ask what the preprocessor keyword ID is.
750 switch (II->getPPKeywordID()) {
751 default: break;
752 // C99 6.10.1 - Conditional Inclusion.
753 case tok::pp_if:
754 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
755 case tok::pp_ifdef:
756 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
757 case tok::pp_ifndef:
758 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
759 case tok::pp_elif:
760 return HandleElifDirective(Result);
761 case tok::pp_else:
762 return HandleElseDirective(Result);
763 case tok::pp_endif:
764 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000765
Chris Lattnerf64b3522008-03-09 01:54:53 +0000766 // C99 6.10.2 - Source File Inclusion.
767 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000768 // Handle #include.
769 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000770 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000771 // Handle -imacros.
772 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000773
Chris Lattnerf64b3522008-03-09 01:54:53 +0000774 // C99 6.10.3 - Macro Replacement.
775 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000776 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000777 case tok::pp_undef:
778 return HandleUndefDirective(Result);
779
780 // C99 6.10.4 - Line Control.
781 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000782 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattnerf64b3522008-03-09 01:54:53 +0000784 // C99 6.10.5 - Error Directive.
785 case tok::pp_error:
786 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000787
Chris Lattnerf64b3522008-03-09 01:54:53 +0000788 // C99 6.10.6 - Pragma Directive.
789 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000790 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000791
Chris Lattnerf64b3522008-03-09 01:54:53 +0000792 // GNU Extensions.
793 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000794 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000795 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000796 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattnerf64b3522008-03-09 01:54:53 +0000798 case tok::pp_warning:
799 Diag(Result, diag::ext_pp_warning_directive);
800 return HandleUserDiagnosticDirective(Result, true);
801 case tok::pp_ident:
802 return HandleIdentSCCSDirective(Result);
803 case tok::pp_sccs:
804 return HandleIdentSCCSDirective(Result);
805 case tok::pp_assert:
806 //isExtension = true; // FIXME: implement #assert
807 break;
808 case tok::pp_unassert:
809 //isExtension = true; // FIXME: implement #unassert
810 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000811
Douglas Gregor663b48f2012-01-03 19:48:16 +0000812 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000813 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000814 return HandleMacroPublicDirective(Result);
815 break;
816
Douglas Gregor663b48f2012-01-03 19:48:16 +0000817 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000818 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000819 return HandleMacroPrivateDirective(Result);
820 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000821 }
822 break;
823 }
Mike Stump11289f42009-09-09 15:08:12 +0000824
Chris Lattner2d17ab72009-03-18 21:00:25 +0000825 // If this is a .S file, treat unknown # directives as non-preprocessor
826 // directives. This is important because # may be a comment or introduce
827 // various pseudo-ops. Just return the # token and push back the following
828 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000829 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000830 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000831 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000832 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000833 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000834
835 // If the second token is a hashhash token, then we need to translate it to
836 // unknown so the token lexer doesn't try to perform token pasting.
837 if (Result.is(tok::hashhash))
838 Toks[1].setKind(tok::unknown);
839
Chris Lattner2d17ab72009-03-18 21:00:25 +0000840 // Enter this token stream so that we re-lex the tokens. Make sure to
841 // enable macro expansion, in case the token after the # is an identifier
842 // that is expanded.
843 EnterTokenStream(Toks, 2, false, true);
844 return;
845 }
Mike Stump11289f42009-09-09 15:08:12 +0000846
Chris Lattnerf64b3522008-03-09 01:54:53 +0000847 // If we reached here, the preprocessing token is not valid!
848 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000849
Chris Lattnerf64b3522008-03-09 01:54:53 +0000850 // Read the rest of the PP line.
851 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chris Lattnerf64b3522008-03-09 01:54:53 +0000853 // Okay, we're done parsing the directive.
854}
855
Chris Lattner76e68962009-01-26 06:19:46 +0000856/// GetLineValue - Convert a numeric token into an unsigned value, emitting
857/// Diagnostic DiagID if it is invalid, and returning the value in Val.
858static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000859 unsigned DiagID, Preprocessor &PP,
860 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000861 if (DigitTok.isNot(tok::numeric_constant)) {
862 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000863
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000864 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000865 PP.DiscardUntilEndOfDirective();
866 return true;
867 }
Mike Stump11289f42009-09-09 15:08:12 +0000868
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000869 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000870 IntegerBuffer.resize(DigitTok.getLength());
871 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000872 bool Invalid = false;
873 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
874 if (Invalid)
875 return true;
876
Chris Lattnerd66f1722009-04-18 18:35:15 +0000877 // Verify that we have a simple digit-sequence, and compute the value. This
878 // is always a simple digit string computed in decimal, so we do this manually
879 // here.
880 Val = 0;
881 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +0000882 // C++1y [lex.fcon]p1:
883 // Optional separating single quotes in a digit-sequence are ignored
884 if (DigitTokBegin[i] == '\'')
885 continue;
886
Jordan Rosea7d03842013-02-08 22:30:41 +0000887 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000888 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000889 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000890 PP.DiscardUntilEndOfDirective();
891 return true;
892 }
Mike Stump11289f42009-09-09 15:08:12 +0000893
Chris Lattnerd66f1722009-04-18 18:35:15 +0000894 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
895 if (NextVal < Val) { // overflow.
896 PP.Diag(DigitTok, DiagID);
897 PP.DiscardUntilEndOfDirective();
898 return true;
899 }
900 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000901 }
Mike Stump11289f42009-09-09 15:08:12 +0000902
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000903 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000904 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
905 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000906
Chris Lattner76e68962009-01-26 06:19:46 +0000907 return false;
908}
909
James Dennettf6333ac2012-06-22 05:46:07 +0000910/// \brief Handle a \#line directive: C99 6.10.4.
911///
912/// The two acceptable forms are:
913/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000914/// # line digit-sequence
915/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000916/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000917void Preprocessor::HandleLineDirective(Token &Tok) {
918 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
919 // expanded.
920 Token DigitTok;
921 Lex(DigitTok);
922
Chris Lattner100c65e2009-01-26 05:29:08 +0000923 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +0000924 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000925 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +0000926 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000927
928 if (LineNo == 0)
929 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +0000930
Chris Lattner76e68962009-01-26 06:19:46 +0000931 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
932 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +0000933 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000934 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +0000935 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +0000936 if (LineNo >= LineLimit)
937 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000938 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +0000939 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000941 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +0000942 Token StrTok;
943 Lex(StrTok);
944
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000945 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
946 // string followed by eod.
947 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +0000948 ; // ok
949 else if (StrTok.isNot(tok::string_literal)) {
950 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +0000951 return DiscardUntilEndOfDirective();
952 } else if (StrTok.hasUDSuffix()) {
953 Diag(StrTok, diag::err_invalid_string_udl);
954 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +0000955 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000956 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +0000957 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +0000958 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000959 if (Literal.hadError)
960 return DiscardUntilEndOfDirective();
961 if (Literal.Pascal) {
962 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
963 return DiscardUntilEndOfDirective();
964 }
Jay Foad9a6b0982011-06-21 15:13:30 +0000965 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +0000966
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000967 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +0000968 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
969 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +0000970 }
Mike Stump11289f42009-09-09 15:08:12 +0000971
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000972 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +0000973
Chris Lattner839150e2009-03-27 17:13:49 +0000974 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +0000975 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
976 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +0000977 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +0000978}
979
Chris Lattner76e68962009-01-26 06:19:46 +0000980/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
981/// marker directive.
982static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
983 bool &IsSystemHeader, bool &IsExternCHeader,
984 Preprocessor &PP) {
985 unsigned FlagVal;
986 Token FlagTok;
987 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000988 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000989 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
990 return true;
991
992 if (FlagVal == 1) {
993 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +0000994
Chris Lattner76e68962009-01-26 06:19:46 +0000995 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000996 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +0000997 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
998 return true;
999 } else if (FlagVal == 2) {
1000 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001001
Chris Lattner1c967782009-02-04 06:25:26 +00001002 SourceManager &SM = PP.getSourceManager();
1003 // If we are leaving the current presumed file, check to make sure the
1004 // presumed include stack isn't empty!
1005 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001006 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001007 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001008 if (PLoc.isInvalid())
1009 return true;
1010
Chris Lattner1c967782009-02-04 06:25:26 +00001011 // If there is no include loc (main file) or if the include loc is in a
1012 // different physical file, then we aren't in a "1" line marker flag region.
1013 SourceLocation IncLoc = PLoc.getIncludeLoc();
1014 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001015 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001016 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1017 PP.DiscardUntilEndOfDirective();
1018 return true;
1019 }
Mike Stump11289f42009-09-09 15:08:12 +00001020
Chris Lattner76e68962009-01-26 06:19:46 +00001021 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001022 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001023 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1024 return true;
1025 }
1026
1027 // We must have 3 if there are still flags.
1028 if (FlagVal != 3) {
1029 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001030 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001031 return true;
1032 }
Mike Stump11289f42009-09-09 15:08:12 +00001033
Chris Lattner76e68962009-01-26 06:19:46 +00001034 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001035
Chris Lattner76e68962009-01-26 06:19:46 +00001036 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001037 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001038 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001039 return true;
1040
1041 // We must have 4 if there is yet another flag.
1042 if (FlagVal != 4) {
1043 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001044 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001045 return true;
1046 }
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattner76e68962009-01-26 06:19:46 +00001048 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001049
Chris Lattner76e68962009-01-26 06:19:46 +00001050 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001051 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001052
1053 // There are no more valid flags here.
1054 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001055 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001056 return true;
1057}
1058
1059/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1060/// one of the following forms:
1061///
1062/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001063/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001064/// # 42 "file" ('1' | '2')? '3' '4'?
1065///
1066void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1067 // Validate the number and convert it to an unsigned. GNU does not have a
1068 // line # limit other than it fit in 32-bits.
1069 unsigned LineNo;
1070 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001071 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001072 return;
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattner76e68962009-01-26 06:19:46 +00001074 Token StrTok;
1075 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001076
Chris Lattner76e68962009-01-26 06:19:46 +00001077 bool IsFileEntry = false, IsFileExit = false;
1078 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001079 int FilenameID = -1;
1080
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001081 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1082 // string followed by eod.
1083 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001084 ; // ok
1085 else if (StrTok.isNot(tok::string_literal)) {
1086 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001087 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001088 } else if (StrTok.hasUDSuffix()) {
1089 Diag(StrTok, diag::err_invalid_string_udl);
1090 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001091 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001092 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001093 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001094 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001095 if (Literal.hadError)
1096 return DiscardUntilEndOfDirective();
1097 if (Literal.Pascal) {
1098 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1099 return DiscardUntilEndOfDirective();
1100 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001101 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001102
Chris Lattner76e68962009-01-26 06:19:46 +00001103 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001104 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001105 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001106 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001107 }
Mike Stump11289f42009-09-09 15:08:12 +00001108
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001109 // Create a line note with this information.
1110 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001111 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001112 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001113
Chris Lattner839150e2009-03-27 17:13:49 +00001114 // If the preprocessor has callbacks installed, notify them of the #line
1115 // change. This is used so that the line marker comes out in -E mode for
1116 // example.
1117 if (Callbacks) {
1118 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1119 if (IsFileEntry)
1120 Reason = PPCallbacks::EnterFile;
1121 else if (IsFileExit)
1122 Reason = PPCallbacks::ExitFile;
1123 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1124 if (IsExternCHeader)
1125 FileKind = SrcMgr::C_ExternCSystem;
1126 else if (IsSystemHeader)
1127 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001128
Chris Lattnerc745cec2010-04-14 04:28:50 +00001129 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001130 }
Chris Lattner76e68962009-01-26 06:19:46 +00001131}
1132
1133
Chris Lattner38d7fd22009-01-26 05:30:54 +00001134/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1135///
Mike Stump11289f42009-09-09 15:08:12 +00001136void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001137 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001138 // PTH doesn't emit #warning or #error directives.
1139 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001140 return CurPTHLexer->DiscardToEndOfLine();
1141
Chris Lattnerf64b3522008-03-09 01:54:53 +00001142 // Read the rest of the line raw. We do this because we don't want macros
1143 // to be expanded and we don't require that the tokens be valid preprocessing
1144 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1145 // collapse multiple consequtive white space between tokens, but this isn't
1146 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001147 SmallString<128> Message;
1148 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001149
1150 // Find the first non-whitespace character, so that we can make the
1151 // diagnostic more succinct.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001152 StringRef Msg = Message.str().ltrim(" ");
1153
Chris Lattner100c65e2009-01-26 05:29:08 +00001154 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001155 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001156 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001157 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001158}
1159
1160/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1161///
1162void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1163 // Yes, this directive is an extension.
1164 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001165
Chris Lattnerf64b3522008-03-09 01:54:53 +00001166 // Read the string argument.
1167 Token StrTok;
1168 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001169
Chris Lattnerf64b3522008-03-09 01:54:53 +00001170 // If the token kind isn't a string, it's a malformed directive.
1171 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001172 StrTok.isNot(tok::wide_string_literal)) {
1173 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001174 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001175 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001176 return;
1177 }
Mike Stump11289f42009-09-09 15:08:12 +00001178
Richard Smithd67aea22012-03-06 03:21:47 +00001179 if (StrTok.hasUDSuffix()) {
1180 Diag(StrTok, diag::err_invalid_string_udl);
1181 return DiscardUntilEndOfDirective();
1182 }
1183
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001184 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001185 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001186
Douglas Gregordc970f02010-03-16 22:30:13 +00001187 if (Callbacks) {
1188 bool Invalid = false;
1189 std::string Str = getSpelling(StrTok, &Invalid);
1190 if (!Invalid)
1191 Callbacks->Ident(Tok.getLocation(), Str);
1192 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001193}
1194
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001195/// \brief Handle a #public directive.
1196void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001197 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001198 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001199
1200 // Error reading macro name? If so, diagnostic already issued.
1201 if (MacroNameTok.is(tok::eod))
1202 return;
1203
Douglas Gregor663b48f2012-01-03 19:48:16 +00001204 // Check to see if this is the last token on the #__public_macro line.
1205 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001206
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001207 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001208 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001209 MacroDirective *MD = getMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001210
1211 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001212 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001213 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001214 return;
1215 }
1216
1217 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001218 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1219 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001220}
1221
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001222/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001223void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1224 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001225 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregorebf00492011-10-17 15:32:29 +00001226
1227 // Error reading macro name? If so, diagnostic already issued.
1228 if (MacroNameTok.is(tok::eod))
1229 return;
1230
Douglas Gregor663b48f2012-01-03 19:48:16 +00001231 // Check to see if this is the last token on the #__private_macro line.
1232 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001233
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001234 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001235 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001236 MacroDirective *MD = getMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001237
1238 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001239 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001240 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001241 return;
1242 }
1243
1244 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001245 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1246 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001247}
1248
Chris Lattnerf64b3522008-03-09 01:54:53 +00001249//===----------------------------------------------------------------------===//
1250// Preprocessor Include Directive Handling.
1251//===----------------------------------------------------------------------===//
1252
1253/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001254/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001255/// true if the input filename was in <>'s or false if it were in ""'s. The
1256/// caller is expected to provide a buffer that is large enough to hold the
1257/// spelling of the filename, but is also expected to handle the case when
1258/// this method decides to use a different buffer.
1259bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001260 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001261 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001262 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001263
Chris Lattnerf64b3522008-03-09 01:54:53 +00001264 // Make sure the filename is <x> or "x".
1265 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001266 if (Buffer[0] == '<') {
1267 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001268 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001269 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001270 return true;
1271 }
1272 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001273 } else if (Buffer[0] == '"') {
1274 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001275 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001276 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001277 return true;
1278 }
1279 isAngled = false;
1280 } else {
1281 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001282 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001283 return true;
1284 }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Chris Lattnerf64b3522008-03-09 01:54:53 +00001286 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001287 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001288 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001289 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001290 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Chris Lattnerf64b3522008-03-09 01:54:53 +00001293 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001294 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001295 return isAngled;
1296}
1297
James Dennett4a4f72d2013-11-27 01:27:40 +00001298// \brief Handle cases where the \#include name is expanded from a macro
1299// as multiple tokens, which need to be glued together.
1300//
1301// This occurs for code like:
1302// \code
1303// \#define FOO <a/b.h>
1304// \#include FOO
1305// \endcode
1306// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1307//
1308// This code concatenates and consumes tokens up to the '>' token. It returns
1309// false if the > was found, otherwise it returns true if it finds and consumes
1310// the EOD marker.
1311bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001312 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001313 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001314
John Thompsonb5353522009-10-30 13:49:06 +00001315 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001316 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001317 End = CurTok.getLocation();
1318
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001319 // FIXME: Provide code completion for #includes.
1320 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001321 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001322 Lex(CurTok);
1323 continue;
1324 }
1325
Chris Lattnerf64b3522008-03-09 01:54:53 +00001326 // Append the spelling of this token to the buffer. If there was a space
1327 // before it, add it now.
1328 if (CurTok.hasLeadingSpace())
1329 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001330
Chris Lattnerf64b3522008-03-09 01:54:53 +00001331 // Get the spelling of the token, directly into FilenameBuffer if possible.
1332 unsigned PreAppendSize = FilenameBuffer.size();
1333 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001334
Chris Lattnerf64b3522008-03-09 01:54:53 +00001335 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001336 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001337
Chris Lattnerf64b3522008-03-09 01:54:53 +00001338 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1339 if (BufPtr != &FilenameBuffer[PreAppendSize])
1340 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001341
Chris Lattnerf64b3522008-03-09 01:54:53 +00001342 // Resize FilenameBuffer to the correct size.
1343 if (CurTok.getLength() != ActualLen)
1344 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001345
Chris Lattnerf64b3522008-03-09 01:54:53 +00001346 // If we found the '>' marker, return success.
1347 if (CurTok.is(tok::greater))
1348 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001349
John Thompsonb5353522009-10-30 13:49:06 +00001350 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001351 }
1352
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001353 // If we hit the eod marker, emit an error and return true so that the caller
1354 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001355 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001356 return true;
1357}
1358
Richard Smith34f30512013-11-23 04:06:09 +00001359/// \brief Push a token onto the token stream containing an annotation.
1360static void EnterAnnotationToken(Preprocessor &PP,
1361 SourceLocation Begin, SourceLocation End,
1362 tok::TokenKind Kind, void *AnnotationVal) {
1363 Token *Tok = new Token[1];
1364 Tok[0].startToken();
1365 Tok[0].setKind(Kind);
1366 Tok[0].setLocation(Begin);
1367 Tok[0].setAnnotationEndLoc(End);
1368 Tok[0].setAnnotationValue(AnnotationVal);
1369 PP.EnterTokenStream(Tok, 1, true, true);
1370}
1371
James Dennettf6333ac2012-06-22 05:46:07 +00001372/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1373/// the file to be included from the lexer, then include it! This is a common
1374/// routine with functionality shared between \#include, \#include_next and
1375/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001376/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001377void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1378 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001379 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001380 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001381 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();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001472#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001473 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001474#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001475 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001476 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001477 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001478 isAngled, LookupFrom, LookupFromFile, CurDir,
1479 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001480 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : nullptr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001481
Douglas Gregor11729f02011-11-30 18:12:06 +00001482 if (Callbacks) {
1483 if (!File) {
1484 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001485 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001486 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1487 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1488 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001489 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001490 HeaderInfo.AddSearchPath(DL, isAngled);
1491
1492 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001493 File = LookupFile(
1494 FilenameLoc,
1495 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1496 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
1497 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1498 : nullptr,
1499 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001500 }
1501 }
1502 }
1503
Daniel Jasper07e6c402013-08-05 20:26:17 +00001504 if (!SuggestedModule || !getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001505 // Notify the callback object that we've seen an inclusion directive.
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001506 Callbacks->InclusionDirective(HashLoc, IncludeTok,
1507 LangOpts.MSVCCompat ? NormalizedPath.c_str()
1508 : Filename,
1509 isAngled, FilenameRange, File, SearchPath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001510 RelativePath, /*ImportedModule=*/nullptr);
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001511 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001512 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001513
1514 if (!File) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001515 if (!SuppressIncludeNotFoundError) {
1516 // If the file could not be located and it was included via angle
1517 // brackets, we can attempt a lookup as though it were a quoted path to
1518 // provide the user with a possible fixit.
1519 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001520 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001521 FilenameLoc,
1522 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1523 LookupFrom, LookupFromFile, CurDir,
1524 Callbacks ? &SearchPath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001525 Callbacks ? &RelativePath : nullptr,
1526 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1527 : nullptr);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001528 if (File) {
1529 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1530 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1531 Filename <<
1532 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1533 }
1534 }
1535 // If the file is still not found, just go with the vanilla diagnostic
1536 if (!File)
1537 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1538 }
1539 if (!File)
1540 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001541 }
1542
Douglas Gregor97eec242011-09-15 22:00:41 +00001543 // If we are supposed to import a module rather than including the header,
1544 // do so now.
Ben Langmuirb537a3a2014-07-23 15:30:23 +00001545 if (SuggestedModule && getLangOpts().Modules &&
1546 SuggestedModule.getModule()->getTopLevelModuleName() !=
1547 getLangOpts().ImplementationOfModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001548 // Compute the module access path corresponding to this module.
1549 // FIXME: Should we have a second loadModule() overload to avoid this
1550 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001551 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001552 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001553 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1554 FilenameTok.getLocation()));
1555 std::reverse(Path.begin(), Path.end());
1556
Douglas Gregor41e115a2011-11-30 18:02:36 +00001557 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001558 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001559 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1560 if (I)
1561 PathString += '.';
1562 PathString += Path[I].first->getName();
1563 }
1564 int IncludeKind = 0;
1565
1566 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1567 case tok::pp_include:
1568 IncludeKind = 0;
1569 break;
1570
1571 case tok::pp_import:
1572 IncludeKind = 1;
1573 break;
1574
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001575 case tok::pp_include_next:
1576 IncludeKind = 2;
1577 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001578
1579 case tok::pp___include_macros:
1580 IncludeKind = 3;
1581 break;
1582
1583 default:
1584 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001585 }
1586
Douglas Gregor2537a362011-12-08 17:01:29 +00001587 // Determine whether we are actually building the module that this
1588 // include directive maps to.
1589 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001590 = Path[0].first->getName() == getLangOpts().CurrentModule;
Richard Smith34f30512013-11-23 04:06:09 +00001591
David Blaikiebbafb8a2012-03-11 07:00:24 +00001592 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001593 // If we're not building the imported module, warn that we're going
1594 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001595 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001596 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1597 /*IsTokenRange=*/false);
1598 Diag(HashLoc, diag::warn_auto_module_import)
1599 << IncludeKind << PathString
1600 << FixItHint::CreateReplacement(ReplaceRange,
Douglas Gregorc50d4922012-12-11 22:11:52 +00001601 "@import " + PathString.str().str() + ";");
Douglas Gregor2537a362011-12-08 17:01:29 +00001602 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001603
Richard Smithce587f52013-11-15 04:24:58 +00001604 // Load the module. Only make macros visible. We'll make the declarations
1605 // visible when the parser gets here.
1606 Module::NameVisibilityKind Visibility = Module::MacrosVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001607 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001608 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1609 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001610 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001611 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001612
1613 if (!Imported && hadModuleLoaderFatalFailure()) {
1614 // With a fatal failure in the module loader, we abort parsing.
1615 Token &Result = IncludeTok;
1616 if (CurLexer) {
1617 Result.startToken();
1618 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1619 CurLexer->cutOffLexing();
1620 } else {
1621 assert(CurPTHLexer && "#include but no current lexer set!");
1622 CurPTHLexer->getEOF(Result);
1623 }
1624 return;
1625 }
Richard Smithce587f52013-11-15 04:24:58 +00001626
Douglas Gregor2537a362011-12-08 17:01:29 +00001627 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001628 if (!BuildingImportedModule && Imported) {
1629 if (Callbacks) {
1630 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1631 FilenameRange, File,
1632 SearchPath, RelativePath, Imported);
1633 }
Richard Smithce587f52013-11-15 04:24:58 +00001634
1635 if (IncludeKind != 3) {
1636 // Let the parser know that we hit a module import, and it should
1637 // make the module visible.
1638 // FIXME: Produce this as the current token directly, rather than
1639 // allocating a new token for it.
Richard Smith34f30512013-11-23 04:06:09 +00001640 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include,
1641 Imported);
Richard Smithce587f52013-11-15 04:24:58 +00001642 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001643 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001644 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001645
1646 // If we failed to find a submodule that we expected to find, we can
1647 // continue. Otherwise, there's an error in the included file, so we
1648 // don't want to include it.
1649 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1650 return;
1651 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001652 }
1653
1654 if (Callbacks && SuggestedModule) {
1655 // We didn't notify the callback object that we've seen an inclusion
1656 // directive before. Now that we are parsing the include normally and not
1657 // turning it to a module import, notify the callback object.
1658 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1659 FilenameRange, File,
1660 SearchPath, RelativePath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001661 /*ImportedModule=*/nullptr);
Douglas Gregor97eec242011-09-15 22:00:41 +00001662 }
1663
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001664 // The #included file will be considered to be a system header if either it is
1665 // in a system include directory, or if the #includer is a system include
1666 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001667 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001668 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001669 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001670
Chris Lattner72286d62010-04-19 20:44:31 +00001671 // Ask HeaderInfo if we should enter this #include file. If not, #including
1672 // this file will have no effect.
1673 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001674 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001675 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001676 return;
1677 }
1678
Chris Lattnerf64b3522008-03-09 01:54:53 +00001679 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001680 SourceLocation IncludePos = End;
1681 // If the filename string was the result of macro expansions, set the include
1682 // position on the file where it will be included and after the expansions.
1683 if (IncludePos.isMacroID())
1684 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1685 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001686 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687
Richard Smith34f30512013-11-23 04:06:09 +00001688 // Determine if we're switching to building a new submodule, and which one.
1689 ModuleMap::KnownHeader BuildingModule;
1690 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) {
1691 Module *RequestingModule = getModuleForLocation(FilenameLoc);
1692 BuildingModule =
1693 HeaderInfo.getModuleMap().findModuleForHeader(File, RequestingModule);
1694 }
1695
1696 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00001697 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
1698 return;
Richard Smith34f30512013-11-23 04:06:09 +00001699
1700 // If we're walking into another part of the same module, let the parser
1701 // know that any future declarations are within that other submodule.
Richard Smith67294e22014-01-31 20:47:44 +00001702 if (BuildingModule) {
1703 assert(!CurSubmodule && "should not have marked this as a module yet");
1704 CurSubmodule = BuildingModule.getModule();
1705
Richard Smith34f30512013-11-23 04:06:09 +00001706 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin,
Richard Smith67294e22014-01-31 20:47:44 +00001707 CurSubmodule);
1708 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001709}
1710
James Dennettf6333ac2012-06-22 05:46:07 +00001711/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001712///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001713void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1714 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001715 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001716
Chris Lattnerf64b3522008-03-09 01:54:53 +00001717 // #include_next is like #include, except that we start searching after
1718 // the current found directory. If we can't do this, issue a
1719 // diagnostic.
1720 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00001721 const FileEntry *LookupFromFile = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001722 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001723 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001724 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001725 } else if (CurSubmodule) {
1726 // Start looking up in the directory *after* the one in which the current
1727 // file would be found, if any.
1728 assert(CurPPLexer && "#include_next directive in macro?");
1729 LookupFromFile = CurPPLexer->getFileEntry();
1730 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001731 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001732 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1733 } else {
1734 // Start looking up in the next directory.
1735 ++Lookup;
1736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
Richard Smith25d50752014-10-20 00:15:49 +00001738 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
1739 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001740}
1741
James Dennettf6333ac2012-06-22 05:46:07 +00001742/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001743void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1744 // The Microsoft #import directive takes a type library and generates header
1745 // files from it, and includes those. This is beyond the scope of what clang
1746 // does, so we ignore it and error out. However, #import can optionally have
1747 // trailing attributes that span multiple lines. We're going to eat those
1748 // so we can continue processing from there.
1749 Diag(Tok, diag::err_pp_import_directive_ms );
1750
1751 // Read tokens until we get to the end of the directive. Note that the
1752 // directive can be split over multiple lines using the backslash character.
1753 DiscardUntilEndOfDirective();
1754}
1755
James Dennettf6333ac2012-06-22 05:46:07 +00001756/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001757///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001758void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1759 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001760 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00001761 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00001762 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001763 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001764 }
Richard Smith25d50752014-10-20 00:15:49 +00001765 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001766}
1767
Chris Lattner58a1eb02009-04-08 18:46:40 +00001768/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1769/// pseudo directive in the predefines buffer. This handles it by sucking all
1770/// tokens through the preprocessor and discarding them (only keeping the side
1771/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001772void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1773 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001774 // This directive should only occur in the predefines buffer. If not, emit an
1775 // error and reject it.
1776 SourceLocation Loc = IncludeMacrosTok.getLocation();
1777 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1778 Diag(IncludeMacrosTok.getLocation(),
1779 diag::pp_include_macros_out_of_predefines);
1780 DiscardUntilEndOfDirective();
1781 return;
1782 }
Mike Stump11289f42009-09-09 15:08:12 +00001783
Chris Lattnere01d82b2009-04-08 20:53:24 +00001784 // Treat this as a normal #include for checking purposes. If this is
1785 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00001786 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00001787
Chris Lattnere01d82b2009-04-08 20:53:24 +00001788 Token TmpTok;
1789 do {
1790 Lex(TmpTok);
1791 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1792 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001793}
1794
Chris Lattnerf64b3522008-03-09 01:54:53 +00001795//===----------------------------------------------------------------------===//
1796// Preprocessor Macro Directive Handling.
1797//===----------------------------------------------------------------------===//
1798
1799/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1800/// definition has just been read. Lex the rest of the arguments and the
1801/// closing ), updating MI with what we learn. Return true if an error occurs
1802/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001803bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001804 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001805
Chris Lattnerf64b3522008-03-09 01:54:53 +00001806 while (1) {
1807 LexUnexpandedToken(Tok);
1808 switch (Tok.getKind()) {
1809 case tok::r_paren:
1810 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001811 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001812 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001813 // Otherwise we have #define FOO(A,)
1814 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1815 return true;
1816 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001817 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001818 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001819 diag::warn_cxx98_compat_variadic_macro :
1820 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001821
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001822 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1823 if (LangOpts.OpenCL) {
1824 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1825 return true;
1826 }
1827
Chris Lattnerf64b3522008-03-09 01:54:53 +00001828 // Lex the token after the identifier.
1829 LexUnexpandedToken(Tok);
1830 if (Tok.isNot(tok::r_paren)) {
1831 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1832 return true;
1833 }
1834 // Add the __VA_ARGS__ identifier as an argument.
1835 Arguments.push_back(Ident__VA_ARGS__);
1836 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001837 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001838 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001839 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001840 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1841 return true;
1842 default:
1843 // Handle keywords and identifiers here to accept things like
1844 // #define Foo(for) for.
1845 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00001846 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001847 // #define X(1
1848 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1849 return true;
1850 }
1851
1852 // If this is already used as an argument, it is used multiple times (e.g.
1853 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001854 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001855 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001856 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001857 return true;
1858 }
Mike Stump11289f42009-09-09 15:08:12 +00001859
Chris Lattnerf64b3522008-03-09 01:54:53 +00001860 // Add the argument to the macro info.
1861 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001862
Chris Lattnerf64b3522008-03-09 01:54:53 +00001863 // Lex the token after the identifier.
1864 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001865
Chris Lattnerf64b3522008-03-09 01:54:53 +00001866 switch (Tok.getKind()) {
1867 default: // #define X(A B
1868 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1869 return true;
1870 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001871 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001872 return false;
1873 case tok::comma: // #define X(A,
1874 break;
1875 case tok::ellipsis: // #define X(A... -> GCC extension
1876 // Diagnose extension.
1877 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001878
Chris Lattnerf64b3522008-03-09 01:54:53 +00001879 // Lex the token after the identifier.
1880 LexUnexpandedToken(Tok);
1881 if (Tok.isNot(tok::r_paren)) {
1882 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1883 return true;
1884 }
Mike Stump11289f42009-09-09 15:08:12 +00001885
Chris Lattnerf64b3522008-03-09 01:54:53 +00001886 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001887 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001888 return false;
1889 }
1890 }
1891 }
1892}
1893
James Dennettf6333ac2012-06-22 05:46:07 +00001894/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00001895/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001896void Preprocessor::HandleDefineDirective(Token &DefineTok,
1897 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001898 ++NumDefined;
1899
1900 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001901 ReadMacroName(MacroNameTok, MU_Define);
Mike Stump11289f42009-09-09 15:08:12 +00001902
Chris Lattnerf64b3522008-03-09 01:54:53 +00001903 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001904 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00001905 return;
1906
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001907 Token LastTok = MacroNameTok;
1908
Chris Lattnerf64b3522008-03-09 01:54:53 +00001909 // If we are supposed to keep comments in #defines, reenable comment saving
1910 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00001911 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00001912
Chris Lattnerf64b3522008-03-09 01:54:53 +00001913 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00001914 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001915
Chris Lattnerf64b3522008-03-09 01:54:53 +00001916 Token Tok;
1917 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001918
Chris Lattnerf64b3522008-03-09 01:54:53 +00001919 // If this is a function-like macro definition, parse the argument list,
1920 // marking each of the identifiers as being used as macro arguments. Also,
1921 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001922 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00001923 if (ImmediatelyAfterHeaderGuard) {
1924 // Save this macro information since it may part of a header guard.
1925 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
1926 MacroNameTok.getLocation());
1927 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001928 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00001929 } else if (Tok.hasLeadingSpace()) {
1930 // This is a normal token with leading space. Clear the leading space
1931 // marker on the first token to get proper expansion.
1932 Tok.clearFlag(Token::LeadingSpace);
1933 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001934 // This is a function-like macro definition. Read the argument list.
1935 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001936 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001937 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001938 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00001939 DiscardUntilEndOfDirective();
1940 return;
1941 }
1942
Chris Lattner249c38b2009-04-19 18:26:34 +00001943 // If this is a definition of a variadic C99 function-like macro, not using
1944 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00001945
Chris Lattner249c38b2009-04-19 18:26:34 +00001946 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1947 // This gets unpoisoned where it is allowed.
1948 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1949 if (MI->isC99Varargs())
1950 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00001951
Chris Lattnerf64b3522008-03-09 01:54:53 +00001952 // Read the first token after the arg list for down below.
1953 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001954 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001955 // C99 requires whitespace between the macro definition and the body. Emit
1956 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00001957 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001958 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00001959 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1960 // first character of a replacement list is not a character required by
1961 // subclause 5.2.1, then there shall be white-space separation between the
1962 // identifier and the replacement list.". 5.2.1 lists this set:
1963 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1964 // is irrelevant here.
1965 bool isInvalid = false;
1966 if (Tok.is(tok::at)) // @ is not in the list above.
1967 isInvalid = true;
1968 else if (Tok.is(tok::unknown)) {
1969 // If we have an unknown token, it is something strange like "`". Since
1970 // all of valid characters would have lexed into a single character
1971 // token of some sort, we know this is not a valid case.
1972 isInvalid = true;
1973 }
1974 if (isInvalid)
1975 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1976 else
1977 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001978 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001979
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001980 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001981 LastTok = Tok;
1982
Chris Lattnerf64b3522008-03-09 01:54:53 +00001983 // Read the rest of the macro body.
1984 if (MI->isObjectLike()) {
1985 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001986 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001987 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001988 MI->AddTokenToBody(Tok);
1989 // Get the next token of the macro.
1990 LexUnexpandedToken(Tok);
1991 }
Mike Stump11289f42009-09-09 15:08:12 +00001992
Chris Lattnerf64b3522008-03-09 01:54:53 +00001993 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00001994 // Otherwise, read the body of a function-like macro. While we are at it,
1995 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1996 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001997 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00001998 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001999
Eli Friedman14d3c792012-11-14 02:18:46 +00002000 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002001 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002002
Chris Lattnerf64b3522008-03-09 01:54:53 +00002003 // Get the next token of the macro.
2004 LexUnexpandedToken(Tok);
2005 continue;
2006 }
Mike Stump11289f42009-09-09 15:08:12 +00002007
Richard Smith701a3522013-07-09 01:00:29 +00002008 // If we're in -traditional mode, then we should ignore stringification
2009 // and token pasting. Mark the tokens as unknown so as not to confuse
2010 // things.
2011 if (getLangOpts().TraditionalCPP) {
2012 Tok.setKind(tok::unknown);
2013 MI->AddTokenToBody(Tok);
2014
2015 // Get the next token of the macro.
2016 LexUnexpandedToken(Tok);
2017 continue;
2018 }
2019
Eli Friedman14d3c792012-11-14 02:18:46 +00002020 if (Tok.is(tok::hashhash)) {
2021
2022 // If we see token pasting, check if it looks like the gcc comma
2023 // pasting extension. We'll use this information to suppress
2024 // diagnostics later on.
2025
2026 // Get the next token of the macro.
2027 LexUnexpandedToken(Tok);
2028
2029 if (Tok.is(tok::eod)) {
2030 MI->AddTokenToBody(LastTok);
2031 break;
2032 }
2033
2034 unsigned NumTokens = MI->getNumTokens();
2035 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2036 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2037 MI->setHasCommaPasting();
2038
David Majnemer76faf1f2013-11-05 09:30:17 +00002039 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002040 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002041 continue;
2042 }
2043
Chris Lattnerf64b3522008-03-09 01:54:53 +00002044 // Get the next token of the macro.
2045 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Chris Lattner83bd8282009-05-25 17:16:10 +00002047 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002048 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002049 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2050
2051 // If this is assembler-with-cpp mode, we accept random gibberish after
2052 // the '#' because '#' is often a comment character. However, change
2053 // the kind of the token to tok::unknown so that the preprocessor isn't
2054 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002055 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002056 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002057 MI->AddTokenToBody(LastTok);
2058 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002059 } else {
2060 Diag(Tok, diag::err_pp_stringize_not_parameter);
Mike Stump11289f42009-09-09 15:08:12 +00002061
Chris Lattner83bd8282009-05-25 17:16:10 +00002062 // Disable __VA_ARGS__ again.
2063 Ident__VA_ARGS__->setIsPoisoned(true);
2064 return;
2065 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
Chris Lattner83bd8282009-05-25 17:16:10 +00002068 // Things look ok, add the '#' and param name tokens to the macro.
2069 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002070 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002071 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002072
Chris Lattnerf64b3522008-03-09 01:54:53 +00002073 // Get the next token of the macro.
2074 LexUnexpandedToken(Tok);
2075 }
2076 }
Mike Stump11289f42009-09-09 15:08:12 +00002077
2078
Chris Lattnerf64b3522008-03-09 01:54:53 +00002079 // Disable __VA_ARGS__ again.
2080 Ident__VA_ARGS__->setIsPoisoned(true);
2081
Chris Lattner57540c52011-04-15 05:22:18 +00002082 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002083 // replacement list.
2084 unsigned NumTokens = MI->getNumTokens();
2085 if (NumTokens != 0) {
2086 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2087 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002088 return;
2089 }
2090 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2091 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002092 return;
2093 }
2094 }
Mike Stump11289f42009-09-09 15:08:12 +00002095
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002096 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002097
Chris Lattnerf64b3522008-03-09 01:54:53 +00002098 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002099 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002100 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002101 // It is very common for system headers to have tons of macro redefinitions
2102 // and for warnings to be disabled in system headers. If this is the case,
2103 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002104 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002105 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002106 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002107 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002108
Richard Smith7b242542013-03-06 00:46:00 +00002109 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2110 // C++ [cpp.predefined]p4, but allow it as an extension.
2111 if (OtherMI->isBuiltinMacro())
2112 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002113 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002114 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002115 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002116 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002117 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2118 << MacroNameTok.getIdentifierInfo();
2119 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2120 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002121 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002122 if (OtherMI->isWarnIfUnused())
2123 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002124 }
Mike Stump11289f42009-09-09 15:08:12 +00002125
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002126 DefMacroDirective *MD =
2127 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002128
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002129 assert(!MI->isUsed());
2130 // If we need warning for not using the macro, add its location in the
2131 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002132 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002133 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002134 MI->setIsWarnIfUnused(true);
2135 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2136 }
2137
Chris Lattner928e9092009-04-12 01:39:54 +00002138 // If the callbacks want to know, tell them about the macro definition.
2139 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002140 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002141}
2142
James Dennettf6333ac2012-06-22 05:46:07 +00002143/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002144///
2145void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2146 ++NumUndefined;
2147
2148 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002149 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002150
Chris Lattnerf64b3522008-03-09 01:54:53 +00002151 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002152 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002153 return;
Mike Stump11289f42009-09-09 15:08:12 +00002154
Chris Lattnerf64b3522008-03-09 01:54:53 +00002155 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002156 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002157
Chris Lattnerf64b3522008-03-09 01:54:53 +00002158 // Okay, we finally have a valid identifier to undef.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002159 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo());
Craig Topperd2d442c2014-05-17 23:10:59 +00002160 const MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002161
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002162 // If the callbacks want to know, tell them about the macro #undef.
2163 // Note: no matter if the macro was defined or not.
2164 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002165 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002166
Chris Lattnerf64b3522008-03-09 01:54:53 +00002167 // If the macro is not defined, this is a noop undef, just return.
Craig Topperd2d442c2014-05-17 23:10:59 +00002168 if (!MI)
2169 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002170
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002171 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002172 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002173
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002174 if (MI->isWarnIfUnused())
2175 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2176
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002177 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2178 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002179}
2180
2181
2182//===----------------------------------------------------------------------===//
2183// Preprocessor Conditional Directive Handling.
2184//===----------------------------------------------------------------------===//
2185
James Dennettf6333ac2012-06-22 05:46:07 +00002186/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2187/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2188/// true if any tokens have been returned or pp-directives activated before this
2189/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002190///
2191void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2192 bool ReadAnyTokensBeforeDirective) {
2193 ++NumIf;
2194 Token DirectiveTok = Result;
2195
2196 Token MacroNameTok;
2197 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002198
Chris Lattnerf64b3522008-03-09 01:54:53 +00002199 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002200 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002201 // Skip code until we get to #endif. This helps with recovery by not
2202 // emitting an error when the #endif is reached.
2203 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2204 /*Foundnonskip*/false, /*FoundElse*/false);
2205 return;
2206 }
Mike Stump11289f42009-09-09 15:08:12 +00002207
Chris Lattnerf64b3522008-03-09 01:54:53 +00002208 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002209 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002210
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002211 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002212 MacroDirective *MD = getMacroDirective(MII);
Craig Topperd2d442c2014-05-17 23:10:59 +00002213 MacroInfo *MI = MD ? MD->getMacroInfo() : nullptr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002214
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002215 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002216 // If the start of a top-level #ifdef and if the macro is not defined,
2217 // inform MIOpt that this might be the start of a proper include guard.
2218 // Otherwise it is some other form of unknown conditional which we can't
2219 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002220 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002221 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002222 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002223 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002224 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002225 }
2226
Chris Lattnerf64b3522008-03-09 01:54:53 +00002227 // If there is a macro, process it.
2228 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002229 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002230
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002231 if (Callbacks) {
2232 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002233 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002234 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002235 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002236 }
2237
Chris Lattnerf64b3522008-03-09 01:54:53 +00002238 // Should we include the stuff contained by this directive?
2239 if (!MI == isIfndef) {
2240 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002241 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2242 /*wasskip*/false, /*foundnonskip*/true,
2243 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002244 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002245 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002246 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002247 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002248 /*FoundElse*/false);
2249 }
2250}
2251
James Dennettf6333ac2012-06-22 05:46:07 +00002252/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002253///
2254void Preprocessor::HandleIfDirective(Token &IfToken,
2255 bool ReadAnyTokensBeforeDirective) {
2256 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002257
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002258 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002259 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002260 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2261 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2262 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002263
2264 // If this condition is equivalent to #ifndef X, and if this is the first
2265 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002266 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002267 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002268 // FIXME: Pass in the location of the macro name, not the 'if' token.
2269 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002270 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002271 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002272 }
2273
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002274 if (Callbacks)
2275 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002276 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002277 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002278
Chris Lattnerf64b3522008-03-09 01:54:53 +00002279 // Should we include the stuff contained by this directive?
2280 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002281 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002282 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002283 /*foundnonskip*/true, /*foundelse*/false);
2284 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002285 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002286 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002287 /*FoundElse*/false);
2288 }
2289}
2290
James Dennettf6333ac2012-06-22 05:46:07 +00002291/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002292///
2293void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2294 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002295
Chris Lattnerf64b3522008-03-09 01:54:53 +00002296 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002297 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002298
Chris Lattnerf64b3522008-03-09 01:54:53 +00002299 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002300 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002301 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002302 Diag(EndifToken, diag::err_pp_endif_without_if);
2303 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002304 }
Mike Stump11289f42009-09-09 15:08:12 +00002305
Chris Lattnerf64b3522008-03-09 01:54:53 +00002306 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002307 if (CurPPLexer->getConditionalStackDepth() == 0)
2308 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002309
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002310 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002311 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002312
2313 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002314 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002315}
2316
James Dennettf6333ac2012-06-22 05:46:07 +00002317/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002318///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002319void Preprocessor::HandleElseDirective(Token &Result) {
2320 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002321
Chris Lattnerf64b3522008-03-09 01:54:53 +00002322 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002323 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002324
Chris Lattnerf64b3522008-03-09 01:54:53 +00002325 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002326 if (CurPPLexer->popConditionalLevel(CI)) {
2327 Diag(Result, diag::pp_err_else_without_if);
2328 return;
2329 }
Mike Stump11289f42009-09-09 15:08:12 +00002330
Chris Lattnerf64b3522008-03-09 01:54:53 +00002331 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002332 if (CurPPLexer->getConditionalStackDepth() == 0)
2333 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002334
2335 // If this is a #else with a #else before it, report the error.
2336 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002337
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002338 if (Callbacks)
2339 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2340
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002341 // Finally, skip the rest of the contents of this block.
2342 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002343 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002344}
2345
James Dennettf6333ac2012-06-22 05:46:07 +00002346/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002347///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002348void Preprocessor::HandleElifDirective(Token &ElifToken) {
2349 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002350
Chris Lattnerf64b3522008-03-09 01:54:53 +00002351 // #elif directive in a non-skipping conditional... start skipping.
2352 // We don't care what the condition is, because we will always skip it (since
2353 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002354 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002355 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002356 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002357
2358 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002359 if (CurPPLexer->popConditionalLevel(CI)) {
2360 Diag(ElifToken, diag::pp_err_elif_without_if);
2361 return;
2362 }
Mike Stump11289f42009-09-09 15:08:12 +00002363
Chris Lattnerf64b3522008-03-09 01:54:53 +00002364 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002365 if (CurPPLexer->getConditionalStackDepth() == 0)
2366 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002367
Chris Lattnerf64b3522008-03-09 01:54:53 +00002368 // If this is a #elif with a #else before it, report the error.
2369 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002370
2371 if (Callbacks)
2372 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002373 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002374 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002375
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002376 // Finally, skip the rest of the contents of this block.
2377 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002378 /*FoundElse*/CI.FoundElse,
2379 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002380}