blob: 82f94d7da4ec270eb8b91639401b6011a97f3a06 [file] [log] [blame]
Chris Lattner89620152008-03-09 03:13:06 +00001//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
Chris Lattnerf64b3522008-03-09 01:54:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
James Dennettf6333ac2012-06-22 05:46:07 +00009///
10/// \file
11/// \brief Implements # directive processing for the Preprocessor.
12///
Chris Lattnerf64b3522008-03-09 01:54:53 +000013//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Chris Lattner710bb872009-11-30 04:18:44 +000016#include "clang/Basic/FileManager.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/CodeCompletionHandler.h"
19#include "clang/Lex/HeaderSearch.h"
Daniel Jasper07e6c402013-08-05 20:26:17 +000020#include "clang/Lex/HeaderSearchOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/LexDiagnostic.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Lex/MacroInfo.h"
24#include "clang/Lex/ModuleLoader.h"
25#include "clang/Lex/Pragma.h"
Chris Lattner100c65e2009-01-26 05:29:08 +000026#include "llvm/ADT/APInt.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000027#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000028#include "llvm/Support/Path.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000029#include "llvm/Support/SaveAndRestore.h"
Chris Lattnerf64b3522008-03-09 01:54:53 +000030using namespace clang;
31
32//===----------------------------------------------------------------------===//
33// Utility Methods for Preprocessor Directive Handling.
34//===----------------------------------------------------------------------===//
35
Chris Lattnerc0a585d2010-08-17 15:55:45 +000036MacroInfo *Preprocessor::AllocateMacroInfo() {
Richard Smithee0c4c12014-07-24 01:13:23 +000037 MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
Ted Kremenekc8456f82010-10-19 22:15:20 +000038 MIChain->Next = MIChainHead;
Ted Kremenekc8456f82010-10-19 22:15:20 +000039 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000040 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000041}
42
43MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
44 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000045 new (MI) MacroInfo(L);
46 return MI;
47}
48
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000049MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
50 unsigned SubModuleID) {
Chandler Carruth06dde922014-03-02 13:02:01 +000051 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
52 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000053 DeserializedMacroInfoChain *MIChain =
54 BP.Allocate<DeserializedMacroInfoChain>();
55 MIChain->Next = DeserialMIChainHead;
56 DeserialMIChainHead = MIChain;
57
58 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000059 new (MI) MacroInfo(L);
60 MI->FromASTFile = true;
61 MI->setOwningModuleID(SubModuleID);
62 return MI;
63}
64
Richard Smith50474bf2015-04-23 23:29:05 +000065DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
66 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000067 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000068}
69
70UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000071Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000072 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000073}
74
75VisibilityMacroDirective *
76Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
77 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000078 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000079}
80
James Dennettf6333ac2012-06-22 05:46:07 +000081/// \brief Read and discard all tokens remaining on the current line until
82/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000083void Preprocessor::DiscardUntilEndOfDirective() {
84 Token Tmp;
85 do {
86 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000087 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000088 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000089}
90
Serge Pavlov07c0f042014-12-18 11:14:21 +000091/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
92enum MacroDiag {
93 MD_NoWarn, //> Not a reserved identifier
94 MD_KeywordDef, //> Macro hides keyword, enabled by default
95 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
96};
97
98/// \brief Checks if the specified identifier is reserved in the specified
99/// language.
100/// This function does not check if the identifier is a keyword.
101static bool isReservedId(StringRef Text, const LangOptions &Lang) {
102 // C++ [macro.names], C11 7.1.3:
103 // All identifiers that begin with an underscore and either an uppercase
104 // letter or another underscore are always reserved for any use.
105 if (Text.size() >= 2 && Text[0] == '_' &&
106 (isUppercase(Text[1]) || Text[1] == '_'))
107 return true;
108 // C++ [global.names]
109 // Each name that contains a double underscore ... is reserved to the
110 // implementation for any use.
111 if (Lang.CPlusPlus) {
112 if (Text.find("__") != StringRef::npos)
113 return true;
114 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000115 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000116}
117
Serge Pavlov07c0f042014-12-18 11:14:21 +0000118static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
119 const LangOptions &Lang = PP.getLangOpts();
120 StringRef Text = II->getName();
121 if (isReservedId(Text, Lang))
122 return MD_ReservedMacro;
123 if (II->isKeyword(Lang))
124 return MD_KeywordDef;
125 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
126 return MD_KeywordDef;
127 return MD_NoWarn;
128}
129
130static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
131 const LangOptions &Lang = PP.getLangOpts();
132 StringRef Text = II->getName();
133 // Do not warn on keyword undef. It is generally harmless and widely used.
134 if (isReservedId(Text, Lang))
135 return MD_ReservedMacro;
136 return MD_NoWarn;
137}
138
139bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
140 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000141 // Missing macro name?
142 if (MacroNameTok.is(tok::eod))
143 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
144
145 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
146 if (!II) {
147 bool Invalid = false;
148 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
149 if (Invalid)
150 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000151 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000152
Alp Tokerf33619c2014-05-31 03:38:08 +0000153 if (!II->isCPlusPlusOperatorKeyword())
154 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000155
Alp Tokere03e9e12014-05-31 16:32:22 +0000156 // C++ 2.5p2: Alternative tokens behave the same as its primary token
157 // except for their spellings.
158 Diag(MacroNameTok, getLangOpts().MicrosoftExt
159 ? diag::ext_pp_operator_used_as_macro_name
160 : diag::err_pp_operator_used_as_macro_name)
161 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000162
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000163 // Allow #defining |and| and friends for Microsoft compatibility or
164 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000165 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000166 }
167
Serge Pavlovd024f522014-10-24 17:31:32 +0000168 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000169 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
170 return Diag(MacroNameTok, diag::err_defined_macro_name);
171 }
172
Richard Smith20e883e2015-04-29 23:20:19 +0000173 if (isDefineUndef == MU_Undef) {
174 auto *MI = getMacroInfo(II);
175 if (MI && MI->isBuiltinMacro()) {
176 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
177 // and C++ [cpp.predefined]p4], but allow it as an extension.
178 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
179 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000180 }
181
Serge Pavlov07c0f042014-12-18 11:14:21 +0000182 // If defining/undefining reserved identifier or a keyword, we need to issue
183 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000184 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000185 if (ShadowFlag)
186 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000187 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
188 (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000189 MacroDiag D = MD_NoWarn;
190 if (isDefineUndef == MU_Define) {
191 D = shouldWarnOnMacroDef(*this, II);
192 }
193 else if (isDefineUndef == MU_Undef)
194 D = shouldWarnOnMacroUndef(*this, II);
195 if (D == MD_KeywordDef) {
196 // We do not want to warn on some patterns widely used in configuration
197 // scripts. This requires analyzing next tokens, so do not issue warnings
198 // now, only inform caller.
199 if (ShadowFlag)
200 *ShadowFlag = true;
201 }
202 if (D == MD_ReservedMacro)
203 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000204 }
205
Alp Tokerb05e0b52014-05-21 06:13:51 +0000206 // Okay, we got a good identifier.
207 return false;
208}
209
James Dennettf6333ac2012-06-22 05:46:07 +0000210/// \brief Lex and validate a macro name, which occurs after a
211/// \#define or \#undef.
212///
Serge Pavlovd024f522014-10-24 17:31:32 +0000213/// This sets the token kind to eod and discards the rest of the macro line if
214/// the macro name is invalid.
215///
216/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000217/// \param isDefineUndef Context in which macro is used.
218/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
219void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
220 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000221 // Read the token, don't allow macro expansion on it.
222 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000223
Douglas Gregor12785102010-08-24 20:21:13 +0000224 if (MacroNameTok.is(tok::code_completion)) {
225 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000226 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000227 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000228 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000229 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000230
Serge Pavlov07c0f042014-12-18 11:14:21 +0000231 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000232 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000233
234 // Invalid macro name, read and discard the rest of the line and set the
235 // token kind to tok::eod if necessary.
236 if (MacroNameTok.isNot(tok::eod)) {
237 MacroNameTok.setKind(tok::eod);
238 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000239 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000240}
241
James Dennettf6333ac2012-06-22 05:46:07 +0000242/// \brief Ensure that the next token is a tok::eod token.
243///
244/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000245/// true, then we consider macros that expand to zero tokens as being ok.
246void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000247 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000248 // Lex unexpanded tokens for most directives: macros might expand to zero
249 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
250 // #line) allow empty macros.
251 if (EnableMacros)
252 Lex(Tmp);
253 else
254 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000255
Chris Lattnerf64b3522008-03-09 01:54:53 +0000256 // There should be no tokens after the directive, but we allow them as an
257 // extension.
258 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
259 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000260
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000261 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000262 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000263 // or if this is a macro-style preprocessing directive, because it is more
264 // trouble than it is worth to insert /**/ and check that there is no /**/
265 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000266 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000267 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000268 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000269 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
270 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000271 DiscardUntilEndOfDirective();
272 }
273}
274
275
276
James Dennettf6333ac2012-06-22 05:46:07 +0000277/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
278/// decided that the subsequent tokens are in the \#if'd out portion of the
279/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000280/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000281/// this \#if directive, so \#else/\#elif blocks should never be entered.
282/// If ElseOk is true, then \#else directives are ok, if not, then we have
283/// already seen one so a \#else directive is a duplicate. When this returns,
284/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000285void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
286 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000287 bool FoundElse,
288 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000289 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000290 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000291
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000292 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000293 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000294
Ted Kremenek56572ab2008-12-12 18:34:08 +0000295 if (CurPTHLexer) {
296 PTHSkipExcludedConditionalBlock();
297 return;
298 }
Mike Stump11289f42009-09-09 15:08:12 +0000299
Chris Lattnerf64b3522008-03-09 01:54:53 +0000300 // Enter raw mode to disable identifier lookup (and thus macro expansion),
301 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000302 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000303 Token Tok;
304 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000305 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000306
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000307 if (Tok.is(tok::code_completion)) {
308 if (CodeComplete)
309 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000310 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000311 continue;
312 }
313
Chris Lattnerf64b3522008-03-09 01:54:53 +0000314 // If this is the end of the buffer, we have an error.
315 if (Tok.is(tok::eof)) {
316 // Emit errors for each unterminated conditional on the stack, including
317 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000318 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000319 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000320 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
321 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000322 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000323 }
324
Chris Lattnerf64b3522008-03-09 01:54:53 +0000325 // Just return and let the caller lex after this #include.
326 break;
327 }
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattnerf64b3522008-03-09 01:54:53 +0000329 // If this token is not a preprocessor directive, just skip it.
330 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
331 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000332
Chris Lattnerf64b3522008-03-09 01:54:53 +0000333 // We just parsed a # character at the start of a line, so we're in
334 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000335 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000336 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000337 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000338
Mike Stump11289f42009-09-09 15:08:12 +0000339
Chris Lattnerf64b3522008-03-09 01:54:53 +0000340 // Read the next token, the directive flavor.
341 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000342
Chris Lattnerf64b3522008-03-09 01:54:53 +0000343 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
344 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000345 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000346 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000347 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000348 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000349 continue;
350 }
351
352 // If the first letter isn't i or e, it isn't intesting to us. We know that
353 // this is safe in the face of spelling differences, because there is no way
354 // to spell an i/e in a strange way that is another letter. Skipping this
355 // allows us to avoid looking up the identifier info for #define/#undef and
356 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000357 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000358
Alp Toker2d57cea2014-05-17 04:53:25 +0000359 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000360 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000361 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000362 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000363 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000364 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000365 continue;
366 }
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattnerf64b3522008-03-09 01:54:53 +0000368 // Get the identifier name without trigraphs or embedded newlines. Note
369 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
370 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000371 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000372 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000373 if (!Tok.needsCleaning() && RI.size() < 20) {
374 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000375 } else {
376 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000377 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000378 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000379 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000380 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000381 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000382 continue;
383 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000384 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000385 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000386 }
Mike Stump11289f42009-09-09 15:08:12 +0000387
Benjamin Kramer144884642009-12-31 13:32:38 +0000388 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000389 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000390 if (Sub.empty() || // "if"
391 Sub == "def" || // "ifdef"
392 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000393 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
394 // bother parsing the condition.
395 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000396 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000397 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000398 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000399 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000400 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000401 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000402 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000403 PPConditionalInfo CondInfo;
404 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000405 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000406 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000407 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattnerf64b3522008-03-09 01:54:53 +0000409 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000410 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000411 // Restore the value of LexingRawMode so that trailing comments
412 // are handled correctly, if we've reached the outermost block.
413 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000414 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000415 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000416 if (Callbacks)
417 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000418 break;
Richard Smithd0124572012-06-21 00:35:03 +0000419 } else {
420 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000421 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000422 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000423 // #else directive in a skipping conditional. If not in some other
424 // skipping conditional, and if #else hasn't already been seen, enter it
425 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000426 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000427
Chris Lattnerf64b3522008-03-09 01:54:53 +0000428 // If this is a #else with a #else before it, report the error.
429 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattnerf64b3522008-03-09 01:54:53 +0000431 // Note that we've seen a #else in this conditional.
432 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000433
Chris Lattnerf64b3522008-03-09 01:54:53 +0000434 // If the conditional is at the top level, and the #if block wasn't
435 // entered, enter the #else block now.
436 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
437 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000438 // Restore the value of LexingRawMode so that trailing comments
439 // are handled correctly.
440 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000441 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000442 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000443 if (Callbacks)
444 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000445 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000446 } else {
447 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000448 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000449 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000450 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000451
John Thompson17c35732013-12-04 20:19:30 +0000452 // If this is a #elif with a #else before it, report the error.
453 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
454
Chris Lattnerf64b3522008-03-09 01:54:53 +0000455 // If this is in a skipping block or if we're already handled this #if
456 // block, don't bother parsing the condition.
457 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
458 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000459 } else {
John Thompson17c35732013-12-04 20:19:30 +0000460 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000461 // Restore the value of LexingRawMode so that identifiers are
462 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000463 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
464 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000465 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000466 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000467 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000468 if (Callbacks) {
469 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000470 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000471 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000472 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000473 }
474 // If this condition is true, enter it!
475 if (CondValue) {
476 CondInfo.FoundNonSkip = true;
477 break;
478 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000479 }
480 }
481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000483 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000484 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000485 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000486 }
487
488 // Finally, if we are out of the conditional (saw an #endif or ran off the end
489 // of the file, just stop skipping and return to lexing whatever came after
490 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000491 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000492
493 if (Callbacks) {
494 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
495 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
496 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000497}
498
Ted Kremenek56572ab2008-12-12 18:34:08 +0000499void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000500
501 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000502 assert(CurPTHLexer);
503 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000504
Ted Kremenek56572ab2008-12-12 18:34:08 +0000505 // Skip to the next '#else', '#elif', or #endif.
506 if (CurPTHLexer->SkipBlock()) {
507 // We have reached an #endif. Both the '#' and 'endif' tokens
508 // have been consumed by the PTHLexer. Just pop off the condition level.
509 PPConditionalInfo CondInfo;
510 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000511 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000512 assert(!InCond && "Can't be skipping if not in a conditional!");
513 break;
514 }
Mike Stump11289f42009-09-09 15:08:12 +0000515
Ted Kremenek56572ab2008-12-12 18:34:08 +0000516 // We have reached a '#else' or '#elif'. Lex the next token to get
517 // the directive flavor.
518 Token Tok;
519 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000520
Ted Kremenek56572ab2008-12-12 18:34:08 +0000521 // We can actually look up the IdentifierInfo here since we aren't in
522 // raw mode.
523 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
524
525 if (K == tok::pp_else) {
526 // #else: Enter the else condition. We aren't in a nested condition
527 // since we skip those. We're always in the one matching the last
528 // blocked we skipped.
529 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
530 // Note that we've seen a #else in this conditional.
531 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000532
Ted Kremenek56572ab2008-12-12 18:34:08 +0000533 // If the #if block wasn't entered then enter the #else block now.
534 if (!CondInfo.FoundNonSkip) {
535 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000536
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000537 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000538 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000539 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000540 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000541
Ted Kremenek56572ab2008-12-12 18:34:08 +0000542 break;
543 }
Mike Stump11289f42009-09-09 15:08:12 +0000544
Ted Kremenek56572ab2008-12-12 18:34:08 +0000545 // Otherwise skip this block.
546 continue;
547 }
Mike Stump11289f42009-09-09 15:08:12 +0000548
Ted Kremenek56572ab2008-12-12 18:34:08 +0000549 assert(K == tok::pp_elif);
550 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
551
552 // If this is a #elif with a #else before it, report the error.
553 if (CondInfo.FoundElse)
554 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000555
Ted Kremenek56572ab2008-12-12 18:34:08 +0000556 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000557 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000558 if (CondInfo.FoundNonSkip)
559 continue;
560
561 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000562 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000563 CurPTHLexer->ParsingPreprocessorDirective = true;
564 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
565 CurPTHLexer->ParsingPreprocessorDirective = false;
566
567 // If this condition is true, enter it!
568 if (ShouldEnter) {
569 CondInfo.FoundNonSkip = true;
570 break;
571 }
572
573 // Otherwise, skip this block and go to the next one.
574 continue;
575 }
576}
577
Richard Smith2a553082015-04-23 22:58:06 +0000578Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000579 ModuleMap &ModMap = HeaderInfo.getModuleMap();
Richard Smith2a553082015-04-23 22:58:06 +0000580 if (SourceMgr.isInMainFile(Loc)) {
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000581 if (Module *CurMod = getCurrentModule())
582 return CurMod; // Compiling a module.
583 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
584 }
585 // Try to determine the module of the include directive.
Daniel Jasper88d86952013-12-03 20:30:36 +0000586 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
Richard Smith2a553082015-04-23 22:58:06 +0000587 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000588 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
589 // The include comes from a file.
590 return ModMap.findModuleForHeader(EntryOfIncl).getModule();
591 } else {
592 // The include does not come from a file,
593 // so it is probably a module compilation.
594 return getCurrentModule();
595 }
596}
597
Richard Smith2a553082015-04-23 22:58:06 +0000598Module *Preprocessor::getModuleContainingLocation(SourceLocation Loc) {
599 return HeaderInfo.getModuleMap().inferModuleFromLocation(
600 FullSourceLoc(Loc, SourceMgr));
601}
602
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000603const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000604 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000605 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000606 bool isAngled,
607 const DirectoryLookup *FromDir,
Richard Smith25d50752014-10-20 00:15:49 +0000608 const FileEntry *FromFile,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000609 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000610 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000611 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000612 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000613 bool SkipCache) {
Will Wilson0fafd342013-12-27 19:46:16 +0000614 // If the header lookup mechanism may be relative to the current inclusion
615 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000616 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
617 Includers;
Richard Smith25d50752014-10-20 00:15:49 +0000618 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000619 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000620 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000621
Chris Lattner022923a2009-02-04 19:45:07 +0000622 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000623 // predefines buffer or the module includes buffer. Any other file is not
624 // lexed with a normal lexer, so it won't be scanned for preprocessor
625 // directives.
626 //
627 // If we have the predefines buffer, resolve #include references (which come
628 // from the -include command line argument) from the current working
629 // directory instead of relative to the main file.
630 //
631 // If we have the module includes buffer, resolve #include references (which
632 // come from header declarations in the module map) relative to the module
633 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000634 if (!FileEnt) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000635 if (FID == SourceMgr.getMainFileID() && MainFileDir)
636 Includers.push_back(std::make_pair(nullptr, MainFileDir));
637 else if ((FileEnt =
638 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000639 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
640 } else {
641 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
642 }
Will Wilson0fafd342013-12-27 19:46:16 +0000643
644 // MSVC searches the current include stack from top to bottom for
645 // headers included by quoted include directives.
646 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000647 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000648 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
649 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
650 if (IsFileLexer(ISEntry))
651 if ((FileEnt = SourceMgr.getFileEntryForID(
652 ISEntry.ThePPLexer->getFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000653 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000654 }
Chris Lattner022923a2009-02-04 19:45:07 +0000655 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000656 }
Mike Stump11289f42009-09-09 15:08:12 +0000657
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000658 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000659
660 if (FromFile) {
661 // We're supposed to start looking from after a particular file. Search
662 // the include path until we find that file or run out of files.
663 const DirectoryLookup *TmpCurDir = CurDir;
664 const DirectoryLookup *TmpFromDir = nullptr;
665 while (const FileEntry *FE = HeaderInfo.LookupFile(
666 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
667 Includers, SearchPath, RelativePath, SuggestedModule,
668 SkipCache)) {
669 // Keep looking as if this file did a #include_next.
670 TmpFromDir = TmpCurDir;
671 ++TmpFromDir;
672 if (FE == FromFile) {
673 // Found it.
674 FromDir = TmpFromDir;
675 CurDir = TmpCurDir;
676 break;
677 }
678 }
679 }
680
681 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000682 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000683 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
684 RelativePath, SuggestedModule, SkipCache);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000685 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000686 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000687 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
688 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000689 return FE;
690 }
Mike Stump11289f42009-09-09 15:08:12 +0000691
Will Wilson0fafd342013-12-27 19:46:16 +0000692 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000693 // Otherwise, see if this is a subframework header. If so, this is relative
694 // to one of the headers on the #include stack. Walk the list of the current
695 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000696 if (IsFileLexer()) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000697 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000698 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000699 SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000700 SuggestedModule))) {
701 if (SuggestedModule && !LangOpts.AsmPreprocessor)
702 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
703 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000704 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000705 }
706 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000707 }
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000709 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
710 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000711 if (IsFileLexer(ISEntry)) {
Mike Stump11289f42009-09-09 15:08:12 +0000712 if ((CurFileEnt =
Ben Langmuir71e1a642014-05-05 21:44:13 +0000713 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000714 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000715 Filename, CurFileEnt, SearchPath, RelativePath,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000716 SuggestedModule))) {
717 if (SuggestedModule && !LangOpts.AsmPreprocessor)
718 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
719 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000720 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000721 }
722 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000723 }
724 }
Mike Stump11289f42009-09-09 15:08:12 +0000725
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000726 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000727 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000728}
729
Chris Lattnerf64b3522008-03-09 01:54:53 +0000730
731//===----------------------------------------------------------------------===//
732// Preprocessor Directive Handling.
733//===----------------------------------------------------------------------===//
734
David Blaikied5321242012-06-06 18:52:13 +0000735class Preprocessor::ResetMacroExpansionHelper {
736public:
737 ResetMacroExpansionHelper(Preprocessor *pp)
738 : PP(pp), save(pp->DisableMacroExpansion) {
739 if (pp->MacroExpansionInDirectivesOverride)
740 pp->DisableMacroExpansion = false;
741 }
742 ~ResetMacroExpansionHelper() {
743 PP->DisableMacroExpansion = save;
744 }
745private:
746 Preprocessor *PP;
747 bool save;
748};
749
Chris Lattnerf64b3522008-03-09 01:54:53 +0000750/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000751/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000752/// lexer/preprocessor state, and advances the lexer(s) so that the next token
753/// read is the correct one.
754void Preprocessor::HandleDirective(Token &Result) {
755 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000756
Chris Lattnerf64b3522008-03-09 01:54:53 +0000757 // We just parsed a # character at the start of a line, so we're in directive
758 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000759 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000760 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000761 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000762
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000763 bool ImmediatelyAfterTopLevelIfndef =
764 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
765 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
766
Chris Lattnerf64b3522008-03-09 01:54:53 +0000767 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000768
Chris Lattnerf64b3522008-03-09 01:54:53 +0000769 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000770 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000771 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000772 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000773
Chris Lattner2d17ab72009-03-18 21:00:25 +0000774 // Save the '#' token in case we need to return it later.
775 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000776
Chris Lattnerf64b3522008-03-09 01:54:53 +0000777 // Read the next token, the directive flavor. This isn't expanded due to
778 // C99 6.10.3p8.
779 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000780
Chris Lattnerf64b3522008-03-09 01:54:53 +0000781 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
782 // #define A(x) #x
783 // A(abc
784 // #warning blah
785 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000786 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
787 // not support this for #include-like directives, since that can result in
788 // terrible diagnostics, and does not work in GCC.
789 if (InMacroArgs) {
790 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
791 switch (II->getPPKeywordID()) {
792 case tok::pp_include:
793 case tok::pp_import:
794 case tok::pp_include_next:
795 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000796 case tok::pp_pragma:
797 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000798 DiscardUntilEndOfDirective();
799 return;
800 default:
801 break;
802 }
803 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000804 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000805 }
Mike Stump11289f42009-09-09 15:08:12 +0000806
David Blaikied5321242012-06-06 18:52:13 +0000807 // Temporarily enable macro expansion if set so
808 // and reset to previous state when returning from this function.
809 ResetMacroExpansionHelper helper(this);
810
Chris Lattnerf64b3522008-03-09 01:54:53 +0000811 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000812 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000813 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000814 case tok::code_completion:
815 if (CodeComplete)
816 CodeComplete->CodeCompleteDirective(
817 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000818 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000819 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000820 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000821 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000822 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000823 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000824 default:
825 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000826 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000827
Chris Lattnerf64b3522008-03-09 01:54:53 +0000828 // Ask what the preprocessor keyword ID is.
829 switch (II->getPPKeywordID()) {
830 default: break;
831 // C99 6.10.1 - Conditional Inclusion.
832 case tok::pp_if:
833 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
834 case tok::pp_ifdef:
835 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
836 case tok::pp_ifndef:
837 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
838 case tok::pp_elif:
839 return HandleElifDirective(Result);
840 case tok::pp_else:
841 return HandleElseDirective(Result);
842 case tok::pp_endif:
843 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000844
Chris Lattnerf64b3522008-03-09 01:54:53 +0000845 // C99 6.10.2 - Source File Inclusion.
846 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000847 // Handle #include.
848 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000849 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000850 // Handle -imacros.
851 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chris Lattnerf64b3522008-03-09 01:54:53 +0000853 // C99 6.10.3 - Macro Replacement.
854 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000855 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000856 case tok::pp_undef:
857 return HandleUndefDirective(Result);
858
859 // C99 6.10.4 - Line Control.
860 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +0000861 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000862
Chris Lattnerf64b3522008-03-09 01:54:53 +0000863 // C99 6.10.5 - Error Directive.
864 case tok::pp_error:
865 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +0000866
Chris Lattnerf64b3522008-03-09 01:54:53 +0000867 // C99 6.10.6 - Pragma Directive.
868 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000869 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +0000870
Chris Lattnerf64b3522008-03-09 01:54:53 +0000871 // GNU Extensions.
872 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000873 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000874 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000875 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000876
Chris Lattnerf64b3522008-03-09 01:54:53 +0000877 case tok::pp_warning:
878 Diag(Result, diag::ext_pp_warning_directive);
879 return HandleUserDiagnosticDirective(Result, true);
880 case tok::pp_ident:
881 return HandleIdentSCCSDirective(Result);
882 case tok::pp_sccs:
883 return HandleIdentSCCSDirective(Result);
884 case tok::pp_assert:
885 //isExtension = true; // FIXME: implement #assert
886 break;
887 case tok::pp_unassert:
888 //isExtension = true; // FIXME: implement #unassert
889 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000890
Douglas Gregor663b48f2012-01-03 19:48:16 +0000891 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000892 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000893 return HandleMacroPublicDirective(Result);
894 break;
895
Douglas Gregor663b48f2012-01-03 19:48:16 +0000896 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +0000897 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +0000898 return HandleMacroPrivateDirective(Result);
899 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000900 }
901 break;
902 }
Mike Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattner2d17ab72009-03-18 21:00:25 +0000904 // If this is a .S file, treat unknown # directives as non-preprocessor
905 // directives. This is important because # may be a comment or introduce
906 // various pseudo-ops. Just return the # token and push back the following
907 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000908 if (getLangOpts().AsmPreprocessor) {
Daniel Dunbar48b4d1e2009-07-13 21:48:50 +0000909 Token *Toks = new Token[2];
Chris Lattner2d17ab72009-03-18 21:00:25 +0000910 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +0000911 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +0000912 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +0000913
914 // If the second token is a hashhash token, then we need to translate it to
915 // unknown so the token lexer doesn't try to perform token pasting.
916 if (Result.is(tok::hashhash))
917 Toks[1].setKind(tok::unknown);
918
Chris Lattner2d17ab72009-03-18 21:00:25 +0000919 // Enter this token stream so that we re-lex the tokens. Make sure to
920 // enable macro expansion, in case the token after the # is an identifier
921 // that is expanded.
922 EnterTokenStream(Toks, 2, false, true);
923 return;
924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
Chris Lattnerf64b3522008-03-09 01:54:53 +0000926 // If we reached here, the preprocessing token is not valid!
927 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +0000928
Chris Lattnerf64b3522008-03-09 01:54:53 +0000929 // Read the rest of the PP line.
930 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +0000931
Chris Lattnerf64b3522008-03-09 01:54:53 +0000932 // Okay, we're done parsing the directive.
933}
934
Chris Lattner76e68962009-01-26 06:19:46 +0000935/// GetLineValue - Convert a numeric token into an unsigned value, emitting
936/// Diagnostic DiagID if it is invalid, and returning the value in Val.
937static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +0000938 unsigned DiagID, Preprocessor &PP,
939 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +0000940 if (DigitTok.isNot(tok::numeric_constant)) {
941 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000943 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +0000944 PP.DiscardUntilEndOfDirective();
945 return true;
946 }
Mike Stump11289f42009-09-09 15:08:12 +0000947
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000948 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +0000949 IntegerBuffer.resize(DigitTok.getLength());
950 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +0000951 bool Invalid = false;
952 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
953 if (Invalid)
954 return true;
955
Chris Lattnerd66f1722009-04-18 18:35:15 +0000956 // Verify that we have a simple digit-sequence, and compute the value. This
957 // is always a simple digit string computed in decimal, so we do this manually
958 // here.
959 Val = 0;
960 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +0000961 // C++1y [lex.fcon]p1:
962 // Optional separating single quotes in a digit-sequence are ignored
963 if (DigitTokBegin[i] == '\'')
964 continue;
965
Jordan Rosea7d03842013-02-08 22:30:41 +0000966 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +0000967 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +0000968 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +0000969 PP.DiscardUntilEndOfDirective();
970 return true;
971 }
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattnerd66f1722009-04-18 18:35:15 +0000973 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
974 if (NextVal < Val) { // overflow.
975 PP.Diag(DigitTok, DiagID);
976 PP.DiscardUntilEndOfDirective();
977 return true;
978 }
979 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +0000980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981
Fariborz Jahanian0638c152012-06-26 21:19:20 +0000982 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +0000983 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
984 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +0000985
Chris Lattner76e68962009-01-26 06:19:46 +0000986 return false;
987}
988
James Dennettf6333ac2012-06-22 05:46:07 +0000989/// \brief Handle a \#line directive: C99 6.10.4.
990///
991/// The two acceptable forms are:
992/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000993/// # line digit-sequence
994/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +0000995/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +0000996void Preprocessor::HandleLineDirective(Token &Tok) {
997 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
998 // expanded.
999 Token DigitTok;
1000 Lex(DigitTok);
1001
Chris Lattner100c65e2009-01-26 05:29:08 +00001002 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001003 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001004 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001005 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001006
1007 if (LineNo == 0)
1008 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001009
Chris Lattner76e68962009-01-26 06:19:46 +00001010 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1011 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001012 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001013 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001014 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001015 if (LineNo >= LineLimit)
1016 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001017 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001018 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001019
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001020 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001021 Token StrTok;
1022 Lex(StrTok);
1023
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001024 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1025 // string followed by eod.
1026 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001027 ; // ok
1028 else if (StrTok.isNot(tok::string_literal)) {
1029 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001030 return DiscardUntilEndOfDirective();
1031 } else if (StrTok.hasUDSuffix()) {
1032 Diag(StrTok, diag::err_invalid_string_udl);
1033 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001034 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001035 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001036 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001037 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001038 if (Literal.hadError)
1039 return DiscardUntilEndOfDirective();
1040 if (Literal.Pascal) {
1041 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1042 return DiscardUntilEndOfDirective();
1043 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001044 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001045
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001046 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001047 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1048 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001049 }
Mike Stump11289f42009-09-09 15:08:12 +00001050
Chris Lattner1eaa70a2009-02-03 21:52:55 +00001051 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chris Lattner839150e2009-03-27 17:13:49 +00001053 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001054 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1055 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +00001056 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +00001057}
1058
Chris Lattner76e68962009-01-26 06:19:46 +00001059/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1060/// marker directive.
1061static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1062 bool &IsSystemHeader, bool &IsExternCHeader,
1063 Preprocessor &PP) {
1064 unsigned FlagVal;
1065 Token FlagTok;
1066 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001067 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001068 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1069 return true;
1070
1071 if (FlagVal == 1) {
1072 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattner76e68962009-01-26 06:19:46 +00001074 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001075 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001076 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1077 return true;
1078 } else if (FlagVal == 2) {
1079 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001080
Chris Lattner1c967782009-02-04 06:25:26 +00001081 SourceManager &SM = PP.getSourceManager();
1082 // If we are leaving the current presumed file, check to make sure the
1083 // presumed include stack isn't empty!
1084 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001085 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001086 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001087 if (PLoc.isInvalid())
1088 return true;
1089
Chris Lattner1c967782009-02-04 06:25:26 +00001090 // If there is no include loc (main file) or if the include loc is in a
1091 // different physical file, then we aren't in a "1" line marker flag region.
1092 SourceLocation IncLoc = PLoc.getIncludeLoc();
1093 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001094 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001095 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1096 PP.DiscardUntilEndOfDirective();
1097 return true;
1098 }
Mike Stump11289f42009-09-09 15:08:12 +00001099
Chris Lattner76e68962009-01-26 06:19:46 +00001100 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001101 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001102 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1103 return true;
1104 }
1105
1106 // We must have 3 if there are still flags.
1107 if (FlagVal != 3) {
1108 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001109 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001110 return true;
1111 }
Mike Stump11289f42009-09-09 15:08:12 +00001112
Chris Lattner76e68962009-01-26 06:19:46 +00001113 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001114
Chris Lattner76e68962009-01-26 06:19:46 +00001115 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001116 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001117 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001118 return true;
1119
1120 // We must have 4 if there is yet another flag.
1121 if (FlagVal != 4) {
1122 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001123 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001124 return true;
1125 }
Mike Stump11289f42009-09-09 15:08:12 +00001126
Chris Lattner76e68962009-01-26 06:19:46 +00001127 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001128
Chris Lattner76e68962009-01-26 06:19:46 +00001129 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001130 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001131
1132 // There are no more valid flags here.
1133 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001134 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001135 return true;
1136}
1137
1138/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1139/// one of the following forms:
1140///
1141/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001142/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001143/// # 42 "file" ('1' | '2')? '3' '4'?
1144///
1145void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1146 // Validate the number and convert it to an unsigned. GNU does not have a
1147 // line # limit other than it fit in 32-bits.
1148 unsigned LineNo;
1149 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001150 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001151 return;
Mike Stump11289f42009-09-09 15:08:12 +00001152
Chris Lattner76e68962009-01-26 06:19:46 +00001153 Token StrTok;
1154 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001155
Chris Lattner76e68962009-01-26 06:19:46 +00001156 bool IsFileEntry = false, IsFileExit = false;
1157 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001158 int FilenameID = -1;
1159
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001160 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1161 // string followed by eod.
1162 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001163 ; // ok
1164 else if (StrTok.isNot(tok::string_literal)) {
1165 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001166 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001167 } else if (StrTok.hasUDSuffix()) {
1168 Diag(StrTok, diag::err_invalid_string_udl);
1169 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001170 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001171 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001172 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001173 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001174 if (Literal.hadError)
1175 return DiscardUntilEndOfDirective();
1176 if (Literal.Pascal) {
1177 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1178 return DiscardUntilEndOfDirective();
1179 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001180 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001181
Chris Lattner76e68962009-01-26 06:19:46 +00001182 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001183 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001184 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001185 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001186 }
Mike Stump11289f42009-09-09 15:08:12 +00001187
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001188 // Create a line note with this information.
1189 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001190 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001191 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001192
Chris Lattner839150e2009-03-27 17:13:49 +00001193 // If the preprocessor has callbacks installed, notify them of the #line
1194 // change. This is used so that the line marker comes out in -E mode for
1195 // example.
1196 if (Callbacks) {
1197 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1198 if (IsFileEntry)
1199 Reason = PPCallbacks::EnterFile;
1200 else if (IsFileExit)
1201 Reason = PPCallbacks::ExitFile;
1202 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1203 if (IsExternCHeader)
1204 FileKind = SrcMgr::C_ExternCSystem;
1205 else if (IsSystemHeader)
1206 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001207
Chris Lattnerc745cec2010-04-14 04:28:50 +00001208 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001209 }
Chris Lattner76e68962009-01-26 06:19:46 +00001210}
1211
1212
Chris Lattner38d7fd22009-01-26 05:30:54 +00001213/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1214///
Mike Stump11289f42009-09-09 15:08:12 +00001215void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001216 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001217 // PTH doesn't emit #warning or #error directives.
1218 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001219 return CurPTHLexer->DiscardToEndOfLine();
1220
Chris Lattnerf64b3522008-03-09 01:54:53 +00001221 // Read the rest of the line raw. We do this because we don't want macros
1222 // to be expanded and we don't require that the tokens be valid preprocessing
1223 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1224 // collapse multiple consequtive white space between tokens, but this isn't
1225 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001226 SmallString<128> Message;
1227 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001228
1229 // Find the first non-whitespace character, so that we can make the
1230 // diagnostic more succinct.
Yaron Keren92e1b622015-03-18 10:17:07 +00001231 StringRef Msg = StringRef(Message).ltrim(" ");
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001232
Chris Lattner100c65e2009-01-26 05:29:08 +00001233 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001234 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001235 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001236 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001237}
1238
1239/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1240///
1241void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1242 // Yes, this directive is an extension.
1243 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001244
Chris Lattnerf64b3522008-03-09 01:54:53 +00001245 // Read the string argument.
1246 Token StrTok;
1247 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001248
Chris Lattnerf64b3522008-03-09 01:54:53 +00001249 // If the token kind isn't a string, it's a malformed directive.
1250 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001251 StrTok.isNot(tok::wide_string_literal)) {
1252 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001253 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001254 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001255 return;
1256 }
Mike Stump11289f42009-09-09 15:08:12 +00001257
Richard Smithd67aea22012-03-06 03:21:47 +00001258 if (StrTok.hasUDSuffix()) {
1259 Diag(StrTok, diag::err_invalid_string_udl);
1260 return DiscardUntilEndOfDirective();
1261 }
1262
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001263 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001264 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001265
Douglas Gregordc970f02010-03-16 22:30:13 +00001266 if (Callbacks) {
1267 bool Invalid = false;
1268 std::string Str = getSpelling(StrTok, &Invalid);
1269 if (!Invalid)
1270 Callbacks->Ident(Tok.getLocation(), Str);
1271 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001272}
1273
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001274/// \brief Handle a #public directive.
1275void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001276 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001277 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001278
1279 // Error reading macro name? If so, diagnostic already issued.
1280 if (MacroNameTok.is(tok::eod))
1281 return;
1282
Douglas Gregor663b48f2012-01-03 19:48:16 +00001283 // Check to see if this is the last token on the #__public_macro line.
1284 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001285
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001286 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001287 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001288 MacroDirective *MD = getLocalMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001289
1290 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001291 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001292 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001293 return;
1294 }
1295
1296 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001297 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1298 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001299}
1300
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001301/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001302void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1303 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001304 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregorebf00492011-10-17 15:32:29 +00001305
1306 // Error reading macro name? If so, diagnostic already issued.
1307 if (MacroNameTok.is(tok::eod))
1308 return;
1309
Douglas Gregor663b48f2012-01-03 19:48:16 +00001310 // Check to see if this is the last token on the #__private_macro line.
1311 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001312
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001313 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001314 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001315 MacroDirective *MD = getLocalMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001316
1317 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001318 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001319 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001320 return;
1321 }
1322
1323 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001324 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1325 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001326}
1327
Chris Lattnerf64b3522008-03-09 01:54:53 +00001328//===----------------------------------------------------------------------===//
1329// Preprocessor Include Directive Handling.
1330//===----------------------------------------------------------------------===//
1331
1332/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001333/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001334/// true if the input filename was in <>'s or false if it were in ""'s. The
1335/// caller is expected to provide a buffer that is large enough to hold the
1336/// spelling of the filename, but is also expected to handle the case when
1337/// this method decides to use a different buffer.
1338bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001339 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001340 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001341 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001342
Chris Lattnerf64b3522008-03-09 01:54:53 +00001343 // Make sure the filename is <x> or "x".
1344 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001345 if (Buffer[0] == '<') {
1346 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001347 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001348 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001349 return true;
1350 }
1351 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001352 } else if (Buffer[0] == '"') {
1353 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001354 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001355 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001356 return true;
1357 }
1358 isAngled = false;
1359 } else {
1360 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001361 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001362 return true;
1363 }
Mike Stump11289f42009-09-09 15:08:12 +00001364
Chris Lattnerf64b3522008-03-09 01:54:53 +00001365 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001366 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001367 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001368 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001369 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001370 }
Mike Stump11289f42009-09-09 15:08:12 +00001371
Chris Lattnerf64b3522008-03-09 01:54:53 +00001372 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001373 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001374 return isAngled;
1375}
1376
James Dennett4a4f72d2013-11-27 01:27:40 +00001377// \brief Handle cases where the \#include name is expanded from a macro
1378// as multiple tokens, which need to be glued together.
1379//
1380// This occurs for code like:
1381// \code
1382// \#define FOO <a/b.h>
1383// \#include FOO
1384// \endcode
1385// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1386//
1387// This code concatenates and consumes tokens up to the '>' token. It returns
1388// false if the > was found, otherwise it returns true if it finds and consumes
1389// the EOD marker.
1390bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001391 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001392 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001393
John Thompsonb5353522009-10-30 13:49:06 +00001394 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001395 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001396 End = CurTok.getLocation();
1397
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001398 // FIXME: Provide code completion for #includes.
1399 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001400 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001401 Lex(CurTok);
1402 continue;
1403 }
1404
Chris Lattnerf64b3522008-03-09 01:54:53 +00001405 // Append the spelling of this token to the buffer. If there was a space
1406 // before it, add it now.
1407 if (CurTok.hasLeadingSpace())
1408 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001409
Chris Lattnerf64b3522008-03-09 01:54:53 +00001410 // Get the spelling of the token, directly into FilenameBuffer if possible.
1411 unsigned PreAppendSize = FilenameBuffer.size();
1412 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001413
Chris Lattnerf64b3522008-03-09 01:54:53 +00001414 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001415 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001416
Chris Lattnerf64b3522008-03-09 01:54:53 +00001417 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1418 if (BufPtr != &FilenameBuffer[PreAppendSize])
1419 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001420
Chris Lattnerf64b3522008-03-09 01:54:53 +00001421 // Resize FilenameBuffer to the correct size.
1422 if (CurTok.getLength() != ActualLen)
1423 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001424
Chris Lattnerf64b3522008-03-09 01:54:53 +00001425 // If we found the '>' marker, return success.
1426 if (CurTok.is(tok::greater))
1427 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001428
John Thompsonb5353522009-10-30 13:49:06 +00001429 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001430 }
1431
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001432 // If we hit the eod marker, emit an error and return true so that the caller
1433 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001434 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001435 return true;
1436}
1437
Richard Smith34f30512013-11-23 04:06:09 +00001438/// \brief Push a token onto the token stream containing an annotation.
1439static void EnterAnnotationToken(Preprocessor &PP,
1440 SourceLocation Begin, SourceLocation End,
1441 tok::TokenKind Kind, void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001442 // FIXME: Produce this as the current token directly, rather than
1443 // allocating a new token for it.
Richard Smith34f30512013-11-23 04:06:09 +00001444 Token *Tok = new Token[1];
1445 Tok[0].startToken();
1446 Tok[0].setKind(Kind);
1447 Tok[0].setLocation(Begin);
1448 Tok[0].setAnnotationEndLoc(End);
1449 Tok[0].setAnnotationValue(AnnotationVal);
1450 PP.EnterTokenStream(Tok, 1, true, true);
1451}
1452
Richard Smith63b6fce2015-05-18 04:45:41 +00001453/// \brief Produce a diagnostic informing the user that a #include or similar
1454/// was implicitly treated as a module import.
1455static void diagnoseAutoModuleImport(
1456 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1457 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1458 SourceLocation PathEnd) {
1459 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1460
1461 SmallString<128> PathString;
1462 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1463 if (I)
1464 PathString += '.';
1465 PathString += Path[I].first->getName();
1466 }
1467 int IncludeKind = 0;
1468
1469 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1470 case tok::pp_include:
1471 IncludeKind = 0;
1472 break;
1473
1474 case tok::pp_import:
1475 IncludeKind = 1;
1476 break;
1477
1478 case tok::pp_include_next:
1479 IncludeKind = 2;
1480 break;
1481
1482 case tok::pp___include_macros:
1483 IncludeKind = 3;
1484 break;
1485
1486 default:
1487 llvm_unreachable("unknown include directive kind");
1488 }
1489
1490 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1491 /*IsTokenRange=*/false);
1492 PP.Diag(HashLoc, diag::warn_auto_module_import)
1493 << IncludeKind << PathString
1494 << FixItHint::CreateReplacement(ReplaceRange,
1495 ("@import " + PathString + ";").str());
1496}
1497
James Dennettf6333ac2012-06-22 05:46:07 +00001498/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1499/// the file to be included from the lexer, then include it! This is a common
1500/// routine with functionality shared between \#include, \#include_next and
1501/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001502/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001503void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1504 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001505 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001506 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001507 bool isImport) {
1508
1509 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001510 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001511
Chris Lattnerf64b3522008-03-09 01:54:53 +00001512 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001513 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001514 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001515 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001516 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001517
Chris Lattnerf64b3522008-03-09 01:54:53 +00001518 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001519 case tok::eod:
1520 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001521 return;
Mike Stump11289f42009-09-09 15:08:12 +00001522
Chris Lattnerf64b3522008-03-09 01:54:53 +00001523 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001524 case tok::string_literal:
1525 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001526 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001527 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001528 break;
Mike Stump11289f42009-09-09 15:08:12 +00001529
Chris Lattnerf64b3522008-03-09 01:54:53 +00001530 case tok::less:
1531 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1532 // case, glue the tokens together into FilenameBuffer and interpret those.
1533 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001534 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001535 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001536 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001537 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001538 break;
1539 default:
1540 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1541 DiscardUntilEndOfDirective();
1542 return;
1543 }
Mike Stump11289f42009-09-09 15:08:12 +00001544
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001545 CharSourceRange FilenameRange
1546 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001547 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001548 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001549 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001550 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1551 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001552 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001553 DiscardUntilEndOfDirective();
1554 return;
1555 }
Mike Stump11289f42009-09-09 15:08:12 +00001556
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001557 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001558 // we allow macros that expand to nothing after the filename, because this
1559 // falls into the category of "#include pp-tokens new-line" specified in
1560 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001561 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001562
1563 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001564 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1565 Diag(FilenameTok, diag::err_pp_include_too_deep);
1566 return;
1567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
John McCall32f5fe12011-09-30 05:12:12 +00001569 // Complain about attempts to #include files in an audit pragma.
1570 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1571 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1572 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1573
1574 // Immediately leave the pragma.
1575 PragmaARCCFCodeAuditedLoc = SourceLocation();
1576 }
1577
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001578 // Complain about attempts to #include files in an assume-nonnull pragma.
1579 if (PragmaAssumeNonNullLoc.isValid()) {
1580 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1581 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1582
1583 // Immediately leave the pragma.
1584 PragmaAssumeNonNullLoc = SourceLocation();
1585 }
1586
Aaron Ballman611306e2012-03-02 22:51:54 +00001587 if (HeaderInfo.HasIncludeAliasMap()) {
1588 // Map the filename with the brackets still attached. If the name doesn't
1589 // map to anything, fall back on the filename we've already gotten the
1590 // spelling for.
1591 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1592 if (!NewName.empty())
1593 Filename = NewName;
1594 }
1595
Chris Lattnerf64b3522008-03-09 01:54:53 +00001596 // Search include directories.
1597 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001598 SmallString<1024> SearchPath;
1599 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001600 // We get the raw path only if we have 'Callbacks' to which we later pass
1601 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001602 ModuleMap::KnownHeader SuggestedModule;
1603 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001604 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001605 if (LangOpts.MSVCCompat) {
1606 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001607#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001608 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001609#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001610 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001611 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001612 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001613 isAngled, LookupFrom, LookupFromFile, CurDir,
1614 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001615 &SuggestedModule);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001616
Richard Smithdbbc5232015-05-14 02:25:44 +00001617 if (!File) {
1618 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001619 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001620 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001621 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1622 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1623 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001624 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001625 HeaderInfo.AddSearchPath(DL, isAngled);
1626
1627 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001628 File = LookupFile(
1629 FilenameLoc,
1630 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1631 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001632 &SuggestedModule, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001633 }
1634 }
1635 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001636
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001637 if (!SuppressIncludeNotFoundError) {
1638 // If the file could not be located and it was included via angle
1639 // brackets, we can attempt a lookup as though it were a quoted path to
1640 // provide the user with a possible fixit.
1641 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001642 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001643 FilenameLoc,
1644 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1645 LookupFrom, LookupFromFile, CurDir,
1646 Callbacks ? &SearchPath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001647 Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001648 &SuggestedModule);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001649 if (File) {
1650 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1651 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1652 Filename <<
1653 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1654 }
1655 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001656
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001657 // If the file is still not found, just go with the vanilla diagnostic
1658 if (!File)
1659 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1660 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001661 }
1662
Richard Smith63b6fce2015-05-18 04:45:41 +00001663 // Should we enter the source file? Set to false if either the source file is
1664 // known to have no effect beyond its effect on module visibility -- that is,
1665 // if it's got an include guard that is already defined or is a modular header
1666 // we've imported or already built.
1667 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001668
Richard Smith63b6fce2015-05-18 04:45:41 +00001669 // Determine whether we should try to import the module for this #include, if
1670 // there is one. Don't do so if precompiled module support is disabled or we
1671 // are processing this module textually (because we're building the module).
1672 if (File && SuggestedModule && getLangOpts().Modules &&
1673 SuggestedModule.getModule()->getTopLevelModuleName() !=
1674 getLangOpts().CurrentModule &&
1675 SuggestedModule.getModule()->getTopLevelModuleName() !=
1676 getLangOpts().ImplementationOfModule) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001677
1678 // If this include corresponds to a module but that module is
1679 // unavailable, diagnose the situation and bail out.
1680 if (!SuggestedModule.getModule()->isAvailable()) {
1681 clang::Module::Requirement Requirement;
1682 clang::Module::UnresolvedHeaderDirective MissingHeader;
1683 Module *M = SuggestedModule.getModule();
1684 // Identify the cause.
1685 (void)M->isAvailable(getLangOpts(), getTargetInfo(), Requirement,
1686 MissingHeader);
1687 if (MissingHeader.FileNameLoc.isValid()) {
1688 Diag(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1689 << MissingHeader.IsUmbrella << MissingHeader.FileName;
1690 } else {
1691 Diag(M->DefinitionLoc, diag::err_module_unavailable)
1692 << M->getFullModuleName() << Requirement.second << Requirement.first;
1693 }
1694 Diag(FilenameTok.getLocation(),
1695 diag::note_implicit_top_level_module_import_here)
1696 << M->getTopLevelModuleName();
1697 return;
1698 }
1699
Douglas Gregor71944202011-11-30 00:36:36 +00001700 // Compute the module access path corresponding to this module.
1701 // FIXME: Should we have a second loadModule() overload to avoid this
1702 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001703 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001704 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001705 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1706 FilenameTok.getLocation()));
1707 std::reverse(Path.begin(), Path.end());
1708
Douglas Gregor41e115a2011-11-30 18:02:36 +00001709 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001710 // We only do this in Objective-C, where we have a module-import syntax.
1711 if (getLangOpts().ObjC2)
1712 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Douglas Gregor41e115a2011-11-30 18:02:36 +00001713
Richard Smith10434f32015-05-02 02:08:26 +00001714 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001715 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001716 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1717 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001718 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1719 IncludeTok.getLocation(), Path, Module::Hidden,
1720 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001721 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001722 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001723
Richard Smith63b6fce2015-05-18 04:45:41 +00001724 if (Imported)
1725 ShouldEnter = false;
1726 else if (Imported.isMissingExpected()) {
1727 // We failed to find a submodule that we assumed would exist (because it
1728 // was in the directory of an umbrella header, for instance), but no
1729 // actual module exists for it (because the umbrella header is
1730 // incomplete). Treat this as a textual inclusion.
1731 SuggestedModule = ModuleMap::KnownHeader();
1732 } else {
1733 // We hit an error processing the import. Bail out.
1734 if (hadModuleLoaderFatalFailure()) {
1735 // With a fatal failure in the module loader, we abort parsing.
1736 Token &Result = IncludeTok;
1737 if (CurLexer) {
1738 Result.startToken();
1739 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1740 CurLexer->cutOffLexing();
1741 } else {
1742 assert(CurPTHLexer && "#include but no current lexer set!");
1743 CurPTHLexer->getEOF(Result);
1744 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001745 }
1746 return;
1747 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001748 }
1749
Richard Smith63b6fce2015-05-18 04:45:41 +00001750 if (Callbacks) {
1751 // Notify the callback object that we've seen an inclusion directive.
1752 Callbacks->InclusionDirective(
1753 HashLoc, IncludeTok,
1754 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1755 FilenameRange, File, SearchPath, RelativePath,
1756 ShouldEnter ? nullptr : SuggestedModule.getModule());
Douglas Gregor97eec242011-09-15 22:00:41 +00001757 }
Richard Smith63b6fce2015-05-18 04:45:41 +00001758
1759 if (!File)
1760 return;
Douglas Gregor97eec242011-09-15 22:00:41 +00001761
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001762 // The #included file will be considered to be a system header if either it is
1763 // in a system include directory, or if the #includer is a system include
1764 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001765 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001766 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001767 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001768
Richard Smith54ef4c32015-05-19 19:58:11 +00001769 // FIXME: If we have a suggested module, and we've already visited this file,
1770 // don't bother entering it again. We know it has no further effect.
1771
Chris Lattner72286d62010-04-19 20:44:31 +00001772 // Ask HeaderInfo if we should enter this #include file. If not, #including
Richard Smith54ef4c32015-05-19 19:58:11 +00001773 // this file will have no effect.
Richard Smith63b6fce2015-05-18 04:45:41 +00001774 if (ShouldEnter &&
Richard Smith035f6dc2015-07-01 01:51:38 +00001775 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
1776 SuggestedModule.getModule())) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001777 ShouldEnter = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001778 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001779 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Richard Smith63b6fce2015-05-18 04:45:41 +00001780 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001781
Richard Smith63b6fce2015-05-18 04:45:41 +00001782 // If we don't need to enter the file, stop now.
1783 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001784 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00001785 if (auto *M = SuggestedModule.getModule()) {
1786 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00001787
1788 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
1789 tok::pp___include_macros)
Richard Smitha0aafa32015-05-18 03:52:30 +00001790 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00001791 }
Chris Lattner72286d62010-04-19 20:44:31 +00001792 return;
1793 }
1794
Chris Lattnerf64b3522008-03-09 01:54:53 +00001795 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00001796 SourceLocation IncludePos = End;
1797 // If the filename string was the result of macro expansions, set the include
1798 // position on the file where it will be included and after the expansions.
1799 if (IncludePos.isMacroID())
1800 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
1801 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Peter Collingbourned395b932011-06-30 16:41:03 +00001802 assert(!FID.isInvalid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001803
Richard Smith34f30512013-11-23 04:06:09 +00001804 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00001805 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
1806 return;
Richard Smith34f30512013-11-23 04:06:09 +00001807
Richard Smitha0aafa32015-05-18 03:52:30 +00001808 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00001809 if (auto *M = SuggestedModule.getModule()) {
Richard Smith67294e22014-01-31 20:47:44 +00001810 assert(!CurSubmodule && "should not have marked this as a module yet");
Richard Smitha0aafa32015-05-18 03:52:30 +00001811 CurSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00001812
Richard Smitha0aafa32015-05-18 03:52:30 +00001813 // Let the macro handling code know that any future macros are within
1814 // the new submodule.
1815 EnterSubmodule(M, HashLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +00001816
Richard Smitha0aafa32015-05-18 03:52:30 +00001817 // Let the parser know that any future declarations are within the new
1818 // submodule.
1819 // FIXME: There's no point doing this if we're handling a #__include_macros
1820 // directive.
1821 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00001822 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001823}
1824
James Dennettf6333ac2012-06-22 05:46:07 +00001825/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001826///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001827void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1828 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001829 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001830
Chris Lattnerf64b3522008-03-09 01:54:53 +00001831 // #include_next is like #include, except that we start searching after
1832 // the current found directory. If we can't do this, issue a
1833 // diagnostic.
1834 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00001835 const FileEntry *LookupFromFile = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001836 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001837 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001838 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001839 } else if (CurSubmodule) {
1840 // Start looking up in the directory *after* the one in which the current
1841 // file would be found, if any.
1842 assert(CurPPLexer && "#include_next directive in macro?");
1843 LookupFromFile = CurPPLexer->getFileEntry();
1844 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001845 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001846 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1847 } else {
1848 // Start looking up in the next directory.
1849 ++Lookup;
1850 }
Mike Stump11289f42009-09-09 15:08:12 +00001851
Richard Smith25d50752014-10-20 00:15:49 +00001852 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
1853 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001854}
1855
James Dennettf6333ac2012-06-22 05:46:07 +00001856/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00001857void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
1858 // The Microsoft #import directive takes a type library and generates header
1859 // files from it, and includes those. This is beyond the scope of what clang
1860 // does, so we ignore it and error out. However, #import can optionally have
1861 // trailing attributes that span multiple lines. We're going to eat those
1862 // so we can continue processing from there.
1863 Diag(Tok, diag::err_pp_import_directive_ms );
1864
1865 // Read tokens until we get to the end of the directive. Note that the
1866 // directive can be split over multiple lines using the backslash character.
1867 DiscardUntilEndOfDirective();
1868}
1869
James Dennettf6333ac2012-06-22 05:46:07 +00001870/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001871///
Douglas Gregor796d76a2010-10-20 22:00:55 +00001872void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1873 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00001874 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00001875 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00001876 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00001877 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00001878 }
Richard Smith25d50752014-10-20 00:15:49 +00001879 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001880}
1881
Chris Lattner58a1eb02009-04-08 18:46:40 +00001882/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1883/// pseudo directive in the predefines buffer. This handles it by sucking all
1884/// tokens through the preprocessor and discarding them (only keeping the side
1885/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00001886void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1887 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00001888 // This directive should only occur in the predefines buffer. If not, emit an
1889 // error and reject it.
1890 SourceLocation Loc = IncludeMacrosTok.getLocation();
1891 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1892 Diag(IncludeMacrosTok.getLocation(),
1893 diag::pp_include_macros_out_of_predefines);
1894 DiscardUntilEndOfDirective();
1895 return;
1896 }
Mike Stump11289f42009-09-09 15:08:12 +00001897
Chris Lattnere01d82b2009-04-08 20:53:24 +00001898 // Treat this as a normal #include for checking purposes. If this is
1899 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00001900 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00001901
Chris Lattnere01d82b2009-04-08 20:53:24 +00001902 Token TmpTok;
1903 do {
1904 Lex(TmpTok);
1905 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1906 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00001907}
1908
Chris Lattnerf64b3522008-03-09 01:54:53 +00001909//===----------------------------------------------------------------------===//
1910// Preprocessor Macro Directive Handling.
1911//===----------------------------------------------------------------------===//
1912
1913/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1914/// definition has just been read. Lex the rest of the arguments and the
1915/// closing ), updating MI with what we learn. Return true if an error occurs
1916/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00001917bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001918 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00001919
Chris Lattnerf64b3522008-03-09 01:54:53 +00001920 while (1) {
1921 LexUnexpandedToken(Tok);
1922 switch (Tok.getKind()) {
1923 case tok::r_paren:
1924 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00001925 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00001926 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001927 // Otherwise we have #define FOO(A,)
1928 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1929 return true;
1930 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00001931 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001932 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00001933 diag::warn_cxx98_compat_variadic_macro :
1934 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001935
Joey Gouly1d58cdb2013-01-17 17:35:00 +00001936 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
1937 if (LangOpts.OpenCL) {
1938 Diag(Tok, diag::err_pp_opencl_variadic_macros);
1939 return true;
1940 }
1941
Chris Lattnerf64b3522008-03-09 01:54:53 +00001942 // Lex the token after the identifier.
1943 LexUnexpandedToken(Tok);
1944 if (Tok.isNot(tok::r_paren)) {
1945 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1946 return true;
1947 }
1948 // Add the __VA_ARGS__ identifier as an argument.
1949 Arguments.push_back(Ident__VA_ARGS__);
1950 MI->setIsC99Varargs();
Chris Lattner70946da2009-02-20 22:46:43 +00001951 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001952 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001953 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00001954 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1955 return true;
1956 default:
1957 // Handle keywords and identifiers here to accept things like
1958 // #define Foo(for) for.
1959 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00001960 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001961 // #define X(1
1962 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1963 return true;
1964 }
1965
1966 // If this is already used as an argument, it is used multiple times (e.g.
1967 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00001968 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00001969 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00001970 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001971 return true;
1972 }
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattnerf64b3522008-03-09 01:54:53 +00001974 // Add the argument to the macro info.
1975 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00001976
Chris Lattnerf64b3522008-03-09 01:54:53 +00001977 // Lex the token after the identifier.
1978 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00001979
Chris Lattnerf64b3522008-03-09 01:54:53 +00001980 switch (Tok.getKind()) {
1981 default: // #define X(A B
1982 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1983 return true;
1984 case tok::r_paren: // #define X(A)
Chris Lattner70946da2009-02-20 22:46:43 +00001985 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001986 return false;
1987 case tok::comma: // #define X(A,
1988 break;
1989 case tok::ellipsis: // #define X(A... -> GCC extension
1990 // Diagnose extension.
1991 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00001992
Chris Lattnerf64b3522008-03-09 01:54:53 +00001993 // Lex the token after the identifier.
1994 LexUnexpandedToken(Tok);
1995 if (Tok.isNot(tok::r_paren)) {
1996 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1997 return true;
1998 }
Mike Stump11289f42009-09-09 15:08:12 +00001999
Chris Lattnerf64b3522008-03-09 01:54:53 +00002000 MI->setIsGNUVarargs();
Chris Lattner70946da2009-02-20 22:46:43 +00002001 MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002002 return false;
2003 }
2004 }
2005 }
2006}
2007
Serge Pavlov07c0f042014-12-18 11:14:21 +00002008static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2009 const LangOptions &LOptions) {
2010 if (MI->getNumTokens() == 1) {
2011 const Token &Value = MI->getReplacementToken(0);
2012
2013 // Macro that is identity, like '#define inline inline' is a valid pattern.
2014 if (MacroName.getKind() == Value.getKind())
2015 return true;
2016
2017 // Macro that maps a keyword to the same keyword decorated with leading/
2018 // trailing underscores is a valid pattern:
2019 // #define inline __inline
2020 // #define inline __inline__
2021 // #define inline _inline (in MS compatibility mode)
2022 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2023 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2024 if (!II->isKeyword(LOptions))
2025 return false;
2026 StringRef ValueText = II->getName();
2027 StringRef TrimmedValue = ValueText;
2028 if (!ValueText.startswith("__")) {
2029 if (ValueText.startswith("_"))
2030 TrimmedValue = TrimmedValue.drop_front(1);
2031 else
2032 return false;
2033 } else {
2034 TrimmedValue = TrimmedValue.drop_front(2);
2035 if (TrimmedValue.endswith("__"))
2036 TrimmedValue = TrimmedValue.drop_back(2);
2037 }
2038 return TrimmedValue.equals(MacroText);
2039 } else {
2040 return false;
2041 }
2042 }
2043
2044 // #define inline
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00002045 if (MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2046 tok::kw_const) &&
Serge Pavlov07c0f042014-12-18 11:14:21 +00002047 MI->getNumTokens() == 0) {
2048 return true;
2049 }
2050
2051 return false;
2052}
2053
James Dennettf6333ac2012-06-22 05:46:07 +00002054/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00002055/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002056void Preprocessor::HandleDefineDirective(Token &DefineTok,
2057 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002058 ++NumDefined;
2059
2060 Token MacroNameTok;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002061 bool MacroShadowsKeyword;
2062 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
Mike Stump11289f42009-09-09 15:08:12 +00002063
Chris Lattnerf64b3522008-03-09 01:54:53 +00002064 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002065 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002066 return;
2067
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002068 Token LastTok = MacroNameTok;
2069
Chris Lattnerf64b3522008-03-09 01:54:53 +00002070 // If we are supposed to keep comments in #defines, reenable comment saving
2071 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00002072 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00002073
Chris Lattnerf64b3522008-03-09 01:54:53 +00002074 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002075 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002076
Chris Lattnerf64b3522008-03-09 01:54:53 +00002077 Token Tok;
2078 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002079
Chris Lattnerf64b3522008-03-09 01:54:53 +00002080 // If this is a function-like macro definition, parse the argument list,
2081 // marking each of the identifiers as being used as macro arguments. Also,
2082 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002083 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002084 if (ImmediatelyAfterHeaderGuard) {
2085 // Save this macro information since it may part of a header guard.
2086 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2087 MacroNameTok.getLocation());
2088 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002089 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002090 } else if (Tok.hasLeadingSpace()) {
2091 // This is a normal token with leading space. Clear the leading space
2092 // marker on the first token to get proper expansion.
2093 Tok.clearFlag(Token::LeadingSpace);
2094 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002095 // This is a function-like macro definition. Read the argument list.
2096 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002097 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002098 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002099 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002100 DiscardUntilEndOfDirective();
2101 return;
2102 }
2103
Chris Lattner249c38b2009-04-19 18:26:34 +00002104 // If this is a definition of a variadic C99 function-like macro, not using
2105 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chris Lattner249c38b2009-04-19 18:26:34 +00002107 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2108 // This gets unpoisoned where it is allowed.
2109 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2110 if (MI->isC99Varargs())
2111 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00002112
Chris Lattnerf64b3522008-03-09 01:54:53 +00002113 // Read the first token after the arg list for down below.
2114 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002115 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002116 // C99 requires whitespace between the macro definition and the body. Emit
2117 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002118 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002119 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002120 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2121 // first character of a replacement list is not a character required by
2122 // subclause 5.2.1, then there shall be white-space separation between the
2123 // identifier and the replacement list.". 5.2.1 lists this set:
2124 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2125 // is irrelevant here.
2126 bool isInvalid = false;
2127 if (Tok.is(tok::at)) // @ is not in the list above.
2128 isInvalid = true;
2129 else if (Tok.is(tok::unknown)) {
2130 // If we have an unknown token, it is something strange like "`". Since
2131 // all of valid characters would have lexed into a single character
2132 // token of some sort, we know this is not a valid case.
2133 isInvalid = true;
2134 }
2135 if (isInvalid)
2136 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2137 else
2138 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002139 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002140
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002141 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002142 LastTok = Tok;
2143
Chris Lattnerf64b3522008-03-09 01:54:53 +00002144 // Read the rest of the macro body.
2145 if (MI->isObjectLike()) {
2146 // Object-like macros are very simple, just read their body.
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 MI->AddTokenToBody(Tok);
2150 // Get the next token of the macro.
2151 LexUnexpandedToken(Tok);
2152 }
Mike Stump11289f42009-09-09 15:08:12 +00002153
Chris Lattnerf64b3522008-03-09 01:54:53 +00002154 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002155 // Otherwise, read the body of a function-like macro. While we are at it,
2156 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2157 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002158 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002159 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002160
Eli Friedman14d3c792012-11-14 02:18:46 +00002161 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002162 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002163
Chris Lattnerf64b3522008-03-09 01:54:53 +00002164 // Get the next token of the macro.
2165 LexUnexpandedToken(Tok);
2166 continue;
2167 }
Mike Stump11289f42009-09-09 15:08:12 +00002168
Richard Smith701a3522013-07-09 01:00:29 +00002169 // If we're in -traditional mode, then we should ignore stringification
2170 // and token pasting. Mark the tokens as unknown so as not to confuse
2171 // things.
2172 if (getLangOpts().TraditionalCPP) {
2173 Tok.setKind(tok::unknown);
2174 MI->AddTokenToBody(Tok);
2175
2176 // Get the next token of the macro.
2177 LexUnexpandedToken(Tok);
2178 continue;
2179 }
2180
Eli Friedman14d3c792012-11-14 02:18:46 +00002181 if (Tok.is(tok::hashhash)) {
2182
2183 // If we see token pasting, check if it looks like the gcc comma
2184 // pasting extension. We'll use this information to suppress
2185 // diagnostics later on.
2186
2187 // Get the next token of the macro.
2188 LexUnexpandedToken(Tok);
2189
2190 if (Tok.is(tok::eod)) {
2191 MI->AddTokenToBody(LastTok);
2192 break;
2193 }
2194
2195 unsigned NumTokens = MI->getNumTokens();
2196 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2197 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2198 MI->setHasCommaPasting();
2199
David Majnemer76faf1f2013-11-05 09:30:17 +00002200 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002201 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002202 continue;
2203 }
2204
Chris Lattnerf64b3522008-03-09 01:54:53 +00002205 // Get the next token of the macro.
2206 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002207
Chris Lattner83bd8282009-05-25 17:16:10 +00002208 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002209 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002210 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2211
2212 // If this is assembler-with-cpp mode, we accept random gibberish after
2213 // the '#' because '#' is often a comment character. However, change
2214 // the kind of the token to tok::unknown so that the preprocessor isn't
2215 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002216 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002217 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002218 MI->AddTokenToBody(LastTok);
2219 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002220 } else {
2221 Diag(Tok, diag::err_pp_stringize_not_parameter);
Mike Stump11289f42009-09-09 15:08:12 +00002222
Chris Lattner83bd8282009-05-25 17:16:10 +00002223 // Disable __VA_ARGS__ again.
2224 Ident__VA_ARGS__->setIsPoisoned(true);
2225 return;
2226 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002227 }
Mike Stump11289f42009-09-09 15:08:12 +00002228
Chris Lattner83bd8282009-05-25 17:16:10 +00002229 // Things look ok, add the '#' and param name tokens to the macro.
2230 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002231 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002232 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002233
Chris Lattnerf64b3522008-03-09 01:54:53 +00002234 // Get the next token of the macro.
2235 LexUnexpandedToken(Tok);
2236 }
2237 }
Mike Stump11289f42009-09-09 15:08:12 +00002238
Serge Pavlov07c0f042014-12-18 11:14:21 +00002239 if (MacroShadowsKeyword &&
2240 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2241 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2242 }
Mike Stump11289f42009-09-09 15:08:12 +00002243
Chris Lattnerf64b3522008-03-09 01:54:53 +00002244 // Disable __VA_ARGS__ again.
2245 Ident__VA_ARGS__->setIsPoisoned(true);
2246
Chris Lattner57540c52011-04-15 05:22:18 +00002247 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002248 // replacement list.
2249 unsigned NumTokens = MI->getNumTokens();
2250 if (NumTokens != 0) {
2251 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2252 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002253 return;
2254 }
2255 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2256 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002257 return;
2258 }
2259 }
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002261 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002262
Chris Lattnerf64b3522008-03-09 01:54:53 +00002263 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002264 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002265 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
Chris Lattner5244f342009-01-16 19:50:11 +00002266 // It is very common for system headers to have tons of macro redefinitions
2267 // and for warnings to be disabled in system headers. If this is the case,
2268 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002269 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002270 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002271 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002272 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002273
Richard Smith7b242542013-03-06 00:46:00 +00002274 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2275 // C++ [cpp.predefined]p4, but allow it as an extension.
2276 if (OtherMI->isBuiltinMacro())
2277 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002278 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002279 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002280 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002281 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002282 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2283 << MacroNameTok.getIdentifierInfo();
2284 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2285 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002286 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002287 if (OtherMI->isWarnIfUnused())
2288 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002289 }
Mike Stump11289f42009-09-09 15:08:12 +00002290
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002291 DefMacroDirective *MD =
2292 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002293
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002294 assert(!MI->isUsed());
2295 // If we need warning for not using the macro, add its location in the
2296 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002297 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002298 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002299 MI->setIsWarnIfUnused(true);
2300 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2301 }
2302
Chris Lattner928e9092009-04-12 01:39:54 +00002303 // If the callbacks want to know, tell them about the macro definition.
2304 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002305 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002306}
2307
James Dennettf6333ac2012-06-22 05:46:07 +00002308/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002309///
2310void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2311 ++NumUndefined;
2312
2313 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002314 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002315
Chris Lattnerf64b3522008-03-09 01:54:53 +00002316 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002317 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002318 return;
Mike Stump11289f42009-09-09 15:08:12 +00002319
Chris Lattnerf64b3522008-03-09 01:54:53 +00002320 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002321 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002322
Richard Smith20e883e2015-04-29 23:20:19 +00002323 // Okay, we have a valid identifier to undef.
2324 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002325 auto MD = getMacroDefinition(II);
Mike Stump11289f42009-09-09 15:08:12 +00002326
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002327 // If the callbacks want to know, tell them about the macro #undef.
2328 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002329 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002330 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002331
Chris Lattnerf64b3522008-03-09 01:54:53 +00002332 // If the macro is not defined, this is a noop undef, just return.
Richard Smith36bd40d2015-05-04 03:15:40 +00002333 const MacroInfo *MI = MD.getMacroInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002334 if (!MI)
2335 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002336
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002337 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002338 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002339
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002340 if (MI->isWarnIfUnused())
2341 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2342
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002343 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2344 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002345}
2346
2347
2348//===----------------------------------------------------------------------===//
2349// Preprocessor Conditional Directive Handling.
2350//===----------------------------------------------------------------------===//
2351
James Dennettf6333ac2012-06-22 05:46:07 +00002352/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2353/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2354/// true if any tokens have been returned or pp-directives activated before this
2355/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002356///
2357void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2358 bool ReadAnyTokensBeforeDirective) {
2359 ++NumIf;
2360 Token DirectiveTok = Result;
2361
2362 Token MacroNameTok;
2363 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002364
Chris Lattnerf64b3522008-03-09 01:54:53 +00002365 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002366 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002367 // Skip code until we get to #endif. This helps with recovery by not
2368 // emitting an error when the #endif is reached.
2369 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2370 /*Foundnonskip*/false, /*FoundElse*/false);
2371 return;
2372 }
Mike Stump11289f42009-09-09 15:08:12 +00002373
Chris Lattnerf64b3522008-03-09 01:54:53 +00002374 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002375 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002376
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002377 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002378 auto MD = getMacroDefinition(MII);
2379 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002380
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002381 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002382 // If the start of a top-level #ifdef and if the macro is not defined,
2383 // inform MIOpt that this might be the start of a proper include guard.
2384 // Otherwise it is some other form of unknown conditional which we can't
2385 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002386 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002387 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002388 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002389 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002390 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002391 }
2392
Chris Lattnerf64b3522008-03-09 01:54:53 +00002393 // If there is a macro, process it.
2394 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002395 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002396
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002397 if (Callbacks) {
2398 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002399 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002400 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002401 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002402 }
2403
Chris Lattnerf64b3522008-03-09 01:54:53 +00002404 // Should we include the stuff contained by this directive?
2405 if (!MI == isIfndef) {
2406 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002407 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2408 /*wasskip*/false, /*foundnonskip*/true,
2409 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002410 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002411 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002412 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002413 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002414 /*FoundElse*/false);
2415 }
2416}
2417
James Dennettf6333ac2012-06-22 05:46:07 +00002418/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002419///
2420void Preprocessor::HandleIfDirective(Token &IfToken,
2421 bool ReadAnyTokensBeforeDirective) {
2422 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002423
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002424 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002425 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002426 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2427 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2428 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002429
2430 // If this condition is equivalent to #ifndef X, and if this is the first
2431 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002432 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002433 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002434 // FIXME: Pass in the location of the macro name, not the 'if' token.
2435 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002436 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002437 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002438 }
2439
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002440 if (Callbacks)
2441 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002442 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002443 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002444
Chris Lattnerf64b3522008-03-09 01:54:53 +00002445 // Should we include the stuff contained by this directive?
2446 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002447 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002448 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002449 /*foundnonskip*/true, /*foundelse*/false);
2450 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002451 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002452 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002453 /*FoundElse*/false);
2454 }
2455}
2456
James Dennettf6333ac2012-06-22 05:46:07 +00002457/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002458///
2459void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2460 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002461
Chris Lattnerf64b3522008-03-09 01:54:53 +00002462 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002463 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002464
Chris Lattnerf64b3522008-03-09 01:54:53 +00002465 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002466 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002467 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002468 Diag(EndifToken, diag::err_pp_endif_without_if);
2469 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002470 }
Mike Stump11289f42009-09-09 15:08:12 +00002471
Chris Lattnerf64b3522008-03-09 01:54:53 +00002472 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002473 if (CurPPLexer->getConditionalStackDepth() == 0)
2474 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002475
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002476 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002477 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002478
2479 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002480 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002481}
2482
James Dennettf6333ac2012-06-22 05:46:07 +00002483/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002484///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002485void Preprocessor::HandleElseDirective(Token &Result) {
2486 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002487
Chris Lattnerf64b3522008-03-09 01:54:53 +00002488 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002489 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002490
Chris Lattnerf64b3522008-03-09 01:54:53 +00002491 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002492 if (CurPPLexer->popConditionalLevel(CI)) {
2493 Diag(Result, diag::pp_err_else_without_if);
2494 return;
2495 }
Mike Stump11289f42009-09-09 15:08:12 +00002496
Chris Lattnerf64b3522008-03-09 01:54:53 +00002497 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002498 if (CurPPLexer->getConditionalStackDepth() == 0)
2499 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002500
2501 // If this is a #else with a #else before it, report the error.
2502 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002503
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002504 if (Callbacks)
2505 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2506
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002507 // Finally, skip the rest of the contents of this block.
2508 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002509 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002510}
2511
James Dennettf6333ac2012-06-22 05:46:07 +00002512/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002513///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002514void Preprocessor::HandleElifDirective(Token &ElifToken) {
2515 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002516
Chris Lattnerf64b3522008-03-09 01:54:53 +00002517 // #elif directive in a non-skipping conditional... start skipping.
2518 // We don't care what the condition is, because we will always skip it (since
2519 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002520 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002521 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002522 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002523
2524 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002525 if (CurPPLexer->popConditionalLevel(CI)) {
2526 Diag(ElifToken, diag::pp_err_elif_without_if);
2527 return;
2528 }
Mike Stump11289f42009-09-09 15:08:12 +00002529
Chris Lattnerf64b3522008-03-09 01:54:53 +00002530 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002531 if (CurPPLexer->getConditionalStackDepth() == 0)
2532 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002533
Chris Lattnerf64b3522008-03-09 01:54:53 +00002534 // If this is a #elif with a #else before it, report the error.
2535 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002536
2537 if (Callbacks)
2538 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002539 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002540 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002541
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002542 // Finally, skip the rest of the contents of this block.
2543 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002544 /*FoundElse*/CI.FoundElse,
2545 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002546}