blob: 320c16dbec2568250ffd95634fdd91584e5b311a [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"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000030
Chris Lattnerf64b3522008-03-09 01:54:53 +000031using namespace clang;
32
33//===----------------------------------------------------------------------===//
34// Utility Methods for Preprocessor Directive Handling.
35//===----------------------------------------------------------------------===//
36
Chris Lattnerc0a585d2010-08-17 15:55:45 +000037MacroInfo *Preprocessor::AllocateMacroInfo() {
Richard Smithee0c4c12014-07-24 01:13:23 +000038 MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
Ted Kremenekc8456f82010-10-19 22:15:20 +000039 MIChain->Next = MIChainHead;
Ted Kremenekc8456f82010-10-19 22:15:20 +000040 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000041 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000042}
43
44MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
45 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000046 new (MI) MacroInfo(L);
47 return MI;
48}
49
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000050MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
51 unsigned SubModuleID) {
Chandler Carruth06dde922014-03-02 13:02:01 +000052 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
53 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000054 DeserializedMacroInfoChain *MIChain =
55 BP.Allocate<DeserializedMacroInfoChain>();
56 MIChain->Next = DeserialMIChainHead;
57 DeserialMIChainHead = MIChain;
58
59 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000060 new (MI) MacroInfo(L);
61 MI->FromASTFile = true;
62 MI->setOwningModuleID(SubModuleID);
63 return MI;
64}
65
Richard Smith50474bf2015-04-23 23:29:05 +000066DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
67 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000068 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000069}
70
71UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000072Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000073 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000074}
75
76VisibilityMacroDirective *
77Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
78 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000079 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000080}
81
James Dennettf6333ac2012-06-22 05:46:07 +000082/// \brief Read and discard all tokens remaining on the current line until
83/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000084void Preprocessor::DiscardUntilEndOfDirective() {
85 Token Tmp;
86 do {
87 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000088 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000089 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000090}
91
Serge Pavlov07c0f042014-12-18 11:14:21 +000092/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
93enum MacroDiag {
94 MD_NoWarn, //> Not a reserved identifier
95 MD_KeywordDef, //> Macro hides keyword, enabled by default
96 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
97};
98
99/// \brief Checks if the specified identifier is reserved in the specified
100/// language.
101/// This function does not check if the identifier is a keyword.
102static bool isReservedId(StringRef Text, const LangOptions &Lang) {
103 // C++ [macro.names], C11 7.1.3:
104 // All identifiers that begin with an underscore and either an uppercase
105 // letter or another underscore are always reserved for any use.
106 if (Text.size() >= 2 && Text[0] == '_' &&
107 (isUppercase(Text[1]) || Text[1] == '_'))
108 return true;
109 // C++ [global.names]
110 // Each name that contains a double underscore ... is reserved to the
111 // implementation for any use.
112 if (Lang.CPlusPlus) {
113 if (Text.find("__") != StringRef::npos)
114 return true;
115 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000116 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000117}
118
Serge Pavlov07c0f042014-12-18 11:14:21 +0000119static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
120 const LangOptions &Lang = PP.getLangOpts();
121 StringRef Text = II->getName();
122 if (isReservedId(Text, Lang))
123 return MD_ReservedMacro;
124 if (II->isKeyword(Lang))
125 return MD_KeywordDef;
126 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
127 return MD_KeywordDef;
128 return MD_NoWarn;
129}
130
131static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
132 const LangOptions &Lang = PP.getLangOpts();
133 StringRef Text = II->getName();
134 // Do not warn on keyword undef. It is generally harmless and widely used.
135 if (isReservedId(Text, Lang))
136 return MD_ReservedMacro;
137 return MD_NoWarn;
138}
139
140bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
141 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000142 // Missing macro name?
143 if (MacroNameTok.is(tok::eod))
144 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
145
146 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
147 if (!II) {
148 bool Invalid = false;
149 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
150 if (Invalid)
151 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000152 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000153
Alp Tokerf33619c2014-05-31 03:38:08 +0000154 if (!II->isCPlusPlusOperatorKeyword())
155 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000156
Alp Tokere03e9e12014-05-31 16:32:22 +0000157 // C++ 2.5p2: Alternative tokens behave the same as its primary token
158 // except for their spellings.
159 Diag(MacroNameTok, getLangOpts().MicrosoftExt
160 ? diag::ext_pp_operator_used_as_macro_name
161 : diag::err_pp_operator_used_as_macro_name)
162 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000163
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000164 // Allow #defining |and| and friends for Microsoft compatibility or
165 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000166 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000167 }
168
Serge Pavlovd024f522014-10-24 17:31:32 +0000169 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000170 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
171 return Diag(MacroNameTok, diag::err_defined_macro_name);
172 }
173
Richard Smith20e883e2015-04-29 23:20:19 +0000174 if (isDefineUndef == MU_Undef) {
175 auto *MI = getMacroInfo(II);
176 if (MI && MI->isBuiltinMacro()) {
177 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
178 // and C++ [cpp.predefined]p4], but allow it as an extension.
179 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
180 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000181 }
182
Serge Pavlov07c0f042014-12-18 11:14:21 +0000183 // If defining/undefining reserved identifier or a keyword, we need to issue
184 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000185 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000186 if (ShadowFlag)
187 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000188 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
189 (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000190 MacroDiag D = MD_NoWarn;
191 if (isDefineUndef == MU_Define) {
192 D = shouldWarnOnMacroDef(*this, II);
193 }
194 else if (isDefineUndef == MU_Undef)
195 D = shouldWarnOnMacroUndef(*this, II);
196 if (D == MD_KeywordDef) {
197 // We do not want to warn on some patterns widely used in configuration
198 // scripts. This requires analyzing next tokens, so do not issue warnings
199 // now, only inform caller.
200 if (ShadowFlag)
201 *ShadowFlag = true;
202 }
203 if (D == MD_ReservedMacro)
204 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000205 }
206
Alp Tokerb05e0b52014-05-21 06:13:51 +0000207 // Okay, we got a good identifier.
208 return false;
209}
210
James Dennettf6333ac2012-06-22 05:46:07 +0000211/// \brief Lex and validate a macro name, which occurs after a
212/// \#define or \#undef.
213///
Serge Pavlovd024f522014-10-24 17:31:32 +0000214/// This sets the token kind to eod and discards the rest of the macro line if
215/// the macro name is invalid.
216///
217/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000218/// \param isDefineUndef Context in which macro is used.
219/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
220void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
221 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000222 // Read the token, don't allow macro expansion on it.
223 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000224
Douglas Gregor12785102010-08-24 20:21:13 +0000225 if (MacroNameTok.is(tok::code_completion)) {
226 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000227 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000228 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000229 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000230 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000231
Serge Pavlov07c0f042014-12-18 11:14:21 +0000232 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000233 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000234
235 // Invalid macro name, read and discard the rest of the line and set the
236 // token kind to tok::eod if necessary.
237 if (MacroNameTok.isNot(tok::eod)) {
238 MacroNameTok.setKind(tok::eod);
239 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000240 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000241}
242
James Dennettf6333ac2012-06-22 05:46:07 +0000243/// \brief Ensure that the next token is a tok::eod token.
244///
245/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000246/// true, then we consider macros that expand to zero tokens as being ok.
247void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000248 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000249 // Lex unexpanded tokens for most directives: macros might expand to zero
250 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
251 // #line) allow empty macros.
252 if (EnableMacros)
253 Lex(Tmp);
254 else
255 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000256
Chris Lattnerf64b3522008-03-09 01:54:53 +0000257 // There should be no tokens after the directive, but we allow them as an
258 // extension.
259 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
260 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000261
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000262 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000263 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000264 // or if this is a macro-style preprocessing directive, because it is more
265 // trouble than it is worth to insert /**/ and check that there is no /**/
266 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000267 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000268 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000269 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000270 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
271 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000272 DiscardUntilEndOfDirective();
273 }
274}
275
James Dennettf6333ac2012-06-22 05:46:07 +0000276/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
277/// decided that the subsequent tokens are in the \#if'd out portion of the
278/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000279/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000280/// this \#if directive, so \#else/\#elif blocks should never be entered.
281/// If ElseOk is true, then \#else directives are ok, if not, then we have
282/// already seen one so a \#else directive is a duplicate. When this returns,
283/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000284void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
285 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000286 bool FoundElse,
287 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000288 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000289 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000290
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000291 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000292 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000293
Ted Kremenek56572ab2008-12-12 18:34:08 +0000294 if (CurPTHLexer) {
295 PTHSkipExcludedConditionalBlock();
296 return;
297 }
Mike Stump11289f42009-09-09 15:08:12 +0000298
Chris Lattnerf64b3522008-03-09 01:54:53 +0000299 // Enter raw mode to disable identifier lookup (and thus macro expansion),
300 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000301 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000302 Token Tok;
303 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000304 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000305
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000306 if (Tok.is(tok::code_completion)) {
307 if (CodeComplete)
308 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000309 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000310 continue;
311 }
312
Chris Lattnerf64b3522008-03-09 01:54:53 +0000313 // If this is the end of the buffer, we have an error.
314 if (Tok.is(tok::eof)) {
315 // Emit errors for each unterminated conditional on the stack, including
316 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000317 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000318 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000319 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
320 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000321 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000322 }
323
Chris Lattnerf64b3522008-03-09 01:54:53 +0000324 // Just return and let the caller lex after this #include.
325 break;
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
Chris Lattnerf64b3522008-03-09 01:54:53 +0000328 // If this token is not a preprocessor directive, just skip it.
329 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
330 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000331
Chris Lattnerf64b3522008-03-09 01:54:53 +0000332 // We just parsed a # character at the start of a line, so we're in
333 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000334 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000335 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000336 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000337
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattnerf64b3522008-03-09 01:54:53 +0000339 // Read the next token, the directive flavor.
340 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chris Lattnerf64b3522008-03-09 01:54:53 +0000342 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
343 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000344 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000345 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000346 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000347 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000348 continue;
349 }
350
351 // If the first letter isn't i or e, it isn't intesting to us. We know that
352 // this is safe in the face of spelling differences, because there is no way
353 // to spell an i/e in a strange way that is another letter. Skipping this
354 // allows us to avoid looking up the identifier info for #define/#undef and
355 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000356 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000357
Alp Toker2d57cea2014-05-17 04:53:25 +0000358 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000359 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000360 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000361 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000362 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000363 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000364 continue;
365 }
Mike Stump11289f42009-09-09 15:08:12 +0000366
Chris Lattnerf64b3522008-03-09 01:54:53 +0000367 // Get the identifier name without trigraphs or embedded newlines. Note
368 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
369 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000370 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000371 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000372 if (!Tok.needsCleaning() && RI.size() < 20) {
373 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000374 } else {
375 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000376 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000377 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000378 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000379 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000380 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000381 continue;
382 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000383 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000384 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000385 }
Mike Stump11289f42009-09-09 15:08:12 +0000386
Benjamin Kramer144884642009-12-31 13:32:38 +0000387 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000388 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000389 if (Sub.empty() || // "if"
390 Sub == "def" || // "ifdef"
391 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000392 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
393 // bother parsing the condition.
394 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000395 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000396 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000397 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000398 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000399 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000400 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000401 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000402 PPConditionalInfo CondInfo;
403 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000404 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000405 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattnerf64b3522008-03-09 01:54:53 +0000408 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000409 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000410 // Restore the value of LexingRawMode so that trailing comments
411 // are handled correctly, if we've reached the outermost block.
412 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000413 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000414 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000415 if (Callbacks)
416 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000417 break;
Richard Smithd0124572012-06-21 00:35:03 +0000418 } else {
419 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000420 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000421 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000422 // #else directive in a skipping conditional. If not in some other
423 // skipping conditional, and if #else hasn't already been seen, enter it
424 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000425 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000426
Chris Lattnerf64b3522008-03-09 01:54:53 +0000427 // If this is a #else with a #else before it, report the error.
428 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattnerf64b3522008-03-09 01:54:53 +0000430 // Note that we've seen a #else in this conditional.
431 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000432
Chris Lattnerf64b3522008-03-09 01:54:53 +0000433 // If the conditional is at the top level, and the #if block wasn't
434 // entered, enter the #else block now.
435 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
436 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000437 // Restore the value of LexingRawMode so that trailing comments
438 // are handled correctly.
439 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000440 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000441 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000442 if (Callbacks)
443 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000444 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000445 } else {
446 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000447 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000448 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000449 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000450
John Thompson17c35732013-12-04 20:19:30 +0000451 // If this is a #elif with a #else before it, report the error.
452 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
453
Chris Lattnerf64b3522008-03-09 01:54:53 +0000454 // If this is in a skipping block or if we're already handled this #if
455 // block, don't bother parsing the condition.
456 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
457 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000458 } else {
John Thompson17c35732013-12-04 20:19:30 +0000459 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000460 // Restore the value of LexingRawMode so that identifiers are
461 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000462 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
463 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000464 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000465 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000466 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000467 if (Callbacks) {
468 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000469 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000470 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000471 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000472 }
473 // If this condition is true, enter it!
474 if (CondValue) {
475 CondInfo.FoundNonSkip = true;
476 break;
477 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000478 }
479 }
480 }
Mike Stump11289f42009-09-09 15:08:12 +0000481
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000482 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000483 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000484 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000485 }
486
487 // Finally, if we are out of the conditional (saw an #endif or ran off the end
488 // of the file, just stop skipping and return to lexing whatever came after
489 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000490 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000491
492 if (Callbacks) {
493 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
494 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
495 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000496}
497
Ted Kremenek56572ab2008-12-12 18:34:08 +0000498void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000499 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000500 assert(CurPTHLexer);
501 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000502
Ted Kremenek56572ab2008-12-12 18:34:08 +0000503 // Skip to the next '#else', '#elif', or #endif.
504 if (CurPTHLexer->SkipBlock()) {
505 // We have reached an #endif. Both the '#' and 'endif' tokens
506 // have been consumed by the PTHLexer. Just pop off the condition level.
507 PPConditionalInfo CondInfo;
508 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000509 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000510 assert(!InCond && "Can't be skipping if not in a conditional!");
511 break;
512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Ted Kremenek56572ab2008-12-12 18:34:08 +0000514 // We have reached a '#else' or '#elif'. Lex the next token to get
515 // the directive flavor.
516 Token Tok;
517 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000518
Ted Kremenek56572ab2008-12-12 18:34:08 +0000519 // We can actually look up the IdentifierInfo here since we aren't in
520 // raw mode.
521 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
522
523 if (K == tok::pp_else) {
524 // #else: Enter the else condition. We aren't in a nested condition
525 // since we skip those. We're always in the one matching the last
526 // blocked we skipped.
527 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
528 // Note that we've seen a #else in this conditional.
529 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000530
Ted Kremenek56572ab2008-12-12 18:34:08 +0000531 // If the #if block wasn't entered then enter the #else block now.
532 if (!CondInfo.FoundNonSkip) {
533 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000534
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000535 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000536 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000537 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000538 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000539
Ted Kremenek56572ab2008-12-12 18:34:08 +0000540 break;
541 }
Mike Stump11289f42009-09-09 15:08:12 +0000542
Ted Kremenek56572ab2008-12-12 18:34:08 +0000543 // Otherwise skip this block.
544 continue;
545 }
Mike Stump11289f42009-09-09 15:08:12 +0000546
Ted Kremenek56572ab2008-12-12 18:34:08 +0000547 assert(K == tok::pp_elif);
548 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
549
550 // If this is a #elif with a #else before it, report the error.
551 if (CondInfo.FoundElse)
552 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000553
Ted Kremenek56572ab2008-12-12 18:34:08 +0000554 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000555 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000556 if (CondInfo.FoundNonSkip)
557 continue;
558
559 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000560 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000561 CurPTHLexer->ParsingPreprocessorDirective = true;
562 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
563 CurPTHLexer->ParsingPreprocessorDirective = false;
564
565 // If this condition is true, enter it!
566 if (ShouldEnter) {
567 CondInfo.FoundNonSkip = true;
568 break;
569 }
570
571 // Otherwise, skip this block and go to the next one.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000572 }
573}
574
Richard Smith2a553082015-04-23 22:58:06 +0000575Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000576 if (!SourceMgr.isInMainFile(Loc)) {
577 // Try to determine the module of the include directive.
578 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
579 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
580 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
581 // The include comes from an included file.
582 return HeaderInfo.getModuleMap()
583 .findModuleForHeader(EntryOfIncl)
584 .getModule();
585 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000586 }
Richard Smith7e82e012016-02-19 22:25:36 +0000587
588 // This is either in the main file or not in a file at all. It belongs
589 // to the current module, if there is one.
590 return getLangOpts().CurrentModule.empty()
591 ? nullptr
592 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000593}
594
Richard Smith2a553082015-04-23 22:58:06 +0000595Module *Preprocessor::getModuleContainingLocation(SourceLocation Loc) {
596 return HeaderInfo.getModuleMap().inferModuleFromLocation(
597 FullSourceLoc(Loc, SourceMgr));
598}
599
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000600const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000601 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000602 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000603 bool isAngled,
604 const DirectoryLookup *FromDir,
Richard Smith25d50752014-10-20 00:15:49 +0000605 const FileEntry *FromFile,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000606 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000607 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000608 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000609 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000610 bool SkipCache) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000611 Module *RequestingModule = getModuleForLocation(FilenameLoc);
612
Will Wilson0fafd342013-12-27 19:46:16 +0000613 // If the header lookup mechanism may be relative to the current inclusion
614 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000615 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
616 Includers;
Richard Smith25d50752014-10-20 00:15:49 +0000617 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000618 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000619 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000620
Chris Lattner022923a2009-02-04 19:45:07 +0000621 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000622 // predefines buffer or the module includes buffer. Any other file is not
623 // lexed with a normal lexer, so it won't be scanned for preprocessor
624 // directives.
625 //
626 // If we have the predefines buffer, resolve #include references (which come
627 // from the -include command line argument) from the current working
628 // directory instead of relative to the main file.
629 //
630 // If we have the module includes buffer, resolve #include references (which
631 // come from header declarations in the module map) relative to the module
632 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000633 if (!FileEnt) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000634 if (FID == SourceMgr.getMainFileID() && MainFileDir)
635 Includers.push_back(std::make_pair(nullptr, MainFileDir));
636 else if ((FileEnt =
637 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000638 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
639 } else {
640 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
641 }
Will Wilson0fafd342013-12-27 19:46:16 +0000642
643 // MSVC searches the current include stack from top to bottom for
644 // headers included by quoted include directives.
645 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000646 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000647 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
648 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
649 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000650 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000651 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000652 }
Chris Lattner022923a2009-02-04 19:45:07 +0000653 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000654 }
Mike Stump11289f42009-09-09 15:08:12 +0000655
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000656 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000657
658 if (FromFile) {
659 // We're supposed to start looking from after a particular file. Search
660 // the include path until we find that file or run out of files.
661 const DirectoryLookup *TmpCurDir = CurDir;
662 const DirectoryLookup *TmpFromDir = nullptr;
663 while (const FileEntry *FE = HeaderInfo.LookupFile(
664 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000665 Includers, SearchPath, RelativePath, RequestingModule,
666 SuggestedModule, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000667 // Keep looking as if this file did a #include_next.
668 TmpFromDir = TmpCurDir;
669 ++TmpFromDir;
670 if (FE == FromFile) {
671 // Found it.
672 FromDir = TmpFromDir;
673 CurDir = TmpCurDir;
674 break;
675 }
676 }
677 }
678
679 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000680 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000681 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000682 RelativePath, RequestingModule, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000683 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000684 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000685 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000686 RequestingModule, FilenameLoc, Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000687 return FE;
688 }
Mike Stump11289f42009-09-09 15:08:12 +0000689
Will Wilson0fafd342013-12-27 19:46:16 +0000690 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000691 // Otherwise, see if this is a subframework header. If so, this is relative
692 // to one of the headers on the #include stack. Walk the list of the current
693 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000694 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000695 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000696 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000697 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000698 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000699 SuggestedModule))) {
700 if (SuggestedModule && !LangOpts.AsmPreprocessor)
701 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000702 RequestingModule, FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000703 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000704 }
705 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000706 }
Mike Stump11289f42009-09-09 15:08:12 +0000707
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000708 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
709 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000710 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000711 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000712 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000713 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000714 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000715 if (SuggestedModule && !LangOpts.AsmPreprocessor)
716 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith3d5b48c2015-10-16 21:42:56 +0000717 RequestingModule, FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000718 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000719 }
720 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000721 }
722 }
Mike Stump11289f42009-09-09 15:08:12 +0000723
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000724 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000725 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000726}
727
Chris Lattnerf64b3522008-03-09 01:54:53 +0000728//===----------------------------------------------------------------------===//
729// Preprocessor Directive Handling.
730//===----------------------------------------------------------------------===//
731
David Blaikied5321242012-06-06 18:52:13 +0000732class Preprocessor::ResetMacroExpansionHelper {
733public:
734 ResetMacroExpansionHelper(Preprocessor *pp)
735 : PP(pp), save(pp->DisableMacroExpansion) {
736 if (pp->MacroExpansionInDirectivesOverride)
737 pp->DisableMacroExpansion = false;
738 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000739
David Blaikied5321242012-06-06 18:52:13 +0000740 ~ResetMacroExpansionHelper() {
741 PP->DisableMacroExpansion = save;
742 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000743
David Blaikied5321242012-06-06 18:52:13 +0000744private:
745 Preprocessor *PP;
746 bool save;
747};
748
Chris Lattnerf64b3522008-03-09 01:54:53 +0000749/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000750/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000751/// lexer/preprocessor state, and advances the lexer(s) so that the next token
752/// read is the correct one.
753void Preprocessor::HandleDirective(Token &Result) {
754 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattnerf64b3522008-03-09 01:54:53 +0000756 // We just parsed a # character at the start of a line, so we're in directive
757 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000758 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000759 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000760 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000761
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000762 bool ImmediatelyAfterTopLevelIfndef =
763 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
764 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
765
Chris Lattnerf64b3522008-03-09 01:54:53 +0000766 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000767
Chris Lattnerf64b3522008-03-09 01:54:53 +0000768 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000769 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000770 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000771 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000772
Chris Lattner2d17ab72009-03-18 21:00:25 +0000773 // Save the '#' token in case we need to return it later.
774 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000775
Chris Lattnerf64b3522008-03-09 01:54:53 +0000776 // Read the next token, the directive flavor. This isn't expanded due to
777 // C99 6.10.3p8.
778 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000779
Chris Lattnerf64b3522008-03-09 01:54:53 +0000780 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
781 // #define A(x) #x
782 // A(abc
783 // #warning blah
784 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000785 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
786 // not support this for #include-like directives, since that can result in
787 // terrible diagnostics, and does not work in GCC.
788 if (InMacroArgs) {
789 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
790 switch (II->getPPKeywordID()) {
791 case tok::pp_include:
792 case tok::pp_import:
793 case tok::pp_include_next:
794 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000795 case tok::pp_pragma:
796 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000797 DiscardUntilEndOfDirective();
798 return;
799 default:
800 break;
801 }
802 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000803 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000804 }
Mike Stump11289f42009-09-09 15:08:12 +0000805
David Blaikied5321242012-06-06 18:52:13 +0000806 // Temporarily enable macro expansion if set so
807 // and reset to previous state when returning from this function.
808 ResetMacroExpansionHelper helper(this);
809
Chris Lattnerf64b3522008-03-09 01:54:53 +0000810 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000811 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000812 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000813 case tok::code_completion:
814 if (CodeComplete)
815 CodeComplete->CodeCompleteDirective(
816 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000817 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000818 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000819 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000820 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000821 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000822 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000823 default:
824 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000825 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000826
Chris Lattnerf64b3522008-03-09 01:54:53 +0000827 // Ask what the preprocessor keyword ID is.
828 switch (II->getPPKeywordID()) {
829 default: break;
830 // C99 6.10.1 - Conditional Inclusion.
831 case tok::pp_if:
832 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
833 case tok::pp_ifdef:
834 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
835 case tok::pp_ifndef:
836 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
837 case tok::pp_elif:
838 return HandleElifDirective(Result);
839 case tok::pp_else:
840 return HandleElseDirective(Result);
841 case tok::pp_endif:
842 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000843
Chris Lattnerf64b3522008-03-09 01:54:53 +0000844 // C99 6.10.2 - Source File Inclusion.
845 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000846 // Handle #include.
847 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000848 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000849 // Handle -imacros.
850 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chris Lattnerf64b3522008-03-09 01:54:53 +0000852 // C99 6.10.3 - Macro Replacement.
853 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000854 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000855 case tok::pp_undef:
856 return HandleUndefDirective(Result);
857
858 // C99 6.10.4 - Line Control.
859 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000860 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000861
Chris Lattnerf64b3522008-03-09 01:54:53 +0000862 // C99 6.10.5 - Error Directive.
863 case tok::pp_error:
864 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000865
Chris Lattnerf64b3522008-03-09 01:54:53 +0000866 // C99 6.10.6 - Pragma Directive.
867 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000868 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000869
Chris Lattnerf64b3522008-03-09 01:54:53 +0000870 // GNU Extensions.
871 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000872 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000873 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000874 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000875
Chris Lattnerf64b3522008-03-09 01:54:53 +0000876 case tok::pp_warning:
877 Diag(Result, diag::ext_pp_warning_directive);
878 return HandleUserDiagnosticDirective(Result, true);
879 case tok::pp_ident:
880 return HandleIdentSCCSDirective(Result);
881 case tok::pp_sccs:
882 return HandleIdentSCCSDirective(Result);
883 case tok::pp_assert:
884 //isExtension = true; // FIXME: implement #assert
885 break;
886 case tok::pp_unassert:
887 //isExtension = true; // FIXME: implement #unassert
888 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000889
Douglas Gregor663b48f2012-01-03 19:48:16 +0000890 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000891 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000892 return HandleMacroPublicDirective(Result);
893 break;
894
Douglas Gregor663b48f2012-01-03 19:48:16 +0000895 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000896 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000897 return HandleMacroPrivateDirective(Result);
898 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000899 }
900 break;
901 }
Mike Stump11289f42009-09-09 15:08:12 +0000902
Chris Lattner2d17ab72009-03-18 21:00:25 +0000903 // If this is a .S file, treat unknown # directives as non-preprocessor
904 // directives. This is important because # may be a comment or introduce
905 // various pseudo-ops. Just return the # token and push back the following
906 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000907 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +0000908 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +0000909 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000910 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000911 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000912
913 // If the second token is a hashhash token, then we need to translate it to
914 // unknown so the token lexer doesn't try to perform token pasting.
915 if (Result.is(tok::hashhash))
916 Toks[1].setKind(tok::unknown);
917
Chris Lattner2d17ab72009-03-18 21:00:25 +0000918 // Enter this token stream so that we re-lex the tokens. Make sure to
919 // enable macro expansion, in case the token after the # is an identifier
920 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +0000921 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +0000922 return;
923 }
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattnerf64b3522008-03-09 01:54:53 +0000925 // If we reached here, the preprocessing token is not valid!
926 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000927
Chris Lattnerf64b3522008-03-09 01:54:53 +0000928 // Read the rest of the PP line.
929 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000930
Chris Lattnerf64b3522008-03-09 01:54:53 +0000931 // Okay, we're done parsing the directive.
932}
933
Chris Lattner76e68962009-01-26 06:19:46 +0000934/// GetLineValue - Convert a numeric token into an unsigned value, emitting
935/// Diagnostic DiagID if it is invalid, and returning the value in Val.
936static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000937 unsigned DiagID, Preprocessor &PP,
938 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000939 if (DigitTok.isNot(tok::numeric_constant)) {
940 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000941
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000942 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000943 PP.DiscardUntilEndOfDirective();
944 return true;
945 }
Mike Stump11289f42009-09-09 15:08:12 +0000946
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000947 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000948 IntegerBuffer.resize(DigitTok.getLength());
949 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000950 bool Invalid = false;
951 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
952 if (Invalid)
953 return true;
954
Chris Lattnerd66f1722009-04-18 18:35:15 +0000955 // Verify that we have a simple digit-sequence, and compute the value. This
956 // is always a simple digit string computed in decimal, so we do this manually
957 // here.
958 Val = 0;
959 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +0000960 // C++1y [lex.fcon]p1:
961 // Optional separating single quotes in a digit-sequence are ignored
962 if (DigitTokBegin[i] == '\'')
963 continue;
964
Jordan Rosea7d03842013-02-08 22:30:41 +0000965 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000966 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000967 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000968 PP.DiscardUntilEndOfDirective();
969 return true;
970 }
Mike Stump11289f42009-09-09 15:08:12 +0000971
Chris Lattnerd66f1722009-04-18 18:35:15 +0000972 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
973 if (NextVal < Val) { // overflow.
974 PP.Diag(DigitTok, DiagID);
975 PP.DiscardUntilEndOfDirective();
976 return true;
977 }
978 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000979 }
Mike Stump11289f42009-09-09 15:08:12 +0000980
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000981 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000982 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
983 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000984
Chris Lattner76e68962009-01-26 06:19:46 +0000985 return false;
986}
987
James Dennettf6333ac2012-06-22 05:46:07 +0000988/// \brief Handle a \#line directive: C99 6.10.4.
989///
990/// The two acceptable forms are:
991/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000992/// # line digit-sequence
993/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000994/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000995void Preprocessor::HandleLineDirective(Token &Tok) {
996 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
997 // expanded.
998 Token DigitTok;
999 Lex(DigitTok);
1000
Chris Lattner100c65e2009-01-26 05:29:08 +00001001 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001002 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001003 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001004 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001005
1006 if (LineNo == 0)
1007 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001008
Chris Lattner76e68962009-01-26 06:19:46 +00001009 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1010 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001011 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001012 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001013 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001014 if (LineNo >= LineLimit)
1015 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001016 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001017 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001019 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001020 Token StrTok;
1021 Lex(StrTok);
1022
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001023 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1024 // string followed by eod.
1025 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001026 ; // ok
1027 else if (StrTok.isNot(tok::string_literal)) {
1028 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001029 return DiscardUntilEndOfDirective();
1030 } else if (StrTok.hasUDSuffix()) {
1031 Diag(StrTok, diag::err_invalid_string_udl);
1032 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001033 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001034 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001035 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001036 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001037 if (Literal.hadError)
1038 return DiscardUntilEndOfDirective();
1039 if (Literal.Pascal) {
1040 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1041 return DiscardUntilEndOfDirective();
1042 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001043 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001044
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001045 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001046 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1047 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001048 }
Mike Stump11289f42009-09-09 15:08:12 +00001049
Chris Lattner1eaa70a2009-02-03 21:52:55 +00001050 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +00001051
Chris Lattner839150e2009-03-27 17:13:49 +00001052 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001053 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1054 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +00001055 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +00001056}
1057
Chris Lattner76e68962009-01-26 06:19:46 +00001058/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1059/// marker directive.
1060static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1061 bool &IsSystemHeader, bool &IsExternCHeader,
1062 Preprocessor &PP) {
1063 unsigned FlagVal;
1064 Token FlagTok;
1065 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001066 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001067 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1068 return true;
1069
1070 if (FlagVal == 1) {
1071 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattner76e68962009-01-26 06:19:46 +00001073 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001074 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001075 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1076 return true;
1077 } else if (FlagVal == 2) {
1078 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001079
Chris Lattner1c967782009-02-04 06:25:26 +00001080 SourceManager &SM = PP.getSourceManager();
1081 // If we are leaving the current presumed file, check to make sure the
1082 // presumed include stack isn't empty!
1083 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001084 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001085 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001086 if (PLoc.isInvalid())
1087 return true;
1088
Chris Lattner1c967782009-02-04 06:25:26 +00001089 // If there is no include loc (main file) or if the include loc is in a
1090 // different physical file, then we aren't in a "1" line marker flag region.
1091 SourceLocation IncLoc = PLoc.getIncludeLoc();
1092 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001093 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001094 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1095 PP.DiscardUntilEndOfDirective();
1096 return true;
1097 }
Mike Stump11289f42009-09-09 15:08:12 +00001098
Chris Lattner76e68962009-01-26 06:19:46 +00001099 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001100 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001101 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1102 return true;
1103 }
1104
1105 // We must have 3 if there are still flags.
1106 if (FlagVal != 3) {
1107 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001108 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001109 return true;
1110 }
Mike Stump11289f42009-09-09 15:08:12 +00001111
Chris Lattner76e68962009-01-26 06:19:46 +00001112 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001113
Chris Lattner76e68962009-01-26 06:19:46 +00001114 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001115 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001116 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001117 return true;
1118
1119 // We must have 4 if there is yet another flag.
1120 if (FlagVal != 4) {
1121 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001122 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001123 return true;
1124 }
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattner76e68962009-01-26 06:19:46 +00001126 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattner76e68962009-01-26 06:19:46 +00001128 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001129 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001130
1131 // There are no more valid flags here.
1132 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001133 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001134 return true;
1135}
1136
1137/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1138/// one of the following forms:
1139///
1140/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001141/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001142/// # 42 "file" ('1' | '2')? '3' '4'?
1143///
1144void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1145 // Validate the number and convert it to an unsigned. GNU does not have a
1146 // line # limit other than it fit in 32-bits.
1147 unsigned LineNo;
1148 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001149 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001150 return;
Mike Stump11289f42009-09-09 15:08:12 +00001151
Chris Lattner76e68962009-01-26 06:19:46 +00001152 Token StrTok;
1153 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001154
Chris Lattner76e68962009-01-26 06:19:46 +00001155 bool IsFileEntry = false, IsFileExit = false;
1156 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001157 int FilenameID = -1;
1158
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001159 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1160 // string followed by eod.
1161 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001162 ; // ok
1163 else if (StrTok.isNot(tok::string_literal)) {
1164 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001165 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001166 } else if (StrTok.hasUDSuffix()) {
1167 Diag(StrTok, diag::err_invalid_string_udl);
1168 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001169 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001170 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001171 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001172 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001173 if (Literal.hadError)
1174 return DiscardUntilEndOfDirective();
1175 if (Literal.Pascal) {
1176 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1177 return DiscardUntilEndOfDirective();
1178 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001179 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001180
Chris Lattner76e68962009-01-26 06:19:46 +00001181 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001182 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001183 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001184 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001185 }
Mike Stump11289f42009-09-09 15:08:12 +00001186
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001187 // Create a line note with this information.
1188 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001189 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001190 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001191
Chris Lattner839150e2009-03-27 17:13:49 +00001192 // If the preprocessor has callbacks installed, notify them of the #line
1193 // change. This is used so that the line marker comes out in -E mode for
1194 // example.
1195 if (Callbacks) {
1196 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1197 if (IsFileEntry)
1198 Reason = PPCallbacks::EnterFile;
1199 else if (IsFileExit)
1200 Reason = PPCallbacks::ExitFile;
1201 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1202 if (IsExternCHeader)
1203 FileKind = SrcMgr::C_ExternCSystem;
1204 else if (IsSystemHeader)
1205 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001206
Chris Lattnerc745cec2010-04-14 04:28:50 +00001207 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001208 }
Chris Lattner76e68962009-01-26 06:19:46 +00001209}
1210
Chris Lattner38d7fd22009-01-26 05:30:54 +00001211/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1212///
Mike Stump11289f42009-09-09 15:08:12 +00001213void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001214 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001215 // PTH doesn't emit #warning or #error directives.
1216 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001217 return CurPTHLexer->DiscardToEndOfLine();
1218
Chris Lattnerf64b3522008-03-09 01:54:53 +00001219 // Read the rest of the line raw. We do this because we don't want macros
1220 // to be expanded and we don't require that the tokens be valid preprocessing
1221 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1222 // collapse multiple consequtive white space between tokens, but this isn't
1223 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001224 SmallString<128> Message;
1225 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001226
1227 // Find the first non-whitespace character, so that we can make the
1228 // diagnostic more succinct.
Vedant Kumar409506e2016-02-16 02:14:44 +00001229 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001230
Chris Lattner100c65e2009-01-26 05:29:08 +00001231 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001232 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001233 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001234 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001235}
1236
1237/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1238///
1239void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1240 // Yes, this directive is an extension.
1241 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001242
Chris Lattnerf64b3522008-03-09 01:54:53 +00001243 // Read the string argument.
1244 Token StrTok;
1245 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001246
Chris Lattnerf64b3522008-03-09 01:54:53 +00001247 // If the token kind isn't a string, it's a malformed directive.
1248 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001249 StrTok.isNot(tok::wide_string_literal)) {
1250 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001251 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001252 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001253 return;
1254 }
Mike Stump11289f42009-09-09 15:08:12 +00001255
Richard Smithd67aea22012-03-06 03:21:47 +00001256 if (StrTok.hasUDSuffix()) {
1257 Diag(StrTok, diag::err_invalid_string_udl);
1258 return DiscardUntilEndOfDirective();
1259 }
1260
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001261 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001262 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001263
Douglas Gregordc970f02010-03-16 22:30:13 +00001264 if (Callbacks) {
1265 bool Invalid = false;
1266 std::string Str = getSpelling(StrTok, &Invalid);
1267 if (!Invalid)
1268 Callbacks->Ident(Tok.getLocation(), Str);
1269 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001270}
1271
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001272/// \brief Handle a #public directive.
1273void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001274 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001275 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001276
1277 // Error reading macro name? If so, diagnostic already issued.
1278 if (MacroNameTok.is(tok::eod))
1279 return;
1280
Douglas Gregor663b48f2012-01-03 19:48:16 +00001281 // Check to see if this is the last token on the #__public_macro line.
1282 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001283
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001284 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001285 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001286 MacroDirective *MD = getLocalMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001287
1288 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001289 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001290 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001291 return;
1292 }
1293
1294 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001295 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1296 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001297}
1298
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001299/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001300void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1301 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001302 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregorebf00492011-10-17 15:32:29 +00001303
1304 // Error reading macro name? If so, diagnostic already issued.
1305 if (MacroNameTok.is(tok::eod))
1306 return;
1307
Douglas Gregor663b48f2012-01-03 19:48:16 +00001308 // Check to see if this is the last token on the #__private_macro line.
1309 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001310
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001311 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001312 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001313 MacroDirective *MD = getLocalMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001314
1315 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001316 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001317 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001318 return;
1319 }
1320
1321 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001322 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1323 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001324}
1325
Chris Lattnerf64b3522008-03-09 01:54:53 +00001326//===----------------------------------------------------------------------===//
1327// Preprocessor Include Directive Handling.
1328//===----------------------------------------------------------------------===//
1329
1330/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001331/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001332/// true if the input filename was in <>'s or false if it were in ""'s. The
1333/// caller is expected to provide a buffer that is large enough to hold the
1334/// spelling of the filename, but is also expected to handle the case when
1335/// this method decides to use a different buffer.
1336bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001337 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001338 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001339 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattnerf64b3522008-03-09 01:54:53 +00001341 // Make sure the filename is <x> or "x".
1342 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001343 if (Buffer[0] == '<') {
1344 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001345 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001346 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001347 return true;
1348 }
1349 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001350 } else if (Buffer[0] == '"') {
1351 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001352 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001353 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001354 return true;
1355 }
1356 isAngled = false;
1357 } else {
1358 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001359 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001360 return true;
1361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Chris Lattnerf64b3522008-03-09 01:54:53 +00001363 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001364 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001365 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001366 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001367 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001368 }
Mike Stump11289f42009-09-09 15:08:12 +00001369
Chris Lattnerf64b3522008-03-09 01:54:53 +00001370 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001371 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001372 return isAngled;
1373}
1374
James Dennett4a4f72d2013-11-27 01:27:40 +00001375// \brief Handle cases where the \#include name is expanded from a macro
1376// as multiple tokens, which need to be glued together.
1377//
1378// This occurs for code like:
1379// \code
1380// \#define FOO <a/b.h>
1381// \#include FOO
1382// \endcode
1383// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1384//
1385// This code concatenates and consumes tokens up to the '>' token. It returns
1386// false if the > was found, otherwise it returns true if it finds and consumes
1387// the EOD marker.
1388bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001389 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001390 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001391
John Thompsonb5353522009-10-30 13:49:06 +00001392 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001393 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001394 End = CurTok.getLocation();
1395
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001396 // FIXME: Provide code completion for #includes.
1397 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001398 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001399 Lex(CurTok);
1400 continue;
1401 }
1402
Chris Lattnerf64b3522008-03-09 01:54:53 +00001403 // Append the spelling of this token to the buffer. If there was a space
1404 // before it, add it now.
1405 if (CurTok.hasLeadingSpace())
1406 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001407
Chris Lattnerf64b3522008-03-09 01:54:53 +00001408 // Get the spelling of the token, directly into FilenameBuffer if possible.
1409 unsigned PreAppendSize = FilenameBuffer.size();
1410 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001411
Chris Lattnerf64b3522008-03-09 01:54:53 +00001412 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001413 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001414
Chris Lattnerf64b3522008-03-09 01:54:53 +00001415 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1416 if (BufPtr != &FilenameBuffer[PreAppendSize])
1417 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001418
Chris Lattnerf64b3522008-03-09 01:54:53 +00001419 // Resize FilenameBuffer to the correct size.
1420 if (CurTok.getLength() != ActualLen)
1421 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001422
Chris Lattnerf64b3522008-03-09 01:54:53 +00001423 // If we found the '>' marker, return success.
1424 if (CurTok.is(tok::greater))
1425 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001426
John Thompsonb5353522009-10-30 13:49:06 +00001427 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001428 }
1429
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001430 // If we hit the eod marker, emit an error and return true so that the caller
1431 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001432 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001433 return true;
1434}
1435
Richard Smith34f30512013-11-23 04:06:09 +00001436/// \brief Push a token onto the token stream containing an annotation.
1437static void EnterAnnotationToken(Preprocessor &PP,
1438 SourceLocation Begin, SourceLocation End,
1439 tok::TokenKind Kind, void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001440 // FIXME: Produce this as the current token directly, rather than
1441 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001442 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001443 Tok[0].startToken();
1444 Tok[0].setKind(Kind);
1445 Tok[0].setLocation(Begin);
1446 Tok[0].setAnnotationEndLoc(End);
1447 Tok[0].setAnnotationValue(AnnotationVal);
David Blaikie2eabcc92016-02-09 18:52:09 +00001448 PP.EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001449}
1450
Richard Smith63b6fce2015-05-18 04:45:41 +00001451/// \brief Produce a diagnostic informing the user that a #include or similar
1452/// was implicitly treated as a module import.
1453static void diagnoseAutoModuleImport(
1454 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1455 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1456 SourceLocation PathEnd) {
1457 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1458
1459 SmallString<128> PathString;
1460 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1461 if (I)
1462 PathString += '.';
1463 PathString += Path[I].first->getName();
1464 }
1465 int IncludeKind = 0;
1466
1467 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1468 case tok::pp_include:
1469 IncludeKind = 0;
1470 break;
1471
1472 case tok::pp_import:
1473 IncludeKind = 1;
1474 break;
1475
1476 case tok::pp_include_next:
1477 IncludeKind = 2;
1478 break;
1479
1480 case tok::pp___include_macros:
1481 IncludeKind = 3;
1482 break;
1483
1484 default:
1485 llvm_unreachable("unknown include directive kind");
1486 }
1487
1488 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1489 /*IsTokenRange=*/false);
1490 PP.Diag(HashLoc, diag::warn_auto_module_import)
1491 << IncludeKind << PathString
1492 << FixItHint::CreateReplacement(ReplaceRange,
1493 ("@import " + PathString + ";").str());
1494}
1495
James Dennettf6333ac2012-06-22 05:46:07 +00001496/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1497/// the file to be included from the lexer, then include it! This is a common
1498/// routine with functionality shared between \#include, \#include_next and
1499/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001500/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001501void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1502 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001503 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001504 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001505 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001506 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001507 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001508
Chris Lattnerf64b3522008-03-09 01:54:53 +00001509 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001510 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001511 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001512 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001513 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001514
Chris Lattnerf64b3522008-03-09 01:54:53 +00001515 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001516 case tok::eod:
1517 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001518 return;
Mike Stump11289f42009-09-09 15:08:12 +00001519
Chris Lattnerf64b3522008-03-09 01:54:53 +00001520 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001521 case tok::string_literal:
1522 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001523 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001524 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001525 break;
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattnerf64b3522008-03-09 01:54:53 +00001527 case tok::less:
1528 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1529 // case, glue the tokens together into FilenameBuffer and interpret those.
1530 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001531 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001532 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001533 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001534 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001535 break;
1536 default:
1537 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1538 DiscardUntilEndOfDirective();
1539 return;
1540 }
Mike Stump11289f42009-09-09 15:08:12 +00001541
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001542 CharSourceRange FilenameRange
1543 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001544 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001545 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001546 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001547 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1548 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001549 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001550 DiscardUntilEndOfDirective();
1551 return;
1552 }
Mike Stump11289f42009-09-09 15:08:12 +00001553
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001554 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001555 // we allow macros that expand to nothing after the filename, because this
1556 // falls into the category of "#include pp-tokens new-line" specified in
1557 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001558 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001559
1560 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001561 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1562 Diag(FilenameTok, diag::err_pp_include_too_deep);
1563 return;
1564 }
Mike Stump11289f42009-09-09 15:08:12 +00001565
John McCall32f5fe12011-09-30 05:12:12 +00001566 // Complain about attempts to #include files in an audit pragma.
1567 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1568 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1569 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1570
1571 // Immediately leave the pragma.
1572 PragmaARCCFCodeAuditedLoc = SourceLocation();
1573 }
1574
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001575 // Complain about attempts to #include files in an assume-nonnull pragma.
1576 if (PragmaAssumeNonNullLoc.isValid()) {
1577 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1578 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1579
1580 // Immediately leave the pragma.
1581 PragmaAssumeNonNullLoc = SourceLocation();
1582 }
1583
Aaron Ballman611306e2012-03-02 22:51:54 +00001584 if (HeaderInfo.HasIncludeAliasMap()) {
1585 // Map the filename with the brackets still attached. If the name doesn't
1586 // map to anything, fall back on the filename we've already gotten the
1587 // spelling for.
1588 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1589 if (!NewName.empty())
1590 Filename = NewName;
1591 }
1592
Chris Lattnerf64b3522008-03-09 01:54:53 +00001593 // Search include directories.
1594 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001595 SmallString<1024> SearchPath;
1596 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001597 // We get the raw path only if we have 'Callbacks' to which we later pass
1598 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001599 ModuleMap::KnownHeader SuggestedModule;
1600 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001601 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001602 if (LangOpts.MSVCCompat) {
1603 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001604#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001605 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001606#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001607 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001608 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001609 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001610 isAngled, LookupFrom, LookupFromFile, CurDir,
1611 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001612 &SuggestedModule);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001613
Richard Smithdbbc5232015-05-14 02:25:44 +00001614 if (!File) {
1615 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001616 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001617 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001618 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1619 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1620 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001621 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001622 HeaderInfo.AddSearchPath(DL, isAngled);
1623
1624 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001625 File = LookupFile(
1626 FilenameLoc,
1627 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1628 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001629 &SuggestedModule, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001630 }
1631 }
1632 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001633
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001634 if (!SuppressIncludeNotFoundError) {
1635 // If the file could not be located and it was included via angle
1636 // brackets, we can attempt a lookup as though it were a quoted path to
1637 // provide the user with a possible fixit.
1638 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001639 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001640 FilenameLoc,
1641 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1642 LookupFrom, LookupFromFile, CurDir,
1643 Callbacks ? &SearchPath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001644 Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001645 &SuggestedModule);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001646 if (File) {
1647 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1648 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1649 Filename <<
1650 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1651 }
1652 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001653
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001654 // If the file is still not found, just go with the vanilla diagnostic
1655 if (!File)
1656 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1657 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001658 }
1659
Richard Smith63b6fce2015-05-18 04:45:41 +00001660 // Should we enter the source file? Set to false if either the source file is
1661 // known to have no effect beyond its effect on module visibility -- that is,
1662 // if it's got an include guard that is already defined or is a modular header
1663 // we've imported or already built.
1664 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001665
Richard Smith63b6fce2015-05-18 04:45:41 +00001666 // Determine whether we should try to import the module for this #include, if
1667 // there is one. Don't do so if precompiled module support is disabled or we
1668 // are processing this module textually (because we're building the module).
1669 if (File && SuggestedModule && getLangOpts().Modules &&
1670 SuggestedModule.getModule()->getTopLevelModuleName() !=
Richard Smith7e82e012016-02-19 22:25:36 +00001671 getLangOpts().CurrentModule) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001672 // If this include corresponds to a module but that module is
1673 // unavailable, diagnose the situation and bail out.
1674 if (!SuggestedModule.getModule()->isAvailable()) {
1675 clang::Module::Requirement Requirement;
1676 clang::Module::UnresolvedHeaderDirective MissingHeader;
1677 Module *M = SuggestedModule.getModule();
1678 // Identify the cause.
1679 (void)M->isAvailable(getLangOpts(), getTargetInfo(), Requirement,
1680 MissingHeader);
1681 if (MissingHeader.FileNameLoc.isValid()) {
1682 Diag(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1683 << MissingHeader.IsUmbrella << MissingHeader.FileName;
1684 } else {
1685 Diag(M->DefinitionLoc, diag::err_module_unavailable)
1686 << M->getFullModuleName() << Requirement.second << Requirement.first;
1687 }
1688 Diag(FilenameTok.getLocation(),
1689 diag::note_implicit_top_level_module_import_here)
1690 << M->getTopLevelModuleName();
1691 return;
1692 }
1693
Douglas Gregor71944202011-11-30 00:36:36 +00001694 // Compute the module access path corresponding to this module.
1695 // FIXME: Should we have a second loadModule() overload to avoid this
1696 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001697 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001698 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001699 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1700 FilenameTok.getLocation()));
1701 std::reverse(Path.begin(), Path.end());
1702
Douglas Gregor41e115a2011-11-30 18:02:36 +00001703 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001704 // We only do this in Objective-C, where we have a module-import syntax.
1705 if (getLangOpts().ObjC2)
1706 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Douglas Gregor41e115a2011-11-30 18:02:36 +00001707
Richard Smith10434f32015-05-02 02:08:26 +00001708 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001709 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001710 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1711 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001712 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1713 IncludeTok.getLocation(), Path, Module::Hidden,
1714 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001715 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001716 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001717
Richard Smith63b6fce2015-05-18 04:45:41 +00001718 if (Imported)
1719 ShouldEnter = false;
1720 else if (Imported.isMissingExpected()) {
1721 // We failed to find a submodule that we assumed would exist (because it
1722 // was in the directory of an umbrella header, for instance), but no
1723 // actual module exists for it (because the umbrella header is
1724 // incomplete). Treat this as a textual inclusion.
1725 SuggestedModule = ModuleMap::KnownHeader();
1726 } else {
1727 // We hit an error processing the import. Bail out.
1728 if (hadModuleLoaderFatalFailure()) {
1729 // With a fatal failure in the module loader, we abort parsing.
1730 Token &Result = IncludeTok;
1731 if (CurLexer) {
1732 Result.startToken();
1733 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1734 CurLexer->cutOffLexing();
1735 } else {
1736 assert(CurPTHLexer && "#include but no current lexer set!");
1737 CurPTHLexer->getEOF(Result);
1738 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001739 }
1740 return;
1741 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001742 }
1743
Richard Smith63b6fce2015-05-18 04:45:41 +00001744 if (Callbacks) {
1745 // Notify the callback object that we've seen an inclusion directive.
1746 Callbacks->InclusionDirective(
1747 HashLoc, IncludeTok,
1748 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1749 FilenameRange, File, SearchPath, RelativePath,
1750 ShouldEnter ? nullptr : SuggestedModule.getModule());
Douglas Gregor97eec242011-09-15 22:00:41 +00001751 }
Richard Smith63b6fce2015-05-18 04:45:41 +00001752
1753 if (!File)
1754 return;
Douglas Gregor97eec242011-09-15 22:00:41 +00001755
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001756 // The #included file will be considered to be a system header if either it is
1757 // in a system include directory, or if the #includer is a system include
1758 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001759 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001760 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001761 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001762
Richard Smith54ef4c32015-05-19 19:58:11 +00001763 // FIXME: If we have a suggested module, and we've already visited this file,
1764 // don't bother entering it again. We know it has no further effect.
1765
Chris Lattner72286d62010-04-19 20:44:31 +00001766 // Ask HeaderInfo if we should enter this #include file. If not, #including
Richard Smith54ef4c32015-05-19 19:58:11 +00001767 // this file will have no effect.
Richard Smith63b6fce2015-05-18 04:45:41 +00001768 if (ShouldEnter &&
Richard Smith035f6dc2015-07-01 01:51:38 +00001769 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
1770 SuggestedModule.getModule())) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001771 ShouldEnter = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001772 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001773 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Richard Smith63b6fce2015-05-18 04:45:41 +00001774 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001775
Richard Smith63b6fce2015-05-18 04:45:41 +00001776 // If we don't need to enter the file, stop now.
1777 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001778 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00001779 if (auto *M = SuggestedModule.getModule()) {
1780 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00001781
1782 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
1783 tok::pp___include_macros)
Richard Smitha0aafa32015-05-18 03:52:30 +00001784 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00001785 }
Chris Lattner72286d62010-04-19 20:44:31 +00001786 return;
1787 }
1788
Chris Lattnerf64b3522008-03-09 01:54:53 +00001789 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001790 SourceLocation IncludePos = End;
1791 // If the filename string was the result of macro expansions, set the include
1792 // position on the file where it will be included and after the expansions.
1793 if (IncludePos.isMacroID())
1794 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1795 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00001796 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001797
Richard Smith34f30512013-11-23 04:06:09 +00001798 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00001799 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
1800 return;
Richard Smith34f30512013-11-23 04:06:09 +00001801
Richard Smitha0aafa32015-05-18 03:52:30 +00001802 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00001803 if (auto *M = SuggestedModule.getModule()) {
Richard Smith67294e22014-01-31 20:47:44 +00001804 assert(!CurSubmodule && "should not have marked this as a module yet");
Richard Smitha0aafa32015-05-18 03:52:30 +00001805 CurSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00001806
Richard Smitha0aafa32015-05-18 03:52:30 +00001807 // Let the macro handling code know that any future macros are within
1808 // the new submodule.
1809 EnterSubmodule(M, HashLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +00001810
Richard Smitha0aafa32015-05-18 03:52:30 +00001811 // Let the parser know that any future declarations are within the new
1812 // submodule.
1813 // FIXME: There's no point doing this if we're handling a #__include_macros
1814 // directive.
1815 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00001816 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001817}
1818
James Dennettf6333ac2012-06-22 05:46:07 +00001819/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001820///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001821void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1822 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001823 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001824
Chris Lattnerf64b3522008-03-09 01:54:53 +00001825 // #include_next is like #include, except that we start searching after
1826 // the current found directory. If we can't do this, issue a
1827 // diagnostic.
1828 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00001829 const FileEntry *LookupFromFile = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001830 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001831 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001832 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001833 } else if (CurSubmodule) {
1834 // Start looking up in the directory *after* the one in which the current
1835 // file would be found, if any.
1836 assert(CurPPLexer && "#include_next directive in macro?");
1837 LookupFromFile = CurPPLexer->getFileEntry();
1838 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001839 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001840 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1841 } else {
1842 // Start looking up in the next directory.
1843 ++Lookup;
1844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
Richard Smith25d50752014-10-20 00:15:49 +00001846 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
1847 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001848}
1849
James Dennettf6333ac2012-06-22 05:46:07 +00001850/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001851void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1852 // The Microsoft #import directive takes a type library and generates header
1853 // files from it, and includes those. This is beyond the scope of what clang
1854 // does, so we ignore it and error out. However, #import can optionally have
1855 // trailing attributes that span multiple lines. We're going to eat those
1856 // so we can continue processing from there.
1857 Diag(Tok, diag::err_pp_import_directive_ms );
1858
1859 // Read tokens until we get to the end of the directive. Note that the
1860 // directive can be split over multiple lines using the backslash character.
1861 DiscardUntilEndOfDirective();
1862}
1863
James Dennettf6333ac2012-06-22 05:46:07 +00001864/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001865///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001866void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1867 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001868 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00001869 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00001870 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001871 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001872 }
Richard Smith25d50752014-10-20 00:15:49 +00001873 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001874}
1875
Chris Lattner58a1eb02009-04-08 18:46:40 +00001876/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1877/// pseudo directive in the predefines buffer. This handles it by sucking all
1878/// tokens through the preprocessor and discarding them (only keeping the side
1879/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001880void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1881 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001882 // This directive should only occur in the predefines buffer. If not, emit an
1883 // error and reject it.
1884 SourceLocation Loc = IncludeMacrosTok.getLocation();
1885 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1886 Diag(IncludeMacrosTok.getLocation(),
1887 diag::pp_include_macros_out_of_predefines);
1888 DiscardUntilEndOfDirective();
1889 return;
1890 }
Mike Stump11289f42009-09-09 15:08:12 +00001891
Chris Lattnere01d82b2009-04-08 20:53:24 +00001892 // Treat this as a normal #include for checking purposes. If this is
1893 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00001894 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00001895
Chris Lattnere01d82b2009-04-08 20:53:24 +00001896 Token TmpTok;
1897 do {
1898 Lex(TmpTok);
1899 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1900 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001901}
1902
Chris Lattnerf64b3522008-03-09 01:54:53 +00001903//===----------------------------------------------------------------------===//
1904// Preprocessor Macro Directive Handling.
1905//===----------------------------------------------------------------------===//
1906
1907/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1908/// definition has just been read. Lex the rest of the arguments and the
1909/// closing ), updating MI with what we learn. Return true if an error occurs
1910/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001911bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001912 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001913
Chris Lattnerf64b3522008-03-09 01:54:53 +00001914 while (1) {
1915 LexUnexpandedToken(Tok);
1916 switch (Tok.getKind()) {
1917 case tok::r_paren:
1918 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001919 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001920 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001921 // Otherwise we have #define FOO(A,)
1922 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1923 return true;
1924 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001925 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001926 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001927 diag::warn_cxx98_compat_variadic_macro :
1928 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001929
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001930 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1931 if (LangOpts.OpenCL) {
1932 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1933 return true;
1934 }
1935
Chris Lattnerf64b3522008-03-09 01:54:53 +00001936 // Lex the token after the identifier.
1937 LexUnexpandedToken(Tok);
1938 if (Tok.isNot(tok::r_paren)) {
1939 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1940 return true;
1941 }
1942 // Add the __VA_ARGS__ identifier as an argument.
1943 Arguments.push_back(Ident__VA_ARGS__);
1944 MI->setIsC99Varargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00001945 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001946 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001947 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001948 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1949 return true;
1950 default:
1951 // Handle keywords and identifiers here to accept things like
1952 // #define Foo(for) for.
1953 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00001954 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001955 // #define X(1
1956 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1957 return true;
1958 }
1959
1960 // If this is already used as an argument, it is used multiple times (e.g.
1961 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001962 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001963 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001964 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001965 return true;
1966 }
Mike Stump11289f42009-09-09 15:08:12 +00001967
Chris Lattnerf64b3522008-03-09 01:54:53 +00001968 // Add the argument to the macro info.
1969 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001970
Chris Lattnerf64b3522008-03-09 01:54:53 +00001971 // Lex the token after the identifier.
1972 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattnerf64b3522008-03-09 01:54:53 +00001974 switch (Tok.getKind()) {
1975 default: // #define X(A B
1976 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1977 return true;
1978 case tok::r_paren: // #define X(A)
Craig Topperd96b3f92015-10-22 04:59:52 +00001979 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001980 return false;
1981 case tok::comma: // #define X(A,
1982 break;
1983 case tok::ellipsis: // #define X(A... -> GCC extension
1984 // Diagnose extension.
1985 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001986
Chris Lattnerf64b3522008-03-09 01:54:53 +00001987 // Lex the token after the identifier.
1988 LexUnexpandedToken(Tok);
1989 if (Tok.isNot(tok::r_paren)) {
1990 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1991 return true;
1992 }
Mike Stump11289f42009-09-09 15:08:12 +00001993
Chris Lattnerf64b3522008-03-09 01:54:53 +00001994 MI->setIsGNUVarargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00001995 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001996 return false;
1997 }
1998 }
1999 }
2000}
2001
Serge Pavlov07c0f042014-12-18 11:14:21 +00002002static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2003 const LangOptions &LOptions) {
2004 if (MI->getNumTokens() == 1) {
2005 const Token &Value = MI->getReplacementToken(0);
2006
2007 // Macro that is identity, like '#define inline inline' is a valid pattern.
2008 if (MacroName.getKind() == Value.getKind())
2009 return true;
2010
2011 // Macro that maps a keyword to the same keyword decorated with leading/
2012 // trailing underscores is a valid pattern:
2013 // #define inline __inline
2014 // #define inline __inline__
2015 // #define inline _inline (in MS compatibility mode)
2016 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2017 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2018 if (!II->isKeyword(LOptions))
2019 return false;
2020 StringRef ValueText = II->getName();
2021 StringRef TrimmedValue = ValueText;
2022 if (!ValueText.startswith("__")) {
2023 if (ValueText.startswith("_"))
2024 TrimmedValue = TrimmedValue.drop_front(1);
2025 else
2026 return false;
2027 } else {
2028 TrimmedValue = TrimmedValue.drop_front(2);
2029 if (TrimmedValue.endswith("__"))
2030 TrimmedValue = TrimmedValue.drop_back(2);
2031 }
2032 return TrimmedValue.equals(MacroText);
2033 } else {
2034 return false;
2035 }
2036 }
2037
2038 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002039 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2040 tok::kw_const) &&
2041 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002042}
2043
James Dennettf6333ac2012-06-22 05:46:07 +00002044/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00002045/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002046void Preprocessor::HandleDefineDirective(Token &DefineTok,
2047 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002048 ++NumDefined;
2049
2050 Token MacroNameTok;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002051 bool MacroShadowsKeyword;
2052 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
Mike Stump11289f42009-09-09 15:08:12 +00002053
Chris Lattnerf64b3522008-03-09 01:54:53 +00002054 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002055 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002056 return;
2057
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002058 Token LastTok = MacroNameTok;
2059
Chris Lattnerf64b3522008-03-09 01:54:53 +00002060 // If we are supposed to keep comments in #defines, reenable comment saving
2061 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00002062 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00002063
Chris Lattnerf64b3522008-03-09 01:54:53 +00002064 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002065 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002066
Chris Lattnerf64b3522008-03-09 01:54:53 +00002067 Token Tok;
2068 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002069
Chris Lattnerf64b3522008-03-09 01:54:53 +00002070 // If this is a function-like macro definition, parse the argument list,
2071 // marking each of the identifiers as being used as macro arguments. Also,
2072 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002073 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002074 if (ImmediatelyAfterHeaderGuard) {
2075 // Save this macro information since it may part of a header guard.
2076 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2077 MacroNameTok.getLocation());
2078 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002079 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002080 } else if (Tok.hasLeadingSpace()) {
2081 // This is a normal token with leading space. Clear the leading space
2082 // marker on the first token to get proper expansion.
2083 Tok.clearFlag(Token::LeadingSpace);
2084 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002085 // This is a function-like macro definition. Read the argument list.
2086 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002087 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002088 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002089 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002090 DiscardUntilEndOfDirective();
2091 return;
2092 }
2093
Chris Lattner249c38b2009-04-19 18:26:34 +00002094 // If this is a definition of a variadic C99 function-like macro, not using
2095 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00002096
Chris Lattner249c38b2009-04-19 18:26:34 +00002097 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2098 // This gets unpoisoned where it is allowed.
2099 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2100 if (MI->isC99Varargs())
2101 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00002102
Chris Lattnerf64b3522008-03-09 01:54:53 +00002103 // Read the first token after the arg list for down below.
2104 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002105 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002106 // C99 requires whitespace between the macro definition and the body. Emit
2107 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002108 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002109 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002110 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2111 // first character of a replacement list is not a character required by
2112 // subclause 5.2.1, then there shall be white-space separation between the
2113 // identifier and the replacement list.". 5.2.1 lists this set:
2114 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2115 // is irrelevant here.
2116 bool isInvalid = false;
2117 if (Tok.is(tok::at)) // @ is not in the list above.
2118 isInvalid = true;
2119 else if (Tok.is(tok::unknown)) {
2120 // If we have an unknown token, it is something strange like "`". Since
2121 // all of valid characters would have lexed into a single character
2122 // token of some sort, we know this is not a valid case.
2123 isInvalid = true;
2124 }
2125 if (isInvalid)
2126 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2127 else
2128 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002129 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002130
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002131 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002132 LastTok = Tok;
2133
Chris Lattnerf64b3522008-03-09 01:54:53 +00002134 // Read the rest of the macro body.
2135 if (MI->isObjectLike()) {
2136 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002137 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002138 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002139 MI->AddTokenToBody(Tok);
2140 // Get the next token of the macro.
2141 LexUnexpandedToken(Tok);
2142 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002143 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002144 // Otherwise, read the body of a function-like macro. While we are at it,
2145 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2146 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002147 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002148 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002149
Eli Friedman14d3c792012-11-14 02:18:46 +00002150 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002151 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002152
Chris Lattnerf64b3522008-03-09 01:54:53 +00002153 // Get the next token of the macro.
2154 LexUnexpandedToken(Tok);
2155 continue;
2156 }
Mike Stump11289f42009-09-09 15:08:12 +00002157
Richard Smith701a3522013-07-09 01:00:29 +00002158 // If we're in -traditional mode, then we should ignore stringification
2159 // and token pasting. Mark the tokens as unknown so as not to confuse
2160 // things.
2161 if (getLangOpts().TraditionalCPP) {
2162 Tok.setKind(tok::unknown);
2163 MI->AddTokenToBody(Tok);
2164
2165 // Get the next token of the macro.
2166 LexUnexpandedToken(Tok);
2167 continue;
2168 }
2169
Eli Friedman14d3c792012-11-14 02:18:46 +00002170 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002171 // If we see token pasting, check if it looks like the gcc comma
2172 // pasting extension. We'll use this information to suppress
2173 // diagnostics later on.
2174
2175 // Get the next token of the macro.
2176 LexUnexpandedToken(Tok);
2177
2178 if (Tok.is(tok::eod)) {
2179 MI->AddTokenToBody(LastTok);
2180 break;
2181 }
2182
2183 unsigned NumTokens = MI->getNumTokens();
2184 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2185 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2186 MI->setHasCommaPasting();
2187
David Majnemer76faf1f2013-11-05 09:30:17 +00002188 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002189 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002190 continue;
2191 }
2192
Chris Lattnerf64b3522008-03-09 01:54:53 +00002193 // Get the next token of the macro.
2194 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002195
Chris Lattner83bd8282009-05-25 17:16:10 +00002196 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002197 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002198 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2199
2200 // If this is assembler-with-cpp mode, we accept random gibberish after
2201 // the '#' because '#' is often a comment character. However, change
2202 // the kind of the token to tok::unknown so that the preprocessor isn't
2203 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002204 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002205 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002206 MI->AddTokenToBody(LastTok);
2207 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002208 } else {
2209 Diag(Tok, diag::err_pp_stringize_not_parameter);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattner83bd8282009-05-25 17:16:10 +00002211 // Disable __VA_ARGS__ again.
2212 Ident__VA_ARGS__->setIsPoisoned(true);
2213 return;
2214 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002215 }
Mike Stump11289f42009-09-09 15:08:12 +00002216
Chris Lattner83bd8282009-05-25 17:16:10 +00002217 // Things look ok, add the '#' and param name tokens to the macro.
2218 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002219 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002220 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002221
Chris Lattnerf64b3522008-03-09 01:54:53 +00002222 // Get the next token of the macro.
2223 LexUnexpandedToken(Tok);
2224 }
2225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
Serge Pavlov07c0f042014-12-18 11:14:21 +00002227 if (MacroShadowsKeyword &&
2228 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2229 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2230 }
Mike Stump11289f42009-09-09 15:08:12 +00002231
Chris Lattnerf64b3522008-03-09 01:54:53 +00002232 // Disable __VA_ARGS__ again.
2233 Ident__VA_ARGS__->setIsPoisoned(true);
2234
Chris Lattner57540c52011-04-15 05:22:18 +00002235 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002236 // replacement list.
2237 unsigned NumTokens = MI->getNumTokens();
2238 if (NumTokens != 0) {
2239 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2240 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002241 return;
2242 }
2243 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2244 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002245 return;
2246 }
2247 }
Mike Stump11289f42009-09-09 15:08:12 +00002248
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002249 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002250
Chris Lattnerf64b3522008-03-09 01:54:53 +00002251 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002252 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002253 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002254 // In Objective-C, ignore attempts to directly redefine the builtin
2255 // definitions of the ownership qualifiers. It's still possible to
2256 // #undef them.
2257 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2258 return II->isStr("__strong") ||
2259 II->isStr("__weak") ||
2260 II->isStr("__unsafe_unretained") ||
2261 II->isStr("__autoreleasing");
2262 };
2263 if (getLangOpts().ObjC1 &&
2264 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2265 == getPredefinesFileID() &&
2266 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2267 // Warn if it changes the tokens.
2268 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2269 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2270 !MI->isIdenticalTo(*OtherMI, *this,
2271 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2272 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2273 }
2274 assert(!OtherMI->isWarnIfUnused());
2275 return;
2276 }
2277
Chris Lattner5244f342009-01-16 19:50:11 +00002278 // It is very common for system headers to have tons of macro redefinitions
2279 // and for warnings to be disabled in system headers. If this is the case,
2280 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002281 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002282 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002283 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002284 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002285
Richard Smith7b242542013-03-06 00:46:00 +00002286 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2287 // C++ [cpp.predefined]p4, but allow it as an extension.
2288 if (OtherMI->isBuiltinMacro())
2289 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002290 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002291 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002292 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002293 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002294 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2295 << MacroNameTok.getIdentifierInfo();
2296 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2297 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002298 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002299 if (OtherMI->isWarnIfUnused())
2300 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002301 }
Mike Stump11289f42009-09-09 15:08:12 +00002302
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002303 DefMacroDirective *MD =
2304 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002305
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002306 assert(!MI->isUsed());
2307 // If we need warning for not using the macro, add its location in the
2308 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002309 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002310 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002311 MI->setIsWarnIfUnused(true);
2312 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2313 }
2314
Chris Lattner928e9092009-04-12 01:39:54 +00002315 // If the callbacks want to know, tell them about the macro definition.
2316 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002317 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002318}
2319
James Dennettf6333ac2012-06-22 05:46:07 +00002320/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002321///
2322void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2323 ++NumUndefined;
2324
2325 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002326 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002327
Chris Lattnerf64b3522008-03-09 01:54:53 +00002328 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002329 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002330 return;
Mike Stump11289f42009-09-09 15:08:12 +00002331
Chris Lattnerf64b3522008-03-09 01:54:53 +00002332 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002333 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002334
Richard Smith20e883e2015-04-29 23:20:19 +00002335 // Okay, we have a valid identifier to undef.
2336 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002337 auto MD = getMacroDefinition(II);
Mike Stump11289f42009-09-09 15:08:12 +00002338
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002339 // If the callbacks want to know, tell them about the macro #undef.
2340 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002341 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002342 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002343
Chris Lattnerf64b3522008-03-09 01:54:53 +00002344 // If the macro is not defined, this is a noop undef, just return.
Richard Smith36bd40d2015-05-04 03:15:40 +00002345 const MacroInfo *MI = MD.getMacroInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002346 if (!MI)
2347 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002348
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002349 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002350 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002351
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002352 if (MI->isWarnIfUnused())
2353 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2354
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002355 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2356 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002357}
2358
Chris Lattnerf64b3522008-03-09 01:54:53 +00002359//===----------------------------------------------------------------------===//
2360// Preprocessor Conditional Directive Handling.
2361//===----------------------------------------------------------------------===//
2362
James Dennettf6333ac2012-06-22 05:46:07 +00002363/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2364/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2365/// true if any tokens have been returned or pp-directives activated before this
2366/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002367///
2368void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2369 bool ReadAnyTokensBeforeDirective) {
2370 ++NumIf;
2371 Token DirectiveTok = Result;
2372
2373 Token MacroNameTok;
2374 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002375
Chris Lattnerf64b3522008-03-09 01:54:53 +00002376 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002377 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002378 // Skip code until we get to #endif. This helps with recovery by not
2379 // emitting an error when the #endif is reached.
2380 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2381 /*Foundnonskip*/false, /*FoundElse*/false);
2382 return;
2383 }
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattnerf64b3522008-03-09 01:54:53 +00002385 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002386 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002387
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002388 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002389 auto MD = getMacroDefinition(MII);
2390 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002391
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002392 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002393 // If the start of a top-level #ifdef and if the macro is not defined,
2394 // inform MIOpt that this might be the start of a proper include guard.
2395 // Otherwise it is some other form of unknown conditional which we can't
2396 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002397 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002398 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002399 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002400 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002401 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002402 }
2403
Chris Lattnerf64b3522008-03-09 01:54:53 +00002404 // If there is a macro, process it.
2405 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002406 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002407
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002408 if (Callbacks) {
2409 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002410 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002411 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002412 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002413 }
2414
Chris Lattnerf64b3522008-03-09 01:54:53 +00002415 // Should we include the stuff contained by this directive?
2416 if (!MI == isIfndef) {
2417 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002418 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2419 /*wasskip*/false, /*foundnonskip*/true,
2420 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002421 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002422 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002423 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002424 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002425 /*FoundElse*/false);
2426 }
2427}
2428
James Dennettf6333ac2012-06-22 05:46:07 +00002429/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002430///
2431void Preprocessor::HandleIfDirective(Token &IfToken,
2432 bool ReadAnyTokensBeforeDirective) {
2433 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002434
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002435 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002436 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002437 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2438 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2439 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002440
2441 // If this condition is equivalent to #ifndef X, and if this is the first
2442 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002443 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002444 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002445 // FIXME: Pass in the location of the macro name, not the 'if' token.
2446 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002447 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002448 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002449 }
2450
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002451 if (Callbacks)
2452 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002453 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002454 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002455
Chris Lattnerf64b3522008-03-09 01:54:53 +00002456 // Should we include the stuff contained by this directive?
2457 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002458 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002459 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002460 /*foundnonskip*/true, /*foundelse*/false);
2461 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002462 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002463 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002464 /*FoundElse*/false);
2465 }
2466}
2467
James Dennettf6333ac2012-06-22 05:46:07 +00002468/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002469///
2470void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2471 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002472
Chris Lattnerf64b3522008-03-09 01:54:53 +00002473 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002474 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002475
Chris Lattnerf64b3522008-03-09 01:54:53 +00002476 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002477 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002478 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002479 Diag(EndifToken, diag::err_pp_endif_without_if);
2480 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002481 }
Mike Stump11289f42009-09-09 15:08:12 +00002482
Chris Lattnerf64b3522008-03-09 01:54:53 +00002483 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002484 if (CurPPLexer->getConditionalStackDepth() == 0)
2485 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002486
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002487 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002488 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002489
2490 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002491 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002492}
2493
James Dennettf6333ac2012-06-22 05:46:07 +00002494/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002495///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002496void Preprocessor::HandleElseDirective(Token &Result) {
2497 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002498
Chris Lattnerf64b3522008-03-09 01:54:53 +00002499 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002500 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattnerf64b3522008-03-09 01:54:53 +00002502 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002503 if (CurPPLexer->popConditionalLevel(CI)) {
2504 Diag(Result, diag::pp_err_else_without_if);
2505 return;
2506 }
Mike Stump11289f42009-09-09 15:08:12 +00002507
Chris Lattnerf64b3522008-03-09 01:54:53 +00002508 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002509 if (CurPPLexer->getConditionalStackDepth() == 0)
2510 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002511
2512 // If this is a #else with a #else before it, report the error.
2513 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002514
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002515 if (Callbacks)
2516 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2517
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002518 // Finally, skip the rest of the contents of this block.
2519 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002520 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002521}
2522
James Dennettf6333ac2012-06-22 05:46:07 +00002523/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002524///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002525void Preprocessor::HandleElifDirective(Token &ElifToken) {
2526 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002527
Chris Lattnerf64b3522008-03-09 01:54:53 +00002528 // #elif directive in a non-skipping conditional... start skipping.
2529 // We don't care what the condition is, because we will always skip it (since
2530 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002531 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002532 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002533 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002534
2535 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002536 if (CurPPLexer->popConditionalLevel(CI)) {
2537 Diag(ElifToken, diag::pp_err_elif_without_if);
2538 return;
2539 }
Mike Stump11289f42009-09-09 15:08:12 +00002540
Chris Lattnerf64b3522008-03-09 01:54:53 +00002541 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002542 if (CurPPLexer->getConditionalStackDepth() == 0)
2543 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002544
Chris Lattnerf64b3522008-03-09 01:54:53 +00002545 // If this is a #elif with a #else before it, report the error.
2546 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002547
2548 if (Callbacks)
2549 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002550 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002551 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002552
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002553 // Finally, skip the rest of the contents of this block.
2554 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002555 /*FoundElse*/CI.FoundElse,
2556 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002557}