blob: 4a36a92fb2154b18cc7b37254a5d510f1d8d4759 [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"
Taewook Ohf42103c2016-06-13 20:40:21 +000027#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/iterator_range.h"
Douglas Gregor41e115a2011-11-30 18:02:36 +000031#include "llvm/Support/ErrorHandling.h"
Rafael Espindolaf6002232014-08-08 21:31:04 +000032#include "llvm/Support/Path.h"
Aaron Ballman6ce00002013-01-16 19:32:21 +000033#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000034
Chris Lattnerf64b3522008-03-09 01:54:53 +000035using namespace clang;
36
37//===----------------------------------------------------------------------===//
38// Utility Methods for Preprocessor Directive Handling.
39//===----------------------------------------------------------------------===//
40
Chris Lattnerc0a585d2010-08-17 15:55:45 +000041MacroInfo *Preprocessor::AllocateMacroInfo() {
Richard Smithee0c4c12014-07-24 01:13:23 +000042 MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
Ted Kremenekc8456f82010-10-19 22:15:20 +000043 MIChain->Next = MIChainHead;
Ted Kremenekc8456f82010-10-19 22:15:20 +000044 MIChainHead = MIChain;
Richard Smithee0c4c12014-07-24 01:13:23 +000045 return &MIChain->MI;
Chris Lattnerc0a585d2010-08-17 15:55:45 +000046}
47
48MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
49 MacroInfo *MI = AllocateMacroInfo();
Ted Kremenek6c7ea112008-12-15 19:56:42 +000050 new (MI) MacroInfo(L);
51 return MI;
52}
53
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000054MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
55 unsigned SubModuleID) {
Chandler Carruth06dde922014-03-02 13:02:01 +000056 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
57 "alignment for MacroInfo is less than the ID");
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000058 DeserializedMacroInfoChain *MIChain =
59 BP.Allocate<DeserializedMacroInfoChain>();
60 MIChain->Next = DeserialMIChainHead;
61 DeserialMIChainHead = MIChain;
62
63 MacroInfo *MI = &MIChain->MI;
Argyrios Kyrtzidis4f32da12013-03-22 21:12:51 +000064 new (MI) MacroInfo(L);
65 MI->FromASTFile = true;
66 MI->setOwningModuleID(SubModuleID);
67 return MI;
68}
69
Richard Smith50474bf2015-04-23 23:29:05 +000070DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
71 SourceLocation Loc) {
Richard Smith713369b2015-04-23 20:40:50 +000072 return new (BP) DefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000073}
74
75UndefMacroDirective *
Richard Smith50474bf2015-04-23 23:29:05 +000076Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
Richard Smith713369b2015-04-23 20:40:50 +000077 return new (BP) UndefMacroDirective(UndefLoc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000078}
79
80VisibilityMacroDirective *
81Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
82 bool isPublic) {
Richard Smithdaa69e02014-07-25 04:40:03 +000083 return new (BP) VisibilityMacroDirective(Loc, isPublic);
Chris Lattnerc0a585d2010-08-17 15:55:45 +000084}
85
James Dennettf6333ac2012-06-22 05:46:07 +000086/// \brief Read and discard all tokens remaining on the current line until
87/// the tok::eod token is found.
Chris Lattnerf64b3522008-03-09 01:54:53 +000088void Preprocessor::DiscardUntilEndOfDirective() {
89 Token Tmp;
90 do {
91 LexUnexpandedToken(Tmp);
Peter Collingbournef29ce972011-02-22 13:49:06 +000092 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +000093 } while (Tmp.isNot(tok::eod));
Chris Lattnerf64b3522008-03-09 01:54:53 +000094}
95
Serge Pavlov07c0f042014-12-18 11:14:21 +000096/// \brief Enumerates possible cases of #define/#undef a reserved identifier.
97enum MacroDiag {
98 MD_NoWarn, //> Not a reserved identifier
99 MD_KeywordDef, //> Macro hides keyword, enabled by default
100 MD_ReservedMacro //> #define of #undef reserved id, disabled by default
101};
102
103/// \brief Checks if the specified identifier is reserved in the specified
104/// language.
105/// This function does not check if the identifier is a keyword.
106static bool isReservedId(StringRef Text, const LangOptions &Lang) {
107 // C++ [macro.names], C11 7.1.3:
108 // All identifiers that begin with an underscore and either an uppercase
109 // letter or another underscore are always reserved for any use.
110 if (Text.size() >= 2 && Text[0] == '_' &&
111 (isUppercase(Text[1]) || Text[1] == '_'))
112 return true;
113 // C++ [global.names]
114 // Each name that contains a double underscore ... is reserved to the
115 // implementation for any use.
116 if (Lang.CPlusPlus) {
117 if (Text.find("__") != StringRef::npos)
118 return true;
119 }
Nico Weber92c14bb2014-12-16 21:16:10 +0000120 return false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000121}
122
Serge Pavlov07c0f042014-12-18 11:14:21 +0000123static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
124 const LangOptions &Lang = PP.getLangOpts();
125 StringRef Text = II->getName();
126 if (isReservedId(Text, Lang))
127 return MD_ReservedMacro;
128 if (II->isKeyword(Lang))
129 return MD_KeywordDef;
130 if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
131 return MD_KeywordDef;
132 return MD_NoWarn;
133}
134
135static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
136 const LangOptions &Lang = PP.getLangOpts();
137 StringRef Text = II->getName();
138 // Do not warn on keyword undef. It is generally harmless and widely used.
139 if (isReservedId(Text, Lang))
140 return MD_ReservedMacro;
141 return MD_NoWarn;
142}
143
Taewook Ohf42103c2016-06-13 20:40:21 +0000144// Return true if we want to issue a diagnostic by default if we
145// encounter this name in a #include with the wrong case. For now,
146// this includes the standard C and C++ headers, Posix headers,
147// and Boost headers. Improper case for these #includes is a
148// potential portability issue.
149static bool warnByDefaultOnWrongCase(StringRef Include) {
150 // If the first component of the path is "boost", treat this like a standard header
151 // for the purposes of diagnostics.
152 if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
153 return true;
154
155 // "condition_variable" is the longest standard header name at 18 characters.
156 // If the include file name is longer than that, it can't be a standard header.
157 static constexpr size_t MaxStdHeaderNameLen = 18u;
158 if (Include.size() > MaxStdHeaderNameLen)
159 return false;
160
161 // Lowercase and normalize the search string.
162 SmallString<32> LowerInclude{Include};
163 for (char &Ch : LowerInclude) {
164 // In the ASCII range?
165 if (Ch < 0 || Ch > 0x7f)
166 return false; // Can't be a standard header
167 // ASCII lowercase:
168 if (Ch >= 'A' && Ch <= 'Z')
169 Ch += 'a' - 'A';
170 // Normalize path separators for comparison purposes.
171 else if (::llvm::sys::path::is_separator(Ch))
172 Ch = '/';
173 }
174
175 // The standard C/C++ and Posix headers
176 return llvm::StringSwitch<bool>(LowerInclude)
177 // C library headers
178 .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
179 .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
180 .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
181 .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
182 .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
183 .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
184
185 // C++ headers for C library facilities
186 .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
187 .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
188 .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
189 .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
190 .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
191 .Case("cwctype", true)
192
193 // C++ library headers
194 .Cases("algorithm", "fstream", "list", "regex", "thread", true)
195 .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
196 .Cases("atomic", "future", "map", "set", "type_traits", true)
197 .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
198 .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
199 .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
200 .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
201 .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
202 .Cases("deque", "istream", "queue", "string", "valarray", true)
203 .Cases("exception", "iterator", "random", "strstream", "vector", true)
204 .Cases("forward_list", "limits", "ratio", "system_error", true)
205
206 // POSIX headers (which aren't also C headers)
207 .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
208 .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
209 .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
210 .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
211 .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
212 .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
213 .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
214 .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
215 .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
216 .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
217 .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
218 .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
219 .Default(false);
220}
221
Serge Pavlov07c0f042014-12-18 11:14:21 +0000222bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
223 bool *ShadowFlag) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000224 // Missing macro name?
225 if (MacroNameTok.is(tok::eod))
226 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
227
228 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
229 if (!II) {
230 bool Invalid = false;
231 std::string Spelling = getSpelling(MacroNameTok, &Invalid);
232 if (Invalid)
233 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerf33619c2014-05-31 03:38:08 +0000234 II = getIdentifierInfo(Spelling);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000235
Alp Tokerf33619c2014-05-31 03:38:08 +0000236 if (!II->isCPlusPlusOperatorKeyword())
237 return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000238
Alp Tokere03e9e12014-05-31 16:32:22 +0000239 // C++ 2.5p2: Alternative tokens behave the same as its primary token
240 // except for their spellings.
241 Diag(MacroNameTok, getLangOpts().MicrosoftExt
242 ? diag::ext_pp_operator_used_as_macro_name
243 : diag::err_pp_operator_used_as_macro_name)
244 << II << MacroNameTok.getKind();
Alp Tokerb05e0b52014-05-21 06:13:51 +0000245
Alp Tokerc5d194fc2014-05-31 03:38:17 +0000246 // Allow #defining |and| and friends for Microsoft compatibility or
247 // recovery when legacy C headers are included in C++.
Alp Tokerf33619c2014-05-31 03:38:08 +0000248 MacroNameTok.setIdentifierInfo(II);
Alp Tokerb05e0b52014-05-21 06:13:51 +0000249 }
250
Serge Pavlovd024f522014-10-24 17:31:32 +0000251 if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
Alp Tokerb05e0b52014-05-21 06:13:51 +0000252 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
253 return Diag(MacroNameTok, diag::err_defined_macro_name);
254 }
255
Richard Smith20e883e2015-04-29 23:20:19 +0000256 if (isDefineUndef == MU_Undef) {
257 auto *MI = getMacroInfo(II);
258 if (MI && MI->isBuiltinMacro()) {
259 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
260 // and C++ [cpp.predefined]p4], but allow it as an extension.
261 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
262 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000263 }
264
Serge Pavlov07c0f042014-12-18 11:14:21 +0000265 // If defining/undefining reserved identifier or a keyword, we need to issue
266 // a warning.
Serge Pavlov83cf0782014-12-11 12:18:08 +0000267 SourceLocation MacroNameLoc = MacroNameTok.getLocation();
Serge Pavlov07c0f042014-12-18 11:14:21 +0000268 if (ShadowFlag)
269 *ShadowFlag = false;
Serge Pavlov83cf0782014-12-11 12:18:08 +0000270 if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
271 (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) {
Serge Pavlov07c0f042014-12-18 11:14:21 +0000272 MacroDiag D = MD_NoWarn;
273 if (isDefineUndef == MU_Define) {
274 D = shouldWarnOnMacroDef(*this, II);
275 }
276 else if (isDefineUndef == MU_Undef)
277 D = shouldWarnOnMacroUndef(*this, II);
278 if (D == MD_KeywordDef) {
279 // We do not want to warn on some patterns widely used in configuration
280 // scripts. This requires analyzing next tokens, so do not issue warnings
281 // now, only inform caller.
282 if (ShadowFlag)
283 *ShadowFlag = true;
284 }
285 if (D == MD_ReservedMacro)
286 Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
Serge Pavlov83cf0782014-12-11 12:18:08 +0000287 }
288
Alp Tokerb05e0b52014-05-21 06:13:51 +0000289 // Okay, we got a good identifier.
290 return false;
291}
292
James Dennettf6333ac2012-06-22 05:46:07 +0000293/// \brief Lex and validate a macro name, which occurs after a
294/// \#define or \#undef.
295///
Serge Pavlovd024f522014-10-24 17:31:32 +0000296/// This sets the token kind to eod and discards the rest of the macro line if
297/// the macro name is invalid.
298///
299/// \param MacroNameTok Token that is expected to be a macro name.
Serge Pavlov07c0f042014-12-18 11:14:21 +0000300/// \param isDefineUndef Context in which macro is used.
301/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
302void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
303 bool *ShadowFlag) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000304 // Read the token, don't allow macro expansion on it.
305 LexUnexpandedToken(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +0000306
Douglas Gregor12785102010-08-24 20:21:13 +0000307 if (MacroNameTok.is(tok::code_completion)) {
308 if (CodeComplete)
Serge Pavlovd024f522014-10-24 17:31:32 +0000309 CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000310 setCodeCompletionReached();
Douglas Gregor12785102010-08-24 20:21:13 +0000311 LexUnexpandedToken(MacroNameTok);
Douglas Gregor12785102010-08-24 20:21:13 +0000312 }
Alp Tokerb05e0b52014-05-21 06:13:51 +0000313
Serge Pavlov07c0f042014-12-18 11:14:21 +0000314 if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
Chris Lattner907dfe92008-11-18 07:59:24 +0000315 return;
Alp Tokerb05e0b52014-05-21 06:13:51 +0000316
317 // Invalid macro name, read and discard the rest of the line and set the
318 // token kind to tok::eod if necessary.
319 if (MacroNameTok.isNot(tok::eod)) {
320 MacroNameTok.setKind(tok::eod);
321 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +0000322 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000323}
324
James Dennettf6333ac2012-06-22 05:46:07 +0000325/// \brief Ensure that the next token is a tok::eod token.
326///
327/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
Chris Lattner0003c272009-04-17 23:30:53 +0000328/// true, then we consider macros that expand to zero tokens as being ok.
329void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000330 Token Tmp;
Chris Lattner0003c272009-04-17 23:30:53 +0000331 // Lex unexpanded tokens for most directives: macros might expand to zero
332 // tokens, causing us to miss diagnosing invalid lines. Some directives (like
333 // #line) allow empty macros.
334 if (EnableMacros)
335 Lex(Tmp);
336 else
337 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattnerf64b3522008-03-09 01:54:53 +0000339 // There should be no tokens after the directive, but we allow them as an
340 // extension.
341 while (Tmp.is(tok::comment)) // Skip comments in -C mode.
342 LexUnexpandedToken(Tmp);
Mike Stump11289f42009-09-09 15:08:12 +0000343
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000344 if (Tmp.isNot(tok::eod)) {
Chris Lattner825676a2009-04-14 05:15:20 +0000345 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000346 // or if this is a macro-style preprocessing directive, because it is more
347 // trouble than it is worth to insert /**/ and check that there is no /**/
348 // in the range also.
Douglas Gregora771f462010-03-31 17:46:05 +0000349 FixItHint Hint;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000350 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000351 !CurTokenLexer)
Douglas Gregora771f462010-03-31 17:46:05 +0000352 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
353 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000354 DiscardUntilEndOfDirective();
355 }
356}
357
James Dennettf6333ac2012-06-22 05:46:07 +0000358/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
359/// decided that the subsequent tokens are in the \#if'd out portion of the
360/// file. Lex the rest of the file, until we see an \#endif. If
Chris Lattnerf64b3522008-03-09 01:54:53 +0000361/// FoundNonSkipPortion is true, then we have already emitted code for part of
James Dennettf6333ac2012-06-22 05:46:07 +0000362/// this \#if directive, so \#else/\#elif blocks should never be entered.
363/// If ElseOk is true, then \#else directives are ok, if not, then we have
364/// already seen one so a \#else directive is a duplicate. When this returns,
365/// the caller can lex the first valid token.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000366void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
367 bool FoundNonSkipPortion,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000368 bool FoundElse,
369 SourceLocation ElseLoc) {
Chris Lattnerf64b3522008-03-09 01:54:53 +0000370 ++NumSkipped;
David Blaikie7d170102013-05-15 07:37:26 +0000371 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
Chris Lattnerf64b3522008-03-09 01:54:53 +0000372
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000373 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000374 FoundNonSkipPortion, FoundElse);
Mike Stump11289f42009-09-09 15:08:12 +0000375
Ted Kremenek56572ab2008-12-12 18:34:08 +0000376 if (CurPTHLexer) {
377 PTHSkipExcludedConditionalBlock();
378 return;
379 }
Mike Stump11289f42009-09-09 15:08:12 +0000380
Chris Lattnerf64b3522008-03-09 01:54:53 +0000381 // Enter raw mode to disable identifier lookup (and thus macro expansion),
382 // disabling warnings, etc.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000383 CurPPLexer->LexingRawMode = true;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000384 Token Tok;
385 while (1) {
Chris Lattnerf406b242010-01-18 22:33:01 +0000386 CurLexer->Lex(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000387
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000388 if (Tok.is(tok::code_completion)) {
389 if (CodeComplete)
390 CodeComplete->CodeCompleteInConditionalExclusion();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000391 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000392 continue;
393 }
394
Chris Lattnerf64b3522008-03-09 01:54:53 +0000395 // If this is the end of the buffer, we have an error.
396 if (Tok.is(tok::eof)) {
397 // Emit errors for each unterminated conditional on the stack, including
398 // the current one.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000399 while (!CurPPLexer->ConditionalStack.empty()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000400 if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Douglas Gregor02690ba2010-08-12 17:04:55 +0000401 Diag(CurPPLexer->ConditionalStack.back().IfLoc,
402 diag::err_pp_unterminated_conditional);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000403 CurPPLexer->ConditionalStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000404 }
405
Chris Lattnerf64b3522008-03-09 01:54:53 +0000406 // Just return and let the caller lex after this #include.
407 break;
408 }
Mike Stump11289f42009-09-09 15:08:12 +0000409
Chris Lattnerf64b3522008-03-09 01:54:53 +0000410 // If this token is not a preprocessor directive, just skip it.
411 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
412 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattnerf64b3522008-03-09 01:54:53 +0000414 // We just parsed a # character at the start of a line, so we're in
415 // directive mode. Tell the lexer this so any newlines we see will be
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000416 // converted into an EOD token (this terminates the macro).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000417 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rose176057b2013-02-22 00:32:00 +0000418 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000419
Mike Stump11289f42009-09-09 15:08:12 +0000420
Chris Lattnerf64b3522008-03-09 01:54:53 +0000421 // Read the next token, the directive flavor.
422 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnerf64b3522008-03-09 01:54:53 +0000424 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
425 // something bogus), skip it.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000426 if (Tok.isNot(tok::raw_identifier)) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000427 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000428 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000429 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000430 continue;
431 }
432
433 // If the first letter isn't i or e, it isn't intesting to us. We know that
434 // this is safe in the face of spelling differences, because there is no way
435 // to spell an i/e in a strange way that is another letter. Skipping this
436 // allows us to avoid looking up the identifier info for #define/#undef and
437 // other common directives.
Alp Toker2d57cea2014-05-17 04:53:25 +0000438 StringRef RI = Tok.getRawIdentifier();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000439
Alp Toker2d57cea2014-05-17 04:53:25 +0000440 char FirstChar = RI[0];
Mike Stump11289f42009-09-09 15:08:12 +0000441 if (FirstChar >= 'a' && FirstChar <= 'z' &&
Chris Lattnerf64b3522008-03-09 01:54:53 +0000442 FirstChar != 'i' && FirstChar != 'e') {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000443 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000444 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000445 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000446 continue;
447 }
Mike Stump11289f42009-09-09 15:08:12 +0000448
Chris Lattnerf64b3522008-03-09 01:54:53 +0000449 // Get the identifier name without trigraphs or embedded newlines. Note
450 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
451 // when skipping.
Benjamin Kramer144884642009-12-31 13:32:38 +0000452 char DirectiveBuf[20];
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000453 StringRef Directive;
Alp Toker2d57cea2014-05-17 04:53:25 +0000454 if (!Tok.needsCleaning() && RI.size() < 20) {
455 Directive = RI;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000456 } else {
457 std::string DirectiveStr = getSpelling(Tok);
Benjamin Kramer144884642009-12-31 13:32:38 +0000458 unsigned IdLen = DirectiveStr.size();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000459 if (IdLen >= 20) {
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000460 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000461 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000462 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000463 continue;
464 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000465 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000466 Directive = StringRef(DirectiveBuf, IdLen);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000467 }
Mike Stump11289f42009-09-09 15:08:12 +0000468
Benjamin Kramer144884642009-12-31 13:32:38 +0000469 if (Directive.startswith("if")) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000470 StringRef Sub = Directive.substr(2);
Benjamin Kramer144884642009-12-31 13:32:38 +0000471 if (Sub.empty() || // "if"
472 Sub == "def" || // "ifdef"
473 Sub == "ndef") { // "ifndef"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000474 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
475 // bother parsing the condition.
476 DiscardUntilEndOfDirective();
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000477 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
Chris Lattnerf64b3522008-03-09 01:54:53 +0000478 /*foundnonskip*/false,
Chandler Carruth540960f2011-01-03 17:40:17 +0000479 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000480 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000481 } else if (Directive[0] == 'e') {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000482 StringRef Sub = Directive.substr(1);
Benjamin Kramer144884642009-12-31 13:32:38 +0000483 if (Sub == "ndif") { // "endif"
Chris Lattnerf64b3522008-03-09 01:54:53 +0000484 PPConditionalInfo CondInfo;
485 CondInfo.WasSkipping = true; // Silence bogus warning.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000486 bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000487 (void)InCond; // Silence warning in no-asserts mode.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000488 assert(!InCond && "Can't be skipping if not in a conditional!");
Mike Stump11289f42009-09-09 15:08:12 +0000489
Chris Lattnerf64b3522008-03-09 01:54:53 +0000490 // If we popped the outermost skipping block, we're done skipping!
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000491 if (!CondInfo.WasSkipping) {
Richard Smith87d8fb92012-06-24 23:56:26 +0000492 // Restore the value of LexingRawMode so that trailing comments
493 // are handled correctly, if we've reached the outermost block.
494 CurPPLexer->LexingRawMode = false;
Richard Smithd0124572012-06-21 00:35:03 +0000495 CheckEndOfDirective("endif");
Richard Smith87d8fb92012-06-24 23:56:26 +0000496 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000497 if (Callbacks)
498 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000499 break;
Richard Smithd0124572012-06-21 00:35:03 +0000500 } else {
501 DiscardUntilEndOfDirective();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000502 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000503 } else if (Sub == "lse") { // "else".
Chris Lattnerf64b3522008-03-09 01:54:53 +0000504 // #else directive in a skipping conditional. If not in some other
505 // skipping conditional, and if #else hasn't already been seen, enter it
506 // as a non-skipping conditional.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000507 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattnerf64b3522008-03-09 01:54:53 +0000509 // If this is a #else with a #else before it, report the error.
510 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000511
Chris Lattnerf64b3522008-03-09 01:54:53 +0000512 // Note that we've seen a #else in this conditional.
513 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000514
Chris Lattnerf64b3522008-03-09 01:54:53 +0000515 // If the conditional is at the top level, and the #if block wasn't
516 // entered, enter the #else block now.
517 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
518 CondInfo.FoundNonSkip = true;
Richard Smith87d8fb92012-06-24 23:56:26 +0000519 // Restore the value of LexingRawMode so that trailing comments
520 // are handled correctly.
521 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000522 CheckEndOfDirective("else");
Richard Smith87d8fb92012-06-24 23:56:26 +0000523 CurPPLexer->LexingRawMode = true;
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000524 if (Callbacks)
525 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000526 break;
Argyrios Kyrtzidis627c14a2011-05-21 04:26:04 +0000527 } else {
528 DiscardUntilEndOfDirective(); // C99 6.10p4.
Chris Lattnerf64b3522008-03-09 01:54:53 +0000529 }
Benjamin Kramer144884642009-12-31 13:32:38 +0000530 } else if (Sub == "lif") { // "elif".
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000531 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000532
John Thompson17c35732013-12-04 20:19:30 +0000533 // If this is a #elif with a #else before it, report the error.
534 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
535
Chris Lattnerf64b3522008-03-09 01:54:53 +0000536 // If this is in a skipping block or if we're already handled this #if
537 // block, don't bother parsing the condition.
538 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
539 DiscardUntilEndOfDirective();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000540 } else {
John Thompson17c35732013-12-04 20:19:30 +0000541 const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000542 // Restore the value of LexingRawMode so that identifiers are
543 // looked up, etc, inside the #elif expression.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000544 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
545 CurPPLexer->LexingRawMode = false;
Craig Topperd2d442c2014-05-17 23:10:59 +0000546 IdentifierInfo *IfNDefMacro = nullptr;
John Thompson17c35732013-12-04 20:19:30 +0000547 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000548 CurPPLexer->LexingRawMode = true;
John Thompson17c35732013-12-04 20:19:30 +0000549 if (Callbacks) {
550 const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +0000551 Callbacks->Elif(Tok.getLocation(),
John Thompson17c35732013-12-04 20:19:30 +0000552 SourceRange(CondBegin, CondEnd),
John Thompson87f9fef2013-12-07 08:41:15 +0000553 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
John Thompson17c35732013-12-04 20:19:30 +0000554 }
555 // If this condition is true, enter it!
556 if (CondValue) {
557 CondInfo.FoundNonSkip = true;
558 break;
559 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000560 }
561 }
562 }
Mike Stump11289f42009-09-09 15:08:12 +0000563
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000564 CurPPLexer->ParsingPreprocessorDirective = false;
Chris Lattnerf64b3522008-03-09 01:54:53 +0000565 // Restore comment saving mode.
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000566 if (CurLexer) CurLexer->resetExtendedTokenMode();
Chris Lattnerf64b3522008-03-09 01:54:53 +0000567 }
568
569 // Finally, if we are out of the conditional (saw an #endif or ran off the end
570 // of the file, just stop skipping and return to lexing whatever came after
571 // the #if block.
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000572 CurPPLexer->LexingRawMode = false;
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +0000573
574 if (Callbacks) {
575 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
576 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
577 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000578}
579
Ted Kremenek56572ab2008-12-12 18:34:08 +0000580void Preprocessor::PTHSkipExcludedConditionalBlock() {
Mike Stump11289f42009-09-09 15:08:12 +0000581 while (1) {
Ted Kremenek56572ab2008-12-12 18:34:08 +0000582 assert(CurPTHLexer);
583 assert(CurPTHLexer->LexingRawMode == false);
Mike Stump11289f42009-09-09 15:08:12 +0000584
Ted Kremenek56572ab2008-12-12 18:34:08 +0000585 // Skip to the next '#else', '#elif', or #endif.
586 if (CurPTHLexer->SkipBlock()) {
587 // We have reached an #endif. Both the '#' and 'endif' tokens
588 // have been consumed by the PTHLexer. Just pop off the condition level.
589 PPConditionalInfo CondInfo;
590 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +0000591 (void)InCond; // Silence warning in no-asserts mode.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000592 assert(!InCond && "Can't be skipping if not in a conditional!");
593 break;
594 }
Mike Stump11289f42009-09-09 15:08:12 +0000595
Ted Kremenek56572ab2008-12-12 18:34:08 +0000596 // We have reached a '#else' or '#elif'. Lex the next token to get
597 // the directive flavor.
598 Token Tok;
599 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000600
Ted Kremenek56572ab2008-12-12 18:34:08 +0000601 // We can actually look up the IdentifierInfo here since we aren't in
602 // raw mode.
603 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
604
605 if (K == tok::pp_else) {
606 // #else: Enter the else condition. We aren't in a nested condition
607 // since we skip those. We're always in the one matching the last
608 // blocked we skipped.
609 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
610 // Note that we've seen a #else in this conditional.
611 CondInfo.FoundElse = true;
Mike Stump11289f42009-09-09 15:08:12 +0000612
Ted Kremenek56572ab2008-12-12 18:34:08 +0000613 // If the #if block wasn't entered then enter the #else block now.
614 if (!CondInfo.FoundNonSkip) {
615 CondInfo.FoundNonSkip = true;
Mike Stump11289f42009-09-09 15:08:12 +0000616
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000617 // Scan until the eod token.
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000618 CurPTHLexer->ParsingPreprocessorDirective = true;
Daniel Dunbar2cba6be2009-04-13 17:57:49 +0000619 DiscardUntilEndOfDirective();
Ted Kremenek1b18ad22008-12-23 01:30:52 +0000620 CurPTHLexer->ParsingPreprocessorDirective = false;
Mike Stump11289f42009-09-09 15:08:12 +0000621
Ted Kremenek56572ab2008-12-12 18:34:08 +0000622 break;
623 }
Mike Stump11289f42009-09-09 15:08:12 +0000624
Ted Kremenek56572ab2008-12-12 18:34:08 +0000625 // Otherwise skip this block.
626 continue;
627 }
Mike Stump11289f42009-09-09 15:08:12 +0000628
Ted Kremenek56572ab2008-12-12 18:34:08 +0000629 assert(K == tok::pp_elif);
630 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
631
632 // If this is a #elif with a #else before it, report the error.
633 if (CondInfo.FoundElse)
634 Diag(Tok, diag::pp_err_elif_after_else);
Mike Stump11289f42009-09-09 15:08:12 +0000635
Ted Kremenek56572ab2008-12-12 18:34:08 +0000636 // If this is in a skipping block or if we're already handled this #if
Mike Stump11289f42009-09-09 15:08:12 +0000637 // block, don't bother parsing the condition. We just skip this block.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000638 if (CondInfo.FoundNonSkip)
639 continue;
640
641 // Evaluate the condition of the #elif.
Craig Topperd2d442c2014-05-17 23:10:59 +0000642 IdentifierInfo *IfNDefMacro = nullptr;
Ted Kremenek56572ab2008-12-12 18:34:08 +0000643 CurPTHLexer->ParsingPreprocessorDirective = true;
644 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
645 CurPTHLexer->ParsingPreprocessorDirective = false;
646
647 // If this condition is true, enter it!
648 if (ShouldEnter) {
649 CondInfo.FoundNonSkip = true;
650 break;
651 }
652
653 // Otherwise, skip this block and go to the next one.
Ted Kremenek56572ab2008-12-12 18:34:08 +0000654 }
655}
656
Richard Smith2a553082015-04-23 22:58:06 +0000657Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
Richard Smith7e82e012016-02-19 22:25:36 +0000658 if (!SourceMgr.isInMainFile(Loc)) {
659 // Try to determine the module of the include directive.
660 // FIXME: Look into directly passing the FileEntry from LookupFile instead.
661 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
662 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
663 // The include comes from an included file.
664 return HeaderInfo.getModuleMap()
665 .findModuleForHeader(EntryOfIncl)
666 .getModule();
667 }
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000668 }
Richard Smith7e82e012016-02-19 22:25:36 +0000669
670 // This is either in the main file or not in a file at all. It belongs
671 // to the current module, if there is one.
672 return getLangOpts().CurrentModule.empty()
673 ? nullptr
674 : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
Daniel Jasperba7f2f72013-09-24 09:14:14 +0000675}
676
Richard Smith2a553082015-04-23 22:58:06 +0000677Module *Preprocessor::getModuleContainingLocation(SourceLocation Loc) {
678 return HeaderInfo.getModuleMap().inferModuleFromLocation(
679 FullSourceLoc(Loc, SourceMgr));
680}
681
Richard Smith4eb83932016-04-27 21:57:05 +0000682const FileEntry *
683Preprocessor::getModuleHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
684 SourceLocation Loc) {
685 // If we have a module import syntax, we shouldn't include a header to
686 // make a particular module visible.
687 if (getLangOpts().ObjC2)
688 return nullptr;
689
690 // Figure out which module we'd want to import.
691 Module *M = getModuleContainingLocation(Loc);
692 if (!M)
693 return nullptr;
694
695 Module *TopM = M->getTopLevelModule();
696 Module *IncM = getModuleForLocation(IncLoc);
697
698 // Walk up through the include stack, looking through textual headers of M
699 // until we hit a non-textual header that we can #include. (We assume textual
700 // headers of a module with non-textual headers aren't meant to be used to
701 // import entities from the module.)
702 auto &SM = getSourceManager();
703 while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
704 auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
705 auto *FE = SM.getFileEntryForID(ID);
706
707 bool InTextualHeader = false;
708 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
709 if (!Header.getModule()->isSubModuleOf(TopM))
710 continue;
711
712 if (!(Header.getRole() & ModuleMap::TextualHeader)) {
713 // If this is an accessible, non-textual header of M's top-level module
714 // that transitively includes the given location and makes the
715 // corresponding module visible, this is the thing to #include.
716 if (Header.isAccessibleFrom(IncM))
717 return FE;
718
719 // It's in a private header; we can't #include it.
720 // FIXME: If there's a public header in some module that re-exports it,
721 // then we could suggest including that, but it's not clear that's the
722 // expected way to make this entity visible.
723 continue;
724 }
725
726 InTextualHeader = true;
727 }
728
729 if (!InTextualHeader)
730 break;
731
732 Loc = SM.getIncludeLoc(ID);
733 }
734
735 return nullptr;
736}
737
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000738const FileEntry *Preprocessor::LookupFile(
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000739 SourceLocation FilenameLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000740 StringRef Filename,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000741 bool isAngled,
742 const DirectoryLookup *FromDir,
Richard Smith25d50752014-10-20 00:15:49 +0000743 const FileEntry *FromFile,
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000744 const DirectoryLookup *&CurDir,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000745 SmallVectorImpl<char> *SearchPath,
Douglas Gregor97eec242011-09-15 22:00:41 +0000746 SmallVectorImpl<char> *RelativePath,
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000747 ModuleMap::KnownHeader *SuggestedModule,
Douglas Gregor8ad31c22011-11-20 17:46:46 +0000748 bool SkipCache) {
Richard Smith3d5b48c2015-10-16 21:42:56 +0000749 Module *RequestingModule = getModuleForLocation(FilenameLoc);
Richard Smith8d4e90b2016-03-14 17:52:37 +0000750 bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
Richard Smith3d5b48c2015-10-16 21:42:56 +0000751
Will Wilson0fafd342013-12-27 19:46:16 +0000752 // If the header lookup mechanism may be relative to the current inclusion
753 // stack, record the parent #includes.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000754 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
755 Includers;
Manman Rene4a5d372016-05-17 02:15:12 +0000756 bool BuildSystemModule = false;
Richard Smith25d50752014-10-20 00:15:49 +0000757 if (!FromDir && !FromFile) {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000758 FileID FID = getCurrentFileLexer()->getFileID();
Will Wilson0fafd342013-12-27 19:46:16 +0000759 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000760
Chris Lattner022923a2009-02-04 19:45:07 +0000761 // If there is no file entry associated with this file, it must be the
Richard Smith3c1a41a2014-12-02 00:08:08 +0000762 // predefines buffer or the module includes buffer. Any other file is not
763 // lexed with a normal lexer, so it won't be scanned for preprocessor
764 // directives.
765 //
766 // If we have the predefines buffer, resolve #include references (which come
767 // from the -include command line argument) from the current working
768 // directory instead of relative to the main file.
769 //
770 // If we have the module includes buffer, resolve #include references (which
771 // come from header declarations in the module map) relative to the module
772 // map file.
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000773 if (!FileEnt) {
Manman Rene4a5d372016-05-17 02:15:12 +0000774 if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000775 Includers.push_back(std::make_pair(nullptr, MainFileDir));
Manman Rene4a5d372016-05-17 02:15:12 +0000776 BuildSystemModule = getCurrentModule()->IsSystem;
777 } else if ((FileEnt =
Richard Smith3c1a41a2014-12-02 00:08:08 +0000778 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000779 Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
780 } else {
781 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
782 }
Will Wilson0fafd342013-12-27 19:46:16 +0000783
784 // MSVC searches the current include stack from top to bottom for
785 // headers included by quoted include directives.
786 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Alp Tokerbfa39342014-01-14 12:51:41 +0000787 if (LangOpts.MSVCCompat && !isAngled) {
Will Wilson0fafd342013-12-27 19:46:16 +0000788 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
789 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
790 if (IsFileLexer(ISEntry))
Yaron Keren65224612015-12-18 10:30:12 +0000791 if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000792 Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
Will Wilson0fafd342013-12-27 19:46:16 +0000793 }
Chris Lattner022923a2009-02-04 19:45:07 +0000794 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000795 }
Mike Stump11289f42009-09-09 15:08:12 +0000796
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000797 CurDir = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +0000798
799 if (FromFile) {
800 // We're supposed to start looking from after a particular file. Search
801 // the include path until we find that file or run out of files.
802 const DirectoryLookup *TmpCurDir = CurDir;
803 const DirectoryLookup *TmpFromDir = nullptr;
804 while (const FileEntry *FE = HeaderInfo.LookupFile(
805 Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000806 Includers, SearchPath, RelativePath, RequestingModule,
807 SuggestedModule, SkipCache)) {
Richard Smith25d50752014-10-20 00:15:49 +0000808 // Keep looking as if this file did a #include_next.
809 TmpFromDir = TmpCurDir;
810 ++TmpFromDir;
811 if (FE == FromFile) {
812 // Found it.
813 FromDir = TmpFromDir;
814 CurDir = TmpCurDir;
815 break;
816 }
817 }
818 }
819
820 // Do a standard file entry lookup.
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000821 const FileEntry *FE = HeaderInfo.LookupFile(
Will Wilson0fafd342013-12-27 19:46:16 +0000822 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
Manman Rene4a5d372016-05-17 02:15:12 +0000823 RelativePath, RequestingModule, SuggestedModule, SkipCache,
824 BuildSystemModule);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000825 if (FE) {
Daniel Jasper5c77e392014-03-14 14:53:17 +0000826 if (SuggestedModule && !LangOpts.AsmPreprocessor)
Daniel Jasper92669ee2013-12-20 12:09:36 +0000827 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000828 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
829 Filename, FE);
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000830 return FE;
831 }
Mike Stump11289f42009-09-09 15:08:12 +0000832
Will Wilson0fafd342013-12-27 19:46:16 +0000833 const FileEntry *CurFileEnt;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000834 // Otherwise, see if this is a subframework header. If so, this is relative
835 // to one of the headers on the #include stack. Walk the list of the current
836 // headers on the #include stack and pass them to HeaderInfo.
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000837 if (IsFileLexer()) {
Yaron Keren65224612015-12-18 10:30:12 +0000838 if ((CurFileEnt = CurPPLexer->getFileEntry())) {
Chandler Carruth3cc331a2011-03-16 18:34:36 +0000839 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
Douglas Gregorf5f94522013-02-08 00:10:48 +0000840 SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000841 RequestingModule,
Ben Langmuir71e1a642014-05-05 21:44:13 +0000842 SuggestedModule))) {
843 if (SuggestedModule && !LangOpts.AsmPreprocessor)
844 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000845 RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
846 Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000847 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000848 }
849 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000850 }
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000852 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
853 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
Ted Kremenek6bc5f3e2008-11-20 16:19:53 +0000854 if (IsFileLexer(ISEntry)) {
Yaron Keren65224612015-12-18 10:30:12 +0000855 if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
Manuel Klimek0c69fd22011-04-26 21:50:03 +0000856 if ((FE = HeaderInfo.LookupSubframeworkHeader(
Douglas Gregorf5f94522013-02-08 00:10:48 +0000857 Filename, CurFileEnt, SearchPath, RelativePath,
Richard Smith3d5b48c2015-10-16 21:42:56 +0000858 RequestingModule, SuggestedModule))) {
Ben Langmuir71e1a642014-05-05 21:44:13 +0000859 if (SuggestedModule && !LangOpts.AsmPreprocessor)
860 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
Richard Smith8d4e90b2016-03-14 17:52:37 +0000861 RequestingModule, RequestingModuleIsModuleInterface,
862 FilenameLoc, Filename, FE);
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000863 return FE;
Ben Langmuir71e1a642014-05-05 21:44:13 +0000864 }
865 }
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000866 }
867 }
Mike Stump11289f42009-09-09 15:08:12 +0000868
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000869 // Otherwise, we really couldn't find the file.
Craig Topperd2d442c2014-05-17 23:10:59 +0000870 return nullptr;
Chris Lattnerf7ad82d2008-03-09 04:17:44 +0000871}
872
Chris Lattnerf64b3522008-03-09 01:54:53 +0000873//===----------------------------------------------------------------------===//
874// Preprocessor Directive Handling.
875//===----------------------------------------------------------------------===//
876
David Blaikied5321242012-06-06 18:52:13 +0000877class Preprocessor::ResetMacroExpansionHelper {
878public:
879 ResetMacroExpansionHelper(Preprocessor *pp)
880 : PP(pp), save(pp->DisableMacroExpansion) {
881 if (pp->MacroExpansionInDirectivesOverride)
882 pp->DisableMacroExpansion = false;
883 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000884
David Blaikied5321242012-06-06 18:52:13 +0000885 ~ResetMacroExpansionHelper() {
886 PP->DisableMacroExpansion = save;
887 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000888
David Blaikied5321242012-06-06 18:52:13 +0000889private:
890 Preprocessor *PP;
891 bool save;
892};
893
Chris Lattnerf64b3522008-03-09 01:54:53 +0000894/// HandleDirective - This callback is invoked when the lexer sees a # token
Mike Stump11289f42009-09-09 15:08:12 +0000895/// at the start of a line. This consumes the directive, modifies the
Chris Lattnerf64b3522008-03-09 01:54:53 +0000896/// lexer/preprocessor state, and advances the lexer(s) so that the next token
897/// read is the correct one.
898void Preprocessor::HandleDirective(Token &Result) {
899 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
Mike Stump11289f42009-09-09 15:08:12 +0000900
Chris Lattnerf64b3522008-03-09 01:54:53 +0000901 // We just parsed a # character at the start of a line, so we're in directive
902 // mode. Tell the lexer this so any newlines we see will be converted into an
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000903 // EOD token (which terminates the directive).
Ted Kremenek30cd88c2008-11-18 00:34:22 +0000904 CurPPLexer->ParsingPreprocessorDirective = true;
Jordan Rosecb8a1ac2013-02-21 18:53:19 +0000905 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
Mike Stump11289f42009-09-09 15:08:12 +0000906
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000907 bool ImmediatelyAfterTopLevelIfndef =
908 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
909 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
910
Chris Lattnerf64b3522008-03-09 01:54:53 +0000911 ++NumDirectives;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000912
Chris Lattnerf64b3522008-03-09 01:54:53 +0000913 // We are about to read a token. For the multiple-include optimization FA to
Mike Stump11289f42009-09-09 15:08:12 +0000914 // work, we have to remember if we had read any tokens *before* this
Chris Lattnerf64b3522008-03-09 01:54:53 +0000915 // pp-directive.
Chris Lattner8cf1f932009-12-14 04:54:40 +0000916 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Mike Stump11289f42009-09-09 15:08:12 +0000917
Chris Lattner2d17ab72009-03-18 21:00:25 +0000918 // Save the '#' token in case we need to return it later.
919 Token SavedHash = Result;
Mike Stump11289f42009-09-09 15:08:12 +0000920
Chris Lattnerf64b3522008-03-09 01:54:53 +0000921 // Read the next token, the directive flavor. This isn't expanded due to
922 // C99 6.10.3p8.
923 LexUnexpandedToken(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000924
Chris Lattnerf64b3522008-03-09 01:54:53 +0000925 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
926 // #define A(x) #x
927 // A(abc
928 // #warning blah
929 // def)
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000930 // If so, the user is relying on undefined behavior, emit a diagnostic. Do
931 // not support this for #include-like directives, since that can result in
932 // terrible diagnostics, and does not work in GCC.
933 if (InMacroArgs) {
934 if (IdentifierInfo *II = Result.getIdentifierInfo()) {
935 switch (II->getPPKeywordID()) {
936 case tok::pp_include:
937 case tok::pp_import:
938 case tok::pp_include_next:
939 case tok::pp___include_macros:
David Majnemerf2d3bc02014-12-28 07:42:49 +0000940 case tok::pp_pragma:
941 Diag(Result, diag::err_embedded_directive) << II->getName();
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000942 DiscardUntilEndOfDirective();
943 return;
944 default:
945 break;
946 }
947 }
Chris Lattnerf64b3522008-03-09 01:54:53 +0000948 Diag(Result, diag::ext_embedded_directive);
Richard Smitheb3ce7c2011-12-16 22:50:01 +0000949 }
Mike Stump11289f42009-09-09 15:08:12 +0000950
David Blaikied5321242012-06-06 18:52:13 +0000951 // Temporarily enable macro expansion if set so
952 // and reset to previous state when returning from this function.
953 ResetMacroExpansionHelper helper(this);
954
Chris Lattnerf64b3522008-03-09 01:54:53 +0000955 switch (Result.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000956 case tok::eod:
Chris Lattnerf64b3522008-03-09 01:54:53 +0000957 return; // null directive.
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000958 case tok::code_completion:
959 if (CodeComplete)
960 CodeComplete->CodeCompleteDirective(
961 CurPPLexer->getConditionalStackDepth() > 0);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000962 setCodeCompletionReached();
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000963 return;
Chris Lattner76e68962009-01-26 06:19:46 +0000964 case tok::numeric_constant: // # 7 GNU line marker directive.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000965 if (getLangOpts().AsmPreprocessor)
Chris Lattner5eb8ae22009-03-18 20:41:10 +0000966 break; // # 4 is not a preprocessor directive in .S files.
Chris Lattner76e68962009-01-26 06:19:46 +0000967 return HandleDigitDirective(Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +0000968 default:
969 IdentifierInfo *II = Result.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000970 if (!II) break; // Not an identifier.
Mike Stump11289f42009-09-09 15:08:12 +0000971
Chris Lattnerf64b3522008-03-09 01:54:53 +0000972 // Ask what the preprocessor keyword ID is.
973 switch (II->getPPKeywordID()) {
974 default: break;
975 // C99 6.10.1 - Conditional Inclusion.
976 case tok::pp_if:
977 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
978 case tok::pp_ifdef:
979 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
980 case tok::pp_ifndef:
981 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
982 case tok::pp_elif:
983 return HandleElifDirective(Result);
984 case tok::pp_else:
985 return HandleElseDirective(Result);
986 case tok::pp_endif:
987 return HandleEndifDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +0000988
Chris Lattnerf64b3522008-03-09 01:54:53 +0000989 // C99 6.10.2 - Source File Inclusion.
990 case tok::pp_include:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000991 // Handle #include.
992 return HandleIncludeDirective(SavedHash.getLocation(), Result);
Chris Lattner14a7f392009-04-08 18:24:34 +0000993 case tok::pp___include_macros:
Douglas Gregor796d76a2010-10-20 22:00:55 +0000994 // Handle -imacros.
995 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +0000996
Chris Lattnerf64b3522008-03-09 01:54:53 +0000997 // C99 6.10.3 - Macro Replacement.
998 case tok::pp_define:
Richard Trieu33a4b3d2013-06-12 21:20:57 +0000999 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001000 case tok::pp_undef:
1001 return HandleUndefDirective(Result);
1002
1003 // C99 6.10.4 - Line Control.
1004 case tok::pp_line:
Chris Lattner100c65e2009-01-26 05:29:08 +00001005 return HandleLineDirective(Result);
Mike Stump11289f42009-09-09 15:08:12 +00001006
Chris Lattnerf64b3522008-03-09 01:54:53 +00001007 // C99 6.10.5 - Error Directive.
1008 case tok::pp_error:
1009 return HandleUserDiagnosticDirective(Result, false);
Mike Stump11289f42009-09-09 15:08:12 +00001010
Chris Lattnerf64b3522008-03-09 01:54:53 +00001011 // C99 6.10.6 - Pragma Directive.
1012 case tok::pp_pragma:
Enea Zaffanella5afb04a2013-07-20 20:09:11 +00001013 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
Mike Stump11289f42009-09-09 15:08:12 +00001014
Chris Lattnerf64b3522008-03-09 01:54:53 +00001015 // GNU Extensions.
1016 case tok::pp_import:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001017 return HandleImportDirective(SavedHash.getLocation(), Result);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001018 case tok::pp_include_next:
Douglas Gregor796d76a2010-10-20 22:00:55 +00001019 return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00001020
Chris Lattnerf64b3522008-03-09 01:54:53 +00001021 case tok::pp_warning:
1022 Diag(Result, diag::ext_pp_warning_directive);
1023 return HandleUserDiagnosticDirective(Result, true);
1024 case tok::pp_ident:
1025 return HandleIdentSCCSDirective(Result);
1026 case tok::pp_sccs:
1027 return HandleIdentSCCSDirective(Result);
1028 case tok::pp_assert:
1029 //isExtension = true; // FIXME: implement #assert
1030 break;
1031 case tok::pp_unassert:
1032 //isExtension = true; // FIXME: implement #unassert
1033 break;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001034
Douglas Gregor663b48f2012-01-03 19:48:16 +00001035 case tok::pp___public_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001036 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001037 return HandleMacroPublicDirective(Result);
1038 break;
1039
Douglas Gregor663b48f2012-01-03 19:48:16 +00001040 case tok::pp___private_macro:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001041 if (getLangOpts().Modules)
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001042 return HandleMacroPrivateDirective(Result);
1043 break;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001044 }
1045 break;
1046 }
Mike Stump11289f42009-09-09 15:08:12 +00001047
Chris Lattner2d17ab72009-03-18 21:00:25 +00001048 // If this is a .S file, treat unknown # directives as non-preprocessor
1049 // directives. This is important because # may be a comment or introduce
1050 // various pseudo-ops. Just return the # token and push back the following
1051 // token to be lexed next time.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001052 if (getLangOpts().AsmPreprocessor) {
David Blaikie2eabcc92016-02-09 18:52:09 +00001053 auto Toks = llvm::make_unique<Token[]>(2);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001054 // Return the # and the token after it.
Mike Stump11289f42009-09-09 15:08:12 +00001055 Toks[0] = SavedHash;
Chris Lattner2d17ab72009-03-18 21:00:25 +00001056 Toks[1] = Result;
Chris Lattner56f64c12011-01-06 05:01:51 +00001057
1058 // If the second token is a hashhash token, then we need to translate it to
1059 // unknown so the token lexer doesn't try to perform token pasting.
1060 if (Result.is(tok::hashhash))
1061 Toks[1].setKind(tok::unknown);
1062
Chris Lattner2d17ab72009-03-18 21:00:25 +00001063 // Enter this token stream so that we re-lex the tokens. Make sure to
1064 // enable macro expansion, in case the token after the # is an identifier
1065 // that is expanded.
David Blaikie2eabcc92016-02-09 18:52:09 +00001066 EnterTokenStream(std::move(Toks), 2, false);
Chris Lattner2d17ab72009-03-18 21:00:25 +00001067 return;
1068 }
Mike Stump11289f42009-09-09 15:08:12 +00001069
Chris Lattnerf64b3522008-03-09 01:54:53 +00001070 // If we reached here, the preprocessing token is not valid!
1071 Diag(Result, diag::err_pp_invalid_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattnerf64b3522008-03-09 01:54:53 +00001073 // Read the rest of the PP line.
1074 DiscardUntilEndOfDirective();
Mike Stump11289f42009-09-09 15:08:12 +00001075
Chris Lattnerf64b3522008-03-09 01:54:53 +00001076 // Okay, we're done parsing the directive.
1077}
1078
Chris Lattner76e68962009-01-26 06:19:46 +00001079/// GetLineValue - Convert a numeric token into an unsigned value, emitting
1080/// Diagnostic DiagID if it is invalid, and returning the value in Val.
1081static bool GetLineValue(Token &DigitTok, unsigned &Val,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001082 unsigned DiagID, Preprocessor &PP,
1083 bool IsGNULineDirective=false) {
Chris Lattner76e68962009-01-26 06:19:46 +00001084 if (DigitTok.isNot(tok::numeric_constant)) {
1085 PP.Diag(DigitTok, DiagID);
Mike Stump11289f42009-09-09 15:08:12 +00001086
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001087 if (DigitTok.isNot(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001088 PP.DiscardUntilEndOfDirective();
1089 return true;
1090 }
Mike Stump11289f42009-09-09 15:08:12 +00001091
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001092 SmallString<64> IntegerBuffer;
Chris Lattner76e68962009-01-26 06:19:46 +00001093 IntegerBuffer.resize(DigitTok.getLength());
1094 const char *DigitTokBegin = &IntegerBuffer[0];
Douglas Gregordc970f02010-03-16 22:30:13 +00001095 bool Invalid = false;
1096 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1097 if (Invalid)
1098 return true;
1099
Chris Lattnerd66f1722009-04-18 18:35:15 +00001100 // Verify that we have a simple digit-sequence, and compute the value. This
1101 // is always a simple digit string computed in decimal, so we do this manually
1102 // here.
1103 Val = 0;
1104 for (unsigned i = 0; i != ActualLength; ++i) {
Richard Smith7f2707a2013-09-26 18:13:20 +00001105 // C++1y [lex.fcon]p1:
1106 // Optional separating single quotes in a digit-sequence are ignored
1107 if (DigitTokBegin[i] == '\'')
1108 continue;
1109
Jordan Rosea7d03842013-02-08 22:30:41 +00001110 if (!isDigit(DigitTokBegin[i])) {
Chris Lattnerd66f1722009-04-18 18:35:15 +00001111 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
Michael Ilsemane910cc82013-04-10 01:04:18 +00001112 diag::err_pp_line_digit_sequence) << IsGNULineDirective;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001113 PP.DiscardUntilEndOfDirective();
1114 return true;
1115 }
Mike Stump11289f42009-09-09 15:08:12 +00001116
Chris Lattnerd66f1722009-04-18 18:35:15 +00001117 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1118 if (NextVal < Val) { // overflow.
1119 PP.Diag(DigitTok, DiagID);
1120 PP.DiscardUntilEndOfDirective();
1121 return true;
1122 }
1123 Val = NextVal;
Chris Lattner76e68962009-01-26 06:19:46 +00001124 }
Mike Stump11289f42009-09-09 15:08:12 +00001125
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001126 if (DigitTokBegin[0] == '0' && Val)
Michael Ilsemane910cc82013-04-10 01:04:18 +00001127 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1128 << IsGNULineDirective;
Mike Stump11289f42009-09-09 15:08:12 +00001129
Chris Lattner76e68962009-01-26 06:19:46 +00001130 return false;
1131}
1132
James Dennettf6333ac2012-06-22 05:46:07 +00001133/// \brief Handle a \#line directive: C99 6.10.4.
1134///
1135/// The two acceptable forms are:
1136/// \verbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001137/// # line digit-sequence
1138/// # line digit-sequence "s-char-sequence"
James Dennettf6333ac2012-06-22 05:46:07 +00001139/// \endverbatim
Chris Lattner100c65e2009-01-26 05:29:08 +00001140void Preprocessor::HandleLineDirective(Token &Tok) {
1141 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
1142 // expanded.
1143 Token DigitTok;
1144 Lex(DigitTok);
1145
Chris Lattner100c65e2009-01-26 05:29:08 +00001146 // Validate the number and convert it to an unsigned.
Chris Lattner76e68962009-01-26 06:19:46 +00001147 unsigned LineNo;
Chris Lattnerd66f1722009-04-18 18:35:15 +00001148 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
Chris Lattner100c65e2009-01-26 05:29:08 +00001149 return;
Fariborz Jahanian0638c152012-06-26 21:19:20 +00001150
1151 if (LineNo == 0)
1152 Diag(DigitTok, diag::ext_pp_line_zero);
Chris Lattner100c65e2009-01-26 05:29:08 +00001153
Chris Lattner76e68962009-01-26 06:19:46 +00001154 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1155 // number greater than 2147483647". C90 requires that the line # be <= 32767.
Eli Friedman192e0342011-10-10 23:35:28 +00001156 unsigned LineLimit = 32768U;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001157 if (LangOpts.C99 || LangOpts.CPlusPlus11)
Eli Friedman192e0342011-10-10 23:35:28 +00001158 LineLimit = 2147483648U;
Chris Lattner100c65e2009-01-26 05:29:08 +00001159 if (LineNo >= LineLimit)
1160 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001161 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Richard Smithacd4d3d2011-10-15 01:18:56 +00001162 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
Mike Stump11289f42009-09-09 15:08:12 +00001163
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001164 int FilenameID = -1;
Chris Lattner100c65e2009-01-26 05:29:08 +00001165 Token StrTok;
1166 Lex(StrTok);
1167
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001168 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1169 // string followed by eod.
1170 if (StrTok.is(tok::eod))
Chris Lattner100c65e2009-01-26 05:29:08 +00001171 ; // ok
1172 else if (StrTok.isNot(tok::string_literal)) {
1173 Diag(StrTok, diag::err_pp_line_invalid_filename);
Richard Smithd67aea22012-03-06 03:21:47 +00001174 return DiscardUntilEndOfDirective();
1175 } else if (StrTok.hasUDSuffix()) {
1176 Diag(StrTok, diag::err_invalid_string_udl);
1177 return DiscardUntilEndOfDirective();
Chris Lattner100c65e2009-01-26 05:29:08 +00001178 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001179 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001180 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001181 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001182 if (Literal.hadError)
1183 return DiscardUntilEndOfDirective();
1184 if (Literal.Pascal) {
1185 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1186 return DiscardUntilEndOfDirective();
1187 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001188 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001189
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001190 // Verify that there is nothing after the string, other than EOD. Because
Chris Lattner0003c272009-04-17 23:30:53 +00001191 // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1192 CheckEndOfDirective("line", true);
Chris Lattner100c65e2009-01-26 05:29:08 +00001193 }
Mike Stump11289f42009-09-09 15:08:12 +00001194
Chris Lattner1eaa70a2009-02-03 21:52:55 +00001195 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
Mike Stump11289f42009-09-09 15:08:12 +00001196
Chris Lattner839150e2009-03-27 17:13:49 +00001197 if (Callbacks)
Chris Lattnerc745cec2010-04-14 04:28:50 +00001198 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1199 PPCallbacks::RenameFile,
Chris Lattner839150e2009-03-27 17:13:49 +00001200 SrcMgr::C_User);
Chris Lattner100c65e2009-01-26 05:29:08 +00001201}
1202
Chris Lattner76e68962009-01-26 06:19:46 +00001203/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1204/// marker directive.
1205static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1206 bool &IsSystemHeader, bool &IsExternCHeader,
1207 Preprocessor &PP) {
1208 unsigned FlagVal;
1209 Token FlagTok;
1210 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001211 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001212 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1213 return true;
1214
1215 if (FlagVal == 1) {
1216 IsFileEntry = true;
Mike Stump11289f42009-09-09 15:08:12 +00001217
Chris Lattner76e68962009-01-26 06:19:46 +00001218 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001219 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001220 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1221 return true;
1222 } else if (FlagVal == 2) {
1223 IsFileExit = true;
Mike Stump11289f42009-09-09 15:08:12 +00001224
Chris Lattner1c967782009-02-04 06:25:26 +00001225 SourceManager &SM = PP.getSourceManager();
1226 // If we are leaving the current presumed file, check to make sure the
1227 // presumed include stack isn't empty!
1228 FileID CurFileID =
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001229 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
Chris Lattner1c967782009-02-04 06:25:26 +00001230 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +00001231 if (PLoc.isInvalid())
1232 return true;
1233
Chris Lattner1c967782009-02-04 06:25:26 +00001234 // If there is no include loc (main file) or if the include loc is in a
1235 // different physical file, then we aren't in a "1" line marker flag region.
1236 SourceLocation IncLoc = PLoc.getIncludeLoc();
1237 if (IncLoc.isInvalid() ||
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001238 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
Chris Lattner1c967782009-02-04 06:25:26 +00001239 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1240 PP.DiscardUntilEndOfDirective();
1241 return true;
1242 }
Mike Stump11289f42009-09-09 15:08:12 +00001243
Chris Lattner76e68962009-01-26 06:19:46 +00001244 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001245 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001246 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1247 return true;
1248 }
1249
1250 // We must have 3 if there are still flags.
1251 if (FlagVal != 3) {
1252 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001253 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001254 return true;
1255 }
Mike Stump11289f42009-09-09 15:08:12 +00001256
Chris Lattner76e68962009-01-26 06:19:46 +00001257 IsSystemHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattner76e68962009-01-26 06:19:46 +00001259 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001260 if (FlagTok.is(tok::eod)) return false;
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001261 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
Chris Lattner76e68962009-01-26 06:19:46 +00001262 return true;
1263
1264 // We must have 4 if there is yet another flag.
1265 if (FlagVal != 4) {
1266 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001267 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001268 return true;
1269 }
Mike Stump11289f42009-09-09 15:08:12 +00001270
Chris Lattner76e68962009-01-26 06:19:46 +00001271 IsExternCHeader = true;
Mike Stump11289f42009-09-09 15:08:12 +00001272
Chris Lattner76e68962009-01-26 06:19:46 +00001273 PP.Lex(FlagTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001274 if (FlagTok.is(tok::eod)) return false;
Chris Lattner76e68962009-01-26 06:19:46 +00001275
1276 // There are no more valid flags here.
1277 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001278 PP.DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001279 return true;
1280}
1281
1282/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1283/// one of the following forms:
1284///
1285/// # 42
Mike Stump11289f42009-09-09 15:08:12 +00001286/// # 42 "file" ('1' | '2')?
Chris Lattner76e68962009-01-26 06:19:46 +00001287/// # 42 "file" ('1' | '2')? '3' '4'?
1288///
1289void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1290 // Validate the number and convert it to an unsigned. GNU does not have a
1291 // line # limit other than it fit in 32-bits.
1292 unsigned LineNo;
1293 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
Michael Ilsemane910cc82013-04-10 01:04:18 +00001294 *this, true))
Chris Lattner76e68962009-01-26 06:19:46 +00001295 return;
Mike Stump11289f42009-09-09 15:08:12 +00001296
Chris Lattner76e68962009-01-26 06:19:46 +00001297 Token StrTok;
1298 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001299
Chris Lattner76e68962009-01-26 06:19:46 +00001300 bool IsFileEntry = false, IsFileExit = false;
1301 bool IsSystemHeader = false, IsExternCHeader = false;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001302 int FilenameID = -1;
1303
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001304 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
1305 // string followed by eod.
1306 if (StrTok.is(tok::eod))
Chris Lattner76e68962009-01-26 06:19:46 +00001307 ; // ok
1308 else if (StrTok.isNot(tok::string_literal)) {
1309 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001310 return DiscardUntilEndOfDirective();
Richard Smithd67aea22012-03-06 03:21:47 +00001311 } else if (StrTok.hasUDSuffix()) {
1312 Diag(StrTok, diag::err_invalid_string_udl);
1313 return DiscardUntilEndOfDirective();
Chris Lattner76e68962009-01-26 06:19:46 +00001314 } else {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001315 // Parse and validate the string, converting it into a unique ID.
Craig Topper9d5583e2014-06-26 04:58:39 +00001316 StringLiteralParser Literal(StrTok, *this);
Douglas Gregorfb65e592011-07-27 05:40:30 +00001317 assert(Literal.isAscii() && "Didn't allow wide strings in");
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001318 if (Literal.hadError)
1319 return DiscardUntilEndOfDirective();
1320 if (Literal.Pascal) {
1321 Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1322 return DiscardUntilEndOfDirective();
1323 }
Jay Foad9a6b0982011-06-21 15:13:30 +00001324 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
Mike Stump11289f42009-09-09 15:08:12 +00001325
Chris Lattner76e68962009-01-26 06:19:46 +00001326 // If a filename was present, read any flags that are present.
Mike Stump11289f42009-09-09 15:08:12 +00001327 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
Chris Lattnerb5fba6f2009-01-26 07:57:50 +00001328 IsSystemHeader, IsExternCHeader, *this))
Chris Lattner76e68962009-01-26 06:19:46 +00001329 return;
Chris Lattner76e68962009-01-26 06:19:46 +00001330 }
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001332 // Create a line note with this information.
1333 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
Mike Stump11289f42009-09-09 15:08:12 +00001334 IsFileEntry, IsFileExit,
Chris Lattner0a1a8d82009-02-04 05:21:58 +00001335 IsSystemHeader, IsExternCHeader);
Mike Stump11289f42009-09-09 15:08:12 +00001336
Chris Lattner839150e2009-03-27 17:13:49 +00001337 // If the preprocessor has callbacks installed, notify them of the #line
1338 // change. This is used so that the line marker comes out in -E mode for
1339 // example.
1340 if (Callbacks) {
1341 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1342 if (IsFileEntry)
1343 Reason = PPCallbacks::EnterFile;
1344 else if (IsFileExit)
1345 Reason = PPCallbacks::ExitFile;
1346 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1347 if (IsExternCHeader)
1348 FileKind = SrcMgr::C_ExternCSystem;
1349 else if (IsSystemHeader)
1350 FileKind = SrcMgr::C_System;
Mike Stump11289f42009-09-09 15:08:12 +00001351
Chris Lattnerc745cec2010-04-14 04:28:50 +00001352 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
Chris Lattner839150e2009-03-27 17:13:49 +00001353 }
Chris Lattner76e68962009-01-26 06:19:46 +00001354}
1355
Chris Lattner38d7fd22009-01-26 05:30:54 +00001356/// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1357///
Mike Stump11289f42009-09-09 15:08:12 +00001358void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001359 bool isWarning) {
Chris Lattner38d7fd22009-01-26 05:30:54 +00001360 // PTH doesn't emit #warning or #error directives.
1361 if (CurPTHLexer)
Chris Lattner100c65e2009-01-26 05:29:08 +00001362 return CurPTHLexer->DiscardToEndOfLine();
1363
Chris Lattnerf64b3522008-03-09 01:54:53 +00001364 // Read the rest of the line raw. We do this because we don't want macros
1365 // to be expanded and we don't require that the tokens be valid preprocessing
1366 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1367 // collapse multiple consequtive white space between tokens, but this isn't
1368 // specified by the standard.
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001369 SmallString<128> Message;
1370 CurLexer->ReadToEndOfLine(&Message);
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001371
1372 // Find the first non-whitespace character, so that we can make the
1373 // diagnostic more succinct.
David Majnemerbf7e0c62016-02-24 22:07:26 +00001374 StringRef Msg = StringRef(Message).ltrim(' ');
Benjamin Kramere5fbc6c2012-05-18 19:32:16 +00001375
Chris Lattner100c65e2009-01-26 05:29:08 +00001376 if (isWarning)
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001377 Diag(Tok, diag::pp_hash_warning) << Msg;
Chris Lattner100c65e2009-01-26 05:29:08 +00001378 else
Ted Kremenek7f4bd162012-02-02 00:16:13 +00001379 Diag(Tok, diag::err_pp_hash_error) << Msg;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001380}
1381
1382/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1383///
1384void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1385 // Yes, this directive is an extension.
1386 Diag(Tok, diag::ext_pp_ident_directive);
Mike Stump11289f42009-09-09 15:08:12 +00001387
Chris Lattnerf64b3522008-03-09 01:54:53 +00001388 // Read the string argument.
1389 Token StrTok;
1390 Lex(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +00001391
Chris Lattnerf64b3522008-03-09 01:54:53 +00001392 // If the token kind isn't a string, it's a malformed directive.
1393 if (StrTok.isNot(tok::string_literal) &&
Chris Lattner907dfe92008-11-18 07:59:24 +00001394 StrTok.isNot(tok::wide_string_literal)) {
1395 Diag(StrTok, diag::err_pp_malformed_ident);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001396 if (StrTok.isNot(tok::eod))
Chris Lattner38d7fd22009-01-26 05:30:54 +00001397 DiscardUntilEndOfDirective();
Chris Lattner907dfe92008-11-18 07:59:24 +00001398 return;
1399 }
Mike Stump11289f42009-09-09 15:08:12 +00001400
Richard Smithd67aea22012-03-06 03:21:47 +00001401 if (StrTok.hasUDSuffix()) {
1402 Diag(StrTok, diag::err_invalid_string_udl);
1403 return DiscardUntilEndOfDirective();
1404 }
1405
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001406 // Verify that there is nothing after the string, other than EOD.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001407 CheckEndOfDirective("ident");
Chris Lattnerf64b3522008-03-09 01:54:53 +00001408
Douglas Gregordc970f02010-03-16 22:30:13 +00001409 if (Callbacks) {
1410 bool Invalid = false;
1411 std::string Str = getSpelling(StrTok, &Invalid);
1412 if (!Invalid)
1413 Callbacks->Ident(Tok.getLocation(), Str);
1414 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00001415}
1416
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001417/// \brief Handle a #public directive.
1418void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001419 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001420 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001421
1422 // Error reading macro name? If so, diagnostic already issued.
1423 if (MacroNameTok.is(tok::eod))
1424 return;
1425
Douglas Gregor663b48f2012-01-03 19:48:16 +00001426 // Check to see if this is the last token on the #__public_macro line.
1427 CheckEndOfDirective("__public_macro");
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001428
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001429 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001430 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001431 MacroDirective *MD = getLocalMacroDirective(II);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001432
1433 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001434 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001435 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001436 return;
1437 }
1438
1439 // Note that this macro has now been exported.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001440 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1441 MacroNameTok.getLocation(), /*IsPublic=*/true));
Douglas Gregorebf00492011-10-17 15:32:29 +00001442}
1443
Douglas Gregor0bf886d2012-01-03 18:24:14 +00001444/// \brief Handle a #private directive.
Douglas Gregorebf00492011-10-17 15:32:29 +00001445void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
1446 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00001447 ReadMacroName(MacroNameTok, MU_Undef);
Douglas Gregorebf00492011-10-17 15:32:29 +00001448
1449 // Error reading macro name? If so, diagnostic already issued.
1450 if (MacroNameTok.is(tok::eod))
1451 return;
1452
Douglas Gregor663b48f2012-01-03 19:48:16 +00001453 // Check to see if this is the last token on the #__private_macro line.
1454 CheckEndOfDirective("__private_macro");
Douglas Gregorebf00492011-10-17 15:32:29 +00001455
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001456 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
Douglas Gregorebf00492011-10-17 15:32:29 +00001457 // Okay, we finally have a valid identifier to undef.
Richard Smith20e883e2015-04-29 23:20:19 +00001458 MacroDirective *MD = getLocalMacroDirective(II);
Douglas Gregorebf00492011-10-17 15:32:29 +00001459
1460 // If the macro is not defined, this is an error.
Craig Topperd2d442c2014-05-17 23:10:59 +00001461 if (!MD) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001462 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
Douglas Gregorebf00492011-10-17 15:32:29 +00001463 return;
1464 }
1465
1466 // Note that this macro has now been marked private.
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001467 appendMacroDirective(II, AllocateVisibilityMacroDirective(
1468 MacroNameTok.getLocation(), /*IsPublic=*/false));
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00001469}
1470
Chris Lattnerf64b3522008-03-09 01:54:53 +00001471//===----------------------------------------------------------------------===//
1472// Preprocessor Include Directive Handling.
1473//===----------------------------------------------------------------------===//
1474
1475/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
James Dennettf6333ac2012-06-22 05:46:07 +00001476/// checked and spelled filename, e.g. as an operand of \#include. This returns
Chris Lattnerf64b3522008-03-09 01:54:53 +00001477/// true if the input filename was in <>'s or false if it were in ""'s. The
1478/// caller is expected to provide a buffer that is large enough to hold the
1479/// spelling of the filename, but is also expected to handle the case when
1480/// this method decides to use a different buffer.
1481bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001482 StringRef &Buffer) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001483 // Get the text form of the filename.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001484 assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
Mike Stump11289f42009-09-09 15:08:12 +00001485
Chris Lattnerf64b3522008-03-09 01:54:53 +00001486 // Make sure the filename is <x> or "x".
1487 bool isAngled;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001488 if (Buffer[0] == '<') {
1489 if (Buffer.back() != '>') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001490 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001491 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001492 return true;
1493 }
1494 isAngled = true;
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001495 } else if (Buffer[0] == '"') {
1496 if (Buffer.back() != '"') {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001497 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001498 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001499 return true;
1500 }
1501 isAngled = false;
1502 } else {
1503 Diag(Loc, diag::err_pp_expects_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001504 Buffer = StringRef();
Chris Lattnerf64b3522008-03-09 01:54:53 +00001505 return true;
1506 }
Mike Stump11289f42009-09-09 15:08:12 +00001507
Chris Lattnerf64b3522008-03-09 01:54:53 +00001508 // Diagnose #include "" as invalid.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001509 if (Buffer.size() <= 2) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001510 Diag(Loc, diag::err_pp_empty_filename);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001511 Buffer = StringRef();
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001512 return true;
Chris Lattnerf64b3522008-03-09 01:54:53 +00001513 }
Mike Stump11289f42009-09-09 15:08:12 +00001514
Chris Lattnerf64b3522008-03-09 01:54:53 +00001515 // Skip the brackets.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001516 Buffer = Buffer.substr(1, Buffer.size()-2);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001517 return isAngled;
1518}
1519
James Dennett4a4f72d2013-11-27 01:27:40 +00001520// \brief Handle cases where the \#include name is expanded from a macro
1521// as multiple tokens, which need to be glued together.
1522//
1523// This occurs for code like:
1524// \code
1525// \#define FOO <a/b.h>
1526// \#include FOO
1527// \endcode
1528// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1529//
1530// This code concatenates and consumes tokens up to the '>' token. It returns
1531// false if the > was found, otherwise it returns true if it finds and consumes
1532// the EOD marker.
1533bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
Douglas Gregor796d76a2010-10-20 22:00:55 +00001534 SourceLocation &End) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001535 Token CurTok;
Mike Stump11289f42009-09-09 15:08:12 +00001536
John Thompsonb5353522009-10-30 13:49:06 +00001537 Lex(CurTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001538 while (CurTok.isNot(tok::eod)) {
Douglas Gregor796d76a2010-10-20 22:00:55 +00001539 End = CurTok.getLocation();
1540
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001541 // FIXME: Provide code completion for #includes.
1542 if (CurTok.is(tok::code_completion)) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001543 setCodeCompletionReached();
Douglas Gregor9c7bd2f2010-12-09 23:35:36 +00001544 Lex(CurTok);
1545 continue;
1546 }
1547
Chris Lattnerf64b3522008-03-09 01:54:53 +00001548 // Append the spelling of this token to the buffer. If there was a space
1549 // before it, add it now.
1550 if (CurTok.hasLeadingSpace())
1551 FilenameBuffer.push_back(' ');
Mike Stump11289f42009-09-09 15:08:12 +00001552
Chris Lattnerf64b3522008-03-09 01:54:53 +00001553 // Get the spelling of the token, directly into FilenameBuffer if possible.
1554 unsigned PreAppendSize = FilenameBuffer.size();
1555 FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
Mike Stump11289f42009-09-09 15:08:12 +00001556
Chris Lattnerf64b3522008-03-09 01:54:53 +00001557 const char *BufPtr = &FilenameBuffer[PreAppendSize];
John Thompsonb5353522009-10-30 13:49:06 +00001558 unsigned ActualLen = getSpelling(CurTok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattnerf64b3522008-03-09 01:54:53 +00001560 // If the token was spelled somewhere else, copy it into FilenameBuffer.
1561 if (BufPtr != &FilenameBuffer[PreAppendSize])
1562 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001563
Chris Lattnerf64b3522008-03-09 01:54:53 +00001564 // Resize FilenameBuffer to the correct size.
1565 if (CurTok.getLength() != ActualLen)
1566 FilenameBuffer.resize(PreAppendSize+ActualLen);
Mike Stump11289f42009-09-09 15:08:12 +00001567
Chris Lattnerf64b3522008-03-09 01:54:53 +00001568 // If we found the '>' marker, return success.
1569 if (CurTok.is(tok::greater))
1570 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001571
John Thompsonb5353522009-10-30 13:49:06 +00001572 Lex(CurTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001573 }
1574
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001575 // If we hit the eod marker, emit an error and return true so that the caller
1576 // knows the EOD has been read.
John Thompsonb5353522009-10-30 13:49:06 +00001577 Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001578 return true;
1579}
1580
Richard Smith34f30512013-11-23 04:06:09 +00001581/// \brief Push a token onto the token stream containing an annotation.
1582static void EnterAnnotationToken(Preprocessor &PP,
1583 SourceLocation Begin, SourceLocation End,
1584 tok::TokenKind Kind, void *AnnotationVal) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001585 // FIXME: Produce this as the current token directly, rather than
1586 // allocating a new token for it.
David Blaikie2eabcc92016-02-09 18:52:09 +00001587 auto Tok = llvm::make_unique<Token[]>(1);
Richard Smith34f30512013-11-23 04:06:09 +00001588 Tok[0].startToken();
1589 Tok[0].setKind(Kind);
1590 Tok[0].setLocation(Begin);
1591 Tok[0].setAnnotationEndLoc(End);
1592 Tok[0].setAnnotationValue(AnnotationVal);
David Blaikie2eabcc92016-02-09 18:52:09 +00001593 PP.EnterTokenStream(std::move(Tok), 1, true);
Richard Smith34f30512013-11-23 04:06:09 +00001594}
1595
Richard Smith63b6fce2015-05-18 04:45:41 +00001596/// \brief Produce a diagnostic informing the user that a #include or similar
1597/// was implicitly treated as a module import.
1598static void diagnoseAutoModuleImport(
1599 Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1600 ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1601 SourceLocation PathEnd) {
1602 assert(PP.getLangOpts().ObjC2 && "no import syntax available");
1603
1604 SmallString<128> PathString;
1605 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
1606 if (I)
1607 PathString += '.';
1608 PathString += Path[I].first->getName();
1609 }
1610 int IncludeKind = 0;
1611
1612 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1613 case tok::pp_include:
1614 IncludeKind = 0;
1615 break;
1616
1617 case tok::pp_import:
1618 IncludeKind = 1;
1619 break;
1620
1621 case tok::pp_include_next:
1622 IncludeKind = 2;
1623 break;
1624
1625 case tok::pp___include_macros:
1626 IncludeKind = 3;
1627 break;
1628
1629 default:
1630 llvm_unreachable("unknown include directive kind");
1631 }
1632
1633 CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1634 /*IsTokenRange=*/false);
1635 PP.Diag(HashLoc, diag::warn_auto_module_import)
1636 << IncludeKind << PathString
1637 << FixItHint::CreateReplacement(ReplaceRange,
1638 ("@import " + PathString + ";").str());
1639}
1640
Taewook Ohf42103c2016-06-13 20:40:21 +00001641// Given a vector of path components and a string containing the real
1642// path to the file, build a properly-cased replacement in the vector,
1643// and return true if the replacement should be suggested.
1644static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1645 StringRef RealPathName) {
1646 auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1647 auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1648 int Cnt = 0;
1649 bool SuggestReplacement = false;
1650 // Below is a best-effort to handle ".." in paths. It is admittedly
1651 // not 100% correct in the presence of symlinks.
1652 for (auto &Component : llvm::reverse(Components)) {
1653 if ("." == Component) {
1654 } else if (".." == Component) {
1655 ++Cnt;
1656 } else if (Cnt) {
1657 --Cnt;
1658 } else if (RealPathComponentIter != RealPathComponentEnd) {
1659 if (Component != *RealPathComponentIter) {
1660 // If these path components differ by more than just case, then we
1661 // may be looking at symlinked paths. Bail on this diagnostic to avoid
1662 // noisy false positives.
1663 SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1664 if (!SuggestReplacement)
1665 break;
1666 Component = *RealPathComponentIter;
1667 }
1668 ++RealPathComponentIter;
1669 }
1670 }
1671 return SuggestReplacement;
1672}
1673
James Dennettf6333ac2012-06-22 05:46:07 +00001674/// HandleIncludeDirective - The "\#include" tokens have just been read, read
1675/// the file to be included from the lexer, then include it! This is a common
1676/// routine with functionality shared between \#include, \#include_next and
1677/// \#import. LookupFrom is set when this is a \#include_next directive, it
Mike Stump11289f42009-09-09 15:08:12 +00001678/// specifies the file to start searching from.
Douglas Gregor796d76a2010-10-20 22:00:55 +00001679void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1680 Token &IncludeTok,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001681 const DirectoryLookup *LookupFrom,
Richard Smith25d50752014-10-20 00:15:49 +00001682 const FileEntry *LookupFromFile,
Chris Lattnerf64b3522008-03-09 01:54:53 +00001683 bool isImport) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001684 Token FilenameTok;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00001685 CurPPLexer->LexIncludeFilename(FilenameTok);
Mike Stump11289f42009-09-09 15:08:12 +00001686
Chris Lattnerf64b3522008-03-09 01:54:53 +00001687 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001688 SmallString<128> FilenameBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001689 StringRef Filename;
Douglas Gregor796d76a2010-10-20 22:00:55 +00001690 SourceLocation End;
Douglas Gregor41e115a2011-11-30 18:02:36 +00001691 SourceLocation CharEnd; // the end of this directive, in characters
Douglas Gregor796d76a2010-10-20 22:00:55 +00001692
Chris Lattnerf64b3522008-03-09 01:54:53 +00001693 switch (FilenameTok.getKind()) {
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001694 case tok::eod:
1695 // If the token kind is EOD, the error has already been diagnosed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00001696 return;
Mike Stump11289f42009-09-09 15:08:12 +00001697
Chris Lattnerf64b3522008-03-09 01:54:53 +00001698 case tok::angle_string_literal:
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00001699 case tok::string_literal:
1700 Filename = getSpelling(FilenameTok, FilenameBuffer);
Douglas Gregor796d76a2010-10-20 22:00:55 +00001701 End = FilenameTok.getLocation();
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001702 CharEnd = End.getLocWithOffset(FilenameTok.getLength());
Chris Lattnerf64b3522008-03-09 01:54:53 +00001703 break;
Mike Stump11289f42009-09-09 15:08:12 +00001704
Chris Lattnerf64b3522008-03-09 01:54:53 +00001705 case tok::less:
1706 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1707 // case, glue the tokens together into FilenameBuffer and interpret those.
1708 FilenameBuffer.push_back('<');
Douglas Gregor796d76a2010-10-20 22:00:55 +00001709 if (ConcatenateIncludeName(FilenameBuffer, End))
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001710 return; // Found <eod> but no ">"? Diagnostic already emitted.
Yaron Keren92e1b622015-03-18 10:17:07 +00001711 Filename = FilenameBuffer;
Argyrios Kyrtzidis2edbc862012-11-01 17:52:58 +00001712 CharEnd = End.getLocWithOffset(1);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001713 break;
1714 default:
1715 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1716 DiscardUntilEndOfDirective();
1717 return;
1718 }
Mike Stump11289f42009-09-09 15:08:12 +00001719
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001720 CharSourceRange FilenameRange
1721 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
Aaron Ballman611306e2012-03-02 22:51:54 +00001722 StringRef OriginalFilename = Filename;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001723 bool isAngled =
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001724 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001725 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1726 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +00001727 if (Filename.empty()) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00001728 DiscardUntilEndOfDirective();
1729 return;
1730 }
Mike Stump11289f42009-09-09 15:08:12 +00001731
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001732 // Verify that there is nothing after the filename, other than EOD. Note that
Chris Lattnerb40289b2009-04-17 23:56:52 +00001733 // we allow macros that expand to nothing after the filename, because this
1734 // falls into the category of "#include pp-tokens new-line" specified in
1735 // C99 6.10.2p4.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001736 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00001737
1738 // Check that we don't have infinite #include recursion.
Chris Lattner907dfe92008-11-18 07:59:24 +00001739 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1740 Diag(FilenameTok, diag::err_pp_include_too_deep);
1741 return;
1742 }
Mike Stump11289f42009-09-09 15:08:12 +00001743
John McCall32f5fe12011-09-30 05:12:12 +00001744 // Complain about attempts to #include files in an audit pragma.
1745 if (PragmaARCCFCodeAuditedLoc.isValid()) {
1746 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1747 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1748
1749 // Immediately leave the pragma.
1750 PragmaARCCFCodeAuditedLoc = SourceLocation();
1751 }
1752
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001753 // Complain about attempts to #include files in an assume-nonnull pragma.
1754 if (PragmaAssumeNonNullLoc.isValid()) {
1755 Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
1756 Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1757
1758 // Immediately leave the pragma.
1759 PragmaAssumeNonNullLoc = SourceLocation();
1760 }
1761
Aaron Ballman611306e2012-03-02 22:51:54 +00001762 if (HeaderInfo.HasIncludeAliasMap()) {
1763 // Map the filename with the brackets still attached. If the name doesn't
1764 // map to anything, fall back on the filename we've already gotten the
1765 // spelling for.
1766 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1767 if (!NewName.empty())
1768 Filename = NewName;
1769 }
1770
Chris Lattnerf64b3522008-03-09 01:54:53 +00001771 // Search include directories.
1772 const DirectoryLookup *CurDir;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001773 SmallString<1024> SearchPath;
1774 SmallString<1024> RelativePath;
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001775 // We get the raw path only if we have 'Callbacks' to which we later pass
1776 // the path.
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001777 ModuleMap::KnownHeader SuggestedModule;
1778 SourceLocation FilenameLoc = FilenameTok.getLocation();
Saleem Abdulrasool729b7d32014-03-12 02:26:08 +00001779 SmallString<128> NormalizedPath;
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001780 if (LangOpts.MSVCCompat) {
1781 NormalizedPath = Filename.str();
Yaron Keren1801d1b2014-08-09 18:13:01 +00001782#ifndef LLVM_ON_WIN32
Rafael Espindolaf6002232014-08-08 21:31:04 +00001783 llvm::sys::path::native(NormalizedPath);
Yaron Keren1801d1b2014-08-09 18:13:01 +00001784#endif
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001785 }
Chandler Carruth3cc331a2011-03-16 18:34:36 +00001786 const FileEntry *File = LookupFile(
Saleem Abdulrasool19803412014-03-11 22:41:45 +00001787 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
Richard Smith25d50752014-10-20 00:15:49 +00001788 isAngled, LookupFrom, LookupFromFile, CurDir,
1789 Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001790 &SuggestedModule);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001791
Richard Smithdbbc5232015-05-14 02:25:44 +00001792 if (!File) {
1793 if (Callbacks) {
Douglas Gregor11729f02011-11-30 18:12:06 +00001794 // Give the clients a chance to recover.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001795 SmallString<128> RecoveryPath;
Douglas Gregor11729f02011-11-30 18:12:06 +00001796 if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1797 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
1798 // Add the recovery path to the list of search paths.
Daniel Dunbarae4feb62013-01-25 01:50:28 +00001799 DirectoryLookup DL(DE, SrcMgr::C_User, false);
Douglas Gregor11729f02011-11-30 18:12:06 +00001800 HeaderInfo.AddSearchPath(DL, isAngled);
1801
1802 // Try the lookup again, skipping the cache.
Richard Smith25d50752014-10-20 00:15:49 +00001803 File = LookupFile(
1804 FilenameLoc,
1805 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1806 LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001807 &SuggestedModule, /*SkipCache*/ true);
Douglas Gregor11729f02011-11-30 18:12:06 +00001808 }
1809 }
1810 }
Craig Topperd2d442c2014-05-17 23:10:59 +00001811
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001812 if (!SuppressIncludeNotFoundError) {
1813 // If the file could not be located and it was included via angle
1814 // brackets, we can attempt a lookup as though it were a quoted path to
1815 // provide the user with a possible fixit.
1816 if (isAngled) {
Daniel Jasper07e6c402013-08-05 20:26:17 +00001817 File = LookupFile(
Richard Smith25d50752014-10-20 00:15:49 +00001818 FilenameLoc,
1819 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, false,
1820 LookupFrom, LookupFromFile, CurDir,
1821 Callbacks ? &SearchPath : nullptr,
Craig Topperd2d442c2014-05-17 23:10:59 +00001822 Callbacks ? &RelativePath : nullptr,
Richard Smith47972af2015-06-16 00:08:24 +00001823 &SuggestedModule);
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001824 if (File) {
1825 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1826 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
1827 Filename <<
1828 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
1829 }
1830 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001831
Aaron Ballman8f94ac62012-07-17 23:19:16 +00001832 // If the file is still not found, just go with the vanilla diagnostic
1833 if (!File)
1834 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1835 }
Douglas Gregor11729f02011-11-30 18:12:06 +00001836 }
1837
Richard Smith63b6fce2015-05-18 04:45:41 +00001838 // Should we enter the source file? Set to false if either the source file is
1839 // known to have no effect beyond its effect on module visibility -- that is,
1840 // if it's got an include guard that is already defined or is a modular header
1841 // we've imported or already built.
1842 bool ShouldEnter = true;
Richard Smithdbbc5232015-05-14 02:25:44 +00001843
Richard Smith63b6fce2015-05-18 04:45:41 +00001844 // Determine whether we should try to import the module for this #include, if
1845 // there is one. Don't do so if precompiled module support is disabled or we
1846 // are processing this module textually (because we're building the module).
1847 if (File && SuggestedModule && getLangOpts().Modules &&
1848 SuggestedModule.getModule()->getTopLevelModuleName() !=
Richard Smith7e82e012016-02-19 22:25:36 +00001849 getLangOpts().CurrentModule) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001850 // If this include corresponds to a module but that module is
1851 // unavailable, diagnose the situation and bail out.
Richard Smith58df3432016-04-12 19:58:30 +00001852 // FIXME: Remove this; loadModule does the same check (but produces
1853 // slightly worse diagnostics).
1854 if (!SuggestedModule.getModule()->isAvailable() &&
Richard Smith68935702016-04-12 20:20:33 +00001855 !SuggestedModule.getModule()
1856 ->getTopLevelModule()
1857 ->HasIncompatibleModuleFile) {
Sean Silva8b7c0392015-08-17 16:39:30 +00001858 clang::Module::Requirement Requirement;
1859 clang::Module::UnresolvedHeaderDirective MissingHeader;
1860 Module *M = SuggestedModule.getModule();
1861 // Identify the cause.
1862 (void)M->isAvailable(getLangOpts(), getTargetInfo(), Requirement,
1863 MissingHeader);
1864 if (MissingHeader.FileNameLoc.isValid()) {
1865 Diag(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1866 << MissingHeader.IsUmbrella << MissingHeader.FileName;
1867 } else {
1868 Diag(M->DefinitionLoc, diag::err_module_unavailable)
1869 << M->getFullModuleName() << Requirement.second << Requirement.first;
1870 }
1871 Diag(FilenameTok.getLocation(),
1872 diag::note_implicit_top_level_module_import_here)
1873 << M->getTopLevelModuleName();
1874 return;
1875 }
1876
Douglas Gregor71944202011-11-30 00:36:36 +00001877 // Compute the module access path corresponding to this module.
1878 // FIXME: Should we have a second loadModule() overload to avoid this
1879 // extra lookup step?
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001880 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001881 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
Douglas Gregor71944202011-11-30 00:36:36 +00001882 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
1883 FilenameTok.getLocation()));
1884 std::reverse(Path.begin(), Path.end());
1885
Douglas Gregor41e115a2011-11-30 18:02:36 +00001886 // Warn that we're replacing the include/import with a module import.
Richard Smith63b6fce2015-05-18 04:45:41 +00001887 // We only do this in Objective-C, where we have a module-import syntax.
1888 if (getLangOpts().ObjC2)
1889 diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
Douglas Gregor41e115a2011-11-30 18:02:36 +00001890
Richard Smith10434f32015-05-02 02:08:26 +00001891 // Load the module to import its macros. We'll make the declarations
Richard Smithce587f52013-11-15 04:24:58 +00001892 // visible when the parser gets here.
Richard Smithdbbc5232015-05-14 02:25:44 +00001893 // FIXME: Pass SuggestedModule in here rather than converting it to a path
1894 // and making the module loader convert it back again.
Richard Smith10434f32015-05-02 02:08:26 +00001895 ModuleLoadResult Imported = TheModuleLoader.loadModule(
1896 IncludeTok.getLocation(), Path, Module::Hidden,
1897 /*IsIncludeDirective=*/true);
Craig Topperd2d442c2014-05-17 23:10:59 +00001898 assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
Argyrios Kyrtzidis051b4432012-09-29 01:06:01 +00001899 "the imported module is different than the suggested one");
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001900
Richard Smith63b6fce2015-05-18 04:45:41 +00001901 if (Imported)
1902 ShouldEnter = false;
1903 else if (Imported.isMissingExpected()) {
1904 // We failed to find a submodule that we assumed would exist (because it
1905 // was in the directory of an umbrella header, for instance), but no
1906 // actual module exists for it (because the umbrella header is
1907 // incomplete). Treat this as a textual inclusion.
1908 SuggestedModule = ModuleMap::KnownHeader();
1909 } else {
1910 // We hit an error processing the import. Bail out.
1911 if (hadModuleLoaderFatalFailure()) {
1912 // With a fatal failure in the module loader, we abort parsing.
1913 Token &Result = IncludeTok;
1914 if (CurLexer) {
1915 Result.startToken();
1916 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
1917 CurLexer->cutOffLexing();
1918 } else {
1919 assert(CurPTHLexer && "#include but no current lexer set!");
1920 CurPTHLexer->getEOF(Result);
1921 }
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001922 }
1923 return;
1924 }
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +00001925 }
1926
Richard Smith63b6fce2015-05-18 04:45:41 +00001927 if (Callbacks) {
1928 // Notify the callback object that we've seen an inclusion directive.
1929 Callbacks->InclusionDirective(
1930 HashLoc, IncludeTok,
1931 LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
1932 FilenameRange, File, SearchPath, RelativePath,
1933 ShouldEnter ? nullptr : SuggestedModule.getModule());
Douglas Gregor97eec242011-09-15 22:00:41 +00001934 }
Richard Smith63b6fce2015-05-18 04:45:41 +00001935
1936 if (!File)
1937 return;
Douglas Gregor97eec242011-09-15 22:00:41 +00001938
Chris Lattnerc88a23e2008-09-26 20:12:23 +00001939 // The #included file will be considered to be a system header if either it is
1940 // in a system include directory, or if the #includer is a system include
1941 // header.
Mike Stump11289f42009-09-09 15:08:12 +00001942 SrcMgr::CharacteristicKind FileCharacter =
Chris Lattnerb03dc762008-09-26 21:18:42 +00001943 std::max(HeaderInfo.getFileDirFlavor(File),
Chris Lattnerc0334162009-01-19 07:59:15 +00001944 SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00001945
Richard Smith54ef4c32015-05-19 19:58:11 +00001946 // FIXME: If we have a suggested module, and we've already visited this file,
1947 // don't bother entering it again. We know it has no further effect.
1948
Taewook Ohf42103c2016-06-13 20:40:21 +00001949 // Issue a diagnostic if the name of the file on disk has a different case
1950 // than the one we're about to open.
1951 const bool CheckIncludePathPortability =
1952 File && !File->tryGetRealPathName().empty();
1953
1954 if (CheckIncludePathPortability) {
1955 StringRef Name = LangOpts.MSVCCompat ? NormalizedPath.str() : Filename;
1956 StringRef RealPathName = File->tryGetRealPathName();
1957 SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
1958 llvm::sys::path::end(Name));
1959
1960 if (trySimplifyPath(Components, RealPathName)) {
1961 SmallString<128> Path;
1962 Path.reserve(Name.size()+2);
1963 Path.push_back(isAngled ? '<' : '"');
1964 for (auto Component : Components) {
1965 Path.append(Component);
1966 // Append the separator the user used, or the close quote
1967 Path.push_back(
1968 Path.size() <= Filename.size() ? Filename[Path.size()-1] :
1969 (isAngled ? '>' : '"'));
1970 }
1971 auto Replacement = Path.str().str();
1972 // For user files and known standard headers, by default we issue a diagnostic.
1973 // For other system headers, we don't. They can be controlled separately.
1974 auto DiagId = (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name)) ?
1975 diag::pp_nonportable_path : diag::pp_nonportable_system_path;
1976 SourceRange Range(FilenameTok.getLocation(), CharEnd);
1977 Diag(FilenameTok, DiagId) << Replacement <<
1978 FixItHint::CreateReplacement(Range, Replacement);
1979 }
1980 }
1981
Chris Lattner72286d62010-04-19 20:44:31 +00001982 // Ask HeaderInfo if we should enter this #include file. If not, #including
Richard Smith54ef4c32015-05-19 19:58:11 +00001983 // this file will have no effect.
Richard Smith63b6fce2015-05-18 04:45:41 +00001984 if (ShouldEnter &&
Richard Smith035f6dc2015-07-01 01:51:38 +00001985 !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
1986 SuggestedModule.getModule())) {
Richard Smith63b6fce2015-05-18 04:45:41 +00001987 ShouldEnter = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001988 if (Callbacks)
Chris Lattner72286d62010-04-19 20:44:31 +00001989 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
Richard Smith63b6fce2015-05-18 04:45:41 +00001990 }
Richard Smithdbbc5232015-05-14 02:25:44 +00001991
Richard Smith63b6fce2015-05-18 04:45:41 +00001992 // If we don't need to enter the file, stop now.
1993 if (!ShouldEnter) {
Richard Smithdbbc5232015-05-14 02:25:44 +00001994 // If this is a module import, make it visible if needed.
Richard Smitha0aafa32015-05-18 03:52:30 +00001995 if (auto *M = SuggestedModule.getModule()) {
1996 makeModuleVisible(M, HashLoc);
Richard Smithdbbc5232015-05-14 02:25:44 +00001997
1998 if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
1999 tok::pp___include_macros)
Richard Smitha0aafa32015-05-18 03:52:30 +00002000 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, M);
Richard Smithdbbc5232015-05-14 02:25:44 +00002001 }
Chris Lattner72286d62010-04-19 20:44:31 +00002002 return;
2003 }
2004
Chris Lattnerf64b3522008-03-09 01:54:53 +00002005 // Look up the file, create a File ID for it.
Argyrios Kyrtzidisa9564502012-03-27 18:47:48 +00002006 SourceLocation IncludePos = End;
2007 // If the filename string was the result of macro expansions, set the include
2008 // position on the file where it will be included and after the expansions.
2009 if (IncludePos.isMacroID())
2010 IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
2011 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
Yaron Keren8b563662015-10-03 10:46:20 +00002012 assert(FID.isValid() && "Expected valid file ID");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002013
Richard Smith34f30512013-11-23 04:06:09 +00002014 // If all is good, enter the new file!
Richard Smith67294e22014-01-31 20:47:44 +00002015 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2016 return;
Richard Smith34f30512013-11-23 04:06:09 +00002017
Richard Smitha0aafa32015-05-18 03:52:30 +00002018 // Determine if we're switching to building a new submodule, and which one.
Richard Smitha0aafa32015-05-18 03:52:30 +00002019 if (auto *M = SuggestedModule.getModule()) {
Richard Smith67294e22014-01-31 20:47:44 +00002020 assert(!CurSubmodule && "should not have marked this as a module yet");
Richard Smitha0aafa32015-05-18 03:52:30 +00002021 CurSubmodule = M;
Richard Smith67294e22014-01-31 20:47:44 +00002022
Richard Smitha0aafa32015-05-18 03:52:30 +00002023 // Let the macro handling code know that any future macros are within
2024 // the new submodule.
2025 EnterSubmodule(M, HashLoc);
Richard Smithb8b2ed62015-04-23 18:18:26 +00002026
Richard Smitha0aafa32015-05-18 03:52:30 +00002027 // Let the parser know that any future declarations are within the new
2028 // submodule.
2029 // FIXME: There's no point doing this if we're handling a #__include_macros
2030 // directive.
2031 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, M);
Richard Smith67294e22014-01-31 20:47:44 +00002032 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002033}
2034
James Dennettf6333ac2012-06-22 05:46:07 +00002035/// HandleIncludeNextDirective - Implements \#include_next.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002036///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002037void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2038 Token &IncludeNextTok) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002039 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
Mike Stump11289f42009-09-09 15:08:12 +00002040
Chris Lattnerf64b3522008-03-09 01:54:53 +00002041 // #include_next is like #include, except that we start searching after
2042 // the current found directory. If we can't do this, issue a
2043 // diagnostic.
2044 const DirectoryLookup *Lookup = CurDirLookup;
Richard Smith25d50752014-10-20 00:15:49 +00002045 const FileEntry *LookupFromFile = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002046 if (isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00002047 Lookup = nullptr;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002048 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00002049 } else if (CurSubmodule) {
2050 // Start looking up in the directory *after* the one in which the current
2051 // file would be found, if any.
2052 assert(CurPPLexer && "#include_next directive in macro?");
2053 LookupFromFile = CurPPLexer->getFileEntry();
2054 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00002055 } else if (!Lookup) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002056 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2057 } else {
2058 // Start looking up in the next directory.
2059 ++Lookup;
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Richard Smith25d50752014-10-20 00:15:49 +00002062 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2063 LookupFromFile);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002064}
2065
James Dennettf6333ac2012-06-22 05:46:07 +00002066/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
Aaron Ballman0467f552012-03-18 03:10:37 +00002067void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2068 // The Microsoft #import directive takes a type library and generates header
2069 // files from it, and includes those. This is beyond the scope of what clang
2070 // does, so we ignore it and error out. However, #import can optionally have
2071 // trailing attributes that span multiple lines. We're going to eat those
2072 // so we can continue processing from there.
2073 Diag(Tok, diag::err_pp_import_directive_ms );
2074
2075 // Read tokens until we get to the end of the directive. Note that the
2076 // directive can be split over multiple lines using the backslash character.
2077 DiscardUntilEndOfDirective();
2078}
2079
James Dennettf6333ac2012-06-22 05:46:07 +00002080/// HandleImportDirective - Implements \#import.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002081///
Douglas Gregor796d76a2010-10-20 22:00:55 +00002082void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2083 Token &ImportTok) {
Aaron Ballman0467f552012-03-18 03:10:37 +00002084 if (!LangOpts.ObjC1) { // #import is standard for ObjC.
Alp Tokerbfa39342014-01-14 12:51:41 +00002085 if (LangOpts.MSVCCompat)
Aaron Ballman0467f552012-03-18 03:10:37 +00002086 return HandleMicrosoftImportDirective(ImportTok);
Chris Lattnerd4a96732009-03-06 04:28:03 +00002087 Diag(ImportTok, diag::ext_pp_import_directive);
Aaron Ballman0467f552012-03-18 03:10:37 +00002088 }
Richard Smith25d50752014-10-20 00:15:49 +00002089 return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002090}
2091
Chris Lattner58a1eb02009-04-08 18:46:40 +00002092/// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2093/// pseudo directive in the predefines buffer. This handles it by sucking all
2094/// tokens through the preprocessor and discarding them (only keeping the side
2095/// effects on the preprocessor).
Douglas Gregor796d76a2010-10-20 22:00:55 +00002096void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2097 Token &IncludeMacrosTok) {
Chris Lattner58a1eb02009-04-08 18:46:40 +00002098 // This directive should only occur in the predefines buffer. If not, emit an
2099 // error and reject it.
2100 SourceLocation Loc = IncludeMacrosTok.getLocation();
2101 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
2102 Diag(IncludeMacrosTok.getLocation(),
2103 diag::pp_include_macros_out_of_predefines);
2104 DiscardUntilEndOfDirective();
2105 return;
2106 }
Mike Stump11289f42009-09-09 15:08:12 +00002107
Chris Lattnere01d82b2009-04-08 20:53:24 +00002108 // Treat this as a normal #include for checking purposes. If this is
2109 // successful, it will push a new lexer onto the include stack.
Richard Smith25d50752014-10-20 00:15:49 +00002110 HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Mike Stump11289f42009-09-09 15:08:12 +00002111
Chris Lattnere01d82b2009-04-08 20:53:24 +00002112 Token TmpTok;
2113 do {
2114 Lex(TmpTok);
2115 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2116 } while (TmpTok.isNot(tok::hashhash));
Chris Lattner58a1eb02009-04-08 18:46:40 +00002117}
2118
Chris Lattnerf64b3522008-03-09 01:54:53 +00002119//===----------------------------------------------------------------------===//
2120// Preprocessor Macro Directive Handling.
2121//===----------------------------------------------------------------------===//
2122
2123/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
2124/// definition has just been read. Lex the rest of the arguments and the
2125/// closing ), updating MI with what we learn. Return true if an error occurs
2126/// parsing the arg list.
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002127bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002128 SmallVector<IdentifierInfo*, 32> Arguments;
Mike Stump11289f42009-09-09 15:08:12 +00002129
Chris Lattnerf64b3522008-03-09 01:54:53 +00002130 while (1) {
2131 LexUnexpandedToken(Tok);
2132 switch (Tok.getKind()) {
2133 case tok::r_paren:
2134 // Found the end of the argument list.
Chris Lattnerf87c5102009-02-20 22:31:31 +00002135 if (Arguments.empty()) // #define FOO()
Chris Lattnerf64b3522008-03-09 01:54:53 +00002136 return false;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002137 // Otherwise we have #define FOO(A,)
2138 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2139 return true;
2140 case tok::ellipsis: // #define X(... -> C99 varargs
David Blaikiebbafb8a2012-03-11 07:00:24 +00002141 if (!LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002142 Diag(Tok, LangOpts.CPlusPlus11 ?
Richard Smithacd4d3d2011-10-15 01:18:56 +00002143 diag::warn_cxx98_compat_variadic_macro :
2144 diag::ext_variadic_macro);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002145
Joey Gouly1d58cdb2013-01-17 17:35:00 +00002146 // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2147 if (LangOpts.OpenCL) {
2148 Diag(Tok, diag::err_pp_opencl_variadic_macros);
2149 return true;
2150 }
2151
Chris Lattnerf64b3522008-03-09 01:54:53 +00002152 // Lex the token after the identifier.
2153 LexUnexpandedToken(Tok);
2154 if (Tok.isNot(tok::r_paren)) {
2155 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2156 return true;
2157 }
2158 // Add the __VA_ARGS__ identifier as an argument.
2159 Arguments.push_back(Ident__VA_ARGS__);
2160 MI->setIsC99Varargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00002161 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002162 return false;
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002163 case tok::eod: // #define X(
Chris Lattnerf64b3522008-03-09 01:54:53 +00002164 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2165 return true;
2166 default:
2167 // Handle keywords and identifiers here to accept things like
2168 // #define Foo(for) for.
2169 IdentifierInfo *II = Tok.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002170 if (!II) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002171 // #define X(1
2172 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2173 return true;
2174 }
2175
2176 // If this is already used as an argument, it is used multiple times (e.g.
2177 // #define X(A,A.
Mike Stump11289f42009-09-09 15:08:12 +00002178 if (std::find(Arguments.begin(), Arguments.end(), II) !=
Chris Lattnerf64b3522008-03-09 01:54:53 +00002179 Arguments.end()) { // C99 6.10.3p6
Chris Lattnerc5cdade2008-11-19 07:33:58 +00002180 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002181 return true;
2182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183
Chris Lattnerf64b3522008-03-09 01:54:53 +00002184 // Add the argument to the macro info.
2185 Arguments.push_back(II);
Mike Stump11289f42009-09-09 15:08:12 +00002186
Chris Lattnerf64b3522008-03-09 01:54:53 +00002187 // Lex the token after the identifier.
2188 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002189
Chris Lattnerf64b3522008-03-09 01:54:53 +00002190 switch (Tok.getKind()) {
2191 default: // #define X(A B
2192 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2193 return true;
2194 case tok::r_paren: // #define X(A)
Craig Topperd96b3f92015-10-22 04:59:52 +00002195 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002196 return false;
2197 case tok::comma: // #define X(A,
2198 break;
2199 case tok::ellipsis: // #define X(A... -> GCC extension
2200 // Diagnose extension.
2201 Diag(Tok, diag::ext_named_variadic_macro);
Mike Stump11289f42009-09-09 15:08:12 +00002202
Chris Lattnerf64b3522008-03-09 01:54:53 +00002203 // Lex the token after the identifier.
2204 LexUnexpandedToken(Tok);
2205 if (Tok.isNot(tok::r_paren)) {
2206 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2207 return true;
2208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209
Chris Lattnerf64b3522008-03-09 01:54:53 +00002210 MI->setIsGNUVarargs();
Craig Topperd96b3f92015-10-22 04:59:52 +00002211 MI->setArgumentList(Arguments, BP);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002212 return false;
2213 }
2214 }
2215 }
2216}
2217
Serge Pavlov07c0f042014-12-18 11:14:21 +00002218static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2219 const LangOptions &LOptions) {
2220 if (MI->getNumTokens() == 1) {
2221 const Token &Value = MI->getReplacementToken(0);
2222
2223 // Macro that is identity, like '#define inline inline' is a valid pattern.
2224 if (MacroName.getKind() == Value.getKind())
2225 return true;
2226
2227 // Macro that maps a keyword to the same keyword decorated with leading/
2228 // trailing underscores is a valid pattern:
2229 // #define inline __inline
2230 // #define inline __inline__
2231 // #define inline _inline (in MS compatibility mode)
2232 StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2233 if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2234 if (!II->isKeyword(LOptions))
2235 return false;
2236 StringRef ValueText = II->getName();
2237 StringRef TrimmedValue = ValueText;
2238 if (!ValueText.startswith("__")) {
2239 if (ValueText.startswith("_"))
2240 TrimmedValue = TrimmedValue.drop_front(1);
2241 else
2242 return false;
2243 } else {
2244 TrimmedValue = TrimmedValue.drop_front(2);
2245 if (TrimmedValue.endswith("__"))
2246 TrimmedValue = TrimmedValue.drop_back(2);
2247 }
2248 return TrimmedValue.equals(MacroText);
2249 } else {
2250 return false;
2251 }
2252 }
2253
2254 // #define inline
Alexander Kornienkoa26c4952015-12-28 15:30:42 +00002255 return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2256 tok::kw_const) &&
2257 MI->getNumTokens() == 0;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002258}
2259
James Dennettf6333ac2012-06-22 05:46:07 +00002260/// HandleDefineDirective - Implements \#define. This consumes the entire macro
Chris Lattnerf64b3522008-03-09 01:54:53 +00002261/// line then lets the caller lex the next real token.
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002262void Preprocessor::HandleDefineDirective(Token &DefineTok,
2263 bool ImmediatelyAfterHeaderGuard) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002264 ++NumDefined;
2265
2266 Token MacroNameTok;
Serge Pavlov07c0f042014-12-18 11:14:21 +00002267 bool MacroShadowsKeyword;
2268 ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
Mike Stump11289f42009-09-09 15:08:12 +00002269
Chris Lattnerf64b3522008-03-09 01:54:53 +00002270 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002271 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002272 return;
2273
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002274 Token LastTok = MacroNameTok;
2275
Chris Lattnerf64b3522008-03-09 01:54:53 +00002276 // If we are supposed to keep comments in #defines, reenable comment saving
2277 // mode.
Ted Kremenek59e003e2008-11-18 00:43:07 +00002278 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
Mike Stump11289f42009-09-09 15:08:12 +00002279
Chris Lattnerf64b3522008-03-09 01:54:53 +00002280 // Create the new macro.
Ted Kremenek6c7ea112008-12-15 19:56:42 +00002281 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002282
Chris Lattnerf64b3522008-03-09 01:54:53 +00002283 Token Tok;
2284 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002285
Chris Lattnerf64b3522008-03-09 01:54:53 +00002286 // If this is a function-like macro definition, parse the argument list,
2287 // marking each of the identifiers as being used as macro arguments. Also,
2288 // check other constraints on the first token of the macro body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002289 if (Tok.is(tok::eod)) {
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002290 if (ImmediatelyAfterHeaderGuard) {
2291 // Save this macro information since it may part of a header guard.
2292 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2293 MacroNameTok.getLocation());
2294 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002295 // If there is no body to this macro, we have no special handling here.
Chris Lattner2425bcb2009-04-18 02:23:25 +00002296 } else if (Tok.hasLeadingSpace()) {
2297 // This is a normal token with leading space. Clear the leading space
2298 // marker on the first token to get proper expansion.
2299 Tok.clearFlag(Token::LeadingSpace);
2300 } else if (Tok.is(tok::l_paren)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002301 // This is a function-like macro definition. Read the argument list.
2302 MI->setIsFunctionLike();
Abramo Bagnarac9e48c02012-03-31 20:17:27 +00002303 if (ReadMacroDefinitionArgList(MI, LastTok)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002304 // Throw away the rest of the line.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002305 if (CurPPLexer->ParsingPreprocessorDirective)
Chris Lattnerf64b3522008-03-09 01:54:53 +00002306 DiscardUntilEndOfDirective();
2307 return;
2308 }
2309
Chris Lattner249c38b2009-04-19 18:26:34 +00002310 // If this is a definition of a variadic C99 function-like macro, not using
2311 // the GNU named varargs extension, enabled __VA_ARGS__.
Mike Stump11289f42009-09-09 15:08:12 +00002312
Chris Lattner249c38b2009-04-19 18:26:34 +00002313 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
2314 // This gets unpoisoned where it is allowed.
2315 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
2316 if (MI->isC99Varargs())
2317 Ident__VA_ARGS__->setIsPoisoned(false);
Mike Stump11289f42009-09-09 15:08:12 +00002318
Chris Lattnerf64b3522008-03-09 01:54:53 +00002319 // Read the first token after the arg list for down below.
2320 LexUnexpandedToken(Tok);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002321 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002322 // C99 requires whitespace between the macro definition and the body. Emit
2323 // a diagnostic for something like "#define X+".
Chris Lattner2425bcb2009-04-18 02:23:25 +00002324 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002325 } else {
Chris Lattner2425bcb2009-04-18 02:23:25 +00002326 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2327 // first character of a replacement list is not a character required by
2328 // subclause 5.2.1, then there shall be white-space separation between the
2329 // identifier and the replacement list.". 5.2.1 lists this set:
2330 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2331 // is irrelevant here.
2332 bool isInvalid = false;
2333 if (Tok.is(tok::at)) // @ is not in the list above.
2334 isInvalid = true;
2335 else if (Tok.is(tok::unknown)) {
2336 // If we have an unknown token, it is something strange like "`". Since
2337 // all of valid characters would have lexed into a single character
2338 // token of some sort, we know this is not a valid case.
2339 isInvalid = true;
2340 }
2341 if (isInvalid)
2342 Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2343 else
2344 Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002345 }
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002346
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002347 if (!Tok.is(tok::eod))
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002348 LastTok = Tok;
2349
Chris Lattnerf64b3522008-03-09 01:54:53 +00002350 // Read the rest of the macro body.
2351 if (MI->isObjectLike()) {
2352 // Object-like macros are very simple, just read their body.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002353 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002354 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002355 MI->AddTokenToBody(Tok);
2356 // Get the next token of the macro.
2357 LexUnexpandedToken(Tok);
2358 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002359 } else {
Chris Lattner83bd8282009-05-25 17:16:10 +00002360 // Otherwise, read the body of a function-like macro. While we are at it,
2361 // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2362 // parameters in function-like macro expansions.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002363 while (Tok.isNot(tok::eod)) {
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002364 LastTok = Tok;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002365
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002366 if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002367 MI->AddTokenToBody(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002368
Chris Lattnerf64b3522008-03-09 01:54:53 +00002369 // Get the next token of the macro.
2370 LexUnexpandedToken(Tok);
2371 continue;
2372 }
Mike Stump11289f42009-09-09 15:08:12 +00002373
Richard Smith701a3522013-07-09 01:00:29 +00002374 // If we're in -traditional mode, then we should ignore stringification
2375 // and token pasting. Mark the tokens as unknown so as not to confuse
2376 // things.
2377 if (getLangOpts().TraditionalCPP) {
2378 Tok.setKind(tok::unknown);
2379 MI->AddTokenToBody(Tok);
2380
2381 // Get the next token of the macro.
2382 LexUnexpandedToken(Tok);
2383 continue;
2384 }
2385
Eli Friedman14d3c792012-11-14 02:18:46 +00002386 if (Tok.is(tok::hashhash)) {
Eli Friedman14d3c792012-11-14 02:18:46 +00002387 // If we see token pasting, check if it looks like the gcc comma
2388 // pasting extension. We'll use this information to suppress
2389 // diagnostics later on.
2390
2391 // Get the next token of the macro.
2392 LexUnexpandedToken(Tok);
2393
2394 if (Tok.is(tok::eod)) {
2395 MI->AddTokenToBody(LastTok);
2396 break;
2397 }
2398
2399 unsigned NumTokens = MI->getNumTokens();
2400 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2401 MI->getReplacementToken(NumTokens-1).is(tok::comma))
2402 MI->setHasCommaPasting();
2403
David Majnemer76faf1f2013-11-05 09:30:17 +00002404 // Things look ok, add the '##' token to the macro.
Eli Friedman14d3c792012-11-14 02:18:46 +00002405 MI->AddTokenToBody(LastTok);
Eli Friedman14d3c792012-11-14 02:18:46 +00002406 continue;
2407 }
2408
Chris Lattnerf64b3522008-03-09 01:54:53 +00002409 // Get the next token of the macro.
2410 LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +00002411
Chris Lattner83bd8282009-05-25 17:16:10 +00002412 // Check for a valid macro arg identifier.
Craig Topperd2d442c2014-05-17 23:10:59 +00002413 if (Tok.getIdentifierInfo() == nullptr ||
Chris Lattner83bd8282009-05-25 17:16:10 +00002414 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
2415
2416 // If this is assembler-with-cpp mode, we accept random gibberish after
2417 // the '#' because '#' is often a comment character. However, change
2418 // the kind of the token to tok::unknown so that the preprocessor isn't
2419 // confused.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002420 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
Chris Lattner83bd8282009-05-25 17:16:10 +00002421 LastTok.setKind(tok::unknown);
Eli Friedmancdf8b882013-06-18 21:33:38 +00002422 MI->AddTokenToBody(LastTok);
2423 continue;
Chris Lattner83bd8282009-05-25 17:16:10 +00002424 } else {
Andy Gibbs6f8cfccb2016-04-01 19:02:20 +00002425 Diag(Tok, diag::err_pp_stringize_not_parameter)
2426 << LastTok.is(tok::hashat);
Mike Stump11289f42009-09-09 15:08:12 +00002427
Chris Lattner83bd8282009-05-25 17:16:10 +00002428 // Disable __VA_ARGS__ again.
2429 Ident__VA_ARGS__->setIsPoisoned(true);
2430 return;
2431 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002432 }
Mike Stump11289f42009-09-09 15:08:12 +00002433
Chris Lattner83bd8282009-05-25 17:16:10 +00002434 // Things look ok, add the '#' and param name tokens to the macro.
2435 MI->AddTokenToBody(LastTok);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002436 MI->AddTokenToBody(Tok);
Chris Lattner83bd8282009-05-25 17:16:10 +00002437 LastTok = Tok;
Mike Stump11289f42009-09-09 15:08:12 +00002438
Chris Lattnerf64b3522008-03-09 01:54:53 +00002439 // Get the next token of the macro.
2440 LexUnexpandedToken(Tok);
2441 }
2442 }
Mike Stump11289f42009-09-09 15:08:12 +00002443
Serge Pavlov07c0f042014-12-18 11:14:21 +00002444 if (MacroShadowsKeyword &&
2445 !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2446 Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2447 }
Mike Stump11289f42009-09-09 15:08:12 +00002448
Chris Lattnerf64b3522008-03-09 01:54:53 +00002449 // Disable __VA_ARGS__ again.
2450 Ident__VA_ARGS__->setIsPoisoned(true);
2451
Chris Lattner57540c52011-04-15 05:22:18 +00002452 // Check that there is no paste (##) operator at the beginning or end of the
Chris Lattnerf64b3522008-03-09 01:54:53 +00002453 // replacement list.
2454 unsigned NumTokens = MI->getNumTokens();
2455 if (NumTokens != 0) {
2456 if (MI->getReplacementToken(0).is(tok::hashhash)) {
2457 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002458 return;
2459 }
2460 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2461 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002462 return;
2463 }
2464 }
Mike Stump11289f42009-09-09 15:08:12 +00002465
Chris Lattnerd6e97af2009-04-21 04:46:33 +00002466 MI->setDefinitionEndLoc(LastTok.getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002467
Chris Lattnerf64b3522008-03-09 01:54:53 +00002468 // Finally, if this identifier already had a macro defined for it, verify that
Alexander Kornienko8b3f6232012-08-29 00:20:03 +00002469 // the macro bodies are identical, and issue diagnostics if they are not.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +00002470 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
John McCall83760372015-12-10 23:31:01 +00002471 // In Objective-C, ignore attempts to directly redefine the builtin
2472 // definitions of the ownership qualifiers. It's still possible to
2473 // #undef them.
2474 auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2475 return II->isStr("__strong") ||
2476 II->isStr("__weak") ||
2477 II->isStr("__unsafe_unretained") ||
2478 II->isStr("__autoreleasing");
2479 };
2480 if (getLangOpts().ObjC1 &&
2481 SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2482 == getPredefinesFileID() &&
2483 isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2484 // Warn if it changes the tokens.
2485 if ((!getDiagnostics().getSuppressSystemWarnings() ||
2486 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2487 !MI->isIdenticalTo(*OtherMI, *this,
2488 /*Syntactic=*/LangOpts.MicrosoftExt)) {
2489 Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2490 }
2491 assert(!OtherMI->isWarnIfUnused());
2492 return;
2493 }
2494
Chris Lattner5244f342009-01-16 19:50:11 +00002495 // It is very common for system headers to have tons of macro redefinitions
2496 // and for warnings to be disabled in system headers. If this is the case,
2497 // then don't bother calling MacroInfo::isIdenticalTo.
Chris Lattner80c21df2009-03-13 21:17:23 +00002498 if (!getDiagnostics().getSuppressSystemWarnings() ||
Chris Lattner5244f342009-01-16 19:50:11 +00002499 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002500 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Chris Lattner5244f342009-01-16 19:50:11 +00002501 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002502
Richard Smith7b242542013-03-06 00:46:00 +00002503 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2504 // C++ [cpp.predefined]p4, but allow it as an extension.
2505 if (OtherMI->isBuiltinMacro())
2506 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
Chris Lattnerc0a585d2010-08-17 15:55:45 +00002507 // Macros must be identical. This means all tokens and whitespace
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002508 // separation must be the same. C99 6.10.3p2.
Richard Smith7b242542013-03-06 00:46:00 +00002509 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
Argyrios Kyrtzidis0c2f30b2013-04-03 17:39:30 +00002510 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
Chris Lattner5244f342009-01-16 19:50:11 +00002511 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2512 << MacroNameTok.getIdentifierInfo();
2513 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2514 }
Chris Lattnerf64b3522008-03-09 01:54:53 +00002515 }
Argyrios Kyrtzidisb495cc12011-01-18 19:50:15 +00002516 if (OtherMI->isWarnIfUnused())
2517 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002518 }
Mike Stump11289f42009-09-09 15:08:12 +00002519
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002520 DefMacroDirective *MD =
2521 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
Mike Stump11289f42009-09-09 15:08:12 +00002522
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002523 assert(!MI->isUsed());
2524 // If we need warning for not using the macro, add its location in the
2525 // warn-because-unused-macro set. If it gets used it will be removed from set.
Eli Friedman5ba37d52013-08-22 00:27:10 +00002526 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002527 !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002528 MI->setIsWarnIfUnused(true);
2529 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2530 }
2531
Chris Lattner928e9092009-04-12 01:39:54 +00002532 // If the callbacks want to know, tell them about the macro definition.
2533 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002534 Callbacks->MacroDefined(MacroNameTok, MD);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002535}
2536
James Dennettf6333ac2012-06-22 05:46:07 +00002537/// HandleUndefDirective - Implements \#undef.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002538///
2539void Preprocessor::HandleUndefDirective(Token &UndefTok) {
2540 ++NumUndefined;
2541
2542 Token MacroNameTok;
Serge Pavlovd024f522014-10-24 17:31:32 +00002543 ReadMacroName(MacroNameTok, MU_Undef);
Mike Stump11289f42009-09-09 15:08:12 +00002544
Chris Lattnerf64b3522008-03-09 01:54:53 +00002545 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002546 if (MacroNameTok.is(tok::eod))
Chris Lattnerf64b3522008-03-09 01:54:53 +00002547 return;
Mike Stump11289f42009-09-09 15:08:12 +00002548
Chris Lattnerf64b3522008-03-09 01:54:53 +00002549 // Check to see if this is the last token on the #undef line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002550 CheckEndOfDirective("undef");
Mike Stump11289f42009-09-09 15:08:12 +00002551
Richard Smith20e883e2015-04-29 23:20:19 +00002552 // Okay, we have a valid identifier to undef.
2553 auto *II = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002554 auto MD = getMacroDefinition(II);
Mike Stump11289f42009-09-09 15:08:12 +00002555
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002556 // If the callbacks want to know, tell them about the macro #undef.
2557 // Note: no matter if the macro was defined or not.
Richard Smith36bd40d2015-05-04 03:15:40 +00002558 if (Callbacks)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002559 Callbacks->MacroUndefined(MacroNameTok, MD);
Argyrios Kyrtzidis99b0a6a2013-01-16 16:52:44 +00002560
Chris Lattnerf64b3522008-03-09 01:54:53 +00002561 // If the macro is not defined, this is a noop undef, just return.
Richard Smith36bd40d2015-05-04 03:15:40 +00002562 const MacroInfo *MI = MD.getMacroInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00002563 if (!MI)
2564 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002565
Argyrios Kyrtzidis22998892011-07-11 20:39:47 +00002566 if (!MI->isUsed() && MI->isWarnIfUnused())
Chris Lattnerf64b3522008-03-09 01:54:53 +00002567 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattnercd6d4b12009-04-21 03:42:09 +00002568
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002569 if (MI->isWarnIfUnused())
2570 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2571
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002572 appendMacroDirective(MacroNameTok.getIdentifierInfo(),
2573 AllocateUndefMacroDirective(MacroNameTok.getLocation()));
Chris Lattnerf64b3522008-03-09 01:54:53 +00002574}
2575
Chris Lattnerf64b3522008-03-09 01:54:53 +00002576//===----------------------------------------------------------------------===//
2577// Preprocessor Conditional Directive Handling.
2578//===----------------------------------------------------------------------===//
2579
James Dennettf6333ac2012-06-22 05:46:07 +00002580/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
2581/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
2582/// true if any tokens have been returned or pp-directives activated before this
2583/// \#ifndef has been lexed.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002584///
2585void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
2586 bool ReadAnyTokensBeforeDirective) {
2587 ++NumIf;
2588 Token DirectiveTok = Result;
2589
2590 Token MacroNameTok;
2591 ReadMacroName(MacroNameTok);
Mike Stump11289f42009-09-09 15:08:12 +00002592
Chris Lattnerf64b3522008-03-09 01:54:53 +00002593 // Error reading macro name? If so, diagnostic already issued.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00002594 if (MacroNameTok.is(tok::eod)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002595 // Skip code until we get to #endif. This helps with recovery by not
2596 // emitting an error when the #endif is reached.
2597 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2598 /*Foundnonskip*/false, /*FoundElse*/false);
2599 return;
2600 }
Mike Stump11289f42009-09-09 15:08:12 +00002601
Chris Lattnerf64b3522008-03-09 01:54:53 +00002602 // Check to see if this is the last token on the #if[n]def line.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002603 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
Chris Lattnerf64b3522008-03-09 01:54:53 +00002604
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002605 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
Richard Smith36bd40d2015-05-04 03:15:40 +00002606 auto MD = getMacroDefinition(MII);
2607 MacroInfo *MI = MD.getMacroInfo();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002608
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002609 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002610 // If the start of a top-level #ifdef and if the macro is not defined,
2611 // inform MIOpt that this might be the start of a proper include guard.
2612 // Otherwise it is some other form of unknown conditional which we can't
2613 // handle.
Craig Topperd2d442c2014-05-17 23:10:59 +00002614 if (!ReadAnyTokensBeforeDirective && !MI) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002615 assert(isIfndef && "#ifdef shouldn't reach here");
Richard Trieu33a4b3d2013-06-12 21:20:57 +00002616 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002617 } else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002618 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002619 }
2620
Chris Lattnerf64b3522008-03-09 01:54:53 +00002621 // If there is a macro, process it.
2622 if (MI) // Mark it used.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002623 markMacroAsUsed(MI);
Mike Stump11289f42009-09-09 15:08:12 +00002624
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002625 if (Callbacks) {
2626 if (isIfndef)
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002627 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002628 else
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +00002629 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002630 }
2631
Chris Lattnerf64b3522008-03-09 01:54:53 +00002632 // Should we include the stuff contained by this directive?
2633 if (!MI == isIfndef) {
2634 // Yes, remember that we are inside a conditional, then lex the next token.
Chris Lattner8cf1f932009-12-14 04:54:40 +00002635 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
2636 /*wasskip*/false, /*foundnonskip*/true,
2637 /*foundelse*/false);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002638 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002639 // No, skip the contents of this block.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002640 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002641 /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002642 /*FoundElse*/false);
2643 }
2644}
2645
James Dennettf6333ac2012-06-22 05:46:07 +00002646/// HandleIfDirective - Implements the \#if directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002647///
2648void Preprocessor::HandleIfDirective(Token &IfToken,
2649 bool ReadAnyTokensBeforeDirective) {
2650 ++NumIf;
Mike Stump11289f42009-09-09 15:08:12 +00002651
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002652 // Parse and evaluate the conditional expression.
Craig Topperd2d442c2014-05-17 23:10:59 +00002653 IdentifierInfo *IfNDefMacro = nullptr;
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002654 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
2655 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2656 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Nuno Lopes363212b2008-06-01 18:31:24 +00002657
2658 // If this condition is equivalent to #ifndef X, and if this is the first
2659 // directive seen, handle it for the multiple-include optimization.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002660 if (CurPPLexer->getConditionalStackDepth() == 0) {
Chris Lattneraa1cccbb2010-02-12 08:03:27 +00002661 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
Richard Smith089ee152013-06-16 05:05:39 +00002662 // FIXME: Pass in the location of the macro name, not the 'if' token.
2663 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
Nuno Lopes363212b2008-06-01 18:31:24 +00002664 else
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002665 CurPPLexer->MIOpt.EnterTopLevelConditional();
Nuno Lopes363212b2008-06-01 18:31:24 +00002666 }
2667
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002668 if (Callbacks)
2669 Callbacks->If(IfToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002670 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002671 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002672
Chris Lattnerf64b3522008-03-09 01:54:53 +00002673 // Should we include the stuff contained by this directive?
2674 if (ConditionalTrue) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002675 // Yes, remember that we are inside a conditional, then lex the next token.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002676 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002677 /*foundnonskip*/true, /*foundelse*/false);
2678 } else {
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002679 // No, skip the contents of this block.
Mike Stump11289f42009-09-09 15:08:12 +00002680 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
Chris Lattnerf64b3522008-03-09 01:54:53 +00002681 /*FoundElse*/false);
2682 }
2683}
2684
James Dennettf6333ac2012-06-22 05:46:07 +00002685/// HandleEndifDirective - Implements the \#endif directive.
Chris Lattnerf64b3522008-03-09 01:54:53 +00002686///
2687void Preprocessor::HandleEndifDirective(Token &EndifToken) {
2688 ++NumEndif;
Mike Stump11289f42009-09-09 15:08:12 +00002689
Chris Lattnerf64b3522008-03-09 01:54:53 +00002690 // Check that this is the whole directive.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002691 CheckEndOfDirective("endif");
Mike Stump11289f42009-09-09 15:08:12 +00002692
Chris Lattnerf64b3522008-03-09 01:54:53 +00002693 PPConditionalInfo CondInfo;
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002694 if (CurPPLexer->popConditionalLevel(CondInfo)) {
Chris Lattnerf64b3522008-03-09 01:54:53 +00002695 // No conditionals on the stack: this is an #endif without an #if.
Chris Lattner907dfe92008-11-18 07:59:24 +00002696 Diag(EndifToken, diag::err_pp_endif_without_if);
2697 return;
Chris Lattnerf64b3522008-03-09 01:54:53 +00002698 }
Mike Stump11289f42009-09-09 15:08:12 +00002699
Chris Lattnerf64b3522008-03-09 01:54:53 +00002700 // If this the end of a top-level #endif, inform MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002701 if (CurPPLexer->getConditionalStackDepth() == 0)
2702 CurPPLexer->MIOpt.ExitTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002703
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002704 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
Chris Lattnerf64b3522008-03-09 01:54:53 +00002705 "This code should only be reachable in the non-skipping case!");
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002706
2707 if (Callbacks)
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002708 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002709}
2710
James Dennettf6333ac2012-06-22 05:46:07 +00002711/// HandleElseDirective - Implements the \#else directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002712///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002713void Preprocessor::HandleElseDirective(Token &Result) {
2714 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002715
Chris Lattnerf64b3522008-03-09 01:54:53 +00002716 // #else directive in a non-skipping conditional... start skipping.
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00002717 CheckEndOfDirective("else");
Mike Stump11289f42009-09-09 15:08:12 +00002718
Chris Lattnerf64b3522008-03-09 01:54:53 +00002719 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002720 if (CurPPLexer->popConditionalLevel(CI)) {
2721 Diag(Result, diag::pp_err_else_without_if);
2722 return;
2723 }
Mike Stump11289f42009-09-09 15:08:12 +00002724
Chris Lattnerf64b3522008-03-09 01:54:53 +00002725 // If this is a top-level #else, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002726 if (CurPPLexer->getConditionalStackDepth() == 0)
2727 CurPPLexer->MIOpt.EnterTopLevelConditional();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002728
2729 // If this is a #else with a #else before it, report the error.
2730 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
Mike Stump11289f42009-09-09 15:08:12 +00002731
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002732 if (Callbacks)
2733 Callbacks->Else(Result.getLocation(), CI.IfLoc);
2734
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002735 // Finally, skip the rest of the contents of this block.
2736 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002737 /*FoundElse*/true, Result.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002738}
2739
James Dennettf6333ac2012-06-22 05:46:07 +00002740/// HandleElifDirective - Implements the \#elif directive.
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002741///
Chris Lattnerf64b3522008-03-09 01:54:53 +00002742void Preprocessor::HandleElifDirective(Token &ElifToken) {
2743 ++NumElse;
Mike Stump11289f42009-09-09 15:08:12 +00002744
Chris Lattnerf64b3522008-03-09 01:54:53 +00002745 // #elif directive in a non-skipping conditional... start skipping.
2746 // We don't care what the condition is, because we will always skip it (since
2747 // the block immediately before it was included).
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002748 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002749 DiscardUntilEndOfDirective();
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002750 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
Chris Lattnerf64b3522008-03-09 01:54:53 +00002751
2752 PPConditionalInfo CI;
Chris Lattner907dfe92008-11-18 07:59:24 +00002753 if (CurPPLexer->popConditionalLevel(CI)) {
2754 Diag(ElifToken, diag::pp_err_elif_without_if);
2755 return;
2756 }
Mike Stump11289f42009-09-09 15:08:12 +00002757
Chris Lattnerf64b3522008-03-09 01:54:53 +00002758 // If this is a top-level #elif, inform the MIOpt.
Ted Kremenek30cd88c2008-11-18 00:34:22 +00002759 if (CurPPLexer->getConditionalStackDepth() == 0)
2760 CurPPLexer->MIOpt.EnterTopLevelConditional();
Mike Stump11289f42009-09-09 15:08:12 +00002761
Chris Lattnerf64b3522008-03-09 01:54:53 +00002762 // If this is a #elif with a #else before it, report the error.
2763 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
Argyrios Kyrtzidisc793a612012-03-05 05:48:09 +00002764
2765 if (Callbacks)
2766 Callbacks->Elif(ElifToken.getLocation(),
John Thompsonb1028562013-07-18 00:00:36 +00002767 SourceRange(ConditionalBegin, ConditionalEnd),
John Thompson87f9fef2013-12-07 08:41:15 +00002768 PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
Chris Lattnerf64b3522008-03-09 01:54:53 +00002769
Craig Silverstein8e3d95e2010-11-06 01:19:03 +00002770 // Finally, skip the rest of the contents of this block.
2771 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
Argyrios Kyrtzidis18bcfd52011-09-27 17:32:05 +00002772 /*FoundElse*/CI.FoundElse,
2773 ElifToken.getLocation());
Chris Lattnerf64b3522008-03-09 01:54:53 +00002774}