blob: 6c25bd87a273dee7f738848ebb7a45ebc7b906e8 [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
Richard Smith50474bf2015-04-23 23:29:05 +000065DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
66 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000067 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000068}
69
70UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000071Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000072 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000073}
74
75VisibilityMacroDirective *
76Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
77 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000078 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000079}
80
Richard Smith50474bf2015-04-23 23:29:05 +000081MacroDirective *
82Preprocessor::AllocateImportedMacroDirective(ModuleMacro *MM,
83 SourceLocation Loc) {
84 if (auto *MI = MM->getMacroInfo())
85 return DefMacroDirective::createImported(*this, MI, Loc, MM);
86 else
87 return UndefMacroDirective::createImported(*this, Loc, MM);
88}
89
James Dennettf6333ac2012-06-22 05:46:07 +000090/// \brief Read and discard all tokens remaining on the current line until
91/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000092void Preprocessor::DiscardUntilEndOfDirective() {
93 Token Tmp;
94 do {
95 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000096 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000097 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000098}
99
Serge Pavlov07c0f042014-12-18 11:14:21 +0000100/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
101enum MacroDiag {
102 MD_NoWarn, //> Not a reserved identifier
103 MD_KeywordDef, //> Macro hides keyword, enabled by default
104 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
105};
106
107/// \brief Checks if the specified identifier is reserved in the specified
108/// language.
109/// This function does not check if the identifier is a keyword.
110static bool isReservedId(StringRef Text, const LangOptions &Lang) {
111 // C++ [macro.names], C11 7.1.3:
112 // All identifiers that begin with an underscore and either an uppercase
113 // letter or another underscore are always reserved for any use.
114 if (Text.size() >= 2 && Text[0] == '_' &&
115 (isUppercase(Text[1]) || Text[1] == '_'))
116 return true;
117 // C++ [global.names]
118 // Each name that contains a double underscore ... is reserved to the
119 // implementation for any use.
120 if (Lang.CPlusPlus) {
121 if (Text.find("__") != StringRef::npos)
122 return true;
123 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000124 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000125}
126
Serge Pavlov07c0f042014-12-18 11:14:21 +0000127static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
128 const LangOptions &Lang = PP.getLangOpts();
129 StringRef Text = II->getName();
130 if (isReservedId(Text, Lang))
131 return MD_ReservedMacro;
132 if (II->isKeyword(Lang))
133 return MD_KeywordDef;
134 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
135 return MD_KeywordDef;
136 return MD_NoWarn;
137}
138
139static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
140 const LangOptions &Lang = PP.getLangOpts();
141 StringRef Text = II->getName();
142 // Do not warn on keyword undef. It is generally harmless and widely used.
143 if (isReservedId(Text, Lang))
144 return MD_ReservedMacro;
145 return MD_NoWarn;
146}
147
148bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
149 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000150 // Missing macro name?
151 if (MacroNameTok.is(tok::eod))
152 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
153
154 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
155 if (!II) {
156 bool Invalid = false;
157 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
158 if (Invalid)
159 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000160 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000161
Alp Tokerf33619c2014-05-31 03:38:08 +0000162 if (!II->isCPlusPlusOperatorKeyword())
163 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000164
Alp Tokere03e9e12014-05-31 16:32:22 +0000165 // C++ 2.5p2: Alternative tokens behave the same as its primary token
166 // except for their spellings.
167 Diag(MacroNameTok, getLangOpts().MicrosoftExt
168 ? diag::ext_pp_operator_used_as_macro_name
169 : diag::err_pp_operator_used_as_macro_name)
170 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000171
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000172 // Allow #defining |and| and friends for Microsoft compatibility or
173 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000174 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000175 }
176
Serge Pavlovd024f522014-10-24 17:31:32 +0000177 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000178 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
179 return Diag(MacroNameTok, diag::err_defined_macro_name);
180 }
181
Richard Smith20e883e2015-04-29 23:20:19 +0000182 if (isDefineUndef == MU_Undef) {
183 auto *MI = getMacroInfo(II);
184 if (MI && MI->isBuiltinMacro()) {
185 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
186 // and C++ [cpp.predefined]p4], but allow it as an extension.
187 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
188 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000189 }
190
Serge Pavlov07c0f042014-12-18 11:14:21 +0000191 // If defining/undefining reserved identifier or a keyword, we need to issue
192 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000193 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000194 if (ShadowFlag)
195 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000196 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
197 (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000198 MacroDiag D = MD_NoWarn;
199 if (isDefineUndef == MU_Define) {
200 D = shouldWarnOnMacroDef(*this, II);
201 }
202 else if (isDefineUndef == MU_Undef)
203 D = shouldWarnOnMacroUndef(*this, II);
204 if (D == MD_KeywordDef) {
205 // We do not want to warn on some patterns widely used in configuration
206 // scripts. This requires analyzing next tokens, so do not issue warnings
207 // now, only inform caller.
208 if (ShadowFlag)
209 *ShadowFlag = true;
210 }
211 if (D == MD_ReservedMacro)
212 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000213 }
214
Alp Tokerb05e0b52014-05-21 06:13:51 +0000215 // Okay, we got a good identifier.
216 return false;
217}
218
James Dennettf6333ac2012-06-22 05:46:07 +0000219/// \brief Lex and validate a macro name, which occurs after a
220/// \#define or \#undef.
221///
Serge Pavlovd024f522014-10-24 17:31:32 +0000222/// This sets the token kind to eod and discards the rest of the macro line if
223/// the macro name is invalid.
224///
225/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000226/// \param isDefineUndef Context in which macro is used.
227/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
228void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
229 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000230 // Read the token, don't allow macro expansion on it.
231 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000232
Douglas Gregor12785102010-08-24 20:21:13 +0000233 if (MacroNameTok.is(tok::code_completion)) {
234 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000235 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000236 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000237 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000238 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000239
Serge Pavlov07c0f042014-12-18 11:14:21 +0000240 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000241 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000242
243 // Invalid macro name, read and discard the rest of the line and set the
244 // token kind to tok::eod if necessary.
245 if (MacroNameTok.isNot(tok::eod)) {
246 MacroNameTok.setKind(tok::eod);
247 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000248 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000249}
250
James Dennettf6333ac2012-06-22 05:46:07 +0000251/// \brief Ensure that the next token is a tok::eod token.
252///
253/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000254/// true, then we consider macros that expand to zero tokens as being ok.
255void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000256 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000257 // Lex unexpanded tokens for most directives: macros might expand to zero
258 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
259 // #line) allow empty macros.
260 if (EnableMacros)
261 Lex(Tmp);
262 else
263 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000264
Chris Lattnerf64b3522008-03-09 01:54:53 +0000265 // There should be no tokens after the directive, but we allow them as an
266 // extension.
267 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
268 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000269
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000270 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000271 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000272 // or if this is a macro-style preprocessing directive, because it is more
273 // trouble than it is worth to insert /**/ and check that there is no /**/
274 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000275 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000276 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000277 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000278 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
279 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280 DiscardUntilEndOfDirective();
281 }
282}
283
284
285
James Dennettf6333ac2012-06-22 05:46:07 +0000286/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
287/// decided that the subsequent tokens are in the \#if'd out portion of the
288/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000289/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000290/// this \#if directive, so \#else/\#elif blocks should never be entered.
291/// If ElseOk is true, then \#else directives are ok, if not, then we have
292/// already seen one so a \#else directive is a duplicate. When this returns,
293/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000294void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
295 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000296 bool FoundElse,
297 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000298 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000299 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000300
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000301 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000302 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000303
Ted Kremenek56572ab2008-12-12 18:34:08 +0000304 if (CurPTHLexer) {
305 PTHSkipExcludedConditionalBlock();
306 return;
307 }
Mike Stump11289f42009-09-09 15:08:12 +0000308
Chris Lattnerf64b3522008-03-09 01:54:53 +0000309 // Enter raw mode to disable identifier lookup (and thus macro expansion),
310 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000311 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000312 Token Tok;
313 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000314 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000315
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000316 if (Tok.is(tok::code_completion)) {
317 if (CodeComplete)
318 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000319 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000320 continue;
321 }
322
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323 // If this is the end of the buffer, we have an error.
324 if (Tok.is(tok::eof)) {
325 // Emit errors for each unterminated conditional on the stack, including
326 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000327 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000328 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000329 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
330 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000331 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000332 }
333
Chris Lattnerf64b3522008-03-09 01:54:53 +0000334 // Just return and let the caller lex after this #include.
335 break;
336 }
Mike Stump11289f42009-09-09 15:08:12 +0000337
Chris Lattnerf64b3522008-03-09 01:54:53 +0000338 // If this token is not a preprocessor directive, just skip it.
339 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
340 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chris Lattnerf64b3522008-03-09 01:54:53 +0000342 // We just parsed a # character at the start of a line, so we're in
343 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000344 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000345 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000346 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000347
Mike Stump11289f42009-09-09 15:08:12 +0000348
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349 // Read the next token, the directive flavor.
350 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000351
Chris Lattnerf64b3522008-03-09 01:54:53 +0000352 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
353 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000354 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000355 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000356 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000357 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000358 continue;
359 }
360
361 // If the first letter isn't i or e, it isn't intesting to us. We know that
362 // this is safe in the face of spelling differences, because there is no way
363 // to spell an i/e in a strange way that is another letter. Skipping this
364 // allows us to avoid looking up the identifier info for #define/#undef and
365 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000366 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000367
Alp Toker2d57cea2014-05-17 04:53:25 +0000368 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000369 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000370 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000371 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000372 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000373 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000374 continue;
375 }
Mike Stump11289f42009-09-09 15:08:12 +0000376
Chris Lattnerf64b3522008-03-09 01:54:53 +0000377 // Get the identifier name without trigraphs or embedded newlines. Note
378 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
379 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000380 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000381 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000382 if (!Tok.needsCleaning() && RI.size() < 20) {
383 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000384 } else {
385 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000386 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000387 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000388 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000389 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000390 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000391 continue;
392 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000393 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000394 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Benjamin Kramer144884642009-12-31 13:32:38 +0000397 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000398 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000399 if (Sub.empty() || // "if"
400 Sub == "def" || // "ifdef"
401 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000402 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
403 // bother parsing the condition.
404 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000405 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000407 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000408 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000409 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000410 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000411 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000412 PPConditionalInfo CondInfo;
413 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000414 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000415 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000416 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattnerf64b3522008-03-09 01:54:53 +0000418 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000419 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000420 // Restore the value of LexingRawMode so that trailing comments
421 // are handled correctly, if we've reached the outermost block.
422 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000423 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000424 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000425 if (Callbacks)
426 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000427 break;
Richard Smithd0124572012-06-21 00:35:03 +0000428 } else {
429 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000430 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000431 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000432 // #else directive in a skipping conditional. If not in some other
433 // skipping conditional, and if #else hasn't already been seen, enter it
434 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000435 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000436
Chris Lattnerf64b3522008-03-09 01:54:53 +0000437 // If this is a #else with a #else before it, report the error.
438 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000439
Chris Lattnerf64b3522008-03-09 01:54:53 +0000440 // Note that we've seen a #else in this conditional.
441 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000442
Chris Lattnerf64b3522008-03-09 01:54:53 +0000443 // If the conditional is at the top level, and the #if block wasn't
444 // entered, enter the #else block now.
445 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
446 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000447 // Restore the value of LexingRawMode so that trailing comments
448 // are handled correctly.
449 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000450 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000451 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000452 if (Callbacks)
453 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000454 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000455 } else {
456 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000457 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000458 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000459 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000460
John Thompson17c35732013-12-04 20:19:30 +0000461 // If this is a #elif with a #else before it, report the error.
462 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
463
Chris Lattnerf64b3522008-03-09 01:54:53 +0000464 // If this is in a skipping block or if we're already handled this #if
465 // block, don't bother parsing the condition.
466 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
467 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000468 } else {
John Thompson17c35732013-12-04 20:19:30 +0000469 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000470 // Restore the value of LexingRawMode so that identifiers are
471 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000472 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
473 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000474 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000475 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000476 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000477 if (Callbacks) {
478 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000479 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000480 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000481 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000482 }
483 // If this condition is true, enter it!
484 if (CondValue) {
485 CondInfo.FoundNonSkip = true;
486 break;
487 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000488 }
489 }
490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000492 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000493 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000494 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000495 }
496
497 // Finally, if we are out of the conditional (saw an #endif or ran off the end
498 // of the file, just stop skipping and return to lexing whatever came after
499 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000500 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000501
502 if (Callbacks) {
503 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
504 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
505 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000506}
507
Ted Kremenek56572ab2008-12-12 18:34:08 +0000508void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000509
510 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000511 assert(CurPTHLexer);
512 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000513
Ted Kremenek56572ab2008-12-12 18:34:08 +0000514 // Skip to the next '#else', '#elif', or #endif.
515 if (CurPTHLexer->SkipBlock()) {
516 // We have reached an #endif. Both the '#' and 'endif' tokens
517 // have been consumed by the PTHLexer. Just pop off the condition level.
518 PPConditionalInfo CondInfo;
519 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000520 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000521 assert(!InCond && "Can't be skipping if not in a conditional!");
522 break;
523 }
Mike Stump11289f42009-09-09 15:08:12 +0000524
Ted Kremenek56572ab2008-12-12 18:34:08 +0000525 // We have reached a '#else' or '#elif'. Lex the next token to get
526 // the directive flavor.
527 Token Tok;
528 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000529
Ted Kremenek56572ab2008-12-12 18:34:08 +0000530 // We can actually look up the IdentifierInfo here since we aren't in
531 // raw mode.
532 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
533
534 if (K == tok::pp_else) {
535 // #else: Enter the else condition. We aren't in a nested condition
536 // since we skip those. We're always in the one matching the last
537 // blocked we skipped.
538 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
539 // Note that we've seen a #else in this conditional.
540 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000541
Ted Kremenek56572ab2008-12-12 18:34:08 +0000542 // If the #if block wasn't entered then enter the #else block now.
543 if (!CondInfo.FoundNonSkip) {
544 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000545
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000546 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000547 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000548 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000549 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000550
Ted Kremenek56572ab2008-12-12 18:34:08 +0000551 break;
552 }
Mike Stump11289f42009-09-09 15:08:12 +0000553
Ted Kremenek56572ab2008-12-12 18:34:08 +0000554 // Otherwise skip this block.
555 continue;
556 }
Mike Stump11289f42009-09-09 15:08:12 +0000557
Ted Kremenek56572ab2008-12-12 18:34:08 +0000558 assert(K == tok::pp_elif);
559 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
560
561 // If this is a #elif with a #else before it, report the error.
562 if (CondInfo.FoundElse)
563 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000564
Ted Kremenek56572ab2008-12-12 18:34:08 +0000565 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000566 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000567 if (CondInfo.FoundNonSkip)
568 continue;
569
570 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000571 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000572 CurPTHLexer->ParsingPreprocessorDirective = true;
573 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
574 CurPTHLexer->ParsingPreprocessorDirective = false;
575
576 // If this condition is true, enter it!
577 if (ShouldEnter) {
578 CondInfo.FoundNonSkip = true;
579 break;
580 }
581
582 // Otherwise, skip this block and go to the next one.
583 continue;
584 }
585}
586
Richard Smith2a553082015-04-23 22:58:06 +0000587Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000588 ModuleMap &ModMap = HeaderInfo.getModuleMap();
Richard Smith2a553082015-04-23 22:58:06 +0000589 if (SourceMgr.isInMainFile(Loc)) {
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000590 if (Module *CurMod = getCurrentModule())
591 return CurMod; // Compiling a module.
592 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
593 }
594 // Try to determine the module of the include directive.
Daniel Jasper88d86952013-12-03 20:30:36 +0000595 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
Richard Smith2a553082015-04-23 22:58:06 +0000596 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000597 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
598 // The include comes from a file.
599 return ModMap.findModuleForHeader(EntryOfIncl).getModule();
600 } else {
601 // The include does not come from a file,
602 // so it is probably a module compilation.
603 return getCurrentModule();
604 }
605}
606
Richard Smith2a553082015-04-23 22:58:06 +0000607Module *Preprocessor::getModuleContainingLocation(SourceLocation Loc) {
608 return HeaderInfo.getModuleMap().inferModuleFromLocation(
609 FullSourceLoc(Loc, SourceMgr));
610}
611
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000612const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000613 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000614 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000615 bool isAngled,
616 const DirectoryLookup *FromDir,
Richard Smith25d50752014-10-20 00:15:49 +0000617 const FileEntry *FromFile,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000618 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000620 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000621 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000622 bool SkipCache) {
Will Wilson0fafd342013-12-27 19:46:16 +0000623 // If the header lookup mechanism may be relative to the current inclusion
624 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000625 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
626 Includers;
Richard Smith25d50752014-10-20 00:15:49 +0000627 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000628 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000629 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattner022923a2009-02-04 19:45:07 +0000631 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000632 // predefines buffer or the module includes buffer. Any other file is not
633 // lexed with a normal lexer, so it won't be scanned for preprocessor
634 // directives.
635 //
636 // If we have the predefines buffer, resolve #include references (which come
637 // from the -include command line argument) from the current working
638 // directory instead of relative to the main file.
639 //
640 // If we have the module includes buffer, resolve #include references (which
641 // come from header declarations in the module map) relative to the module
642 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000643 if (!FileEnt) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000644 if (FID == SourceMgr.getMainFileID() && MainFileDir)
645 Includers.push_back(std::make_pair(nullptr, MainFileDir));
646 else if ((FileEnt =
647 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000648 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
649 } else {
650 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
651 }
Will Wilson0fafd342013-12-27 19:46:16 +0000652
653 // MSVC searches the current include stack from top to bottom for
654 // headers included by quoted include directives.
655 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000656 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000657 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
658 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
659 if (IsFileLexer(ISEntry))
660 if ((FileEnt = SourceMgr.getFileEntryForID(
661 ISEntry.ThePPLexer->getFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000662 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000663 }
Chris Lattner022923a2009-02-04 19:45:07 +0000664 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000665 }
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000667 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000668
669 if (FromFile) {
670 // We're supposed to start looking from after a particular file. Search
671 // the include path until we find that file or run out of files.
672 const DirectoryLookup *TmpCurDir = CurDir;
673 const DirectoryLookup *TmpFromDir = nullptr;
674 while (const FileEntry *FE = HeaderInfo.LookupFile(
675 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
676 Includers, SearchPath, RelativePath, SuggestedModule,
677 SkipCache)) {
678 // Keep looking as if this file did a #include_next.
679 TmpFromDir = TmpCurDir;
680 ++TmpFromDir;
681 if (FE == FromFile) {
682 // Found it.
683 FromDir = TmpFromDir;
684 CurDir = TmpCurDir;
685 break;
686 }
687 }
688 }
689
690 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000691 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000692 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
693 RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000694 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000695 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000696 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
697 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000698 return FE;
699 }
Mike Stump11289f42009-09-09 15:08:12 +0000700
Will Wilson0fafd342013-12-27 19:46:16 +0000701 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000702 // Otherwise, see if this is a subframework header. If so, this is relative
703 // to one of the headers on the #include stack. Walk the list of the current
704 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000705 if (IsFileLexer()) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000706 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000707 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000708 SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000709 SuggestedModule))) {
710 if (SuggestedModule && !LangOpts.AsmPreprocessor)
711 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
712 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000713 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000714 }
715 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000716 }
Mike Stump11289f42009-09-09 15:08:12 +0000717
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000718 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
719 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000720 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000721 if ((CurFileEnt =
Ben Langmuir71e1a642014-05-05 21:44:13 +0000722 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000723 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000724 Filename, CurFileEnt, SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000725 SuggestedModule))) {
726 if (SuggestedModule && !LangOpts.AsmPreprocessor)
727 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
728 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000729 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000730 }
731 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000732 }
733 }
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000735 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000736 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000737}
738
Chris Lattnerf64b3522008-03-09 01:54:53 +0000739
740//===----------------------------------------------------------------------===//
741// Preprocessor Directive Handling.
742//===----------------------------------------------------------------------===//
743
David Blaikied5321242012-06-06 18:52:13 +0000744class Preprocessor::ResetMacroExpansionHelper {
745public:
746 ResetMacroExpansionHelper(Preprocessor *pp)
747 : PP(pp), save(pp->DisableMacroExpansion) {
748 if (pp->MacroExpansionInDirectivesOverride)
749 pp->DisableMacroExpansion = false;
750 }
751 ~ResetMacroExpansionHelper() {
752 PP->DisableMacroExpansion = save;
753 }
754private:
755 Preprocessor *PP;
756 bool save;
757};
758
Chris Lattnerf64b3522008-03-09 01:54:53 +0000759/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000760/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000761/// lexer/preprocessor state, and advances the lexer(s) so that the next token
762/// read is the correct one.
763void Preprocessor::HandleDirective(Token &Result) {
764 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000765
Chris Lattnerf64b3522008-03-09 01:54:53 +0000766 // We just parsed a # character at the start of a line, so we're in directive
767 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000768 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000769 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000770 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000771
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000772 bool ImmediatelyAfterTopLevelIfndef =
773 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
774 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
775
Chris Lattnerf64b3522008-03-09 01:54:53 +0000776 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000777
Chris Lattnerf64b3522008-03-09 01:54:53 +0000778 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000779 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000780 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000781 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000782
Chris Lattner2d17ab72009-03-18 21:00:25 +0000783 // Save the '#' token in case we need to return it later.
784 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattnerf64b3522008-03-09 01:54:53 +0000786 // Read the next token, the directive flavor. This isn't expanded due to
787 // C99 6.10.3p8.
788 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000789
Chris Lattnerf64b3522008-03-09 01:54:53 +0000790 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
791 // #define A(x) #x
792 // A(abc
793 // #warning blah
794 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000795 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
796 // not support this for #include-like directives, since that can result in
797 // terrible diagnostics, and does not work in GCC.
798 if (InMacroArgs) {
799 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
800 switch (II->getPPKeywordID()) {
801 case tok::pp_include:
802 case tok::pp_import:
803 case tok::pp_include_next:
804 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000805 case tok::pp_pragma:
806 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000807 DiscardUntilEndOfDirective();
808 return;
809 default:
810 break;
811 }
812 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000813 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000814 }
Mike Stump11289f42009-09-09 15:08:12 +0000815
David Blaikied5321242012-06-06 18:52:13 +0000816 // Temporarily enable macro expansion if set so
817 // and reset to previous state when returning from this function.
818 ResetMacroExpansionHelper helper(this);
819
Chris Lattnerf64b3522008-03-09 01:54:53 +0000820 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000821 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000822 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000823 case tok::code_completion:
824 if (CodeComplete)
825 CodeComplete->CodeCompleteDirective(
826 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000827 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000828 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000829 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000830 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000831 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000832 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000833 default:
834 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000835 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattnerf64b3522008-03-09 01:54:53 +0000837 // Ask what the preprocessor keyword ID is.
838 switch (II->getPPKeywordID()) {
839 default: break;
840 // C99 6.10.1 - Conditional Inclusion.
841 case tok::pp_if:
842 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
843 case tok::pp_ifdef:
844 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
845 case tok::pp_ifndef:
846 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
847 case tok::pp_elif:
848 return HandleElifDirective(Result);
849 case tok::pp_else:
850 return HandleElseDirective(Result);
851 case tok::pp_endif:
852 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000853
Chris Lattnerf64b3522008-03-09 01:54:53 +0000854 // C99 6.10.2 - Source File Inclusion.
855 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000856 // Handle #include.
857 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000858 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000859 // Handle -imacros.
860 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000861
Chris Lattnerf64b3522008-03-09 01:54:53 +0000862 // C99 6.10.3 - Macro Replacement.
863 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000864 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000865 case tok::pp_undef:
866 return HandleUndefDirective(Result);
867
868 // C99 6.10.4 - Line Control.
869 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000870 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattnerf64b3522008-03-09 01:54:53 +0000872 // C99 6.10.5 - Error Directive.
873 case tok::pp_error:
874 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000875
Chris Lattnerf64b3522008-03-09 01:54:53 +0000876 // C99 6.10.6 - Pragma Directive.
877 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000878 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattnerf64b3522008-03-09 01:54:53 +0000880 // GNU Extensions.
881 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000882 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000883 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000884 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000885
Chris Lattnerf64b3522008-03-09 01:54:53 +0000886 case tok::pp_warning:
887 Diag(Result, diag::ext_pp_warning_directive);
888 return HandleUserDiagnosticDirective(Result, true);
889 case tok::pp_ident:
890 return HandleIdentSCCSDirective(Result);
891 case tok::pp_sccs:
892 return HandleIdentSCCSDirective(Result);
893 case tok::pp_assert:
894 //isExtension = true; // FIXME: implement #assert
895 break;
896 case tok::pp_unassert:
897 //isExtension = true; // FIXME: implement #unassert
898 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000899
Douglas Gregor663b48f2012-01-03 19:48:16 +0000900 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000901 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000902 return HandleMacroPublicDirective(Result);
903 break;
904
Douglas Gregor663b48f2012-01-03 19:48:16 +0000905 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000906 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000907 return HandleMacroPrivateDirective(Result);
908 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000909 }
910 break;
911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Chris Lattner2d17ab72009-03-18 21:00:25 +0000913 // If this is a .S file, treat unknown # directives as non-preprocessor
914 // directives. This is important because # may be a comment or introduce
915 // various pseudo-ops. Just return the # token and push back the following
916 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000917 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000918 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000919 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000920 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000921 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000922
923 // If the second token is a hashhash token, then we need to translate it to
924 // unknown so the token lexer doesn't try to perform token pasting.
925 if (Result.is(tok::hashhash))
926 Toks[1].setKind(tok::unknown);
927
Chris Lattner2d17ab72009-03-18 21:00:25 +0000928 // Enter this token stream so that we re-lex the tokens. Make sure to
929 // enable macro expansion, in case the token after the # is an identifier
930 // that is expanded.
931 EnterTokenStream(Toks, 2, false, true);
932 return;
933 }
Mike Stump11289f42009-09-09 15:08:12 +0000934
Chris Lattnerf64b3522008-03-09 01:54:53 +0000935 // If we reached here, the preprocessing token is not valid!
936 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattnerf64b3522008-03-09 01:54:53 +0000938 // Read the rest of the PP line.
939 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000940
Chris Lattnerf64b3522008-03-09 01:54:53 +0000941 // Okay, we're done parsing the directive.
942}
943
Chris Lattner76e68962009-01-26 06:19:46 +0000944/// GetLineValue - Convert a numeric token into an unsigned value, emitting
945/// Diagnostic DiagID if it is invalid, and returning the value in Val.
946static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000947 unsigned DiagID, Preprocessor &PP,
948 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000949 if (DigitTok.isNot(tok::numeric_constant)) {
950 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000951
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000952 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000953 PP.DiscardUntilEndOfDirective();
954 return true;
955 }
Mike Stump11289f42009-09-09 15:08:12 +0000956
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000957 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000958 IntegerBuffer.resize(DigitTok.getLength());
959 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000960 bool Invalid = false;
961 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
962 if (Invalid)
963 return true;
964
Chris Lattnerd66f1722009-04-18 18:35:15 +0000965 // Verify that we have a simple digit-sequence, and compute the value. This
966 // is always a simple digit string computed in decimal, so we do this manually
967 // here.
968 Val = 0;
969 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +0000970 // C++1y [lex.fcon]p1:
971 // Optional separating single quotes in a digit-sequence are ignored
972 if (DigitTokBegin[i] == '\'')
973 continue;
974
Jordan Rosea7d03842013-02-08 22:30:41 +0000975 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000976 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000977 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000978 PP.DiscardUntilEndOfDirective();
979 return true;
980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981
Chris Lattnerd66f1722009-04-18 18:35:15 +0000982 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
983 if (NextVal < Val) { // overflow.
984 PP.Diag(DigitTok, DiagID);
985 PP.DiscardUntilEndOfDirective();
986 return true;
987 }
988 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000989 }
Mike Stump11289f42009-09-09 15:08:12 +0000990
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000991 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000992 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
993 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000994
Chris Lattner76e68962009-01-26 06:19:46 +0000995 return false;
996}
997
James Dennettf6333ac2012-06-22 05:46:07 +0000998/// \brief Handle a \#line directive: C99 6.10.4.
999///
1000/// The two acceptable forms are:
1001/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001002/// # line digit-sequence
1003/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001004/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001005void Preprocessor::HandleLineDirective(Token &Tok) {
1006 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1007 // expanded.
1008 Token DigitTok;
1009 Lex(DigitTok);
1010
Chris Lattner100c65e2009-01-26 05:29:08 +00001011 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001012 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001013 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001014 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001015
1016 if (LineNo == 0)
1017 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001018
Chris Lattner76e68962009-01-26 06:19:46 +00001019 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1020 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001021 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001022 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001023 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001024 if (LineNo >= LineLimit)
1025 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001026 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001027 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001028
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001029 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001030 Token StrTok;
1031 Lex(StrTok);
1032
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001033 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1034 // string followed by eod.
1035 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001036 ; // ok
1037 else if (StrTok.isNot(tok::string_literal)) {
1038 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001039 return DiscardUntilEndOfDirective();
1040 } else if (StrTok.hasUDSuffix()) {
1041 Diag(StrTok, diag::err_invalid_string_udl);
1042 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001043 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001044 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001045 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001046 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001047 if (Literal.hadError)
1048 return DiscardUntilEndOfDirective();
1049 if (Literal.Pascal) {
1050 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1051 return DiscardUntilEndOfDirective();
1052 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001053 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001054
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001055 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001056 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1057 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001058 }
Mike Stump11289f42009-09-09 15:08:12 +00001059
Chris Lattner1eaa70a2009-02-03 21:52:55 +00001060 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +00001061
Chris Lattner839150e2009-03-27 17:13:49 +00001062 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001063 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1064 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +00001065 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +00001066}
1067
Chris Lattner76e68962009-01-26 06:19:46 +00001068/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1069/// marker directive.
1070static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1071 bool &IsSystemHeader, bool &IsExternCHeader,
1072 Preprocessor &PP) {
1073 unsigned FlagVal;
1074 Token FlagTok;
1075 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001076 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001077 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1078 return true;
1079
1080 if (FlagVal == 1) {
1081 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001082
Chris Lattner76e68962009-01-26 06:19:46 +00001083 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001084 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001085 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1086 return true;
1087 } else if (FlagVal == 2) {
1088 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001089
Chris Lattner1c967782009-02-04 06:25:26 +00001090 SourceManager &SM = PP.getSourceManager();
1091 // If we are leaving the current presumed file, check to make sure the
1092 // presumed include stack isn't empty!
1093 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001094 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001095 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001096 if (PLoc.isInvalid())
1097 return true;
1098
Chris Lattner1c967782009-02-04 06:25:26 +00001099 // If there is no include loc (main file) or if the include loc is in a
1100 // different physical file, then we aren't in a "1" line marker flag region.
1101 SourceLocation IncLoc = PLoc.getIncludeLoc();
1102 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001103 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001104 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1105 PP.DiscardUntilEndOfDirective();
1106 return true;
1107 }
Mike Stump11289f42009-09-09 15:08:12 +00001108
Chris Lattner76e68962009-01-26 06:19:46 +00001109 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001110 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001111 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1112 return true;
1113 }
1114
1115 // We must have 3 if there are still flags.
1116 if (FlagVal != 3) {
1117 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001118 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001119 return true;
1120 }
Mike Stump11289f42009-09-09 15:08:12 +00001121
Chris Lattner76e68962009-01-26 06:19:46 +00001122 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001123
Chris Lattner76e68962009-01-26 06:19:46 +00001124 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001125 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001126 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001127 return true;
1128
1129 // We must have 4 if there is yet another flag.
1130 if (FlagVal != 4) {
1131 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001132 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001133 return true;
1134 }
Mike Stump11289f42009-09-09 15:08:12 +00001135
Chris Lattner76e68962009-01-26 06:19:46 +00001136 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001137
Chris Lattner76e68962009-01-26 06:19:46 +00001138 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001139 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001140
1141 // There are no more valid flags here.
1142 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001143 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001144 return true;
1145}
1146
1147/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1148/// one of the following forms:
1149///
1150/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001151/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001152/// # 42 "file" ('1' | '2')? '3' '4'?
1153///
1154void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1155 // Validate the number and convert it to an unsigned. GNU does not have a
1156 // line # limit other than it fit in 32-bits.
1157 unsigned LineNo;
1158 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001159 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001160 return;
Mike Stump11289f42009-09-09 15:08:12 +00001161
Chris Lattner76e68962009-01-26 06:19:46 +00001162 Token StrTok;
1163 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001164
Chris Lattner76e68962009-01-26 06:19:46 +00001165 bool IsFileEntry = false, IsFileExit = false;
1166 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001167 int FilenameID = -1;
1168
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001169 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1170 // string followed by eod.
1171 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001172 ; // ok
1173 else if (StrTok.isNot(tok::string_literal)) {
1174 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001175 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001176 } else if (StrTok.hasUDSuffix()) {
1177 Diag(StrTok, diag::err_invalid_string_udl);
1178 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001179 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001180 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001181 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001182 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001183 if (Literal.hadError)
1184 return DiscardUntilEndOfDirective();
1185 if (Literal.Pascal) {
1186 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1187 return DiscardUntilEndOfDirective();
1188 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001189 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001190
Chris Lattner76e68962009-01-26 06:19:46 +00001191 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001192 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001193 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001194 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001195 }
Mike Stump11289f42009-09-09 15:08:12 +00001196
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001197 // Create a line note with this information.
1198 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001199 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001200 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001201
Chris Lattner839150e2009-03-27 17:13:49 +00001202 // If the preprocessor has callbacks installed, notify them of the #line
1203 // change. This is used so that the line marker comes out in -E mode for
1204 // example.
1205 if (Callbacks) {
1206 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1207 if (IsFileEntry)
1208 Reason = PPCallbacks::EnterFile;
1209 else if (IsFileExit)
1210 Reason = PPCallbacks::ExitFile;
1211 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1212 if (IsExternCHeader)
1213 FileKind = SrcMgr::C_ExternCSystem;
1214 else if (IsSystemHeader)
1215 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001216
Chris Lattnerc745cec2010-04-14 04:28:50 +00001217 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001218 }
Chris Lattner76e68962009-01-26 06:19:46 +00001219}
1220
1221
Chris Lattner38d7fd22009-01-26 05:30:54 +00001222/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1223///
Mike Stump11289f42009-09-09 15:08:12 +00001224void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001225 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001226 // PTH doesn't emit #warning or #error directives.
1227 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001228 return CurPTHLexer->DiscardToEndOfLine();
1229
Chris Lattnerf64b3522008-03-09 01:54:53 +00001230 // Read the rest of the line raw. We do this because we don't want macros
1231 // to be expanded and we don't require that the tokens be valid preprocessing
1232 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1233 // collapse multiple consequtive white space between tokens, but this isn't
1234 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001235 SmallString<128> Message;
1236 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001237
1238 // Find the first non-whitespace character, so that we can make the
1239 // diagnostic more succinct.
Yaron Keren92e1b622015-03-18 10:17:07 +00001240 StringRef Msg = StringRef(Message).ltrim(" ");
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001241
Chris Lattner100c65e2009-01-26 05:29:08 +00001242 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001243 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001244 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001245 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001246}
1247
1248/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1249///
1250void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1251 // Yes, this directive is an extension.
1252 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Chris Lattnerf64b3522008-03-09 01:54:53 +00001254 // Read the string argument.
1255 Token StrTok;
1256 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001257
Chris Lattnerf64b3522008-03-09 01:54:53 +00001258 // If the token kind isn't a string, it's a malformed directive.
1259 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001260 StrTok.isNot(tok::wide_string_literal)) {
1261 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001262 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001263 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001264 return;
1265 }
Mike Stump11289f42009-09-09 15:08:12 +00001266
Richard Smithd67aea22012-03-06 03:21:47 +00001267 if (StrTok.hasUDSuffix()) {
1268 Diag(StrTok, diag::err_invalid_string_udl);
1269 return DiscardUntilEndOfDirective();
1270 }
1271
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001272 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001273 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001274
Douglas Gregordc970f02010-03-16 22:30:13 +00001275 if (Callbacks) {
1276 bool Invalid = false;
1277 std::string Str = getSpelling(StrTok, &Invalid);
1278 if (!Invalid)
1279 Callbacks->Ident(Tok.getLocation(), Str);
1280 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001281}
1282
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001283/// \brief Handle a #public directive.
1284void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001285 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001286 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001287
1288 // Error reading macro name? If so, diagnostic already issued.
1289 if (MacroNameTok.is(tok::eod))
1290 return;
1291
Douglas Gregor663b48f2012-01-03 19:48:16 +00001292 // Check to see if this is the last token on the #__public_macro line.
1293 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001294
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001295 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001296 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001297 MacroDirective *MD = getLocalMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001298
1299 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001300 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001301 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001302 return;
1303 }
1304
1305 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001306 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1307 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001308}
1309
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001310/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001311void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1312 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001313 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregorebf00492011-10-17 15:32:29 +00001314
1315 // Error reading macro name? If so, diagnostic already issued.
1316 if (MacroNameTok.is(tok::eod))
1317 return;
1318
Douglas Gregor663b48f2012-01-03 19:48:16 +00001319 // Check to see if this is the last token on the #__private_macro line.
1320 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001321
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001322 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001323 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001324 MacroDirective *MD = getLocalMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001325
1326 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001327 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001328 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001329 return;
1330 }
1331
1332 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001333 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1334 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001335}
1336
Chris Lattnerf64b3522008-03-09 01:54:53 +00001337//===----------------------------------------------------------------------===//
1338// Preprocessor Include Directive Handling.
1339//===----------------------------------------------------------------------===//
1340
1341/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001342/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001343/// true if the input filename was in <>'s or false if it were in ""'s. The
1344/// caller is expected to provide a buffer that is large enough to hold the
1345/// spelling of the filename, but is also expected to handle the case when
1346/// this method decides to use a different buffer.
1347bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001348 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001349 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001350 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001351
Chris Lattnerf64b3522008-03-09 01:54:53 +00001352 // Make sure the filename is <x> or "x".
1353 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001354 if (Buffer[0] == '<') {
1355 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001356 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001357 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001358 return true;
1359 }
1360 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001361 } else if (Buffer[0] == '"') {
1362 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001363 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001364 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001365 return true;
1366 }
1367 isAngled = false;
1368 } else {
1369 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001370 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001371 return true;
1372 }
Mike Stump11289f42009-09-09 15:08:12 +00001373
Chris Lattnerf64b3522008-03-09 01:54:53 +00001374 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001375 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001376 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001377 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001378 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001379 }
Mike Stump11289f42009-09-09 15:08:12 +00001380
Chris Lattnerf64b3522008-03-09 01:54:53 +00001381 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001382 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001383 return isAngled;
1384}
1385
James Dennett4a4f72d2013-11-27 01:27:40 +00001386// \brief Handle cases where the \#include name is expanded from a macro
1387// as multiple tokens, which need to be glued together.
1388//
1389// This occurs for code like:
1390// \code
1391// \#define FOO <a/b.h>
1392// \#include FOO
1393// \endcode
1394// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1395//
1396// This code concatenates and consumes tokens up to the '>' token. It returns
1397// false if the > was found, otherwise it returns true if it finds and consumes
1398// the EOD marker.
1399bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001400 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001401 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001402
John Thompsonb5353522009-10-30 13:49:06 +00001403 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001404 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001405 End = CurTok.getLocation();
1406
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001407 // FIXME: Provide code completion for #includes.
1408 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001409 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001410 Lex(CurTok);
1411 continue;
1412 }
1413
Chris Lattnerf64b3522008-03-09 01:54:53 +00001414 // Append the spelling of this token to the buffer. If there was a space
1415 // before it, add it now.
1416 if (CurTok.hasLeadingSpace())
1417 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001418
Chris Lattnerf64b3522008-03-09 01:54:53 +00001419 // Get the spelling of the token, directly into FilenameBuffer if possible.
1420 unsigned PreAppendSize = FilenameBuffer.size();
1421 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001422
Chris Lattnerf64b3522008-03-09 01:54:53 +00001423 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001424 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001425
Chris Lattnerf64b3522008-03-09 01:54:53 +00001426 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1427 if (BufPtr != &FilenameBuffer[PreAppendSize])
1428 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001429
Chris Lattnerf64b3522008-03-09 01:54:53 +00001430 // Resize FilenameBuffer to the correct size.
1431 if (CurTok.getLength() != ActualLen)
1432 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001433
Chris Lattnerf64b3522008-03-09 01:54:53 +00001434 // If we found the '>' marker, return success.
1435 if (CurTok.is(tok::greater))
1436 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001437
John Thompsonb5353522009-10-30 13:49:06 +00001438 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001439 }
1440
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001441 // If we hit the eod marker, emit an error and return true so that the caller
1442 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001443 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001444 return true;
1445}
1446
Richard Smith34f30512013-11-23 04:06:09 +00001447/// \brief Push a token onto the token stream containing an annotation.
1448static void EnterAnnotationToken(Preprocessor &PP,
1449 SourceLocation Begin, SourceLocation End,
1450 tok::TokenKind Kind, void *AnnotationVal) {
1451 Token *Tok = new Token[1];
1452 Tok[0].startToken();
1453 Tok[0].setKind(Kind);
1454 Tok[0].setLocation(Begin);
1455 Tok[0].setAnnotationEndLoc(End);
1456 Tok[0].setAnnotationValue(AnnotationVal);
1457 PP.EnterTokenStream(Tok, 1, true, true);
1458}
1459
James Dennettf6333ac2012-06-22 05:46:07 +00001460/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1461/// the file to be included from the lexer, then include it! This is a common
1462/// routine with functionality shared between \#include, \#include_next and
1463/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001464/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001465void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1466 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001467 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001468 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001469 bool isImport) {
1470
1471 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001472 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001473
Chris Lattnerf64b3522008-03-09 01:54:53 +00001474 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001475 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001476 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001477 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001478 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001479
Chris Lattnerf64b3522008-03-09 01:54:53 +00001480 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001481 case tok::eod:
1482 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001483 return;
Mike Stump11289f42009-09-09 15:08:12 +00001484
Chris Lattnerf64b3522008-03-09 01:54:53 +00001485 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001486 case tok::string_literal:
1487 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001488 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001489 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001490 break;
Mike Stump11289f42009-09-09 15:08:12 +00001491
Chris Lattnerf64b3522008-03-09 01:54:53 +00001492 case tok::less:
1493 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1494 // case, glue the tokens together into FilenameBuffer and interpret those.
1495 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001496 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001497 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001498 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001499 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001500 break;
1501 default:
1502 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1503 DiscardUntilEndOfDirective();
1504 return;
1505 }
Mike Stump11289f42009-09-09 15:08:12 +00001506
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001507 CharSourceRange FilenameRange
1508 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001509 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001510 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001511 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001512 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1513 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001514 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001515 DiscardUntilEndOfDirective();
1516 return;
1517 }
Mike Stump11289f42009-09-09 15:08:12 +00001518
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001519 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001520 // we allow macros that expand to nothing after the filename, because this
1521 // falls into the category of "#include pp-tokens new-line" specified in
1522 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001523 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001524
1525 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001526 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1527 Diag(FilenameTok, diag::err_pp_include_too_deep);
1528 return;
1529 }
Mike Stump11289f42009-09-09 15:08:12 +00001530
John McCall32f5fe12011-09-30 05:12:12 +00001531 // Complain about attempts to #include files in an audit pragma.
1532 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1533 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1534 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1535
1536 // Immediately leave the pragma.
1537 PragmaARCCFCodeAuditedLoc = SourceLocation();
1538 }
1539
Aaron Ballman611306e2012-03-02 22:51:54 +00001540 if (HeaderInfo.HasIncludeAliasMap()) {
1541 // Map the filename with the brackets still attached. If the name doesn't
1542 // map to anything, fall back on the filename we've already gotten the
1543 // spelling for.
1544 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1545 if (!NewName.empty())
1546 Filename = NewName;
1547 }
1548
Chris Lattnerf64b3522008-03-09 01:54:53 +00001549 // Search include directories.
1550 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001551 SmallString<1024> SearchPath;
1552 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001553 // We get the raw path only if we have 'Callbacks' to which we later pass
1554 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001555 ModuleMap::KnownHeader SuggestedModule;
1556 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001557 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001558 if (LangOpts.MSVCCompat) {
1559 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001560#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001561 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001562#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001563 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001564 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001565 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001566 isAngled, LookupFrom, LookupFromFile, CurDir,
1567 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001568 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : nullptr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001569
Douglas Gregor11729f02011-11-30 18:12:06 +00001570 if (Callbacks) {
1571 if (!File) {
1572 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001573 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001574 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1575 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1576 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001577 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001578 HeaderInfo.AddSearchPath(DL, isAngled);
1579
1580 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001581 File = LookupFile(
1582 FilenameLoc,
1583 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1584 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
1585 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1586 : nullptr,
1587 /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001588 }
1589 }
1590 }
1591
Daniel Jasper07e6c402013-08-05 20:26:17 +00001592 if (!SuggestedModule || !getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001593 // Notify the callback object that we've seen an inclusion directive.
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001594 Callbacks->InclusionDirective(HashLoc, IncludeTok,
1595 LangOpts.MSVCCompat ? NormalizedPath.c_str()
1596 : Filename,
1597 isAngled, FilenameRange, File, SearchPath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001598 RelativePath, /*ImportedModule=*/nullptr);
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001599 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001600 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001601
1602 if (!File) {
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001603 if (!SuppressIncludeNotFoundError) {
1604 // If the file could not be located and it was included via angle
1605 // brackets, we can attempt a lookup as though it were a quoted path to
1606 // provide the user with a possible fixit.
1607 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001608 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001609 FilenameLoc,
1610 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1611 LookupFrom, LookupFromFile, CurDir,
1612 Callbacks ? &SearchPath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001613 Callbacks ? &RelativePath : nullptr,
1614 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule
1615 : nullptr);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001616 if (File) {
1617 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1618 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1619 Filename <<
1620 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1621 }
1622 }
1623 // If the file is still not found, just go with the vanilla diagnostic
1624 if (!File)
1625 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1626 }
1627 if (!File)
1628 return;
Douglas Gregor11729f02011-11-30 18:12:06 +00001629 }
1630
Douglas Gregor97eec242011-09-15 22:00:41 +00001631 // If we are supposed to import a module rather than including the header,
1632 // do so now.
Ben Langmuirb537a3a2014-07-23 15:30:23 +00001633 if (SuggestedModule && getLangOpts().Modules &&
1634 SuggestedModule.getModule()->getTopLevelModuleName() !=
1635 getLangOpts().ImplementationOfModule) {
Douglas Gregor71944202011-11-30 00:36:36 +00001636 // Compute the module access path corresponding to this module.
1637 // FIXME: Should we have a second loadModule() overload to avoid this
1638 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001639 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001640 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001641 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1642 FilenameTok.getLocation()));
1643 std::reverse(Path.begin(), Path.end());
1644
Douglas Gregor41e115a2011-11-30 18:02:36 +00001645 // Warn that we're replacing the include/import with a module import.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001646 SmallString<128> PathString;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001647 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1648 if (I)
1649 PathString += '.';
1650 PathString += Path[I].first->getName();
1651 }
1652 int IncludeKind = 0;
1653
1654 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1655 case tok::pp_include:
1656 IncludeKind = 0;
1657 break;
1658
1659 case tok::pp_import:
1660 IncludeKind = 1;
1661 break;
1662
Douglas Gregor4401fbe2011-11-30 18:03:26 +00001663 case tok::pp_include_next:
1664 IncludeKind = 2;
1665 break;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001666
1667 case tok::pp___include_macros:
1668 IncludeKind = 3;
1669 break;
1670
1671 default:
1672 llvm_unreachable("unknown include directive kind");
Douglas Gregor41e115a2011-11-30 18:02:36 +00001673 }
1674
Douglas Gregor2537a362011-12-08 17:01:29 +00001675 // Determine whether we are actually building the module that this
1676 // include directive maps to.
1677 bool BuildingImportedModule
David Blaikiebbafb8a2012-03-11 07:00:24 +00001678 = Path[0].first->getName() == getLangOpts().CurrentModule;
Richard Smith34f30512013-11-23 04:06:09 +00001679
David Blaikiebbafb8a2012-03-11 07:00:24 +00001680 if (!BuildingImportedModule && getLangOpts().ObjC2) {
Douglas Gregor2537a362011-12-08 17:01:29 +00001681 // If we're not building the imported module, warn that we're going
1682 // to automatically turn this inclusion directive into a module import.
Douglas Gregorda82e702012-01-03 19:32:59 +00001683 // We only do this in Objective-C, where we have a module-import syntax.
Douglas Gregor2537a362011-12-08 17:01:29 +00001684 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
1685 /*IsTokenRange=*/false);
1686 Diag(HashLoc, diag::warn_auto_module_import)
Yaron Keren92e1b622015-03-18 10:17:07 +00001687 << IncludeKind << PathString
1688 << FixItHint::CreateReplacement(
1689 ReplaceRange, ("@import " + PathString + ";").str());
Douglas Gregor2537a362011-12-08 17:01:29 +00001690 }
Douglas Gregor41e115a2011-11-30 18:02:36 +00001691
Richard Smithce587f52013-11-15 04:24:58 +00001692 // Load the module. Only make macros visible. We'll make the declarations
1693 // visible when the parser gets here.
1694 Module::NameVisibilityKind Visibility = Module::MacrosVisible;
Douglas Gregor7a626572012-11-29 23:55:25 +00001695 ModuleLoadResult Imported
Douglas Gregor98a52db2011-12-20 00:28:52 +00001696 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
1697 /*IsIncludeDirective=*/true);
Richard Smith753e0072015-04-27 23:21:38 +00001698 ++MacroVisibilityGeneration;
Craig Topperd2d442c2014-05-17 23:10:59 +00001699 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001700 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001701
1702 if (!Imported && hadModuleLoaderFatalFailure()) {
1703 // With a fatal failure in the module loader, we abort parsing.
1704 Token &Result = IncludeTok;
1705 if (CurLexer) {
1706 Result.startToken();
1707 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1708 CurLexer->cutOffLexing();
1709 } else {
1710 assert(CurPTHLexer && "#include but no current lexer set!");
1711 CurPTHLexer->getEOF(Result);
1712 }
1713 return;
1714 }
Richard Smithce587f52013-11-15 04:24:58 +00001715
Douglas Gregor2537a362011-12-08 17:01:29 +00001716 // If this header isn't part of the module we're building, we're done.
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001717 if (!BuildingImportedModule && Imported) {
1718 if (Callbacks) {
1719 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1720 FilenameRange, File,
1721 SearchPath, RelativePath, Imported);
1722 }
Richard Smithce587f52013-11-15 04:24:58 +00001723
1724 if (IncludeKind != 3) {
1725 // Let the parser know that we hit a module import, and it should
1726 // make the module visible.
1727 // FIXME: Produce this as the current token directly, rather than
1728 // allocating a new token for it.
Richard Smith34f30512013-11-23 04:06:09 +00001729 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include,
1730 Imported);
Richard Smithce587f52013-11-15 04:24:58 +00001731 }
Douglas Gregor2537a362011-12-08 17:01:29 +00001732 return;
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001733 }
Douglas Gregor7a626572012-11-29 23:55:25 +00001734
1735 // If we failed to find a submodule that we expected to find, we can
1736 // continue. Otherwise, there's an error in the included file, so we
1737 // don't want to include it.
1738 if (!BuildingImportedModule && !Imported.isMissingExpected()) {
1739 return;
1740 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001741 }
1742
1743 if (Callbacks && SuggestedModule) {
1744 // We didn't notify the callback object that we've seen an inclusion
1745 // directive before. Now that we are parsing the include normally and not
1746 // turning it to a module import, notify the callback object.
1747 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
1748 FilenameRange, File,
1749 SearchPath, RelativePath,
Craig Topperd2d442c2014-05-17 23:10:59 +00001750 /*ImportedModule=*/nullptr);
Douglas Gregor97eec242011-09-15 22:00:41 +00001751 }
1752
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001753 // The #included file will be considered to be a system header if either it is
1754 // in a system include directory, or if the #includer is a system include
1755 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001756 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001757 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001758 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001759
Chris Lattner72286d62010-04-19 20:44:31 +00001760 // Ask HeaderInfo if we should enter this #include file. If not, #including
1761 // this file will have no effect.
Richard Smith20e883e2015-04-29 23:20:19 +00001762 if (!HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport)) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001763 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001764 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Chris Lattner72286d62010-04-19 20:44:31 +00001765 return;
1766 }
1767
Chris Lattnerf64b3522008-03-09 01:54:53 +00001768 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001769 SourceLocation IncludePos = End;
1770 // If the filename string was the result of macro expansions, set the include
1771 // position on the file where it will be included and after the expansions.
1772 if (IncludePos.isMacroID())
1773 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1774 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001775 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001776
Richard Smith34f30512013-11-23 04:06:09 +00001777 // Determine if we're switching to building a new submodule, and which one.
1778 ModuleMap::KnownHeader BuildingModule;
1779 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) {
1780 Module *RequestingModule = getModuleForLocation(FilenameLoc);
1781 BuildingModule =
1782 HeaderInfo.getModuleMap().findModuleForHeader(File, RequestingModule);
1783 }
1784
1785 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00001786 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
1787 return;
Richard Smith34f30512013-11-23 04:06:09 +00001788
1789 // If we're walking into another part of the same module, let the parser
1790 // know that any future declarations are within that other submodule.
Richard Smith67294e22014-01-31 20:47:44 +00001791 if (BuildingModule) {
1792 assert(!CurSubmodule && "should not have marked this as a module yet");
1793 CurSubmodule = BuildingModule.getModule();
1794
Richard Smith50474bf2015-04-23 23:29:05 +00001795 EnterSubmodule(CurSubmodule, HashLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +00001796
Richard Smith34f30512013-11-23 04:06:09 +00001797 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin,
Richard Smith67294e22014-01-31 20:47:44 +00001798 CurSubmodule);
1799 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001800}
1801
James Dennettf6333ac2012-06-22 05:46:07 +00001802/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001803///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001804void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1805 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001806 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001807
Chris Lattnerf64b3522008-03-09 01:54:53 +00001808 // #include_next is like #include, except that we start searching after
1809 // the current found directory. If we can't do this, issue a
1810 // diagnostic.
1811 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00001812 const FileEntry *LookupFromFile = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001813 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001814 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001815 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001816 } else if (CurSubmodule) {
1817 // Start looking up in the directory *after* the one in which the current
1818 // file would be found, if any.
1819 assert(CurPPLexer && "#include_next directive in macro?");
1820 LookupFromFile = CurPPLexer->getFileEntry();
1821 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001822 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001823 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1824 } else {
1825 // Start looking up in the next directory.
1826 ++Lookup;
1827 }
Mike Stump11289f42009-09-09 15:08:12 +00001828
Richard Smith25d50752014-10-20 00:15:49 +00001829 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
1830 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001831}
1832
James Dennettf6333ac2012-06-22 05:46:07 +00001833/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001834void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1835 // The Microsoft #import directive takes a type library and generates header
1836 // files from it, and includes those. This is beyond the scope of what clang
1837 // does, so we ignore it and error out. However, #import can optionally have
1838 // trailing attributes that span multiple lines. We're going to eat those
1839 // so we can continue processing from there.
1840 Diag(Tok, diag::err_pp_import_directive_ms );
1841
1842 // Read tokens until we get to the end of the directive. Note that the
1843 // directive can be split over multiple lines using the backslash character.
1844 DiscardUntilEndOfDirective();
1845}
1846
James Dennettf6333ac2012-06-22 05:46:07 +00001847/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001848///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001849void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1850 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001851 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00001852 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00001853 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001854 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001855 }
Richard Smith25d50752014-10-20 00:15:49 +00001856 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001857}
1858
Chris Lattner58a1eb02009-04-08 18:46:40 +00001859/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1860/// pseudo directive in the predefines buffer. This handles it by sucking all
1861/// tokens through the preprocessor and discarding them (only keeping the side
1862/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001863void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1864 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001865 // This directive should only occur in the predefines buffer. If not, emit an
1866 // error and reject it.
1867 SourceLocation Loc = IncludeMacrosTok.getLocation();
1868 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1869 Diag(IncludeMacrosTok.getLocation(),
1870 diag::pp_include_macros_out_of_predefines);
1871 DiscardUntilEndOfDirective();
1872 return;
1873 }
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattnere01d82b2009-04-08 20:53:24 +00001875 // Treat this as a normal #include for checking purposes. If this is
1876 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00001877 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00001878
Chris Lattnere01d82b2009-04-08 20:53:24 +00001879 Token TmpTok;
1880 do {
1881 Lex(TmpTok);
1882 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1883 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001884}
1885
Chris Lattnerf64b3522008-03-09 01:54:53 +00001886//===----------------------------------------------------------------------===//
1887// Preprocessor Macro Directive Handling.
1888//===----------------------------------------------------------------------===//
1889
1890/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1891/// definition has just been read. Lex the rest of the arguments and the
1892/// closing ), updating MI with what we learn. Return true if an error occurs
1893/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001894bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001895 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001896
Chris Lattnerf64b3522008-03-09 01:54:53 +00001897 while (1) {
1898 LexUnexpandedToken(Tok);
1899 switch (Tok.getKind()) {
1900 case tok::r_paren:
1901 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001902 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001903 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001904 // Otherwise we have #define FOO(A,)
1905 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1906 return true;
1907 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001908 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001909 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001910 diag::warn_cxx98_compat_variadic_macro :
1911 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001912
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001913 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1914 if (LangOpts.OpenCL) {
1915 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1916 return true;
1917 }
1918
Chris Lattnerf64b3522008-03-09 01:54:53 +00001919 // Lex the token after the identifier.
1920 LexUnexpandedToken(Tok);
1921 if (Tok.isNot(tok::r_paren)) {
1922 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1923 return true;
1924 }
1925 // Add the __VA_ARGS__ identifier as an argument.
1926 Arguments.push_back(Ident__VA_ARGS__);
1927 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001928 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001929 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001930 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001931 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1932 return true;
1933 default:
1934 // Handle keywords and identifiers here to accept things like
1935 // #define Foo(for) for.
1936 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00001937 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001938 // #define X(1
1939 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1940 return true;
1941 }
1942
1943 // If this is already used as an argument, it is used multiple times (e.g.
1944 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001945 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001946 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001947 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001948 return true;
1949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
Chris Lattnerf64b3522008-03-09 01:54:53 +00001951 // Add the argument to the macro info.
1952 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001953
Chris Lattnerf64b3522008-03-09 01:54:53 +00001954 // Lex the token after the identifier.
1955 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001956
Chris Lattnerf64b3522008-03-09 01:54:53 +00001957 switch (Tok.getKind()) {
1958 default: // #define X(A B
1959 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1960 return true;
1961 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001962 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001963 return false;
1964 case tok::comma: // #define X(A,
1965 break;
1966 case tok::ellipsis: // #define X(A... -> GCC extension
1967 // Diagnose extension.
1968 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001969
Chris Lattnerf64b3522008-03-09 01:54:53 +00001970 // Lex the token after the identifier.
1971 LexUnexpandedToken(Tok);
1972 if (Tok.isNot(tok::r_paren)) {
1973 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1974 return true;
1975 }
Mike Stump11289f42009-09-09 15:08:12 +00001976
Chris Lattnerf64b3522008-03-09 01:54:53 +00001977 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001978 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001979 return false;
1980 }
1981 }
1982 }
1983}
1984
Serge Pavlov07c0f042014-12-18 11:14:21 +00001985static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
1986 const LangOptions &LOptions) {
1987 if (MI->getNumTokens() == 1) {
1988 const Token &Value = MI->getReplacementToken(0);
1989
1990 // Macro that is identity, like '#define inline inline' is a valid pattern.
1991 if (MacroName.getKind() == Value.getKind())
1992 return true;
1993
1994 // Macro that maps a keyword to the same keyword decorated with leading/
1995 // trailing underscores is a valid pattern:
1996 // #define inline __inline
1997 // #define inline __inline__
1998 // #define inline _inline (in MS compatibility mode)
1999 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2000 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2001 if (!II->isKeyword(LOptions))
2002 return false;
2003 StringRef ValueText = II->getName();
2004 StringRef TrimmedValue = ValueText;
2005 if (!ValueText.startswith("__")) {
2006 if (ValueText.startswith("_"))
2007 TrimmedValue = TrimmedValue.drop_front(1);
2008 else
2009 return false;
2010 } else {
2011 TrimmedValue = TrimmedValue.drop_front(2);
2012 if (TrimmedValue.endswith("__"))
2013 TrimmedValue = TrimmedValue.drop_back(2);
2014 }
2015 return TrimmedValue.equals(MacroText);
2016 } else {
2017 return false;
2018 }
2019 }
2020
2021 // #define inline
2022 if ((MacroName.is(tok::kw_extern) || MacroName.is(tok::kw_inline) ||
2023 MacroName.is(tok::kw_static) || MacroName.is(tok::kw_const)) &&
2024 MI->getNumTokens() == 0) {
2025 return true;
2026 }
2027
2028 return false;
2029}
2030
James Dennettf6333ac2012-06-22 05:46:07 +00002031/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00002032/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002033void Preprocessor::HandleDefineDirective(Token &DefineTok,
2034 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002035 ++NumDefined;
2036
2037 Token MacroNameTok;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002038 bool MacroShadowsKeyword;
2039 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
Mike Stump11289f42009-09-09 15:08:12 +00002040
Chris Lattnerf64b3522008-03-09 01:54:53 +00002041 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002042 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002043 return;
2044
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002045 Token LastTok = MacroNameTok;
2046
Chris Lattnerf64b3522008-03-09 01:54:53 +00002047 // If we are supposed to keep comments in #defines, reenable comment saving
2048 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00002049 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00002050
Chris Lattnerf64b3522008-03-09 01:54:53 +00002051 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002052 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002053
Chris Lattnerf64b3522008-03-09 01:54:53 +00002054 Token Tok;
2055 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Chris Lattnerf64b3522008-03-09 01:54:53 +00002057 // If this is a function-like macro definition, parse the argument list,
2058 // marking each of the identifiers as being used as macro arguments. Also,
2059 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002060 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002061 if (ImmediatelyAfterHeaderGuard) {
2062 // Save this macro information since it may part of a header guard.
2063 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2064 MacroNameTok.getLocation());
2065 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002066 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002067 } else if (Tok.hasLeadingSpace()) {
2068 // This is a normal token with leading space. Clear the leading space
2069 // marker on the first token to get proper expansion.
2070 Tok.clearFlag(Token::LeadingSpace);
2071 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002072 // This is a function-like macro definition. Read the argument list.
2073 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002074 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002075 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002076 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002077 DiscardUntilEndOfDirective();
2078 return;
2079 }
2080
Chris Lattner249c38b2009-04-19 18:26:34 +00002081 // If this is a definition of a variadic C99 function-like macro, not using
2082 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00002083
Chris Lattner249c38b2009-04-19 18:26:34 +00002084 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2085 // This gets unpoisoned where it is allowed.
2086 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2087 if (MI->isC99Varargs())
2088 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00002089
Chris Lattnerf64b3522008-03-09 01:54:53 +00002090 // Read the first token after the arg list for down below.
2091 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002092 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002093 // C99 requires whitespace between the macro definition and the body. Emit
2094 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002095 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002096 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002097 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2098 // first character of a replacement list is not a character required by
2099 // subclause 5.2.1, then there shall be white-space separation between the
2100 // identifier and the replacement list.". 5.2.1 lists this set:
2101 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2102 // is irrelevant here.
2103 bool isInvalid = false;
2104 if (Tok.is(tok::at)) // @ is not in the list above.
2105 isInvalid = true;
2106 else if (Tok.is(tok::unknown)) {
2107 // If we have an unknown token, it is something strange like "`". Since
2108 // all of valid characters would have lexed into a single character
2109 // token of some sort, we know this is not a valid case.
2110 isInvalid = true;
2111 }
2112 if (isInvalid)
2113 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2114 else
2115 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002116 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002117
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002118 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002119 LastTok = Tok;
2120
Chris Lattnerf64b3522008-03-09 01:54:53 +00002121 // Read the rest of the macro body.
2122 if (MI->isObjectLike()) {
2123 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002124 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002125 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002126 MI->AddTokenToBody(Tok);
2127 // Get the next token of the macro.
2128 LexUnexpandedToken(Tok);
2129 }
Mike Stump11289f42009-09-09 15:08:12 +00002130
Chris Lattnerf64b3522008-03-09 01:54:53 +00002131 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002132 // Otherwise, read the body of a function-like macro. While we are at it,
2133 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2134 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002135 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002136 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002137
Eli Friedman14d3c792012-11-14 02:18:46 +00002138 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002139 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002140
Chris Lattnerf64b3522008-03-09 01:54:53 +00002141 // Get the next token of the macro.
2142 LexUnexpandedToken(Tok);
2143 continue;
2144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
Richard Smith701a3522013-07-09 01:00:29 +00002146 // If we're in -traditional mode, then we should ignore stringification
2147 // and token pasting. Mark the tokens as unknown so as not to confuse
2148 // things.
2149 if (getLangOpts().TraditionalCPP) {
2150 Tok.setKind(tok::unknown);
2151 MI->AddTokenToBody(Tok);
2152
2153 // Get the next token of the macro.
2154 LexUnexpandedToken(Tok);
2155 continue;
2156 }
2157
Eli Friedman14d3c792012-11-14 02:18:46 +00002158 if (Tok.is(tok::hashhash)) {
2159
2160 // If we see token pasting, check if it looks like the gcc comma
2161 // pasting extension. We'll use this information to suppress
2162 // diagnostics later on.
2163
2164 // Get the next token of the macro.
2165 LexUnexpandedToken(Tok);
2166
2167 if (Tok.is(tok::eod)) {
2168 MI->AddTokenToBody(LastTok);
2169 break;
2170 }
2171
2172 unsigned NumTokens = MI->getNumTokens();
2173 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2174 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2175 MI->setHasCommaPasting();
2176
David Majnemer76faf1f2013-11-05 09:30:17 +00002177 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002178 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002179 continue;
2180 }
2181
Chris Lattnerf64b3522008-03-09 01:54:53 +00002182 // Get the next token of the macro.
2183 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002184
Chris Lattner83bd8282009-05-25 17:16:10 +00002185 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002186 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002187 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2188
2189 // If this is assembler-with-cpp mode, we accept random gibberish after
2190 // the '#' because '#' is often a comment character. However, change
2191 // the kind of the token to tok::unknown so that the preprocessor isn't
2192 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002193 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002194 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002195 MI->AddTokenToBody(LastTok);
2196 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002197 } else {
2198 Diag(Tok, diag::err_pp_stringize_not_parameter);
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattner83bd8282009-05-25 17:16:10 +00002200 // Disable __VA_ARGS__ again.
2201 Ident__VA_ARGS__->setIsPoisoned(true);
2202 return;
2203 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002204 }
Mike Stump11289f42009-09-09 15:08:12 +00002205
Chris Lattner83bd8282009-05-25 17:16:10 +00002206 // Things look ok, add the '#' and param name tokens to the macro.
2207 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002208 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002209 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattnerf64b3522008-03-09 01:54:53 +00002211 // Get the next token of the macro.
2212 LexUnexpandedToken(Tok);
2213 }
2214 }
Mike Stump11289f42009-09-09 15:08:12 +00002215
Serge Pavlov07c0f042014-12-18 11:14:21 +00002216 if (MacroShadowsKeyword &&
2217 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2218 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2219 }
Mike Stump11289f42009-09-09 15:08:12 +00002220
Chris Lattnerf64b3522008-03-09 01:54:53 +00002221 // Disable __VA_ARGS__ again.
2222 Ident__VA_ARGS__->setIsPoisoned(true);
2223
Chris Lattner57540c52011-04-15 05:22:18 +00002224 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002225 // replacement list.
2226 unsigned NumTokens = MI->getNumTokens();
2227 if (NumTokens != 0) {
2228 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2229 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002230 return;
2231 }
2232 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2233 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002234 return;
2235 }
2236 }
Mike Stump11289f42009-09-09 15:08:12 +00002237
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002238 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002239
Chris Lattnerf64b3522008-03-09 01:54:53 +00002240 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002241 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002242 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002243 // It is very common for system headers to have tons of macro redefinitions
2244 // and for warnings to be disabled in system headers. If this is the case,
2245 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002246 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002247 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002248 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002249 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002250
Richard Smith7b242542013-03-06 00:46:00 +00002251 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2252 // C++ [cpp.predefined]p4, but allow it as an extension.
2253 if (OtherMI->isBuiltinMacro())
2254 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002255 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002256 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002257 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002258 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002259 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2260 << MacroNameTok.getIdentifierInfo();
2261 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2262 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002263 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002264 if (OtherMI->isWarnIfUnused())
2265 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002266 }
Mike Stump11289f42009-09-09 15:08:12 +00002267
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002268 DefMacroDirective *MD =
2269 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002270
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002271 assert(!MI->isUsed());
2272 // If we need warning for not using the macro, add its location in the
2273 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002274 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002275 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002276 MI->setIsWarnIfUnused(true);
2277 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2278 }
2279
Chris Lattner928e9092009-04-12 01:39:54 +00002280 // If the callbacks want to know, tell them about the macro definition.
2281 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002282 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002283}
2284
James Dennettf6333ac2012-06-22 05:46:07 +00002285/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002286///
2287void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2288 ++NumUndefined;
2289
2290 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002291 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002292
Chris Lattnerf64b3522008-03-09 01:54:53 +00002293 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002294 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002295 return;
Mike Stump11289f42009-09-09 15:08:12 +00002296
Chris Lattnerf64b3522008-03-09 01:54:53 +00002297 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002298 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002299
Richard Smith20e883e2015-04-29 23:20:19 +00002300 // Okay, we have a valid identifier to undef.
2301 auto *II = MacroNameTok.getIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002302
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002303 // If the callbacks want to know, tell them about the macro #undef.
2304 // Note: no matter if the macro was defined or not.
Richard Smith20e883e2015-04-29 23:20:19 +00002305 if (Callbacks) {
2306 // FIXME: Tell callbacks about module macros.
2307 MacroDirective *MD = getLocalMacroDirective(II);
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002308 Callbacks->MacroUndefined(MacroNameTok, MD);
Richard Smith20e883e2015-04-29 23:20:19 +00002309 }
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002310
Chris Lattnerf64b3522008-03-09 01:54:53 +00002311 // If the macro is not defined, this is a noop undef, just return.
Richard Smith20e883e2015-04-29 23:20:19 +00002312 const MacroInfo *MI = getMacroInfo(II);
Craig Topperd2d442c2014-05-17 23:10:59 +00002313 if (!MI)
2314 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002315
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002316 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002317 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002318
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002319 if (MI->isWarnIfUnused())
2320 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2321
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002322 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2323 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002324}
2325
2326
2327//===----------------------------------------------------------------------===//
2328// Preprocessor Conditional Directive Handling.
2329//===----------------------------------------------------------------------===//
2330
James Dennettf6333ac2012-06-22 05:46:07 +00002331/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2332/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2333/// true if any tokens have been returned or pp-directives activated before this
2334/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002335///
2336void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2337 bool ReadAnyTokensBeforeDirective) {
2338 ++NumIf;
2339 Token DirectiveTok = Result;
2340
2341 Token MacroNameTok;
2342 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002343
Chris Lattnerf64b3522008-03-09 01:54:53 +00002344 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002345 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002346 // Skip code until we get to #endif. This helps with recovery by not
2347 // emitting an error when the #endif is reached.
2348 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2349 /*Foundnonskip*/false, /*FoundElse*/false);
2350 return;
2351 }
Mike Stump11289f42009-09-09 15:08:12 +00002352
Chris Lattnerf64b3522008-03-09 01:54:53 +00002353 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002354 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002355
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002356 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith20e883e2015-04-29 23:20:19 +00002357 MacroInfo *MI = getMacroInfo(MII);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002358
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002359 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002360 // If the start of a top-level #ifdef and if the macro is not defined,
2361 // inform MIOpt that this might be the start of a proper include guard.
2362 // Otherwise it is some other form of unknown conditional which we can't
2363 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002364 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002365 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002366 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002367 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002368 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002369 }
2370
Chris Lattnerf64b3522008-03-09 01:54:53 +00002371 // If there is a macro, process it.
2372 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002373 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002374
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002375 if (Callbacks) {
Richard Smith20e883e2015-04-29 23:20:19 +00002376 // FIXME: Tell callbacks about module macros.
2377 MacroDirective *MD = getLocalMacroDirective(MII);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002378 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002379 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002380 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002381 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002382 }
2383
Chris Lattnerf64b3522008-03-09 01:54:53 +00002384 // Should we include the stuff contained by this directive?
2385 if (!MI == isIfndef) {
2386 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002387 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2388 /*wasskip*/false, /*foundnonskip*/true,
2389 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002390 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002391 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002392 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002393 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002394 /*FoundElse*/false);
2395 }
2396}
2397
James Dennettf6333ac2012-06-22 05:46:07 +00002398/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002399///
2400void Preprocessor::HandleIfDirective(Token &IfToken,
2401 bool ReadAnyTokensBeforeDirective) {
2402 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002403
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002404 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002405 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002406 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2407 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2408 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002409
2410 // If this condition is equivalent to #ifndef X, and if this is the first
2411 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002412 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002413 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002414 // FIXME: Pass in the location of the macro name, not the 'if' token.
2415 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002416 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002417 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002418 }
2419
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002420 if (Callbacks)
2421 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002422 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002423 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002424
Chris Lattnerf64b3522008-03-09 01:54:53 +00002425 // Should we include the stuff contained by this directive?
2426 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002427 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002428 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002429 /*foundnonskip*/true, /*foundelse*/false);
2430 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002431 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002432 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002433 /*FoundElse*/false);
2434 }
2435}
2436
James Dennettf6333ac2012-06-22 05:46:07 +00002437/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002438///
2439void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2440 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002441
Chris Lattnerf64b3522008-03-09 01:54:53 +00002442 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002443 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002444
Chris Lattnerf64b3522008-03-09 01:54:53 +00002445 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002446 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002447 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002448 Diag(EndifToken, diag::err_pp_endif_without_if);
2449 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451
Chris Lattnerf64b3522008-03-09 01:54:53 +00002452 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002453 if (CurPPLexer->getConditionalStackDepth() == 0)
2454 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002455
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002456 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002457 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002458
2459 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002460 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002461}
2462
James Dennettf6333ac2012-06-22 05:46:07 +00002463/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002464///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002465void Preprocessor::HandleElseDirective(Token &Result) {
2466 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002467
Chris Lattnerf64b3522008-03-09 01:54:53 +00002468 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002469 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002470
Chris Lattnerf64b3522008-03-09 01:54:53 +00002471 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002472 if (CurPPLexer->popConditionalLevel(CI)) {
2473 Diag(Result, diag::pp_err_else_without_if);
2474 return;
2475 }
Mike Stump11289f42009-09-09 15:08:12 +00002476
Chris Lattnerf64b3522008-03-09 01:54:53 +00002477 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002478 if (CurPPLexer->getConditionalStackDepth() == 0)
2479 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002480
2481 // If this is a #else with a #else before it, report the error.
2482 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002483
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002484 if (Callbacks)
2485 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2486
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002487 // Finally, skip the rest of the contents of this block.
2488 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002489 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002490}
2491
James Dennettf6333ac2012-06-22 05:46:07 +00002492/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002493///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002494void Preprocessor::HandleElifDirective(Token &ElifToken) {
2495 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002496
Chris Lattnerf64b3522008-03-09 01:54:53 +00002497 // #elif directive in a non-skipping conditional... start skipping.
2498 // We don't care what the condition is, because we will always skip it (since
2499 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002500 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002501 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002502 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002503
2504 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002505 if (CurPPLexer->popConditionalLevel(CI)) {
2506 Diag(ElifToken, diag::pp_err_elif_without_if);
2507 return;
2508 }
Mike Stump11289f42009-09-09 15:08:12 +00002509
Chris Lattnerf64b3522008-03-09 01:54:53 +00002510 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002511 if (CurPPLexer->getConditionalStackDepth() == 0)
2512 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002513
Chris Lattnerf64b3522008-03-09 01:54:53 +00002514 // If this is a #elif with a #else before it, report the error.
2515 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002516
2517 if (Callbacks)
2518 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002519 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002520 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002521
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002522 // Finally, skip the rest of the contents of this block.
2523 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002524 /*FoundElse*/CI.FoundElse,
2525 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002526}